]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Set the format default to float instead of int.
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - curt@flightgear.org
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/netSocket.h>
45
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/math/sg_random.h>
49
50 // Class refferences
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
58
59
60 #include <Include/general.hxx>
61 #include <Cockpit/cockpit.hxx>
62 #include <Cockpit/radiostack.hxx>
63 #include <Cockpit/hud.hxx>
64 #include <Model/panelnode.hxx>
65 #include <Model/modelmgr.hxx>
66 #include <Model/acmodel.hxx>
67 #include <Scenery/scenery.hxx>
68 #include <Scenery/tilemgr.hxx>
69 #include <FDM/flight.hxx>
70 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
71 #include <FDM/ADA.hxx>
72 #include <ATC/ATCdisplay.hxx>
73 #include <ATC/ATCmgr.hxx>
74 #include <ATC/AIMgr.hxx>
75 #include <Replay/replay.hxx>
76 #include <Time/tmp.hxx>
77 #include <Time/fg_timer.hxx>
78 #include <Environment/environment_mgr.hxx>
79 #include <GUI/new_gui.hxx>
80
81 #ifdef FG_MPLAYER_AS
82 #include <MultiPlayer/multiplaytxmgr.hxx>
83 #include <MultiPlayer/multiplayrxmgr.hxx>
84 #endif
85
86
87
88 #include "fg_commands.hxx"
89 #include "fg_io.hxx"
90 #include "renderer.hxx"
91 #include "splash.hxx"
92 #include "main.hxx"
93
94
95
96 static double real_delta_time_sec = 0.0;
97 double delta_time_sec = 0.0;
98
99
100 #ifdef macintosh
101 #  include <console.h>          // -dw- for command line dialog
102 #endif
103
104 // This is a record containing a bit of global housekeeping information
105 FGGeneral general;
106
107 // Specify our current idle function state.  This is used to run all
108 // our initializations out of the idle callback so that we can get a
109 // splash screen up and running right away.
110 int idle_state = 0;
111 long global_multi_loop;
112
113
114 SGTimeStamp last_time_stamp;
115 SGTimeStamp current_time_stamp;
116
117 // The atexit() functio handler should know when the graphical subsystem
118 // is initialized.
119 extern int _bootstrap_OSInit;
120
121
122
123 // Update internal time dependent calculations (i.e. flight model)
124 // FIXME: this distinction is obsolete; all subsystems now get delta
125 // time on update.
126 void fgUpdateTimeDepCalcs() {
127     static bool inited = false;
128
129     static const SGPropertyNode *replay_master
130         = fgGetNode( "/sim/freeze/replay", true );
131     static SGPropertyNode *replay_time
132         = fgGetNode( "/sim/replay/time", true );
133     // static const SGPropertyNode *replay_end_time
134     //     = fgGetNode( "/sim/replay/end-time", true );
135
136     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
137
138     // Initialize the FDM here if it hasn't been and if we have a
139     // scenery elevation hit.
140
141     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
142     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
143
144     if ( !cur_fdm_state->get_inited() &&
145          globals->get_scenery()->get_cur_elev() > -9990 )
146     {
147         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
148         cur_fdm_state->init();
149         if ( cur_fdm_state->get_bound() ) {
150             cur_fdm_state->unbind();
151         }
152         cur_fdm_state->bind();
153     }
154
155     // conceptually, the following block could be done for each fdm
156     // instance ...
157     if ( cur_fdm_state->get_inited() ) {
158         // we have been inited, and  we are good to go ...
159
160         if ( !inited ) {
161             inited = true;
162         }
163
164         if ( ! replay_master->getBoolValue() ) {
165             cur_fdm_state->update( delta_time_sec );
166         } else {
167             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
168             r->replay( replay_time->getDoubleValue() );
169             replay_time->setDoubleValue( replay_time->getDoubleValue()
170                                          + ( delta_time_sec
171                                              * fgGetInt("/sim/speed-up") ) );
172         }
173     } else {
174         // do nothing, fdm isn't inited yet
175     }
176
177     globals->get_model_mgr()->update(delta_time_sec);
178     globals->get_aircraft_model()->update(delta_time_sec);
179
180     // update the view angle
181     globals->get_viewmgr()->update(delta_time_sec);
182
183     // Update solar system
184     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
185                                   globals->get_time_params()->getLst(),
186                                   cur_fdm_state->get_Latitude() );
187
188     // Update radio stack model
189     current_radiostack->update(delta_time_sec);
190 }
191
192
193 void fgInitTimeDepCalcs( void ) {
194     // noop for now
195 }
196
197
198 static const double alt_adjust_ft = 3.758099;
199 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
200
201
202 // What should we do when we have nothing else to do?  Let's get ready
203 // for the next move and update the display?
204 static void fgMainLoop( void ) {
205     int model_hz = fgGetInt("/sim/model-hz");
206
207     static const SGPropertyNode *longitude
208         = fgGetNode("/position/longitude-deg");
209     static const SGPropertyNode *latitude
210         = fgGetNode("/position/latitude-deg");
211     static const SGPropertyNode *altitude
212         = fgGetNode("/position/altitude-ft");
213     static const SGPropertyNode *clock_freeze
214         = fgGetNode("/sim/freeze/clock", true);
215     static const SGPropertyNode *cur_time_override
216         = fgGetNode("/sim/time/cur-time-override", true);
217     // static const SGPropertyNode *replay_master
218     //     = fgGetNode("/sim/freeze/replay", true);
219
220     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
221
222     // Update the elapsed time.
223     static bool first_time = true;
224     if ( first_time ) {
225         last_time_stamp.stamp();
226         first_time = false;
227     }
228
229     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
230     if ( throttle_hz > 0.0 ) {
231         // simple frame rate throttle
232         double dt = 1000000.0 / throttle_hz;
233         current_time_stamp.stamp();
234         while ( current_time_stamp - last_time_stamp < dt ) {
235             current_time_stamp.stamp();
236         }
237     } else {
238         // run as fast as the app will go
239         current_time_stamp.stamp();
240     }
241
242     real_delta_time_sec
243         = double(current_time_stamp - last_time_stamp) / 1000000.0;
244     if ( clock_freeze->getBoolValue() ) {
245         delta_time_sec = 0;
246     } else {
247         delta_time_sec = real_delta_time_sec;
248     }
249     last_time_stamp = current_time_stamp;
250     globals->inc_sim_time_sec( delta_time_sec );
251     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
252
253     // These are useful, especially for Nasal scripts.
254     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
255     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
256
257     static long remainder = 0;
258     long elapsed;
259 #ifdef FANCY_FRAME_COUNTER
260     int i;
261     double accum;
262 #else
263     static time_t last_time = 0;
264     static int frames = 0;
265 #endif // FANCY_FRAME_COUNTER
266
267     SGTime *t = globals->get_time_params();
268
269     globals->get_event_mgr()->update(delta_time_sec);
270
271     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
272     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
273
274 #if defined( ENABLE_PLIB_JOYSTICK )
275     // Read joystick and update control settings
276     // if ( fgGetString("/sim/control-mode") == "joystick" )
277     // {
278     //    fgJoystickRead();
279     // }
280 #endif
281
282     // Fix elevation.  I'm just sticking this here for now, it should
283     // probably move eventually
284
285     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
286            scenery.get_cur_elev(),
287            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
288            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
289
290     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
291            scenery.get_cur_elev(),
292            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
293            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
294
295     // cout << "Warp = " << globals->get_warp() << endl;
296
297     // update "time"
298     static bool last_clock_freeze = false;
299
300     if ( clock_freeze->getBoolValue() ) {
301         // clock freeze requested
302         if ( cur_time_override->getLongValue() == 0 ) {
303             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
304             globals->set_warp( 0 );
305         }
306     } else {
307         // no clock freeze requested
308         if ( last_clock_freeze == true ) {
309             // clock just unfroze, let's set warp as the difference
310             // between frozen time and current time so we don't get a
311             // time jump (and corresponding sky object and lighting
312             // jump.)
313             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
314             fgSetLong( "/sim/time/cur-time-override", 0 );
315         }
316         if ( globals->get_warp_delta() != 0 ) {
317             globals->inc_warp( globals->get_warp_delta() );
318         }
319     }
320
321     last_clock_freeze = clock_freeze->getBoolValue();
322
323     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
324                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
325                cur_time_override->getLongValue(),
326                globals->get_warp() );
327
328     if (globals->get_warp_delta() != 0) {
329         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
330         l->update( 0.5 );
331     }
332
333     // update magvar model
334     globals->get_mag()->update( longitude->getDoubleValue()
335                               * SGD_DEGREES_TO_RADIANS,
336                             latitude->getDoubleValue()
337                               * SGD_DEGREES_TO_RADIANS,
338                             altitude->getDoubleValue() * SG_FEET_TO_METER,
339                             globals->get_time_params()->getJD() );
340
341     // Get elapsed time (in usec) for this past frame
342     elapsed = fgGetTimeInterval();
343     SG_LOG( SG_ALL, SG_DEBUG, 
344             "Elapsed time interval is = " << elapsed 
345             << ", previous remainder is = " << remainder );
346
347     // Calculate frame rate average
348 #ifdef FANCY_FRAME_COUNTER
349     /* old fps calculation */
350     if ( elapsed > 0 ) {
351         double tmp;
352         accum = 0.0;
353         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
354             tmp = general.get_frame(i);
355             accum += tmp;
356             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
357             general.set_frame(i+1,tmp);
358         }
359         tmp = 1000000.0 / (float)elapsed;
360         general.set_frame(0,tmp);
361         // printf("frame[0] = %.2f\n", general.frames[0]);
362         accum += tmp;
363         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
364         // printf("ave = %.2f\n", general.frame_rate);
365     }
366 #else
367     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
368         general.set_frame_rate( frames );
369         fgSetInt("/sim/frame-rate", frames);
370         SG_LOG( SG_ALL, SG_DEBUG, 
371             "--> Frame rate is = " << general.get_frame_rate() );
372         frames = 0;
373     }
374     last_time = t->get_cur_time();
375     ++frames;
376 #endif
377
378     // Run ATC subsystem
379     if (fgGetBool("/sim/ATC/enabled"))
380         globals->get_ATC_mgr()->update(delta_time_sec);
381
382     // Run the AI subsystem
383     if (fgGetBool("/sim/ai-traffic/enabled"))
384         globals->get_AI_mgr()->update(delta_time_sec);
385
386 #ifdef FG_MPLAYER_AS
387     // Update any multiplayer models
388     globals->get_multiplayer_rx_mgr()->Update();
389 #endif
390
391     // Run flight model
392
393     // Calculate model iterations needed for next frame
394     elapsed += remainder;
395
396     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
397     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
398     SG_LOG( SG_ALL, SG_DEBUG, 
399             "Model iterations needed = " << global_multi_loop
400             << ", new remainder = " << remainder );
401         
402     // chop max interations to something reasonable if the sim was
403     // delayed for an excesive amount of time
404     if ( global_multi_loop > 2.0 * model_hz ) {
405         global_multi_loop = (int)(2.0 * model_hz );
406         remainder = 0;
407     }
408
409     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
410
411     // flight model
412     if ( global_multi_loop > 0) {
413         // first run the flight model each frame until it is intialized
414         // then continue running each frame only after initial scenery load is complete.
415         if (!cur_fdm_state->get_inited() || scenery_loaded) {
416             fgUpdateTimeDepCalcs();
417         }
418     } else {
419         SG_LOG( SG_ALL, SG_DEBUG, 
420             "Elapsed time is zero ... we're zinging" );
421     }
422
423     // Do any I/O channel work that might need to be done
424     globals->get_io()->update( real_delta_time_sec );
425
426     // see if we need to load any deferred-load textures
427     globals->get_matlib()->load_next_deferred();
428
429     // Run audio scheduler
430 #ifdef ENABLE_AUDIO_SUPPORT
431     if ( globals->get_soundmgr()->is_working() ) {
432         globals->get_soundmgr()->update( delta_time_sec );
433     }
434 #endif
435
436     globals->get_subsystem_mgr()->update(delta_time_sec);
437
438     //
439     // Tile Manager updates - see if we need to load any new scenery tiles.
440     //   this code ties together the fdm, viewer and scenery classes...
441     //   we may want to move this to it's own class at some point
442     //
443     double visibility_meters = fgGetDouble("/environment/visibility-m");
444     FGViewer *current_view = globals->get_current_view();
445
446     // get the location data for the primary FDM (now hardcoded to ac model)...
447     SGLocation *acmodel_loc = NULL;
448     acmodel_loc = (SGLocation *)globals->
449         get_aircraft_model()->get3DModel()->getSGLocation();
450
451     // update tile manager for FDM...
452     // ...only if location is different than the current-view location
453     // (to avoid duplicating effort)
454     if( !fgGetBool("/sim/current-view/config/from-model") ) {
455         if( acmodel_loc != NULL ) {
456             globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
457                                                      visibility_meters );
458             globals->get_tile_mgr()->
459                 update( acmodel_loc, visibility_meters,
460                         acmodel_loc->
461                         get_absolute_view_pos(globals->
462                                               get_scenery()->get_center()) );
463             // save results of update in SGLocation for fdm...
464             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
465                 acmodel_loc->
466                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
467                 fgSetDouble("/position/ground-elev-m",
468                             globals->get_scenery()->get_cur_elev());
469             }
470             acmodel_loc->
471                 set_tile_center( globals->get_scenery()->get_next_center() );
472         }
473     }
474
475     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
476                                              visibility_meters );
477     // update tile manager for view...
478     // IMPORTANT!!! the tilemgr update for view location _must_ be
479     // done last after the FDM's until all of Flight Gear code
480     // references the viewer's location for elevation instead of the
481     // "scenery's" current elevation.
482     SGLocation *view_location = globals->get_current_view()->getSGLocation();
483     globals->get_tile_mgr()->update( view_location, visibility_meters,
484                                      current_view->get_absolute_view_pos() );
485     // save results of update in SGLocation for fdm...
486     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
487         current_view->getSGLocation()->
488             set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
489     }
490     current_view->getSGLocation()->
491         set_tile_center( globals->get_scenery()->get_next_center() );
492
493 #ifdef ENABLE_AUDIO_SUPPORT
494     // Right now we make a simplifying assumption that the primary
495     // aircraft is the source of all sounds and that all sounds are
496     // positioned relative to the current view position.
497
498     static sgVec3 last_pos_offset;
499
500     // set positional offset for sources
501     sgVec3 source_pos_offset;
502     sgSubVec3( source_pos_offset,
503                view_location->get_view_pos(), acmodel_loc->get_view_pos() );
504     // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
505     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
506
507     // set the velocity
508     sgVec3 source_vel;
509     sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
510     sgScaleVec3( source_vel, delta_time_sec );
511     sgCopyVec3( last_pos_offset, source_pos_offset );
512     // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
513     globals->get_soundmgr()->set_source_vel_all( source_vel );
514
515     // Right now we make a simplifying assumption that the listener is
516     // always positioned at the origin.
517     sgVec3 listener_pos;
518     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
519     // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
520     globals->get_soundmgr()->set_listener_pos( listener_pos );
521 #endif
522
523     // If fdm location is same as viewer's then we didn't do the
524     // update for fdm location above so we need to save the viewer
525     // results in the fdm SGLocation as well...
526     if( fgGetBool("/sim/current-view/config/from-model") ) {
527         if( acmodel_loc != 0 ) {
528             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
529                 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
530                                              get_cur_elev() );
531                 fgSetDouble("/position/ground-elev-m",
532                             globals->get_scenery()->get_cur_elev());
533             }
534             acmodel_loc->set_tile_center( globals->get_scenery()->
535                                           get_next_center() );
536         }
537     }
538
539     // END Tile Manager udpates
540
541     if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
542         fgSetBool("sim/sceneryloaded",true);
543     }
544
545     if (fgGetBool("/sim/rendering/specular-highlight")) {
546         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
547         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
548     } else {
549         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
550         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
551     }
552
553     fgRequestRedraw();
554
555     SG_LOG( SG_ALL, SG_DEBUG, "" );
556 }
557
558
559 // This is the top level master main function that is registered as
560 // our idle funciton
561
562 // The first few passes take care of initialization things (a couple
563 // per pass) and once everything has been initialized fgMainLoop from
564 // then on.
565
566 static void fgIdleFunction ( void ) {
567     // printf("idle state == %d\n", idle_state);
568
569     if ( idle_state == 0 ) {
570         fgSetBool("sim/initialised", false);
571
572         // Initialize the splash screen right away
573         if ( fgGetBool("/sim/startup/splash-screen") ) {
574             fgSplashInit(fgGetString("/sim/startup/splash-texture"));
575         }
576         
577         idle_state++;
578     } else if ( idle_state == 1 ) {
579         // Initialize audio support
580 #ifdef ENABLE_AUDIO_SUPPORT
581
582         // Start the intro music
583         if ( fgGetBool("/sim/startup/intro-music") ) {
584             SGPath mp3file( globals->get_fg_root() );
585             mp3file.append( "Sounds/intro.mp3" );
586
587             SG_LOG( SG_GENERAL, SG_INFO, 
588                 "Starting intro music: " << mp3file.str() );
589
590 #if defined( __CYGWIN__ )
591             string command = "start /m `cygpath -w " + mp3file.str() + "`";
592 #elif defined( WIN32 )
593             string command = "start /m " + mp3file.str();
594 #else
595             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
596 #endif
597
598             system ( command.c_str() );
599         }
600 #endif
601
602         idle_state++;
603     } else if ( idle_state == 2 ) {
604         // These are a few miscellaneous things that aren't really
605         // "subsystems" but still need to be initialized.
606
607 #ifdef USE_GLIDE
608         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
609             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
610         }
611 #endif
612
613         idle_state++;
614     } else if ( idle_state == 3 ) {
615         // This is the top level init routine which calls all the
616         // other subsystem initialization routines.  If you are adding
617         // a subsystem to flightgear, its initialization call should
618         // located in this routine.
619         if( !fgInitSubsystems()) {
620             SG_LOG( SG_GENERAL, SG_ALERT,
621                 "Subsystem initializations failed ..." );
622             exit(-1);
623         }
624
625         idle_state++;
626     } else if ( idle_state == 4 ) {
627         // Initialize the time offset (warp) after fgInitSubsystem
628         // (which initializes the lighting interpolation tables.)
629         fgInitTimeOffset();
630
631         // setup OpenGL view parameters
632         globals->get_renderer()->init();
633
634         // Read the list of available aircrafts
635         fgReadAircraft();
636
637         idle_state++;
638     } else if ( idle_state == 5 ) {
639
640         idle_state++;
641     } else if ( idle_state == 6 ) {
642         // sleep(1);
643
644         idle_state = 1000;
645
646         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
647         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
648                                          fgGetInt("/sim/startup/ysize") );
649
650     } 
651
652     if ( idle_state == 1000 ) {
653         // We've finished all our initialization steps, from now on we
654         // run the main loop.
655         fgSetBool("sim/initialised",true);
656         fgSetBool("sim/sceneryloaded",false);
657
658         fgRegisterIdleHandler(fgMainLoop);
659     } else {
660         if ( fgGetBool("/sim/startup/splash-screen") ) {
661             fgSplashUpdate(0.0, 1.0);
662         }
663     }
664 }
665
666
667 // Main top level initialization
668 bool fgMainInit( int argc, char **argv ) {
669
670 #if defined( macintosh )
671     freopen ("stdout.txt", "w", stdout );
672     freopen ("stderr.txt", "w", stderr );
673     argc = ccommand( &argv );
674 #endif
675
676     // set default log levels
677     sglog().setLogLevels( SG_ALL, SG_ALERT );
678
679     string version;
680 #ifdef FLIGHTGEAR_VERSION
681     version = FLIGHTGEAR_VERSION;
682 #else
683     version = "unknown version";
684 #endif
685     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
686             << version );
687     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
688
689     // Allocate global data structures.  This needs to happen before
690     // we parse command line options
691
692     globals = new FGGlobals;
693
694     // seed the random number generater
695     sg_srandom_time();
696
697     FGControls *controls = new FGControls;
698     globals->set_controls( controls );
699
700     string_list *col = new string_list;
701     globals->set_channel_options_list( col );
702
703     // Scan the config file(s) and command line options to see if
704     // fg_root was specified (ignore all other options for now)
705     fgInitFGRoot(argc, argv);
706
707     // Check for the correct base package version
708     static char required_version[] = "0.9.6";
709     string base_version = fgBasePackageVersion();
710     if ( !(base_version == required_version) ) {
711         // tell the operator how to use this application
712
713         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
714         cerr << endl << "Base package check failed ... " \
715              << "Found version " << base_version << " at: " \
716              << globals->get_fg_root() << endl;
717         cerr << "Please upgrade to version: " << required_version << endl;
718 #ifdef _MSC_VER
719         cerr << "Hit a key to continue..." << endl;
720         cin.get();
721 #endif
722         exit(-1);
723     }
724
725     // Initialize the Aircraft directory to "" (UIUC)
726     aircraft_dir = "";
727
728     // Load the configuration parameters.  (Command line options
729     // overrides config file options.  Config file options override
730     // defaults.)
731     if ( !fgInitConfig(argc, argv) ) {
732         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
733         exit(-1);
734     }
735
736     // Initialize the Window/Graphics environment.
737 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
738     // Mac OS X command line ("non-bundle") applications call this
739     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
740     // feel free to add comments...
741     fgOSInit(&argc, argv);
742     _bootstrap_OSInit++;
743 #endif
744
745     fgRegisterWindowResizeHandler( FGRenderer::resize );
746     fgRegisterIdleHandler( fgIdleFunction );
747     fgRegisterDrawHandler( FGRenderer::update );
748
749 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
750     bool get_stencil_buffer = true;
751 #else
752     bool get_stencil_buffer = false;
753 #endif
754
755     // Clouds3D requires an alpha channel
756     // clouds may require stencil buffer
757     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
758                     fgGetInt("/sim/startup/ysize"),
759                     fgGetInt("/sim/rendering/bits-per-pixel"),
760                     fgGetBool("/sim/rendering/clouds3d"),
761                     get_stencil_buffer,
762                     fgGetBool("/sim/startup/fullscreen") );
763
764     // This seems to be the absolute earliest in the init sequence
765     // that these calls will return valid info.  Too bad it's after
766     // we've already created and sized out window. :-(
767     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
768     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
769     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
770     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
771
772     GLint tmp;
773     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
774     general.set_glMaxTexSize( tmp );
775     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
776
777     glGetIntegerv( GL_DEPTH_BITS, &tmp );
778     general.set_glDepthBits( tmp );
779     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
780
781     // Initialize plib net interface
782     netInit( &argc, argv );
783
784     // Initialize ssg (from plib).  Needs to come before we do any
785     // other ssg stuff, but after opengl has been initialized.
786     ssgInit();
787
788     // Initialize the user interface (we need to do this before
789     // passing off control to the OS main loop and before
790     // fgInitGeneral to get our fonts !!!
791     guiInit();
792
793     // Read the list of available aircrafts
794     fgReadAircraft();
795
796 #ifdef GL_EXT_texture_lod_bias
797     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
798 #endif
799
800             // get the address of our OpenGL extensions
801     if ( fgGetBool("/sim/rendering/distance-attenuation") )
802     {
803         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
804             glPointParameterIsSupported = true;
805             glPointParameterfPtr = (glPointParameterfProc)
806                                    SGLookupFunction("glPointParameterfEXT");
807             glPointParameterfvPtr = (glPointParameterfvProc)
808                                     SGLookupFunction("glPointParameterfvEXT");
809
810         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
811             glPointParameterIsSupported = true;
812             glPointParameterfPtr = (glPointParameterfProc)
813                                    SGLookupFunction("glPointParameterfARB");
814             glPointParameterfvPtr = (glPointParameterfvProc)
815                                     SGLookupFunction("glPointParameterfvARB");
816         } else
817             glPointParameterIsSupported = false;
818    }
819
820     // based on the requested presets, calculate the true starting
821     // lon, lat
822     fgInitNav();
823     fgInitPosition();
824
825     SGTime *t = fgInitTime();
826     globals->set_time_params( t );
827
828     // Do some quick general initializations
829     if( !fgInitGeneral()) {
830         SG_LOG( SG_GENERAL, SG_ALERT, 
831             "General initializations failed ..." );
832         exit(-1);
833     }
834
835     ////////////////////////////////////////////////////////////////////
836     // Initialize the property-based built-in commands
837     ////////////////////////////////////////////////////////////////////
838     fgInitCommands();
839
840     ////////////////////////////////////////////////////////////////////
841     // Initialize the material manager
842     ////////////////////////////////////////////////////////////////////
843     globals->set_matlib( new SGMaterialLib );
844
845     globals->set_model_lib(new SGModelLib);
846
847     ////////////////////////////////////////////////////////////////////
848     // Initialize the TG scenery subsystem.
849     ////////////////////////////////////////////////////////////////////
850     globals->set_scenery( new FGScenery );
851     globals->get_scenery()->init();
852     globals->get_scenery()->bind();
853     globals->set_tile_mgr( new FGTileMgr );
854
855     ////////////////////////////////////////////////////////////////////
856     // Initialize the general model subsystem.
857     ////////////////////////////////////////////////////////////////////
858     globals->set_model_mgr(new FGModelMgr);
859     globals->get_model_mgr()->init();
860     globals->get_model_mgr()->bind();
861
862     ////////////////////////////////////////////////////////////////////
863     // Initialize the 3D aircraft model subsystem (has a dependency on
864     // the scenery subsystem.)
865     ////////////////////////////////////////////////////////////////////
866     globals->set_aircraft_model(new FGAircraftModel);
867     globals->get_aircraft_model()->init();
868     globals->get_aircraft_model()->bind();
869
870     ////////////////////////////////////////////////////////////////////
871     // Initialize the view manager subsystem.
872     ////////////////////////////////////////////////////////////////////
873     FGViewMgr *viewmgr = new FGViewMgr;
874     globals->set_viewmgr( viewmgr );
875     viewmgr->init();
876     viewmgr->bind();
877
878
879     // Initialize the sky
880     SGPath ephem_data_path( globals->get_fg_root() );
881     ephem_data_path.append( "Astro" );
882     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
883     ephem->update( globals->get_time_params()->getMjd(),
884                    globals->get_time_params()->getLst(),
885                    0.0 );
886     globals->set_ephem( ephem );
887
888     // TODO: move to environment mgr
889     thesky = new SGSky;
890     SGPath texture_path(globals->get_fg_root());
891     texture_path.append("Textures");
892     texture_path.append("Sky");
893     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
894         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
895         thesky->add_cloud_layer(layer);
896     }
897
898     SGPath sky_tex_path( globals->get_fg_root() );
899     sky_tex_path.append( "Textures" );
900     sky_tex_path.append( "Sky" );
901     thesky->texture_path( sky_tex_path.str() );
902
903     // The sun and moon diameters are scaled down numbers of the
904     // actual diameters. This was needed to fit bot the sun and the
905     // moon within the distance to the far clip plane.
906     // Moon diameter:    3,476 kilometers
907     // Sun diameter: 1,390,000 kilometers
908     thesky->build( 80000.0, 80000.0,
909                    463.3, 361.8,
910                    globals->get_ephem()->getNumPlanets(), 
911                    globals->get_ephem()->getPlanets(),
912                    globals->get_ephem()->getNumStars(),
913                    globals->get_ephem()->getStars() );
914
915     // Initialize MagVar model
916     SGMagVar *magvar = new SGMagVar();
917     globals->set_mag( magvar );
918
919
920                                 // kludge to initialize mag compass
921                                 // (should only be done for in-flight
922                                 // startup)
923     // update magvar model
924     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
925                                 * SGD_DEGREES_TO_RADIANS,
926                                 fgGetDouble("/position/latitude-deg")
927                                 * SGD_DEGREES_TO_RADIANS,
928                                 fgGetDouble("/position/altitude-ft")
929                                 * SG_FEET_TO_METER,
930                                 globals->get_time_params()->getJD() );
931     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
932     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
933
934     // airport = new ssgBranch;
935     // airport->setName( "Airport Lighting" );
936     // lighting->addKid( airport );
937
938     // build our custom render states
939     globals->get_renderer()->build_states();
940
941     try {
942         // pass control off to the master event handler
943         fgOSMainLoop();
944     } catch (...) {
945         SG_LOG( SG_ALL, SG_ALERT,
946             "Unknown exception in the main loop. Aborting..." );
947     }
948
949     // we never actually get here ... but to avoid compiler warnings,
950     // etc.
951     return false;
952 }
953
954
955 // end of main.cxx