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>
60 #include <Include/general.hxx>
61 #include <Cockpit/cockpit.hxx>
62 #include <Cockpit/hud.hxx>
63 #include <Model/panelnode.hxx>
64 #include <Model/modelmgr.hxx>
65 #include <Model/acmodel.hxx>
66 #include <Scenery/scenery.hxx>
67 #include <Scenery/tilemgr.hxx>
68 #include <Sound/beacon.hxx>
69 #include <Sound/morse.hxx>
70 #include <FDM/flight.hxx>
71 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
72 // #include <FDM/ADA.hxx>
73 #include <ATC/ATCdisplay.hxx>
74 #include <ATC/ATCmgr.hxx>
75 #include <ATC/AIMgr.hxx>
76 #include <Replay/replay.hxx>
77 #include <Time/tmp.hxx>
78 #include <Time/fg_timer.hxx>
79 #include <Environment/environment_mgr.hxx>
80 #include <GUI/new_gui.hxx>
83 #include <MultiPlayer/multiplaytxmgr.hxx>
84 #include <MultiPlayer/multiplayrxmgr.hxx>
89 #include "fg_commands.hxx"
91 #include "renderer.hxx"
97 static double real_delta_time_sec = 0.0;
98 double delta_time_sec = 0.0;
99 extern float init_volume;
103 # include <console.h> // -dw- for command line dialog
106 // This is a record containing a bit of global housekeeping information
109 // Specify our current idle function state. This is used to run all
110 // our initializations out of the idle callback so that we can get a
111 // splash screen up and running right away.
113 long global_multi_loop;
115 SGTimeStamp last_time_stamp;
116 SGTimeStamp current_time_stamp;
118 // The atexit() functio handler should know when the graphical subsystem
120 extern int _bootstrap_OSInit;
124 // Update internal time dependent calculations (i.e. flight model)
125 // FIXME: this distinction is obsolete; all subsystems now get delta
127 void fgUpdateTimeDepCalcs() {
128 static bool inited = false;
130 static const SGPropertyNode *replay_state
131 = fgGetNode( "/sim/freeze/replay-state", true );
132 static SGPropertyNode *replay_time
133 = fgGetNode( "/sim/replay/time", true );
134 // static const SGPropertyNode *replay_end_time
135 // = fgGetNode( "/sim/replay/end-time", true );
137 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
139 // Initialize the FDM here if it hasn't been and if we have a
140 // scenery elevation hit.
142 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
143 // << " cur_elev = " << scenery.get_cur_elev() << endl;
145 if ( !cur_fdm_state->get_inited() &&
146 globals->get_scenery()->get_cur_elev() > -9990 )
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();
156 // conceptually, the following block could be done for each fdm
158 if ( cur_fdm_state->get_inited() ) {
159 // we have been inited, and we are good to go ...
165 if ( replay_state->getIntValue() == 0 ) {
166 // replay off, run fdm
167 cur_fdm_state->update( delta_time_sec );
169 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
170 r->replay( replay_time->getDoubleValue() );
171 if ( replay_state->getIntValue() == 1 ) {
173 replay_time->setDoubleValue( replay_time->getDoubleValue()
175 * fgGetInt("/sim/speed-up") ) );
176 } else if ( replay_state->getIntValue() == 2 ) {
177 // paused playback (don't advance replay time)
181 // do nothing, fdm isn't inited yet
184 globals->get_model_mgr()->update(delta_time_sec);
185 globals->get_aircraft_model()->update(delta_time_sec);
187 // update the view angle
188 globals->get_viewmgr()->update(delta_time_sec);
190 // Update solar system
191 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
192 globals->get_time_params()->getLst(),
193 cur_fdm_state->get_Latitude() );
198 void fgInitTimeDepCalcs( void ) {
203 static const double alt_adjust_ft = 3.758099;
204 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
207 // What should we do when we have nothing else to do? Let's get ready
208 // for the next move and update the display?
209 static void fgMainLoop( void ) {
210 int model_hz = fgGetInt("/sim/model-hz");
212 static const SGPropertyNode *longitude
213 = fgGetNode("/position/longitude-deg");
214 static const SGPropertyNode *latitude
215 = fgGetNode("/position/latitude-deg");
216 static const SGPropertyNode *altitude
217 = fgGetNode("/position/altitude-ft");
218 static const SGPropertyNode *clock_freeze
219 = fgGetNode("/sim/freeze/clock", true);
220 static const SGPropertyNode *cur_time_override
221 = fgGetNode("/sim/time/cur-time-override", true);
223 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
225 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
227 // Update the elapsed time.
228 static bool first_time = true;
230 last_time_stamp.stamp();
234 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
235 if ( throttle_hz > 0.0 && scenery_loaded ) {
236 static double remainder = 0.0;
238 // simple frame rate throttle
239 double dt = 1000000.0 / throttle_hz + remainder;
240 int wait = dt / 1000;
241 remainder = dt - ( wait * 1000.0 );
243 current_time_stamp.stamp();
244 int t_ms = (int) ( ( current_time_stamp - last_time_stamp ) / 1000 ) ; /* Convert to ms */
246 ulMilliSecondSleep ( wait - t_ms ) ;
248 current_time_stamp.stamp();
250 // run as fast as the app will go
251 current_time_stamp.stamp();
255 = double(current_time_stamp - last_time_stamp) / 1000000.0;
256 // round the real time down to a multiple of 1/model-hz.
257 // this way all systems are updated the _same_ amount of dt.
259 static double rem = 0.0;
260 real_delta_time_sec += rem;
261 double hz = model_hz;
262 double nit = floor(real_delta_time_sec*hz);
263 rem = real_delta_time_sec - nit/hz;
264 real_delta_time_sec = nit/hz;
268 if ( clock_freeze->getBoolValue() ) {
271 delta_time_sec = real_delta_time_sec;
273 last_time_stamp = current_time_stamp;
274 globals->inc_sim_time_sec( delta_time_sec );
275 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
277 // These are useful, especially for Nasal scripts.
278 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
279 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
281 static long remainder = 0;
283 #ifdef FANCY_FRAME_COUNTER
287 static time_t last_time = 0;
288 static int frames = 0;
289 #endif // FANCY_FRAME_COUNTER
291 SGTime *t = globals->get_time_params();
293 globals->get_event_mgr()->update(delta_time_sec);
295 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
296 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
298 #if defined( ENABLE_PLIB_JOYSTICK )
299 // Read joystick and update control settings
300 // if ( fgGetString("/sim/control-mode") == "joystick" )
306 // Fix elevation. I'm just sticking this here for now, it should
307 // probably move eventually
309 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
310 scenery.get_cur_elev(),
311 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
312 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
314 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
315 scenery.get_cur_elev(),
316 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
317 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
319 // cout << "Warp = " << globals->get_warp() << endl;
322 static bool last_clock_freeze = false;
324 if ( clock_freeze->getBoolValue() ) {
325 // clock freeze requested
326 if ( cur_time_override->getLongValue() == 0 ) {
327 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
328 globals->set_warp( 0 );
331 // no clock freeze requested
332 if ( last_clock_freeze == true ) {
333 // clock just unfroze, let's set warp as the difference
334 // between frozen time and current time so we don't get a
335 // time jump (and corresponding sky object and lighting
337 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
338 fgSetLong( "/sim/time/cur-time-override", 0 );
340 if ( globals->get_warp_delta() != 0 ) {
341 globals->inc_warp( globals->get_warp_delta() );
345 last_clock_freeze = clock_freeze->getBoolValue();
347 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
348 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
349 cur_time_override->getLongValue(),
350 globals->get_warp() );
352 if (globals->get_warp_delta() != 0) {
353 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
357 // update magvar model
358 globals->get_mag()->update( longitude->getDoubleValue()
359 * SGD_DEGREES_TO_RADIANS,
360 latitude->getDoubleValue()
361 * SGD_DEGREES_TO_RADIANS,
362 altitude->getDoubleValue() * SG_FEET_TO_METER,
363 globals->get_time_params()->getJD() );
365 // Get elapsed time (in usec) for this past frame
366 elapsed = fgGetTimeInterval();
367 SG_LOG( SG_ALL, SG_DEBUG,
368 "Elapsed time interval is = " << elapsed
369 << ", previous remainder is = " << remainder );
371 // Calculate frame rate average
372 #ifdef FANCY_FRAME_COUNTER
373 /* old fps calculation */
377 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
378 tmp = general.get_frame(i);
380 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
381 general.set_frame(i+1,tmp);
383 tmp = 1000000.0 / (float)elapsed;
384 general.set_frame(0,tmp);
385 // printf("frame[0] = %.2f\n", general.frames[0]);
387 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
388 // printf("ave = %.2f\n", general.frame_rate);
391 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
392 general.set_frame_rate( frames );
393 fgSetInt("/sim/frame-rate", frames);
394 SG_LOG( SG_ALL, SG_DEBUG,
395 "--> Frame rate is = " << general.get_frame_rate() );
398 last_time = t->get_cur_time();
403 if (fgGetBool("/sim/ATC/enabled"))
404 globals->get_ATC_mgr()->update(delta_time_sec);
406 // Run the AI subsystem
407 if (fgGetBool("/sim/ai-traffic/enabled"))
408 globals->get_AI_mgr()->update(delta_time_sec);
411 // Update any multiplayer models
412 globals->get_multiplayer_rx_mgr()->Update();
417 // Calculate model iterations needed for next frame
418 elapsed += remainder;
420 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
421 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
422 SG_LOG( SG_ALL, SG_DEBUG,
423 "Model iterations needed = " << global_multi_loop
424 << ", new remainder = " << remainder );
426 // chop max interations to something reasonable if the sim was
427 // delayed for an excesive amount of time
428 if ( global_multi_loop > 2.0 * model_hz ) {
429 global_multi_loop = (int)(2.0 * model_hz );
434 if ( global_multi_loop > 0) {
435 // first run the flight model each frame until it is intialized
436 // then continue running each frame only after initial scenery load is complete.
437 if (!cur_fdm_state->get_inited() || scenery_loaded) {
438 fgUpdateTimeDepCalcs();
441 SG_LOG( SG_ALL, SG_DEBUG,
442 "Elapsed time is zero ... we're zinging" );
445 // Do any I/O channel work that might need to be done
446 globals->get_io()->update( real_delta_time_sec );
448 // see if we need to load any deferred-load textures
449 globals->get_matlib()->load_next_deferred();
451 // Run audio scheduler
452 #ifdef ENABLE_AUDIO_SUPPORT
453 if ( globals->get_soundmgr()->is_working() ) {
454 globals->get_soundmgr()->update( delta_time_sec );
458 globals->get_subsystem_mgr()->update(delta_time_sec);
461 // Tile Manager updates - see if we need to load any new scenery tiles.
462 // this code ties together the fdm, viewer and scenery classes...
463 // we may want to move this to it's own class at some point
465 double visibility_meters = fgGetDouble("/environment/visibility-m");
466 FGViewer *current_view = globals->get_current_view();
468 // get the location data for the primary FDM (now hardcoded to ac model)...
469 SGLocation *acmodel_loc = NULL;
470 acmodel_loc = (SGLocation *)globals->
471 get_aircraft_model()->get3DModel()->getSGLocation();
473 // update tile manager for FDM...
474 // ...only if location is different than the current-view location
475 // (to avoid duplicating effort)
476 if( !fgGetBool("/sim/current-view/config/from-model") ) {
477 if( acmodel_loc != NULL ) {
478 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
480 globals->get_tile_mgr()->
481 update( acmodel_loc, visibility_meters,
483 get_absolute_view_pos(globals->
484 get_scenery()->get_center()) );
485 // save results of update in SGLocation for fdm...
486 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
488 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
489 fgSetDouble("/position/ground-elev-m",
490 globals->get_scenery()->get_cur_elev());
493 set_tile_center( globals->get_scenery()->get_next_center() );
497 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
499 // update tile manager for view...
500 // IMPORTANT!!! the tilemgr update for view location _must_ be
501 // done last after the FDM's until all of Flight Gear code
502 // references the viewer's location for elevation instead of the
503 // "scenery's" current elevation.
504 SGLocation *view_location = globals->get_current_view()->getSGLocation();
505 globals->get_tile_mgr()->update( view_location, visibility_meters,
506 current_view->get_absolute_view_pos() );
507 // save results of update in SGLocation for fdm...
508 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
509 current_view->getSGLocation()->
510 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
512 current_view->getSGLocation()->
513 set_tile_center( globals->get_scenery()->get_next_center() );
515 #ifdef ENABLE_AUDIO_SUPPORT
516 // Right now we make a simplifying assumption that the primary
517 // aircraft is the source of all sounds and that all sounds are
518 // positioned relative to the current view position.
520 static sgVec3 last_pos_offset;
522 // set positional offset for sources
523 sgVec3 source_pos_offset;
524 sgSubVec3( source_pos_offset,
525 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
526 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
527 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
531 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
532 sgScaleVec3( source_vel, delta_time_sec );
533 sgCopyVec3( last_pos_offset, source_pos_offset );
534 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
535 globals->get_soundmgr()->set_source_vel_all( source_vel );
537 // Right now we make a simplifying assumption that the listener is
538 // always positioned at the origin.
540 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
541 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
542 globals->get_soundmgr()->set_listener_pos( listener_pos );
545 // If fdm location is same as viewer's then we didn't do the
546 // update for fdm location above so we need to save the viewer
547 // results in the fdm SGLocation as well...
548 if( fgGetBool("/sim/current-view/config/from-model") ) {
549 if( acmodel_loc != 0 ) {
550 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
551 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
553 fgSetDouble("/position/ground-elev-m",
554 globals->get_scenery()->get_cur_elev());
556 acmodel_loc->set_tile_center( globals->get_scenery()->
561 // END Tile Manager udpates
563 if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
564 fgSetBool("sim/sceneryloaded",true);
565 fgSetFloat("/sim/sound/volume", init_volume);
566 globals->get_soundmgr()->set_volume(init_volume);
569 if (fgGetBool("/sim/rendering/specular-highlight")) {
570 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
571 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
573 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
574 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
579 SG_LOG( SG_ALL, SG_DEBUG, "" );
583 // This is the top level master main function that is registered as
586 // The first few passes take care of initialization things (a couple
587 // per pass) and once everything has been initialized fgMainLoop from
590 static void fgIdleFunction ( void ) {
591 // printf("idle state == %d\n", idle_state);
593 if ( idle_state == 0 ) {
594 // Initialize the splash screen right away
595 if ( fgGetBool("/sim/startup/splash-screen") ) {
596 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
600 } else if ( idle_state == 1 ) {
601 // Initialize audio support
602 #ifdef ENABLE_AUDIO_SUPPORT
604 // Start the intro music
605 if ( fgGetBool("/sim/startup/intro-music") ) {
606 SGPath mp3file( globals->get_fg_root() );
607 mp3file.append( "Sounds/intro.mp3" );
609 SG_LOG( SG_GENERAL, SG_INFO,
610 "Starting intro music: " << mp3file.str() );
612 #if defined( __CYGWIN__ )
613 string command = "start /m `cygpath -w " + mp3file.str() + "`";
614 #elif defined( WIN32 )
615 string command = "start /m " + mp3file.str();
617 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
620 system ( command.c_str() );
625 } else if ( idle_state == 2 ) {
626 // These are a few miscellaneous things that aren't really
627 // "subsystems" but still need to be initialized.
630 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
631 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
636 } else if ( idle_state == 3 ) {
637 // This is the top level init routine which calls all the
638 // other subsystem initialization routines. If you are adding
639 // a subsystem to flightgear, its initialization call should
640 // located in this routine.
641 if( !fgInitSubsystems()) {
642 SG_LOG( SG_GENERAL, SG_ALERT,
643 "Subsystem initializations failed ..." );
648 } else if ( idle_state == 4 ) {
649 // Initialize the time offset (warp) after fgInitSubsystem
650 // (which initializes the lighting interpolation tables.)
653 // setup OpenGL view parameters
654 globals->get_renderer()->init();
656 // Read the list of available aircrafts
660 } else if ( idle_state == 5 ) {
663 } else if ( idle_state == 6 ) {
668 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
669 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
670 fgGetInt("/sim/startup/ysize") );
674 if ( idle_state == 1000 ) {
675 // We've finished all our initialization steps, from now on we
676 // run the main loop.
677 fgSetBool("sim/sceneryloaded",false);
679 fgRegisterIdleHandler(fgMainLoop);
681 if ( fgGetBool("/sim/startup/splash-screen") ) {
682 fgSplashUpdate(0.0, 1.0);
688 // Main top level initialization
689 bool fgMainInit( int argc, char **argv ) {
691 #if defined( macintosh )
692 freopen ("stdout.txt", "w", stdout );
693 freopen ("stderr.txt", "w", stderr );
694 argc = ccommand( &argv );
697 // set default log levels
698 sglog().setLogLevels( SG_ALL, SG_ALERT );
701 #ifdef FLIGHTGEAR_VERSION
702 version = FLIGHTGEAR_VERSION;
704 version = "unknown version";
706 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
708 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
710 // Allocate global data structures. This needs to happen before
711 // we parse command line options
713 globals = new FGGlobals;
715 // seed the random number generater
718 FGControls *controls = new FGControls;
719 globals->set_controls( controls );
721 string_list *col = new string_list;
722 globals->set_channel_options_list( col );
724 // Scan the config file(s) and command line options to see if
725 // fg_root was specified (ignore all other options for now)
726 fgInitFGRoot(argc, argv);
728 // Check for the correct base package version
729 static char required_version[] = "0.9.8";
730 string base_version = fgBasePackageVersion();
731 if ( !(base_version == required_version) ) {
732 // tell the operator how to use this application
734 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
735 cerr << endl << "Base package check failed ... " \
736 << "Found version " << base_version << " at: " \
737 << globals->get_fg_root() << endl;
738 cerr << "Please upgrade to version: " << required_version << endl;
740 cerr << "Hit a key to continue..." << endl;
746 sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
748 // Initialize the Aircraft directory to "" (UIUC)
751 // Load the configuration parameters. (Command line options
752 // overrides config file options. Config file options override
754 if ( !fgInitConfig(argc, argv) ) {
755 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
759 // Initialize the Window/Graphics environment.
760 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
761 // Mac OS X command line ("non-bundle") applications call this
762 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
763 // feel free to add comments...
764 fgOSInit(&argc, argv);
768 fgRegisterWindowResizeHandler( &FGRenderer::resize );
769 fgRegisterIdleHandler( &fgIdleFunction );
770 fgRegisterDrawHandler( &FGRenderer::update );
772 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
773 bool get_stencil_buffer = true;
775 bool get_stencil_buffer = false;
778 // Clouds3D requires an alpha channel
779 // clouds may require stencil buffer
780 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
781 fgGetInt("/sim/startup/ysize"),
782 fgGetInt("/sim/rendering/bits-per-pixel"),
783 fgGetBool("/sim/rendering/clouds3d"),
785 fgGetBool("/sim/startup/fullscreen") );
787 // This seems to be the absolute earliest in the init sequence
788 // that these calls will return valid info. Too bad it's after
789 // we've already created and sized out window. :-(
790 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
791 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
792 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
793 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
796 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
797 general.set_glMaxTexSize( tmp );
798 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
800 glGetIntegerv( GL_DEPTH_BITS, &tmp );
801 general.set_glDepthBits( tmp );
802 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
804 // Initialize plib net interface
805 netInit( &argc, argv );
807 // Initialize ssg (from plib). Needs to come before we do any
808 // other ssg stuff, but after opengl has been initialized.
811 // Initialize the user interface (we need to do this before
812 // passing off control to the OS main loop and before
813 // fgInitGeneral to get our fonts !!!
816 // Read the list of available aircrafts
819 #ifdef GL_EXT_texture_lod_bias
820 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
823 // get the address of our OpenGL extensions
824 if ( fgGetBool("/sim/rendering/distance-attenuation") )
826 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
827 glPointParameterIsSupported = true;
828 glPointParameterfPtr = (glPointParameterfProc)
829 SGLookupFunction("glPointParameterfEXT");
830 glPointParameterfvPtr = (glPointParameterfvProc)
831 SGLookupFunction("glPointParameterfvEXT");
833 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
834 glPointParameterIsSupported = true;
835 glPointParameterfPtr = (glPointParameterfProc)
836 SGLookupFunction("glPointParameterfARB");
837 glPointParameterfvPtr = (glPointParameterfvProc)
838 SGLookupFunction("glPointParameterfvARB");
840 glPointParameterIsSupported = false;
843 // based on the requested presets, calculate the true starting
848 SGTime *t = fgInitTime();
849 globals->set_time_params( t );
851 // Do some quick general initializations
852 if( !fgInitGeneral()) {
853 SG_LOG( SG_GENERAL, SG_ALERT,
854 "General initializations failed ..." );
858 ////////////////////////////////////////////////////////////////////
859 // Initialize the property-based built-in commands
860 ////////////////////////////////////////////////////////////////////
863 ////////////////////////////////////////////////////////////////////
864 // Initialize the material manager
865 ////////////////////////////////////////////////////////////////////
866 globals->set_matlib( new SGMaterialLib );
868 globals->set_model_lib(new SGModelLib);
870 ////////////////////////////////////////////////////////////////////
871 // Initialize the TG scenery subsystem.
872 ////////////////////////////////////////////////////////////////////
873 globals->set_scenery( new FGScenery );
874 globals->get_scenery()->init();
875 globals->get_scenery()->bind();
876 globals->set_tile_mgr( new FGTileMgr );
878 ////////////////////////////////////////////////////////////////////
879 // Initialize the general model subsystem.
880 ////////////////////////////////////////////////////////////////////
881 globals->set_model_mgr(new FGModelMgr);
882 globals->get_model_mgr()->init();
883 globals->get_model_mgr()->bind();
885 ////////////////////////////////////////////////////////////////////
886 // Initialize the 3D aircraft model subsystem (has a dependency on
887 // the scenery subsystem.)
888 ////////////////////////////////////////////////////////////////////
889 globals->set_aircraft_model(new FGAircraftModel);
890 globals->get_aircraft_model()->init();
891 globals->get_aircraft_model()->bind();
893 ////////////////////////////////////////////////////////////////////
894 // Initialize the view manager subsystem.
895 ////////////////////////////////////////////////////////////////////
896 FGViewMgr *viewmgr = new FGViewMgr;
897 globals->set_viewmgr( viewmgr );
902 // Initialize the sky
903 SGPath ephem_data_path( globals->get_fg_root() );
904 ephem_data_path.append( "Astro" );
905 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
906 ephem->update( globals->get_time_params()->getMjd(),
907 globals->get_time_params()->getLst(),
909 globals->set_ephem( ephem );
911 // TODO: move to environment mgr
913 SGPath texture_path(globals->get_fg_root());
914 texture_path.append("Textures");
915 texture_path.append("Sky");
916 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
917 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
918 thesky->add_cloud_layer(layer);
921 SGPath sky_tex_path( globals->get_fg_root() );
922 sky_tex_path.append( "Textures" );
923 sky_tex_path.append( "Sky" );
924 thesky->texture_path( sky_tex_path.str() );
926 // The sun and moon diameters are scaled down numbers of the
927 // actual diameters. This was needed to fit bot the sun and the
928 // moon within the distance to the far clip plane.
929 // Moon diameter: 3,476 kilometers
930 // Sun diameter: 1,390,000 kilometers
931 thesky->build( 80000.0, 80000.0,
933 globals->get_ephem()->getNumPlanets(),
934 globals->get_ephem()->getPlanets(),
935 globals->get_ephem()->getNumStars(),
936 globals->get_ephem()->getStars() );
938 // Initialize MagVar model
939 SGMagVar *magvar = new SGMagVar();
940 globals->set_mag( magvar );
943 // kludge to initialize mag compass
944 // (should only be done for in-flight
946 // update magvar model
947 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
948 * SGD_DEGREES_TO_RADIANS,
949 fgGetDouble("/position/latitude-deg")
950 * SGD_DEGREES_TO_RADIANS,
951 fgGetDouble("/position/altitude-ft")
953 globals->get_time_params()->getJD() );
954 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
955 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
957 // airport = new ssgBranch;
958 // airport->setName( "Airport Lighting" );
959 // lighting->addKid( airport );
961 // build our custom render states
962 globals->get_renderer()->build_states();
964 // pass control off to the master event handler
967 // we never actually get here ... but to avoid compiler warnings,