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 <Joystick/joystick.hxx>
92 #include <NetworkOLK/network.h>
94 #include <Objects/matlib.hxx>
95 #include <Scenery/scenery.hxx>
96 #include <Scenery/tilemgr.hxx>
97 #ifdef ENABLE_AUDIO_SUPPORT
98 # include <Sound/soundmgr.hxx>
99 # include <Sound/fg_fx.hxx>
100 # include <Sound/morse.hxx>
102 #include <Time/event.hxx>
103 #include <Time/fg_timer.hxx>
104 #include <Time/light.hxx>
105 #include <Time/sunpos.hxx>
106 #include <Time/tmp.hxx>
108 #include <Input/input.hxx>
111 #include <simgear/misc/sgstream.hxx>
112 #include <simgear/math/point3d.hxx>
113 #include <FDM/flight.hxx>
114 #include <FDM/ADA.hxx>
115 #include <Scenery/tileentry.hxx>
117 // Should already be inlcluded by gl.h if needed by your platform so
118 // we shouldn't include this here.
119 // #include <GL/glext.h>
121 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
122 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
124 float default_attenuation[3] = {1.0, 0.0, 0.0};
125 //Required for using GL_extensions
126 void fgLoadDCS (void);
127 void fgUpdateDCS (void);
128 ssgSelector *ship_sel=NULL;
129 // upto 32 instances of a same object can be loaded.
130 ssgTransform *ship_pos[32];
131 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
133 ssgSelector *lightpoints_brightness = new ssgSelector;
134 ssgTransform *lightpoints_transform = new ssgTransform;
135 FGTileEntry *dummy_tile;
139 #ifndef FG_NEW_ENVIRONMENT
140 # include <WeatherCM/FGLocalWeatherDatabase.h>
142 # include <Environment/environment_mgr.hxx>
147 #include "fg_init.hxx"
149 #include "fg_props.hxx"
150 #include "globals.hxx"
151 #include "splash.hxx"
152 #include "viewmgr.hxx"
153 #include "options.hxx"
154 #include "logger.hxx"
158 # include <console.h> // -dw- for command line dialog
162 // This is a record containing a bit of global housekeeping information
165 // Specify our current idle function state. This is used to run all
166 // our initializations out of the glutIdleLoop() so that we can get a
167 // splash screen up and running right away.
168 static int idle_state = 0;
169 static long global_multi_loop;
171 // forward declaration
172 void fgReshape( int width, int height );
175 ssgRoot *scene = NULL;
176 ssgBranch *terrain_branch = NULL;
177 ssgBranch *gnd_lights_branch = NULL;
178 ssgBranch *rwy_lights_branch = NULL;
180 // fog constants. I'm a little nervous about putting actual code out
181 // here but it seems to work (?)
182 static const double m_log01 = -log( 0.01 );
183 static const double sqrt_m_log01 = sqrt( m_log01 );
184 static GLfloat fog_exp_density;
185 static GLfloat fog_exp2_density;
186 static GLfloat fog_exp2_punch_through;
188 ssgRoot *lighting = NULL;
189 // ssgBranch *airport = NULL;
191 #ifdef FG_NETWORK_OLK
192 ssgSelector *fgd_sel = NULL;
193 ssgTransform *fgd_pos = NULL;
196 // current fdm/position used for view
197 FGInterface cur_view_fdm;
203 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
205 { 1.0f, 0.0f, 0.0f, 0.0f },
206 { 0.0f, 0.0f, -1.0f, 0.0f },
207 { 0.0f, 1.0f, 0.0f, 0.0f },
208 { 0.0f, 0.0f, 0.0f, 1.0f }
211 // The following defines flightgear options. Because glutlib will also
212 // want to parse its own options, those options must not be included here
213 // or they will get parsed by the main program option parser. Hence case
214 // is significant for any option added that might be in conflict with
217 // glutlib parses for:
219 // -direct (invalid in Win32)
223 // -indirect (invalid in Win32)
226 // Note that glutlib depends upon strings while this program's
227 // option parser wants only initial characters followed by numbers
232 ssgSimpleState *default_state;
233 ssgSimpleState *hud_and_panel;
234 ssgSimpleState *menus;
236 SGTimeStamp start_time_stamp;
237 SGTimeStamp current_time_stamp;
239 void fgBuildRenderStates( void ) {
240 default_state = new ssgSimpleState;
241 default_state->ref();
242 default_state->disable( GL_TEXTURE_2D );
243 default_state->enable( GL_CULL_FACE );
244 default_state->enable( GL_COLOR_MATERIAL );
245 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
246 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
247 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
248 default_state->disable( GL_BLEND );
249 default_state->disable( GL_ALPHA_TEST );
250 default_state->disable( GL_LIGHTING );
252 hud_and_panel = new ssgSimpleState;
253 hud_and_panel->ref();
254 hud_and_panel->disable( GL_CULL_FACE );
255 hud_and_panel->disable( GL_TEXTURE_2D );
256 hud_and_panel->disable( GL_LIGHTING );
257 hud_and_panel->enable( GL_BLEND );
259 menus = new ssgSimpleState;
261 menus->disable( GL_CULL_FACE );
262 menus->disable( GL_TEXTURE_2D );
263 menus->enable( GL_BLEND );
266 // fgFindNode -- a function that finds a named node in an ssg graph
267 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
268 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
270 } else if ( node->isAKindOf(ssgTypeBranch()) ) {
271 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
272 while ( kid != NULL ) {
273 ssgEntity *n = fgFindNode(kid, name);
277 kid = ((ssgBranch*)node)->getNextKid();
284 // fgInitVisuals() -- Initialize various GL/view parameters
285 void fgInitVisuals( void ) {
288 l = &cur_light_params;
290 #ifndef GLUT_WRONG_VERSION
291 // Go full screen if requested ...
292 if ( fgGetBool("/sim/startup/fullscreen") ) {
297 // If enabled, normal vectors specified with glNormal are scaled
298 // to unit length after transformation. See glNormal.
299 // glEnable( GL_NORMALIZE );
301 glEnable( GL_LIGHTING );
302 glEnable( GL_LIGHT0 );
303 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
306 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
307 ssgGetLight( 0 ) -> setPosition( sunpos );
309 // glFogi (GL_FOG_MODE, GL_LINEAR);
310 glFogi (GL_FOG_MODE, GL_EXP2);
311 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
312 (!fgGetBool("/sim/rendering/shading"))) {
313 // if fastest fog requested, or if flat shading force fastest
314 glHint ( GL_FOG_HINT, GL_FASTEST );
315 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
316 glHint ( GL_FOG_HINT, GL_NICEST );
318 if ( fgGetBool("/sim/rendering/wireframe") ) {
320 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
323 // This is the default anyways, but it can't hurt
324 glFrontFace ( GL_CCW );
327 // glEnable(GL_POINT_SMOOTH);
328 // glEnable(GL_LINE_SMOOTH);
329 // glEnable(GL_POLYGON_SMOOTH);
333 // For HiRes screen Dumps using Brian Pauls TR Library
334 void trRenderFrame( void ) {
336 if ( fgPanelVisible() ) {
337 GLfloat height = fgGetInt("/sim/startup/ysize");
339 (current_panel->getViewHeight() - current_panel->getYOffset())
340 * (height / 768.0) + 1;
341 glTranslatef( 0.0, view_h, 0.0 );
344 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
345 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
347 fgLIGHT *l = &cur_light_params;
349 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
350 l->adj_fog_color[2], l->adj_fog_color[3]);
352 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
354 // set the opengl state to known default values
355 default_state->force();
358 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
359 glFogi ( GL_FOG_MODE, GL_EXP2 );
360 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
362 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
363 // we only update GL_AMBIENT for our lights we will never get
364 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
365 // explicitely to black.
366 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
368 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
370 // texture parameters
371 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
372 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
374 // we need a white diffuse light for the phase of the moon
375 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
378 // draw the ssg scene
379 // return to the desired diffuse color
380 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
381 glEnable( GL_DEPTH_TEST );
382 ssgCullAndDraw( scene );
385 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
386 ssgCullAndDraw( lighting );
388 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
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 ) {
399 static const SGPropertyNode *longitude
400 = fgGetNode("/position/longitude-deg");
401 static const SGPropertyNode *latitude
402 = fgGetNode("/position/latitude-deg");
403 static const SGPropertyNode *altitude
404 = fgGetNode("/position/altitude-ft");
406 // Update the default (kludged) properties.
409 fgLIGHT *l = &cur_light_params;
410 static double last_visibility = -9999;
413 double actual_visibility = thesky->get_visibility();
414 if ( actual_visibility != last_visibility ) {
415 last_visibility = actual_visibility;
417 fog_exp_density = m_log01 / actual_visibility;
418 fog_exp2_density = sqrt_m_log01 / actual_visibility;
419 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 4.0 );
423 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
424 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
425 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
426 // GLfloat mat_shininess[] = { 10.0 };
427 GLbitfield clear_mask;
429 if ( idle_state != 1000 ) {
430 // still initializing, draw the splash screen
431 if ( fgGetBool("/sim/startup/splash-screen") ) {
434 start_time_stamp.stamp(); // Keep resetting the start time
436 // idle_state is now 1000 meaning we've finished all our
437 // initializations and are running the main loop, so this will
438 // now work without seg faulting the system.
440 // Update the elapsed time.
441 current_time_stamp.stamp();
442 globals->set_elapsed_time_ms((current_time_stamp - start_time_stamp)
445 // calculate our current position in cartesian space
446 scenery.set_center( scenery.get_next_center() );
449 fgReshape( fgGetInt("/sim/startup/xsize"),
450 fgGetInt("/sim/startup/ysize") );
452 // set the sun position
453 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
455 clear_mask = GL_DEPTH_BUFFER_BIT;
456 if ( fgGetBool("/sim/rendering/wireframe") ) {
457 clear_mask |= GL_COLOR_BUFFER_BIT;
460 if ( fgGetBool("/sim/rendering/skyblend") ) {
461 if ( fgGetBool("/sim/rendering/textures") ) {
462 // glClearColor(black[0], black[1], black[2], black[3]);
463 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
464 l->adj_fog_color[2], l->adj_fog_color[3]);
465 clear_mask |= GL_COLOR_BUFFER_BIT;
468 glClearColor(l->sky_color[0], l->sky_color[1],
469 l->sky_color[2], l->sky_color[3]);
470 clear_mask |= GL_COLOR_BUFFER_BIT;
472 glClear( clear_mask );
474 // Tell GL we are switching to model view parameters
476 // I really should create a derived ssg node or use a call
477 // back or something so that I can draw the sky within the
478 // ssgCullAndDraw() function, but for now I just mimic what
479 // ssg does to set up the model view matrix
480 glMatrixMode(GL_MODELVIEW);
482 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
484 // set the opengl state to known default values
485 default_state->force();
487 // update fog params if visibility has changed
488 thesky->set_visibility(fgGetDouble("/environment/visibility-m"));
490 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
491 ( global_multi_loop * fgGetInt("/sim/speed-up") )
492 / (double)fgGetInt("/sim/model-hz") );
494 // Set correct opengl fog density
495 glFogf (GL_FOG_DENSITY, fog_exp2_density);
497 // update the sky dome
498 if ( fgGetBool("/sim/rendering/skyblend") ) {
499 /* cout << "thesky->repaint() sky_color = "
500 << cur_light_params.sky_color[0] << " "
501 << cur_light_params.sky_color[1] << " "
502 << cur_light_params.sky_color[2] << " "
503 << cur_light_params.sky_color[3] << endl;
505 << cur_light_params.fog_color[0] << " "
506 << cur_light_params.fog_color[1] << " "
507 << cur_light_params.fog_color[2] << " "
508 << cur_light_params.fog_color[3] << endl;
509 cout << " sun_angle = " << cur_light_params.sun_angle
510 << " moon_angle = " << cur_light_params.moon_angle
512 thesky->repaint( cur_light_params.sky_color,
513 cur_light_params.adj_fog_color,
514 cur_light_params.sun_angle,
515 cur_light_params.moon_angle,
516 globals->get_ephem()->getNumPlanets(),
517 globals->get_ephem()->getPlanets(),
518 globals->get_ephem()->getNumStars(),
519 globals->get_ephem()->getStars() );
521 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
522 << view_pos[1] << " " << view_pos[2] << endl;
523 cout << " zero_elev = " << zero_elev[0] << " "
524 << zero_elev[1] << " " << zero_elev[2]
525 << " lon = " << cur_fdm_state->get_Longitude()
526 << " lat = " << cur_fdm_state->get_Latitude() << endl;
527 cout << " sun_rot = " << cur_light_params.sun_rotation
528 << " gst = " << SGTime::cur_time_params->getGst() << endl;
529 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
530 << " sun dec = " << globals->get_ephem()->getSunDeclination()
531 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
532 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
534 thesky->reposition( globals->get_current_view()->get_view_pos(),
535 globals->get_current_view()->get_zero_elev(),
536 globals->get_current_view()->get_world_up(),
537 longitude->getDoubleValue()
538 * SGD_DEGREES_TO_RADIANS,
539 latitude->getDoubleValue()
540 * SGD_DEGREES_TO_RADIANS,
541 altitude->getDoubleValue() * SG_FEET_TO_METER,
542 cur_light_params.sun_rotation,
543 globals->get_time_params()->getGst(),
544 globals->get_ephem()->getSunRightAscension(),
545 globals->get_ephem()->getSunDeclination(),
547 globals->get_ephem()->getMoonRightAscension(),
548 globals->get_ephem()->getMoonDeclination(),
552 glEnable( GL_DEPTH_TEST );
553 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
555 glFogi( GL_FOG_MODE, GL_EXP2 );
556 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
559 // set sun/lighting parameters
560 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
562 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
563 // we only update GL_AMBIENT for our lights we will never get
564 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
565 // explicitely to black.
566 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
567 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
568 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
570 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
571 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
572 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
574 // texture parameters
575 // glEnable( GL_TEXTURE_2D );
576 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
577 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
579 // glMatrixMode( GL_PROJECTION );
581 ssgSetFOV( globals->get_current_view()->get_h_fov(),
582 globals->get_current_view()->get_v_fov() );
584 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
585 - scenery.get_cur_elev();
587 if (fgGetBool("/cockpit"))
588 ssgSetNearFar( 0.2f, 120000.0f );
589 else if ( agl > 10.0)
590 ssgSetNearFar( 10.0f, 120000.0f );
592 ssgSetNearFar( 0.5f, 120000.0f );
594 current_model.update(0); // FIXME: use real delta time
596 // $$$ begin - added VS Renganthan 17 Oct 2K
598 // $$$ end - added VS Renganthan 17 Oct 2K
600 # ifdef FG_NETWORK_OLK
601 if ( fgGetBool("/sim/networking/network-olk") ) {
603 other = head->next; /* put listpointer to start */
604 while ( other != tail) { /* display all except myself */
605 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
606 other->fgd_sel->select(1);
607 sgSetCoord( &fgdpos, other->sgFGD_COORD );
608 other->fgd_pos->setTransform( &fgdpos );
613 // fgd_sel->select(1);
614 // sgCopyMat4( sgTUX, current_view.sgVIEW);
616 // sgSetCoord( &fgdpos, sgFGD_VIEW );
617 // fgd_pos->setTransform( &fgdpos);
621 // position tile nodes and update range selectors
622 global_tile_mgr.prep_ssg_nodes();
624 if ( fgGetBool("/sim/rendering/skyblend") ) {
625 // draw the sky backdrop
627 // we need a white diffuse light for the phase of the moon
628 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
632 // return to the desired diffuse color
633 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
636 // draw the ssg scene
637 glEnable( GL_DEPTH_TEST );
638 ssgCullAndDraw( scene );
640 // change state for lighting here
643 // Set punch through fog density
644 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
646 #ifdef FG_EXPERIMENTAL_LIGHTING
647 // Enable states for drawing points with GL_extension
648 if (glutExtensionSupported("GL_EXT_point_parameters")) {
649 glEnable(GL_POINT_SMOOTH);
650 float quadratic[3] = {1.0, 0.01, 0.0001};
651 // get the address of our OpenGL extensions
653 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
654 wglGetProcAddress("glPointParameterfEXT");
655 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
656 wglGetProcAddress("glPointParameterfvEXT");
658 // makes the points fade as they move away
659 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
660 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
663 // Enable states for drawing runway lights with spherical mapping
664 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
665 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
666 glEnable(GL_TEXTURE_GEN_S);
667 glEnable(GL_TEXTURE_GEN_T);
669 //Maybe this is not the best way, but it works !!
670 glPolygonMode(GL_FRONT, GL_POINT);
672 glEnable(GL_CULL_FACE);
675 glDisable( GL_LIGHTING );
676 // blending function for runway lights
677 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
681 ssgCullAndDraw( lighting );
683 #ifdef FG_EXPERIMENTAL_LIGHTING
684 if (glutExtensionSupported("GL_EXT_point_parameters")) {
685 // Disable states used for runway lighting
686 glPolygonMode(GL_FRONT, GL_FILL);
688 glDisable(GL_TEXTURE_GEN_S);
689 glDisable(GL_TEXTURE_GEN_T);
690 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
691 default_attenuation);
697 if ( fgGetBool("/sim/rendering/skyblend") ) {
698 // draw the sky cloud layers
699 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
702 // display HUD && Panel
704 glDisable( GL_DEPTH_TEST );
705 // glDisable( GL_CULL_FACE );
706 // glDisable( GL_TEXTURE_2D );
708 // update the input subsystem
709 current_input.update(1); // FIXME: use real dt
711 // update the controls subsystem
712 globals->get_controls()->update(1); // FIXME: use real dt
714 hud_and_panel->apply();
717 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
718 // This only works properly if called before the panel call
719 globals->get_ATC_display()->update(1); // FIXME: use real dt
721 // update the panel subsystem
722 if ( current_panel != NULL ) {
723 current_panel->update(1); // FIXME: use real dt
726 // We can do translucent menus, so why not. :-)
728 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
730 // glDisable ( GL_BLEND ) ;
732 // glEnable( GL_FOG );
734 globals->get_logger()->update(0); // FIXME: use real dt
741 // Update internal time dependent calculations (i.e. flight model)
742 void fgUpdateTimeDepCalcs() {
743 static bool inited = false;
744 static const SGPropertyNode *master_freeze
745 = fgGetNode("/sim/freeze/master");
747 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
749 fgLIGHT *l = &cur_light_params;
754 // Initialize the FDM here if it hasn't been and if we have a
755 // scenery elevation hit.
757 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
758 // << " cur_elev = " << scenery.get_cur_elev() << endl;
760 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
761 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
763 cur_fdm_state->init();
764 if ( cur_fdm_state->get_bound() ) {
765 cur_fdm_state->unbind();
767 cur_fdm_state->bind();
770 // conceptually, the following block could be done for each fdm
772 if ( !cur_fdm_state->get_inited() ) {
773 // do nothing, fdm isn't inited yet
774 } else if ( master_freeze->getBoolValue() ) {
775 // we are frozen, run the fdm's with 0 time slices in case
776 // they want to do something with that.
778 cur_fdm_state->update( 0 );
779 FGSteam::update( 0 );
781 // we have been inited, and we are not frozen, we are good to go ...
784 cur_fdm_state->stamp();
790 long elapsed = current - cur_fdm_state->get_time_stamp();
791 cur_fdm_state->set_time_stamp( current );
792 elapsed += cur_fdm_state->get_remainder();
793 // cout << "elapsed = " << elapsed << endl;
794 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
795 multi_loop = (long)(((double)elapsed * 0.000001) /
796 cur_fdm_state->get_delta_t() );
797 cur_fdm_state->set_multi_loop( multi_loop );
798 long remainder = elapsed - (long)( (multi_loop*1000000) *
799 cur_fdm_state->get_delta_t() );
800 cur_fdm_state->set_remainder( remainder );
801 // cout << "remainder = " << remainder << endl;
803 // chop max interations to something reasonable if the sim was
804 // delayed for an excesive amount of time
805 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
806 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
807 cur_fdm_state->set_remainder( 0 );
810 // cout << "multi_loop = " << multi_loop << endl;
811 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
812 // run Autopilot system
813 globals->get_autopilot()->update(0); // FIXME: use real dt
816 cur_fdm_state->update( 1 );
818 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
821 if ( fgGetString("/sim/view-mode") == "pilot" ) {
822 cur_view_fdm = *cur_fdm_state;
826 // update the view angle
827 globals->get_viewmgr()->update(multi_loop);
831 // Update solar system
832 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
833 globals->get_time_params()->getLst(),
834 cur_fdm_state->get_Latitude() );
836 // Update radio stack model
837 current_radiostack->update(multi_loop);
841 void fgInitTimeDepCalcs( void ) {
844 // #ifdef HAVE_SETITIMER
845 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
846 // fgUpdateTimeDepCalcs );
847 // #endif HAVE_SETITIMER
851 static const double alt_adjust_ft = 3.758099;
852 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
855 // What should we do when we have nothing else to do? Let's get ready
856 // for the next move and update the display?
857 static void fgMainLoop( void ) {
858 static const SGPropertyNode *longitude
859 = fgGetNode("/position/longitude-deg");
860 static const SGPropertyNode *latitude
861 = fgGetNode("/position/latitude-deg");
862 static const SGPropertyNode *altitude
863 = fgGetNode("/position/altitude-ft");
864 static const SGPropertyNode *clock_freeze
865 = fgGetNode("/sim/freeze/clock", true);
866 static const SGPropertyNode *cur_time_override
867 = fgGetNode("/sim/time/cur-time-override", true);
869 static long remainder = 0;
871 #ifdef FANCY_FRAME_COUNTER
875 static time_t last_time = 0;
876 static int frames = 0;
877 #endif // FANCY_FRAME_COUNTER
879 SGTime *t = globals->get_time_params();
881 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
882 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
884 #ifdef FG_NETWORK_OLK
885 if ( fgGetBool("/sim/networking/network-olk") ) {
886 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
887 // printf("FGD: Netupdate\n");
888 fgd_send_com( "A", FGFS_host); // Send Mat4 data
889 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
894 #if defined( ENABLE_PLIB_JOYSTICK )
895 // Read joystick and update control settings
896 // if ( fgGetString("/sim/control-mode") == "joystick" )
900 #elif defined( ENABLE_GLUT_JOYSTICK )
901 // Glut joystick support works by feeding a joystick handler
902 // function to glut. This is taken care of once in the joystick
903 // init routine and we don't have to worry about it again.
906 #ifdef FG_NEW_ENVIRONMENT
907 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
910 // Fix elevation. I'm just sticking this here for now, it should
911 // probably move eventually
913 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
914 scenery.get_cur_elev(),
915 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
916 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
918 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
919 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
920 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
921 // now set aircraft altitude above ground
922 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
923 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
924 scenery.get_cur_elev() + alt_adjust_m - 3.0,
925 scenery.get_cur_elev() + alt_adjust_m );
926 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
929 SG_LOG( SG_ALL, SG_DEBUG,
930 "<*> resetting altitude to "
931 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
936 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
937 scenery.get_cur_elev(),
938 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
939 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
941 // cout << "Warp = " << globals->get_warp() << endl;
944 static bool last_clock_freeze = false;
946 if ( clock_freeze->getBoolValue() ) {
947 // clock freeze requested
948 if ( cur_time_override->getLongValue() == 0 ) {
949 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
950 globals->set_warp( 0 );
953 // no clock freeze requested
954 if ( last_clock_freeze == true ) {
955 // clock just unfroze, let's set warp as the difference
956 // between frozen time and current time so we don't get a
957 // time jump (and corresponding sky object and lighting
959 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
960 fgSetLong( "/sim/time/cur-time-override", 0 );
962 if ( globals->get_warp_delta() != 0 ) {
963 globals->inc_warp( globals->get_warp_delta() );
967 last_clock_freeze = clock_freeze->getBoolValue();
969 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
970 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
971 cur_time_override->getLongValue(),
972 globals->get_warp() );
974 if ( globals->get_warp_delta() != 0 ) {
975 fgUpdateSkyAndLightingParams();
978 // update magvar model
979 globals->get_mag()->update( longitude->getDoubleValue()
980 * SGD_DEGREES_TO_RADIANS,
981 latitude->getDoubleValue()
982 * SGD_DEGREES_TO_RADIANS,
983 altitude->getDoubleValue() * SG_FEET_TO_METER,
984 globals->get_time_params()->getJD() );
986 // Get elapsed time (in usec) for this past frame
987 elapsed = fgGetTimeInterval();
988 SG_LOG( SG_ALL, SG_DEBUG,
989 "Elapsed time interval is = " << elapsed
990 << ", previous remainder is = " << remainder );
992 // Calculate frame rate average
993 #ifdef FANCY_FRAME_COUNTER
994 /* old fps calculation */
998 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
999 tmp = general.get_frame(i);
1001 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1002 general.set_frame(i+1,tmp);
1004 tmp = 1000000.0 / (float)elapsed;
1005 general.set_frame(0,tmp);
1006 // printf("frame[0] = %.2f\n", general.frames[0]);
1008 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1009 // printf("ave = %.2f\n", general.frame_rate);
1012 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1013 general.set_frame_rate( frames );
1014 SG_LOG( SG_ALL, SG_DEBUG,
1015 "--> Frame rate is = " << general.get_frame_rate() );
1018 last_time = t->get_cur_time();
1022 // Run ATC subsystem
1023 globals->get_ATC_mgr()->update(1); // FIXME: use real dt
1027 // Calculate model iterations needed for next frame
1028 elapsed += remainder;
1030 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1031 fgGetInt("/sim/model-hz"));
1032 remainder = elapsed - ( (global_multi_loop*1000000) /
1033 fgGetInt("/sim/model-hz") );
1034 SG_LOG( SG_ALL, SG_DEBUG,
1035 "Model iterations needed = " << global_multi_loop
1036 << ", new remainder = " << remainder );
1038 // chop max interations to something reasonable if the sim was
1039 // delayed for an excesive amount of time
1040 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1041 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1046 if ( global_multi_loop > 0 ) {
1047 fgUpdateTimeDepCalcs();
1049 SG_LOG( SG_ALL, SG_DEBUG,
1050 "Elapsed time is zero ... we're zinging" );
1053 #if ! defined( macintosh )
1054 // Do any I/O channel work that might need to be done
1058 // see if we need to load any new scenery tiles
1059 global_tile_mgr.update( longitude->getDoubleValue(),
1060 latitude->getDoubleValue() );
1062 // see if we need to load any deferred-load textures
1063 material_lib.load_next_deferred();
1065 // Process/manage pending events
1066 global_events.Process();
1068 // Run audio scheduler
1069 #ifdef ENABLE_AUDIO_SUPPORT
1070 if ( fgGetBool("/sim/sound/audible")
1071 && globals->get_soundmgr()->is_working() ) {
1072 globals->get_fx()->update(1); // FIXME: use dt
1073 globals->get_soundmgr()->update(1); // FIXME: use dt
1080 SG_LOG( SG_ALL, SG_DEBUG, "" );
1084 // This is the top level master main function that is registered as
1085 // our idle funciton
1088 // The first few passes take care of initialization things (a couple
1089 // per pass) and once everything has been initialized fgMainLoop from
1092 static void fgIdleFunction ( void ) {
1093 // printf("idle state == %d\n", idle_state);
1095 if ( idle_state == 0 ) {
1096 // Initialize the splash screen right away
1097 if ( fgGetBool("/sim/startup/splash-screen") ) {
1102 } else if ( idle_state == 1 ) {
1103 // Initialize audio support
1104 #ifdef ENABLE_AUDIO_SUPPORT
1106 // Start the intro music
1107 if ( fgGetBool("/sim/startup/intro-music") ) {
1108 SGPath mp3file( globals->get_fg_root() );
1109 mp3file.append( "Sounds/intro.mp3" );
1111 SG_LOG( SG_GENERAL, SG_INFO,
1112 "Starting intro music: " << mp3file.str() );
1114 #if defined( __CYGWIN__ )
1115 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1116 #elif defined( WIN32 )
1117 string command = "start /m " + mp3file.str();
1119 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1122 system ( command.c_str() );
1128 } else if ( idle_state == 2 ) {
1129 // These are a few miscellaneous things that aren't really
1130 // "subsystems" but still need to be initialized.
1133 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1134 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1139 } else if ( idle_state == 3 ) {
1140 // This is the top level init routine which calls all the
1141 // other subsystem initialization routines. If you are adding
1142 // a subsystem to flightgear, its initialization call should
1143 // located in this routine.
1144 if( !fgInitSubsystems()) {
1145 SG_LOG( SG_GENERAL, SG_ALERT,
1146 "Subsystem initializations failed ..." );
1151 } else if ( idle_state == 4 ) {
1152 // setup OpenGL view parameters
1156 } else if ( idle_state == 5 ) {
1159 } else if ( idle_state == 6 ) {
1163 cout << "Panel visible = " << fgPanelVisible() << endl;
1164 fgReshape( fgGetInt("/sim/startup/xsize"),
1165 fgGetInt("/sim/startup/ysize") );
1168 if ( idle_state == 1000 ) {
1169 // We've finished all our initialization steps, from now on we
1170 // run the main loop.
1174 if ( fgGetBool("/sim/startup/splash-screen") ) {
1175 fgSplashUpdate(0.0);
1180 // options.cxx needs to see this for toggle_panel()
1181 // Handle new window size or exposure
1182 void fgReshape( int width, int height ) {
1185 if ( (!fgGetBool("/sim/virtual-cockpit"))
1186 && fgPanelVisible() && idle_state == 1000 ) {
1187 view_h = (int)(height * (current_panel->getViewHeight() -
1188 current_panel->getYOffset()) / 768.0);
1194 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1195 globals->get_viewmgr()->get_view(i)->
1196 set_aspect_ratio((float)view_h / (float)width);
1199 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1201 fgSetInt("/sim/startup/xsize", width);
1202 fgSetInt("/sim/startup/ysize", height);
1203 guiInitMouse(width, height);
1205 ssgSetFOV( globals->get_current_view()->get_h_fov(),
1206 globals->get_current_view()->get_v_fov() );
1212 // Initialize GLUT and define a main window
1213 int fgGlutInit( int *argc, char **argv ) {
1215 #if !defined( macintosh )
1216 // GLUT will extract all glut specific options so later on we only
1217 // need wory about our own.
1218 glutInit(argc, argv);
1221 // Define Display Parameters
1222 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1224 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1225 fgGetInt("/sim/startup/xsize") << "x"
1226 << fgGetInt("/sim/startup/ysize") );
1228 // Define initial window size
1229 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1230 fgGetInt("/sim/startup/ysize") );
1232 // Initialize windows
1233 if ( !fgGetBool("/sim/startup/game-mode")) {
1234 // Open the regular window
1235 glutCreateWindow("FlightGear");
1236 #ifndef GLUT_WRONG_VERSION
1238 // Open the cool new 'game mode' window
1239 char game_mode_str[256];
1240 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1241 fgGetInt("/sim/startup/xsize"),
1242 fgGetInt("/sim/startup/ysize"),
1243 fgGetInt("/sim/rendering/bits-per-pixel"));
1245 SG_LOG( SG_GENERAL, SG_INFO,
1246 "game mode params = " << game_mode_str );
1247 glutGameModeString( game_mode_str );
1248 glutEnterGameMode();
1252 // This seems to be the absolute earliest in the init sequence
1253 // that these calls will return valid info. Too bad it's after
1254 // we've already created and sized out window. :-(
1255 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1256 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1257 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1258 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1261 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1262 general.set_glMaxTexSize( tmp );
1263 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1265 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1266 general.set_glDepthBits( tmp );
1267 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1273 // Initialize GLUT event handlers
1274 int fgGlutInitEvents( void ) {
1275 // call fgReshape() on window resizes
1276 glutReshapeFunc( fgReshape );
1278 // call GLUTkey() on keyboard event
1279 glutKeyboardFunc(GLUTkey);
1280 glutKeyboardUpFunc(GLUTkeyup);
1281 glutSpecialFunc(GLUTspecialkey);
1282 glutSpecialUpFunc(GLUTspecialkeyup);
1284 // call guiMouseFunc() whenever our little rodent is used
1285 glutMouseFunc ( guiMouseFunc );
1286 glutMotionFunc (guiMotionFunc );
1287 glutPassiveMotionFunc (guiMotionFunc );
1289 // call fgMainLoop() whenever there is
1290 // nothing else to do
1291 glutIdleFunc( fgIdleFunction );
1294 glutDisplayFunc( fgRenderFrame );
1301 int mainLoop( int argc, char **argv ) {
1303 #if defined( macintosh )
1304 freopen ("stdout.txt", "w", stdout );
1305 freopen ("stderr.txt", "w", stderr );
1306 argc = ccommand( &argv );
1309 // set default log levels
1310 sglog().setLogLevels( SG_ALL, SG_INFO );
1313 #ifdef FLIGHTGEAR_VERSION
1314 version = FLIGHTGEAR_VERSION;
1316 version = "unknown version";
1318 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1319 << version << endl );
1321 // Allocate global data structures. This needs to happen before
1322 // we parse command line options
1324 globals = new FGGlobals;
1326 #if defined(FG_NEW_ENVIRONMENT)
1327 globals->set_environment_mgr(new FGEnvironmentMgr);
1330 // seed the random number generater
1333 SGRoute *route = new SGRoute;
1334 globals->set_route( route );
1336 FGControls *controls = new FGControls;
1337 globals->set_controls( controls );
1339 FGViewMgr *viewmgr = new FGViewMgr;
1340 globals->set_viewmgr( viewmgr );
1344 string_list *col = new string_list;
1345 globals->set_channel_options_list( col );
1347 // Scan the config file(s) and command line options to see if
1348 // fg_root was specified (ignore all other options for now)
1349 fgInitFGRoot(argc, argv);
1351 // Check for the correct base package version
1352 string base_version = fgBasePackageVersion();
1353 if ( !(base_version == "0.7.9") ) {
1354 // tell the operator how to use this application
1357 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1358 << "Found version " << base_version );
1359 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1363 // Initialize the Aircraft directory to "" (UIUC)
1366 // Load the configuration parameters
1367 if ( !fgInitConfig(argc, argv) ) {
1368 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1372 // Initialize the Window/Graphics environment.
1373 if( !fgGlutInit(&argc, argv) ) {
1374 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1378 // Initialize the various GLUT Event Handlers.
1379 if( !fgGlutInitEvents() ) {
1380 SG_LOG( SG_GENERAL, SG_ALERT,
1381 "GLUT event handler initialization failed ..." );
1385 // Initialize plib net interface
1386 netInit( &argc, argv );
1388 // Initialize ssg (from plib). Needs to come before we do any
1389 // other ssg stuff, but after opengl/glut has been initialized.
1392 // Initialize the user interface (we need to do this before
1393 // passing off control to glut and before fgInitGeneral to get our
1397 #ifdef GL_EXT_texture_lod_bias
1398 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1401 // Set position relative to glide slope if requested
1402 fgSetPosFromGlideSlope();
1404 // set current_options lon/lat if an airport id is specified
1405 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1406 if ( fgGetString("/sim/startup/airport-id").length() ) {
1407 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1408 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1409 fgGetDouble("/orientation/heading-deg") );
1412 SGTime *t = fgInitTime();
1413 globals->set_time_params( t );
1415 // Do some quick general initializations
1416 if( !fgInitGeneral()) {
1417 SG_LOG( SG_GENERAL, SG_ALERT,
1418 "General initializations failed ..." );
1422 SGPath modelpath( globals->get_fg_root() );
1423 ssgModelPath( (char *)modelpath.c_str() );
1426 scene = new ssgRoot;
1427 scene->setName( "Scene" );
1429 lighting = new ssgRoot;
1430 lighting->setName( "Lighting" );
1432 // Initialize the sky
1433 SGPath ephem_data_path( globals->get_fg_root() );
1434 ephem_data_path.append( "Astro" );
1435 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1436 ephem->update( globals->get_time_params()->getMjd(),
1437 globals->get_time_params()->getLst(),
1439 globals->set_ephem( ephem );
1443 SGPath sky_tex_path( globals->get_fg_root() );
1444 sky_tex_path.append( "Textures" );
1445 sky_tex_path.append( "Sky" );
1446 thesky->texture_path( sky_tex_path.str() );
1448 thesky->build( 550.0, 550.0,
1449 globals->get_ephem()->getNumPlanets(),
1450 globals->get_ephem()->getPlanets(), 60000.0,
1451 globals->get_ephem()->getNumStars(),
1452 globals->get_ephem()->getStars(), 60000.0 );
1454 if ( fgGetBool("/environment/clouds/status") ) {
1455 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1456 // SG_CLOUD_OVERCAST );
1457 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1459 200.0, 50.0, 40000.0,
1460 SG_CLOUD_MOSTLY_CLOUDY );
1461 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1462 // SG_CLOUD_MOSTLY_SUNNY );
1463 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1467 // Initialize MagVar model
1468 SGMagVar *magvar = new SGMagVar();
1469 globals->set_mag( magvar );
1472 terrain_branch = new ssgBranch;
1473 terrain_branch->setName( "Terrain" );
1474 scene->addKid( terrain_branch );
1477 gnd_lights_branch = new ssgBranch;
1478 gnd_lights_branch->setName( "Ground Lighting" );
1479 lighting->addKid( gnd_lights_branch );
1481 rwy_lights_branch = new ssgBranch;
1482 rwy_lights_branch->setName( "Runway Lighting" );
1483 lighting->addKid( rwy_lights_branch );
1485 // airport = new ssgBranch;
1486 // airport->setName( "Airport Lighting" );
1487 // lighting->addKid( airport );
1493 // temporary visible aircraft "own ship"
1494 current_model.init();
1496 #ifdef FG_NETWORK_OLK
1497 // Do the network intialization
1498 if ( fgGetBool("/sim/networking/network-olk") ) {
1499 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1503 // build our custom render states
1504 fgBuildRenderStates();
1506 // pass control off to the master GLUT event handler
1509 // we never actually get here ... but to avoid compiler warnings,
1515 // $$$ end - added VS Renganathan, 15 Oct 2K
1516 // - added Venky , 12 Nov 2K
1518 #if defined(__linux__) && defined(__i386__)
1520 static void handleFPE (int);
1525 fpu_control_t fpe_flags = 0;
1526 _FPU_GETCW(fpe_flags);
1527 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1528 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1529 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1530 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1531 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1532 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1533 _FPU_SETCW(fpe_flags);
1534 signal(SIGFPE, handleFPE);
1541 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1545 // Main entry point; catch any exceptions that have made it this far.
1546 int main ( int argc, char **argv ) {
1548 // Enable floating-point exceptions for Linux/x86
1549 #if defined(__linux__) && defined(__i386__)
1553 // Enable floating-point exceptions for Windows
1554 #if defined( _MSC_VER ) && defined( DEBUG )
1555 // Christian, we should document what this does
1556 _control87( _EM_INEXACT, _MCW_EM );
1559 #if defined( HAVE_BC5PLUS )
1560 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1563 // FIXME: add other, more specific
1566 mainLoop(argc, argv);
1567 } catch (sg_throwable &t) {
1568 SG_LOG(SG_GENERAL, SG_ALERT,
1569 "Fatal error: " << t.getFormattedMessage()
1570 << "\n (received from " << t.getOrigin() << ')');
1578 void fgLoadDCS(void) {
1580 ssgEntity *ship_obj = NULL;
1582 char obj_filename[25];
1584 for ( int k = 0; k < 32; k++ ) {
1588 SGPath tile_path( globals->get_fg_root());
1589 tile_path.append( "Scenery" );
1590 tile_path.append( "Objects.txt" );
1591 sg_gzifstream in( tile_path.str() );
1592 if ( ! in.is_open() ) {
1593 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1596 SGPath modelpath( globals->get_fg_root() );
1597 modelpath.append( "Models" );
1598 modelpath.append( "Geometry" );
1600 SGPath texturepath( globals->get_fg_root() );
1601 texturepath.append( "Models" );
1602 texturepath.append( "Textures" );
1604 ssgModelPath( (char *)modelpath.c_str() );
1605 ssgTexturePath( (char *)texturepath.c_str() );
1607 ship_sel = new ssgSelector;
1610 while ( ! in.eof() ) {
1612 if ( in.get( c ) && c == '#' ) {
1616 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1617 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1618 int chj=getchar();*/
1620 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1621 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1623 ship_pos[objc] = new ssgTransform;
1625 // type "repeat" in objects.txt to load one more
1626 // instance of the last object.
1628 if ( strcmp(obj_filename,"repeat") != 0) {
1629 ship_obj = ssgLoad( obj_filename );
1632 if ( ship_obj != NULL ) {
1633 ship_obj->setName(obj_filename);
1635 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1637 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1638 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1639 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1640 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1643 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1647 // temporary hack for deck lights - ultimately should move to PLib (when??)
1648 //const char *extn = file_extension ( obj_filename ) ;
1650 ssgVertexArray *lights = new ssgVertexArray( 100 );
1651 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1652 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1653 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1654 int ltype[500], light_type;
1655 static int ltcount = 0;
1657 sgVec3 rway_dir,rway_normal,lightpt;
1659 modelpath.append(obj_filename);
1660 sg_gzifstream in1( modelpath.str() );
1661 if ( ! in1.is_open() ) {
1662 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1664 while ( ! in1.eof() ) {
1666 if ( in1.get( c ) && c == '#' ) {
1671 //cout << token << endl;
1672 if ( token == "runway" ) {
1674 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1675 } else if ( token == "edgelight" ) {
1677 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1679 } else if ( token == "taxi" ) {
1681 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1683 } else if ( token == "vasi" ) {
1685 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1687 } else if ( token == "threshold" ) {
1689 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1691 } else if ( token == "rabbit" ) {
1693 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1695 } else if ( token == "ols" ) {
1697 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1699 } else if ( token == "red" ) {
1701 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1703 } else if ( token == "green" ) {
1705 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1707 } else if ( token == "lp" ) {
1709 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1710 lightpoints->add( lightpt );
1711 lightnormals->add( rway_normal );
1712 lightdir->add( rway_dir );
1713 ltype[ltcount]= light_type;
1716 if (in1.eof()) break;
1720 if ( lightpoints->getNum() ) {
1721 ssgBranch *lightpoints_branch;
1722 long int dummy = -999;
1723 dummy_tile = new FGTileEntry((SGBucket)dummy);
1724 dummy_tile->lightmaps_sequence = new ssgSelector;
1725 dummy_tile->ols_transform = new ssgTransform;
1727 // call function to generate the runway lights
1728 lightpoints_branch =
1729 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1731 lightpoints_brightness->addKid(lightpoints_branch);
1732 lightpoints_transform->addKid(lightpoints_brightness);
1733 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1734 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1735 lightpoints_transform->ref();
1736 gnd_lights_branch->addKid( lightpoints_transform );
1740 // end hack for deck lights
1744 if (in.eof()) break;
1748 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1750 terrain_branch->addKid( ship_sel ); //add selector node to root node
1757 void fgUpdateDCS (void) {
1759 // double eye_lat,eye_lon,eye_alt;
1760 // static double obj_head;
1761 double sl_radius,obj_latgc;
1762 // float nresultmat[4][4];
1763 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1766 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1767 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1769 // Deck should be the first object in objects.txt in case of fdm=ada
1771 if (fgGetString("/sim/flight-model") == "ada") {
1772 if ((fdm->get_iaux(1))==1)
1774 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1775 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1776 obj_alt[1] = fdm->get_daux(3);
1777 obj_pitch[1] = fdm->get_faux(1);
1778 obj_roll[1] = fdm->get_faux(2);
1782 for ( int m = 0; m < objc; m++ ) {
1783 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1786 //Geodetic to Geocentric angles for rotation
1787 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1789 //moving object gbs-posn in cartesian coords
1790 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1791 Point3D obj_pos = sgGeodToCart( obj_posn );
1793 // Translate moving object w.r.t eye
1794 Point3D Objtrans = obj_pos-scenery.get_center();
1799 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1802 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1804 sgVec3 ship_fwd,ship_rt,ship_up;
1805 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1806 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1807 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1809 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1810 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1811 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1812 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1813 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1814 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1817 sgCopyMat4( sgTUX, sgROT_hdg );
1818 sgPostMultMat4( sgTUX, sgROT_pitch );
1819 sgPostMultMat4( sgTUX, sgROT_roll );
1820 sgPostMultMat4( sgTUX, sgROT_lat );
1821 sgPostMultMat4( sgTUX, sgROT_lon );
1822 sgPostMultMat4( sgTUX, sgTRANS );
1825 sgSetCoord(&shippos, sgTUX );
1826 ship_pos[m]->setTransform( &shippos );
1827 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1829 if (lightpoints_transform) {
1830 lightpoints_transform->setTransform( &shippos );
1831 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1832 if ( sun_angle > 89 ) {
1833 lightpoints_brightness->select(0x01);
1835 lightpoints_brightness->select(0x00);
1844 sgXformPnt3( rp, rway_ols, sgTUX );
1845 vp = globals->get_current_view()->get_view_pos();
1846 to[0] = rp[0]-vp[0];
1847 to[1] = rp[1]-vp[1];
1848 to[2] = rp[2]-vp[2];
1849 float dist = sgLengthVec3( to );
1850 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1852 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1854 ref_elev = elev - 3.75; // +ve above, -ve below
1858 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1859 // if (ref_elev > 0.51) sel = 0x21;
1860 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1861 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1862 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1863 // if (ref_elev < -0.51) sel = 0x30;
1864 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1865 dummy_tile->lightmaps_sequence->select(sel);
1868 sgCopyVec3 (up, ship_up);
1870 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1872 sgScaleVec3 (up, 4.0*ref_elev);
1873 dummy_tile->ols_transform->setTransform(up);
1874 //cout << "ref_elev " << ref_elev << endl;
1876 // end hack for deck lights
1879 if ( ship_sel != NULL ) {
1880 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1884 // $$$ end - added VS Renganathan, 15 Oct 2K
1885 // added Venky , 12 Nov 2K