1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include <simgear/compiler.h>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
35 #ifdef SG_MATH_EXCEPTION_CLASH
44 #include <plib/netSocket.h>
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/math/sg_random.h>
51 #include <simgear/ephemeris/ephemeris.hxx>
52 #include <simgear/scene/model/modellib.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/animation.hxx>
55 #include <simgear/scene/sky/sky.hxx>
56 #include <Time/light.hxx>
57 #include <Include/general.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Cockpit/hud.hxx>
60 #include <Model/panelnode.hxx>
61 #include <Model/modelmgr.hxx>
62 #include <Model/acmodel.hxx>
63 #include <Scenery/scenery.hxx>
64 #include <Scenery/tilemgr.hxx>
65 #include <Sound/beacon.hxx>
66 #include <Sound/morse.hxx>
67 #include <FDM/flight.hxx>
68 // #include <FDM/ADA.hxx>
69 #include <ATC/ATCdisplay.hxx>
70 #include <ATC/ATCmgr.hxx>
71 #include <ATC/AIMgr.hxx>
72 #include <Replay/replay.hxx>
73 #include <Time/tmp.hxx>
74 #include <Time/fg_timer.hxx>
75 #include <Environment/environment_mgr.hxx>
76 #include <GUI/new_gui.hxx>
79 #include <MultiPlayer/multiplaymgr.hpp>
84 #include "fg_commands.hxx"
86 #include "renderer.hxx"
92 static double real_delta_time_sec = 0.0;
93 double delta_time_sec = 0.0;
94 extern float init_volume;
98 # include <console.h> // -dw- for command line dialog
101 // This is a record containing a bit of global housekeeping information
104 // Specify our current idle function state. This is used to run all
105 // our initializations out of the idle callback so that we can get a
106 // splash screen up and running right away.
108 long global_multi_loop;
110 SGTimeStamp last_time_stamp;
111 SGTimeStamp current_time_stamp;
113 // The atexit() functio handler should know when the graphical subsystem
115 extern int _bootstrap_OSInit;
119 // Update internal time dependent calculations (i.e. flight model)
120 // FIXME: this distinction is obsolete; all subsystems now get delta
122 void fgUpdateTimeDepCalcs() {
123 static bool inited = false;
125 static const SGPropertyNode *replay_state
126 = fgGetNode( "/sim/freeze/replay-state", true );
127 static SGPropertyNode *replay_time
128 = fgGetNode( "/sim/replay/time", true );
129 // static const SGPropertyNode *replay_end_time
130 // = fgGetNode( "/sim/replay/end-time", true );
132 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
134 // Initialize the FDM here if it hasn't been and if we have a
135 // scenery elevation hit.
137 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
138 // << " cur_elev = " << scenery.get_cur_elev() << endl;
140 if (!cur_fdm_state->get_inited()) {
141 // Check for scenery around the aircraft.
142 double lon = fgGetDouble("/sim/presets/longitude-deg");
143 double lat = fgGetDouble("/sim/presets/latitude-deg");
144 // We require just to have 50 meter scenery availabe around
147 if (globals->get_tile_mgr()->scenery_available(lat, lon, range)) {
148 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
149 cur_fdm_state->init();
150 if ( cur_fdm_state->get_bound() ) {
151 cur_fdm_state->unbind();
153 cur_fdm_state->bind();
157 // conceptually, the following block could be done for each fdm
159 if ( cur_fdm_state->get_inited() ) {
160 // we have been inited, and we are good to go ...
166 if ( replay_state->getIntValue() == 0 ) {
167 // replay off, run fdm
168 cur_fdm_state->update( delta_time_sec );
170 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
171 r->replay( replay_time->getDoubleValue() );
172 if ( replay_state->getIntValue() == 1 ) {
174 replay_time->setDoubleValue( replay_time->getDoubleValue()
176 * fgGetInt("/sim/speed-up") ) );
177 } else if ( replay_state->getIntValue() == 2 ) {
178 // paused playback (don't advance replay time)
182 // do nothing, fdm isn't inited yet
185 globals->get_model_mgr()->update(delta_time_sec);
186 globals->get_aircraft_model()->update(delta_time_sec);
188 // update the view angle
189 globals->get_viewmgr()->update(delta_time_sec);
191 // Update solar system
192 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
193 globals->get_time_params()->getLst(),
194 cur_fdm_state->get_Latitude() );
199 void fgInitTimeDepCalcs( void ) {
204 static const double alt_adjust_ft = 3.758099;
205 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
208 // What should we do when we have nothing else to do? Let's get ready
209 // for the next move and update the display?
210 static void fgMainLoop( void ) {
211 int model_hz = fgGetInt("/sim/model-hz");
213 static const SGPropertyNode *longitude
214 = fgGetNode("/position/longitude-deg");
215 static const SGPropertyNode *latitude
216 = fgGetNode("/position/latitude-deg");
217 static const SGPropertyNode *altitude
218 = fgGetNode("/position/altitude-ft");
219 static const SGPropertyNode *clock_freeze
220 = fgGetNode("/sim/freeze/clock", true);
221 static const SGPropertyNode *cur_time_override
222 = fgGetNode("/sim/time/cur-time-override", true);
224 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
226 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
228 // Update the elapsed time.
229 static bool first_time = true;
231 last_time_stamp.stamp();
235 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
236 if ( throttle_hz > 0.0 && scenery_loaded ) {
237 // optionally throttle the frame rate (to get consistant frame
238 // rates or reduce cpu usage.
240 double frame_us = 1000000.0 / throttle_hz;
242 #define FG_SLEEP_BASED_TIMING 1
243 #if defined(FG_SLEEP_BASED_TIMING)
244 // sleep based timing loop.
246 // Calling sleep, even usleep() on linux is less accurate than
247 // we like, but it does free up the cpu for other tasks during
248 // the sleep so it is desireable. Because of the way sleep()
249 // is implimented in consumer operating systems like windows
250 // and linux, you almost always sleep a little longer than the
253 // To combat the problem of sleeping to long, we calculate the
254 // desired wait time and shorten it by 2000us (2ms) to avoid
255 // [hopefully] over-sleep'ing. The 2ms value was arrived at
256 // via experimentation. We follow this up at the end with a
257 // simple busy-wait loop to get the final pause timing exactly
260 // Assuming we don't oversleep by more than 2000us, this
261 // should be a reasonable compromise between sleep based
262 // waiting, and busy waiting.
264 // sleep() will always overshoot by a bit so undersleep by
265 // 2000us in the hopes of never oversleeping.
267 if ( frame_us < 0.0 ) {
270 current_time_stamp.stamp();
272 double elapsed_us = current_time_stamp - last_time_stamp;
273 if ( elapsed_us < frame_us ) {
274 double requested_us = frame_us - elapsed_us;
275 ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
279 // busy wait timing loop.
281 // This yields the most accurate timing. If the previous
282 // ulMilliSecondSleep() call is ommitted this will peg the cpu
283 // (which is just fine if FG is the only app you care about.)
284 current_time_stamp.stamp();
285 while ( current_time_stamp - last_time_stamp < frame_us ) {
286 current_time_stamp.stamp();
289 // run as fast as the app will go
290 current_time_stamp.stamp();
294 = double(current_time_stamp - last_time_stamp) / 1000000.0;
295 // round the real time down to a multiple of 1/model-hz.
296 // this way all systems are updated the _same_ amount of dt.
298 static double rem = 0.0;
299 real_delta_time_sec += rem;
300 double hz = model_hz;
301 double nit = floor(real_delta_time_sec*hz);
302 rem = real_delta_time_sec - nit/hz;
303 real_delta_time_sec = nit/hz;
307 if (clock_freeze->getBoolValue() || !scenery_loaded) {
310 delta_time_sec = real_delta_time_sec;
312 last_time_stamp = current_time_stamp;
313 globals->inc_sim_time_sec( delta_time_sec );
314 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
316 // These are useful, especially for Nasal scripts.
317 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
318 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
320 static long remainder = 0;
322 #ifdef FANCY_FRAME_COUNTER
326 static time_t last_time = 0;
327 static int frames = 0;
328 #endif // FANCY_FRAME_COUNTER
330 SGTime *t = globals->get_time_params();
332 globals->get_event_mgr()->update(delta_time_sec);
334 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
335 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
337 #if defined( ENABLE_PLIB_JOYSTICK )
338 // Read joystick and update control settings
339 // if ( fgGetString("/sim/control-mode") == "joystick" )
345 // Fix elevation. I'm just sticking this here for now, it should
346 // probably move eventually
348 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
349 scenery.get_cur_elev(),
350 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
351 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
353 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
354 scenery.get_cur_elev(),
355 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
356 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
358 // cout << "Warp = " << globals->get_warp() << endl;
361 static bool last_clock_freeze = false;
363 if ( clock_freeze->getBoolValue() ) {
364 // clock freeze requested
365 if ( cur_time_override->getLongValue() == 0 ) {
366 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
367 globals->set_warp( 0 );
370 // no clock freeze requested
371 if ( last_clock_freeze == true ) {
372 // clock just unfroze, let's set warp as the difference
373 // between frozen time and current time so we don't get a
374 // time jump (and corresponding sky object and lighting
376 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
377 fgSetLong( "/sim/time/cur-time-override", 0 );
379 if ( globals->get_warp_delta() != 0 ) {
380 globals->inc_warp( globals->get_warp_delta() );
384 last_clock_freeze = clock_freeze->getBoolValue();
386 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
387 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
388 cur_time_override->getLongValue(),
389 globals->get_warp() );
391 if (globals->get_warp_delta() != 0) {
392 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
396 // update magvar model
397 globals->get_mag()->update( longitude->getDoubleValue()
398 * SGD_DEGREES_TO_RADIANS,
399 latitude->getDoubleValue()
400 * SGD_DEGREES_TO_RADIANS,
401 altitude->getDoubleValue() * SG_FEET_TO_METER,
402 globals->get_time_params()->getJD() );
404 // Get elapsed time (in usec) for this past frame
405 elapsed = fgGetTimeInterval();
406 SG_LOG( SG_ALL, SG_DEBUG,
407 "Elapsed time interval is = " << elapsed
408 << ", previous remainder is = " << remainder );
410 // Calculate frame rate average
411 #ifdef FANCY_FRAME_COUNTER
412 /* old fps calculation */
416 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
417 tmp = general.get_frame(i);
419 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
420 general.set_frame(i+1,tmp);
422 tmp = 1000000.0 / (float)elapsed;
423 general.set_frame(0,tmp);
424 // printf("frame[0] = %.2f\n", general.frames[0]);
426 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
427 // printf("ave = %.2f\n", general.frame_rate);
430 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
431 general.set_frame_rate( frames );
432 fgSetInt("/sim/frame-rate", frames);
433 SG_LOG( SG_ALL, SG_DEBUG,
434 "--> Frame rate is = " << general.get_frame_rate() );
437 last_time = t->get_cur_time();
442 if (fgGetBool("/sim/atc/enabled"))
443 globals->get_ATC_mgr()->update(delta_time_sec);
445 // Run the AI subsystem
446 if (fgGetBool("/sim/ai-traffic/enabled"))
447 globals->get_AI_mgr()->update(delta_time_sec);
450 // Update any multiplayer models
451 globals->get_multiplayer_mgr()->Update();
456 // Calculate model iterations needed for next frame
457 elapsed += remainder;
459 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
460 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
461 SG_LOG( SG_ALL, SG_DEBUG,
462 "Model iterations needed = " << global_multi_loop
463 << ", new remainder = " << remainder );
465 // chop max interations to something reasonable if the sim was
466 // delayed for an excesive amount of time
467 if ( global_multi_loop > 2.0 * model_hz ) {
468 global_multi_loop = (int)(2.0 * model_hz );
473 if ( global_multi_loop > 0) {
474 // first run the flight model each frame until it is intialized
475 // then continue running each frame only after initial scenery load is complete.
476 fgUpdateTimeDepCalcs();
478 SG_LOG( SG_ALL, SG_DEBUG,
479 "Elapsed time is zero ... we're zinging" );
482 // Do any I/O channel work that might need to be done
483 globals->get_io()->update( real_delta_time_sec );
485 // see if we need to load any deferred-load textures
486 globals->get_matlib()->load_next_deferred();
488 // Run audio scheduler
489 #ifdef ENABLE_AUDIO_SUPPORT
490 if ( globals->get_soundmgr()->is_working() ) {
491 globals->get_soundmgr()->update( delta_time_sec );
495 globals->get_subsystem_mgr()->update(delta_time_sec);
498 // Tile Manager updates - see if we need to load any new scenery tiles.
499 // this code ties together the fdm, viewer and scenery classes...
500 // we may want to move this to it's own class at some point
502 double visibility_meters = fgGetDouble("/environment/visibility-m");
503 FGViewer *current_view = globals->get_current_view();
505 // Let the scenery center follow the current view position with
508 // Having the scenery center near the view position will eliminate
509 // jitter of objects which are placed very near the view position
510 // and haveing it's center near that view position.
511 // So the 3d insruments of the aircraft will not jitter with this.
513 // Following the view position exactly would introduce jitter of
514 // the scenery tiles (they would be from their center up to 10000m
515 // to the view and this will introduce roundoff too). By stepping
516 // at 30m incements the roundoff error of the scenery tiles is
517 // still present, but we will make exactly the same roundoff error
518 // at each frame until the center is switched to a new
519 // position. This roundoff is still visible but you will most
520 // propably not notice.
521 double *vp = globals->get_current_view()->get_absolute_view_pos();
522 Point3D cntr(vp[0], vp[1], vp[2]);
523 if (30.0*30.0 < cntr.distance3Dsquared(globals->get_scenery()->get_center())) {
524 globals->get_scenery()->set_next_center( cntr );
527 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
529 // update tile manager for view...
530 SGLocation *view_location = globals->get_current_view()->getSGLocation();
531 globals->get_tile_mgr()->update( view_location, visibility_meters );
532 globals->get_scenery()->set_center( cntr );
534 double lon = view_location->getLongitude_deg();
535 double lat = view_location->getLatitude_deg();
536 double alt = view_location->getAltitudeASL_ft() * SG_FEET_TO_METER;
538 // check if we can reuse the groundcache for that purpose.
539 double ref_time, pt[3], r;
540 bool valid = cur_fdm_state->is_valid_m(&ref_time, pt, &r);
542 cntr.distance3Dsquared(Point3D(pt[0], pt[1], pt[2])) < r*r) {
543 // Reuse the cache ...
545 = cur_fdm_state->get_groundlevel_m(lat*SGD_DEGREES_TO_RADIANS,
546 lon*SGD_DEGREES_TO_RADIANS,
548 view_location->set_cur_elev_m( lev );
550 // Do full intersection test.
552 if (globals->get_scenery()->get_elevation_m(lat, lon, alt+2, lev))
553 view_location->set_cur_elev_m( lev );
555 view_location->set_cur_elev_m( -9999.0 );
559 #ifdef ENABLE_AUDIO_SUPPORT
560 // Right now we make a simplifying assumption that the primary
561 // aircraft is the source of all sounds and that all sounds are
562 // positioned relative to the current view position.
564 static sgVec3 last_pos_offset;
566 // get the location data for the primary FDM (now hardcoded to ac model)...
567 SGLocation *acmodel_loc = NULL;
568 acmodel_loc = (SGLocation *)globals->
569 get_aircraft_model()->get3DModel()->getSGLocation();
571 // set positional offset for sources
572 sgdVec3 dsource_pos_offset;
573 sgdSubVec3( dsource_pos_offset,
574 view_location->get_absolute_view_pos(),
575 acmodel_loc->get_absolute_view_pos() );
576 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
577 sgVec3 source_pos_offset;
578 sgSetVec3(source_pos_offset, dsource_pos_offset);
579 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
583 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
584 sgScaleVec3( source_vel, delta_time_sec );
585 sgCopyVec3( last_pos_offset, source_pos_offset );
586 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
587 globals->get_soundmgr()->set_source_vel_all( source_vel );
589 // Right now we make a simplifying assumption that the listener is
590 // always positioned at the origin.
592 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
593 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
594 globals->get_soundmgr()->set_listener_pos( listener_pos );
597 // END Tile Manager udpates
599 if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
600 fgSetBool("sim/sceneryloaded",true);
601 fgSetFloat("/sim/sound/volume", init_volume);
602 globals->get_soundmgr()->set_volume(init_volume);
605 if (fgGetBool("/sim/rendering/specular-highlight")) {
606 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
607 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
609 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
610 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
615 SG_LOG( SG_ALL, SG_DEBUG, "" );
619 // This is the top level master main function that is registered as
622 // The first few passes take care of initialization things (a couple
623 // per pass) and once everything has been initialized fgMainLoop from
626 static void fgIdleFunction ( void ) {
627 if ( idle_state == 0 ) {
629 fgSplashProgress("setting up scenegraph & user interface");
632 } else if ( idle_state == 1 ) {
634 // This seems to be the absolute earliest in the init sequence
635 // that these calls will return valid info. Too bad it's after
636 // we've already created and sized out window. :-(
637 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
638 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
639 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
640 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
643 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
644 general.set_glMaxTexSize( tmp );
645 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
647 glGetIntegerv( GL_DEPTH_BITS, &tmp );
648 general.set_glDepthBits( tmp );
649 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
651 // Initialize ssg (from plib). Needs to come before we do any
652 // other ssg stuff, but after opengl has been initialized.
655 // Initialize the user interface (we need to do this before
656 // passing off control to the OS main loop and before
657 // fgInitGeneral to get our fonts !!!
659 fgSplashProgress("reading aircraft list");
662 } else if ( idle_state == 2 ) {
664 // Read the list of available aircrafts
667 #ifdef GL_EXT_texture_lod_bias
668 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
671 // get the address of our OpenGL extensions
672 if ( fgGetBool("/sim/rendering/distance-attenuation") ) {
673 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
674 glPointParameterIsSupported = true;
675 glPointParameterfPtr = (glPointParameterfProc)
676 SGLookupFunction("glPointParameterfEXT");
677 glPointParameterfvPtr = (glPointParameterfvProc)
678 SGLookupFunction("glPointParameterfvEXT");
680 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
681 glPointParameterIsSupported = true;
682 glPointParameterfPtr = (glPointParameterfProc)
683 SGLookupFunction("glPointParameterfARB");
684 glPointParameterfvPtr = (glPointParameterfvProc)
685 SGLookupFunction("glPointParameterfvARB");
687 glPointParameterIsSupported = false;
689 fgSplashProgress("reading airport & navigation data");
692 } else if ( idle_state == 3 ) {
695 fgSplashProgress("setting up scenery");
698 } else if ( idle_state == 4 ) {
700 // based on the requested presets, calculate the true starting
704 SGTime *t = fgInitTime();
705 globals->set_time_params( t );
707 // Do some quick general initializations
708 if( !fgInitGeneral()) {
709 SG_LOG( SG_GENERAL, SG_ALERT,
710 "General initializations failed ..." );
714 ////////////////////////////////////////////////////////////////////
715 // Initialize the property-based built-in commands
716 ////////////////////////////////////////////////////////////////////
720 ////////////////////////////////////////////////////////////////////
721 // Initialize the material manager
722 ////////////////////////////////////////////////////////////////////
723 globals->set_matlib( new SGMaterialLib );
724 globals->set_model_lib(new SGModelLib);
727 ////////////////////////////////////////////////////////////////////
728 // Initialize the TG scenery subsystem.
729 ////////////////////////////////////////////////////////////////////
730 globals->set_scenery( new FGScenery );
731 globals->get_scenery()->init();
732 globals->get_scenery()->bind();
733 globals->set_tile_mgr( new FGTileMgr );
736 ////////////////////////////////////////////////////////////////////
737 // Initialize the general model subsystem.
738 ////////////////////////////////////////////////////////////////////
739 globals->set_model_mgr(new FGModelMgr);
740 globals->get_model_mgr()->init();
741 globals->get_model_mgr()->bind();
742 fgSplashProgress("loading aircraft");
745 } else if ( idle_state == 5 ) {
747 ////////////////////////////////////////////////////////////////////
748 // Initialize the 3D aircraft model subsystem (has a dependency on
749 // the scenery subsystem.)
750 ////////////////////////////////////////////////////////////////////
751 globals->set_aircraft_model(new FGAircraftModel);
752 globals->get_aircraft_model()->init();
753 globals->get_aircraft_model()->bind();
755 ////////////////////////////////////////////////////////////////////
756 // Initialize the view manager subsystem.
757 ////////////////////////////////////////////////////////////////////
758 FGViewMgr *viewmgr = new FGViewMgr;
759 globals->set_viewmgr( viewmgr );
762 fgSplashProgress("generating sky elements");
765 } else if ( idle_state == 6 ) {
767 // Initialize the sky
768 SGPath ephem_data_path( globals->get_fg_root() );
769 ephem_data_path.append( "Astro" );
770 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
771 ephem->update( globals->get_time_params()->getMjd(),
772 globals->get_time_params()->getLst(),
774 globals->set_ephem( ephem );
776 // TODO: move to environment mgr
778 SGPath texture_path(globals->get_fg_root());
779 texture_path.append("Textures");
780 texture_path.append("Sky");
781 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
782 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
783 thesky->add_cloud_layer(layer);
786 SGPath sky_tex_path( globals->get_fg_root() );
787 sky_tex_path.append( "Textures" );
788 sky_tex_path.append( "Sky" );
789 thesky->texture_path( sky_tex_path.str() );
791 // The sun and moon diameters are scaled down numbers of the
792 // actual diameters. This was needed to fit bot the sun and the
793 // moon within the distance to the far clip plane.
794 // Moon diameter: 3,476 kilometers
795 // Sun diameter: 1,390,000 kilometers
796 thesky->build( 80000.0, 80000.0,
798 globals->get_ephem()->getNumPlanets(),
799 globals->get_ephem()->getPlanets(),
800 globals->get_ephem()->getNumStars(),
801 globals->get_ephem()->getStars() );
803 // Initialize MagVar model
804 SGMagVar *magvar = new SGMagVar();
805 globals->set_mag( magvar );
808 // kludge to initialize mag compass
809 // (should only be done for in-flight
811 // update magvar model
812 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
813 * SGD_DEGREES_TO_RADIANS,
814 fgGetDouble("/position/latitude-deg")
815 * SGD_DEGREES_TO_RADIANS,
816 fgGetDouble("/position/altitude-ft")
818 globals->get_time_params()->getJD() );
819 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
820 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
822 // airport = new ssgBranch;
823 // airport->setName( "Airport Lighting" );
824 // lighting->addKid( airport );
826 // build our custom render states
827 globals->get_renderer()->build_states();
828 fgSplashProgress("initializing subsystems");
831 } else if ( idle_state == 7 ) {
833 // Initialize audio support
834 #ifdef ENABLE_AUDIO_SUPPORT
836 // Start the intro music
837 if ( fgGetBool("/sim/startup/intro-music") ) {
838 SGPath mp3file( globals->get_fg_root() );
839 mp3file.append( "Sounds/intro.mp3" );
841 SG_LOG( SG_GENERAL, SG_INFO,
842 "Starting intro music: " << mp3file.str() );
844 #if defined( __CYGWIN__ )
845 string command = "start /m `cygpath -w " + mp3file.str() + "`";
846 #elif defined( WIN32 )
847 string command = "start /m " + mp3file.str();
849 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
852 system ( command.c_str() );
856 // These are a few miscellaneous things that aren't really
857 // "subsystems" but still need to be initialized.
860 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
861 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
865 // This is the top level init routine which calls all the
866 // other subsystem initialization routines. If you are adding
867 // a subsystem to flightgear, its initialization call should
868 // located in this routine.
869 if( !fgInitSubsystems()) {
870 SG_LOG( SG_GENERAL, SG_ALERT,
871 "Subsystem initializations failed ..." );
874 fgSplashProgress("setting up time & renderer");
877 } else if ( idle_state == 8 ) {
879 // Initialize the time offset (warp) after fgInitSubsystem
880 // (which initializes the lighting interpolation tables.)
883 // setup OpenGL view parameters
884 globals->get_renderer()->init();
886 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
887 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
888 fgGetInt("/sim/startup/ysize") );
890 fgSplashProgress("loading scenery objects");
894 if ( idle_state == 1000 ) {
895 // We've finished all our initialization steps, from now on we
896 // run the main loop.
897 fgSetBool("sim/sceneryloaded", false);
898 fgRegisterIdleHandler( fgMainLoop );
903 // Main top level initialization
904 bool fgMainInit( int argc, char **argv ) {
906 #if defined( macintosh )
907 freopen ("stdout.txt", "w", stdout );
908 freopen ("stderr.txt", "w", stderr );
909 argc = ccommand( &argv );
912 // set default log levels
913 sglog().setLogLevels( SG_ALL, SG_ALERT );
916 #ifdef FLIGHTGEAR_VERSION
917 version = FLIGHTGEAR_VERSION;
919 version = "unknown version";
921 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
923 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
925 // Allocate global data structures. This needs to happen before
926 // we parse command line options
928 globals = new FGGlobals;
930 // seed the random number generater
933 FGControls *controls = new FGControls;
934 globals->set_controls( controls );
936 string_list *col = new string_list;
937 globals->set_channel_options_list( col );
939 // Scan the config file(s) and command line options to see if
940 // fg_root was specified (ignore all other options for now)
941 fgInitFGRoot(argc, argv);
943 // Check for the correct base package version
944 static char required_version[] = "0.9.8";
945 string base_version = fgBasePackageVersion();
946 if ( !(base_version == required_version) ) {
947 // tell the operator how to use this application
949 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
950 cerr << endl << "Base package check failed ... " \
951 << "Found version " << base_version << " at: " \
952 << globals->get_fg_root() << endl;
953 cerr << "Please upgrade to version: " << required_version << endl;
955 cerr << "Hit a key to continue..." << endl;
961 sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
963 // Load the configuration parameters. (Command line options
964 // overrides config file options. Config file options override
966 if ( !fgInitConfig(argc, argv) ) {
967 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
971 // Initialize the Window/Graphics environment.
972 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
973 // Mac OS X command line ("non-bundle") applications call this
974 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
975 // feel free to add comments...
976 fgOSInit(&argc, argv);
980 fgRegisterWindowResizeHandler( &FGRenderer::resize );
981 fgRegisterIdleHandler( &fgIdleFunction );
982 fgRegisterDrawHandler( &FGRenderer::update );
984 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
985 bool get_stencil_buffer = true;
987 bool get_stencil_buffer = false;
990 // Initialize plib net interface
991 netInit( &argc, argv );
993 // Clouds3D requires an alpha channel
994 // clouds may require stencil buffer
995 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
996 fgGetInt("/sim/startup/ysize"),
997 fgGetInt("/sim/rendering/bits-per-pixel"),
998 fgGetBool("/sim/rendering/clouds3d"),
1000 fgGetBool("/sim/startup/fullscreen") );
1002 // Initialize the splash screen right away
1004 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1006 // pass control off to the master event handler
1009 // we never actually get here ... but to avoid compiler warnings,