]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
db569b84ee1d8ac2234e0fa73797a4c6fe407ce7
[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  - http://www.flightgear.org/~curt
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/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>
81
82 #ifdef FG_MPLAYER_AS
83 #include <MultiPlayer/multiplaytxmgr.hxx>
84 #include <MultiPlayer/multiplayrxmgr.hxx>
85 #endif
86
87
88
89 #include "fg_commands.hxx"
90 #include "fg_io.hxx"
91 #include "renderer.hxx"
92 #include "splash.hxx"
93 #include "main.hxx"
94
95
96
97 static double real_delta_time_sec = 0.0;
98 double delta_time_sec = 0.0;
99 extern float init_volume;
100
101
102 #ifdef macintosh
103 #  include <console.h>          // -dw- for command line dialog
104 #endif
105
106 // This is a record containing a bit of global housekeeping information
107 FGGeneral general;
108
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.
112 int idle_state = 0;
113 long global_multi_loop;
114
115 SGTimeStamp last_time_stamp;
116 SGTimeStamp current_time_stamp;
117
118 // The atexit() functio handler should know when the graphical subsystem
119 // is initialized.
120 extern int _bootstrap_OSInit;
121
122
123
124 // Update internal time dependent calculations (i.e. flight model)
125 // FIXME: this distinction is obsolete; all subsystems now get delta
126 // time on update.
127 void fgUpdateTimeDepCalcs() {
128     static bool inited = false;
129
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 );
136
137     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
138
139     // Initialize the FDM here if it hasn't been and if we have a
140     // scenery elevation hit.
141
142     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
143     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
144
145     if ( !cur_fdm_state->get_inited() &&
146          globals->get_scenery()->get_cur_elev() > -9990 )
147     {
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();
152         }
153         cur_fdm_state->bind();
154     }
155
156     // conceptually, the following block could be done for each fdm
157     // instance ...
158     if ( cur_fdm_state->get_inited() ) {
159         // we have been inited, and  we are good to go ...
160
161         if ( !inited ) {
162             inited = true;
163         }
164
165         if ( replay_state->getIntValue() == 0 ) {
166             // replay off, run fdm
167             cur_fdm_state->update( delta_time_sec );
168         } else {
169             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
170             r->replay( replay_time->getDoubleValue() );
171             if ( replay_state->getIntValue() == 1 ) {
172                 // normal playback
173                 replay_time->setDoubleValue( replay_time->getDoubleValue()
174                                              + ( delta_time_sec
175                                                * fgGetInt("/sim/speed-up") ) );
176             } else if ( replay_state->getIntValue() == 2 ) {
177                 // paused playback (don't advance replay time)
178             }
179         }
180     } else {
181         // do nothing, fdm isn't inited yet
182     }
183
184     globals->get_model_mgr()->update(delta_time_sec);
185     globals->get_aircraft_model()->update(delta_time_sec);
186
187     // update the view angle
188     globals->get_viewmgr()->update(delta_time_sec);
189
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() );
194
195 }
196
197
198 void fgInitTimeDepCalcs( void ) {
199     // noop for now
200 }
201
202
203 static const double alt_adjust_ft = 3.758099;
204 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
205
206
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");
211
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);
222
223     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
224
225     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
226
227     // Update the elapsed time.
228     static bool first_time = true;
229     if ( first_time ) {
230         last_time_stamp.stamp();
231         first_time = false;
232     }
233
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;
237
238         // simple frame rate throttle
239         double dt = 1000000.0 / throttle_hz + remainder;
240         int wait = dt / 1000;
241         remainder = dt - ( wait * 1000.0 );
242
243         current_time_stamp.stamp();
244         int t_ms = (int) ( ( current_time_stamp - last_time_stamp ) / 1000 ) ; /* Convert to ms */
245         if ( t_ms < wait ) {
246             ulMilliSecondSleep ( wait - t_ms ) ;
247         }
248         current_time_stamp.stamp();
249     } else {
250         // run as fast as the app will go
251         current_time_stamp.stamp();
252     }
253
254     real_delta_time_sec
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.
258     {
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;
265     }
266
267
268     if ( clock_freeze->getBoolValue() ) {
269         delta_time_sec = 0;
270     } else {
271         delta_time_sec = real_delta_time_sec;
272     }
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() );
276
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);
280
281     static long remainder = 0;
282     long elapsed;
283 #ifdef FANCY_FRAME_COUNTER
284     int i;
285     double accum;
286 #else
287     static time_t last_time = 0;
288     static int frames = 0;
289 #endif // FANCY_FRAME_COUNTER
290
291     SGTime *t = globals->get_time_params();
292
293     globals->get_event_mgr()->update(delta_time_sec);
294
295     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
296     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
297
298 #if defined( ENABLE_PLIB_JOYSTICK )
299     // Read joystick and update control settings
300     // if ( fgGetString("/sim/control-mode") == "joystick" )
301     // {
302     //    fgJoystickRead();
303     // }
304 #endif
305
306     // Fix elevation.  I'm just sticking this here for now, it should
307     // probably move eventually
308
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); */
313
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); */
318
319     // cout << "Warp = " << globals->get_warp() << endl;
320
321     // update "time"
322     static bool last_clock_freeze = false;
323
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 );
329         }
330     } else {
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
336             // jump.)
337             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
338             fgSetLong( "/sim/time/cur-time-override", 0 );
339         }
340         if ( globals->get_warp_delta() != 0 ) {
341             globals->inc_warp( globals->get_warp_delta() );
342         }
343     }
344
345     last_clock_freeze = clock_freeze->getBoolValue();
346
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() );
351
352     if (globals->get_warp_delta() != 0) {
353         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
354         l->update( 0.5 );
355     }
356
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() );
364
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 );
370
371     // Calculate frame rate average
372 #ifdef FANCY_FRAME_COUNTER
373     /* old fps calculation */
374     if ( elapsed > 0 ) {
375         double tmp;
376         accum = 0.0;
377         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
378             tmp = general.get_frame(i);
379             accum += tmp;
380             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
381             general.set_frame(i+1,tmp);
382         }
383         tmp = 1000000.0 / (float)elapsed;
384         general.set_frame(0,tmp);
385         // printf("frame[0] = %.2f\n", general.frames[0]);
386         accum += tmp;
387         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
388         // printf("ave = %.2f\n", general.frame_rate);
389     }
390 #else
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() );
396         frames = 0;
397     }
398     last_time = t->get_cur_time();
399     ++frames;
400 #endif
401
402     // Run ATC subsystem
403     if (fgGetBool("/sim/ATC/enabled"))
404         globals->get_ATC_mgr()->update(delta_time_sec);
405
406     // Run the AI subsystem
407     if (fgGetBool("/sim/ai-traffic/enabled"))
408         globals->get_AI_mgr()->update(delta_time_sec);
409
410 #ifdef FG_MPLAYER_AS
411     // Update any multiplayer models
412     globals->get_multiplayer_rx_mgr()->Update();
413 #endif
414
415     // Run flight model
416
417     // Calculate model iterations needed for next frame
418     elapsed += remainder;
419
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 );
425         
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 );
430         remainder = 0;
431     }
432
433     // flight model
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();
439         }
440     } else {
441         SG_LOG( SG_ALL, SG_DEBUG, 
442             "Elapsed time is zero ... we're zinging" );
443     }
444
445     // Do any I/O channel work that might need to be done
446     globals->get_io()->update( real_delta_time_sec );
447
448     // see if we need to load any deferred-load textures
449     globals->get_matlib()->load_next_deferred();
450
451     // Run audio scheduler
452 #ifdef ENABLE_AUDIO_SUPPORT
453     if ( globals->get_soundmgr()->is_working() ) {
454         globals->get_soundmgr()->update( delta_time_sec );
455     }
456 #endif
457
458     globals->get_subsystem_mgr()->update(delta_time_sec);
459
460     //
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
464     //
465     double visibility_meters = fgGetDouble("/environment/visibility-m");
466     FGViewer *current_view = globals->get_current_view();
467
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();
472
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,
479                                                      visibility_meters );
480             globals->get_tile_mgr()->
481                 update( acmodel_loc, visibility_meters,
482                         acmodel_loc->
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 ) {
487                 acmodel_loc->
488                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
489                 fgSetDouble("/position/ground-elev-m",
490                             globals->get_scenery()->get_cur_elev());
491             }
492             acmodel_loc->
493                 set_tile_center( globals->get_scenery()->get_next_center() );
494         }
495     }
496
497     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
498                                              visibility_meters );
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() );
511     }
512     current_view->getSGLocation()->
513         set_tile_center( globals->get_scenery()->get_next_center() );
514
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.
519
520     static sgVec3 last_pos_offset;
521
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 );
528
529     // set the velocity
530     sgVec3 source_vel;
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 );
536
537     // Right now we make a simplifying assumption that the listener is
538     // always positioned at the origin.
539     sgVec3 listener_pos;
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 );
543 #endif
544
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()->
552                                              get_cur_elev() );
553                 fgSetDouble("/position/ground-elev-m",
554                             globals->get_scenery()->get_cur_elev());
555             }
556             acmodel_loc->set_tile_center( globals->get_scenery()->
557                                           get_next_center() );
558         }
559     }
560
561     // END Tile Manager udpates
562
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);
567     }
568
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);
572     } else {
573         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
574         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
575     }
576
577     fgRequestRedraw();
578
579     SG_LOG( SG_ALL, SG_DEBUG, "" );
580 }
581
582
583 // This is the top level master main function that is registered as
584 // our idle funciton
585
586 // The first few passes take care of initialization things (a couple
587 // per pass) and once everything has been initialized fgMainLoop from
588 // then on.
589
590 static void fgIdleFunction ( void ) {
591     // printf("idle state == %d\n", idle_state);
592
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"));
597         }
598         
599         idle_state++;
600     } else if ( idle_state == 1 ) {
601         // Initialize audio support
602 #ifdef ENABLE_AUDIO_SUPPORT
603
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" );
608
609             SG_LOG( SG_GENERAL, SG_INFO, 
610                 "Starting intro music: " << mp3file.str() );
611
612 #if defined( __CYGWIN__ )
613             string command = "start /m `cygpath -w " + mp3file.str() + "`";
614 #elif defined( WIN32 )
615             string command = "start /m " + mp3file.str();
616 #else
617             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
618 #endif
619
620             system ( command.c_str() );
621         }
622 #endif
623
624         idle_state++;
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.
628
629 #ifdef USE_GLIDE
630         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
631             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
632         }
633 #endif
634
635         idle_state++;
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 ..." );
644             exit(-1);
645         }
646
647         idle_state++;
648     } else if ( idle_state == 4 ) {
649         // Initialize the time offset (warp) after fgInitSubsystem
650         // (which initializes the lighting interpolation tables.)
651         fgInitTimeOffset();
652
653         // setup OpenGL view parameters
654         globals->get_renderer()->init();
655
656         // Read the list of available aircrafts
657         fgReadAircraft();
658
659         idle_state++;
660     } else if ( idle_state == 5 ) {
661
662         idle_state++;
663     } else if ( idle_state == 6 ) {
664         // sleep(1);
665
666         idle_state = 1000;
667
668         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
669         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
670                                          fgGetInt("/sim/startup/ysize") );
671
672     } 
673
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);
678
679         fgRegisterIdleHandler(fgMainLoop);
680     } else {
681         if ( fgGetBool("/sim/startup/splash-screen") ) {
682             fgSplashUpdate(0.0, 1.0);
683         }
684     }
685 }
686
687
688 // Main top level initialization
689 bool fgMainInit( int argc, char **argv ) {
690
691 #if defined( macintosh )
692     freopen ("stdout.txt", "w", stdout );
693     freopen ("stderr.txt", "w", stderr );
694     argc = ccommand( &argv );
695 #endif
696
697     // set default log levels
698     sglog().setLogLevels( SG_ALL, SG_ALERT );
699
700     string version;
701 #ifdef FLIGHTGEAR_VERSION
702     version = FLIGHTGEAR_VERSION;
703 #else
704     version = "unknown version";
705 #endif
706     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
707             << version );
708     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
709
710     // Allocate global data structures.  This needs to happen before
711     // we parse command line options
712
713     globals = new FGGlobals;
714
715     // seed the random number generater
716     sg_srandom_time();
717
718     FGControls *controls = new FGControls;
719     globals->set_controls( controls );
720
721     string_list *col = new string_list;
722     globals->set_channel_options_list( col );
723
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);
727
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
733
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;
739 #ifdef _MSC_VER
740         cerr << "Hit a key to continue..." << endl;
741         cin.get();
742 #endif
743         exit(-1);
744     }
745
746     sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
747
748     // Initialize the Aircraft directory to "" (UIUC)
749     aircraft_dir = "";
750
751     // Load the configuration parameters.  (Command line options
752     // overrides config file options.  Config file options override
753     // defaults.)
754     if ( !fgInitConfig(argc, argv) ) {
755         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
756         exit(-1);
757     }
758
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);
765     _bootstrap_OSInit++;
766 #endif
767
768     fgRegisterWindowResizeHandler( &FGRenderer::resize );
769     fgRegisterIdleHandler( &fgIdleFunction );
770     fgRegisterDrawHandler( &FGRenderer::update );
771
772 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
773     bool get_stencil_buffer = true;
774 #else
775     bool get_stencil_buffer = false;
776 #endif
777
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"),
784                     get_stencil_buffer,
785                     fgGetBool("/sim/startup/fullscreen") );
786
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() );
794
795     GLint tmp;
796     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
797     general.set_glMaxTexSize( tmp );
798     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
799
800     glGetIntegerv( GL_DEPTH_BITS, &tmp );
801     general.set_glDepthBits( tmp );
802     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
803
804     // Initialize plib net interface
805     netInit( &argc, argv );
806
807     // Initialize ssg (from plib).  Needs to come before we do any
808     // other ssg stuff, but after opengl has been initialized.
809     ssgInit();
810
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 !!!
814     guiInit();
815
816     // Read the list of available aircrafts
817     fgReadAircraft();
818
819 #ifdef GL_EXT_texture_lod_bias
820     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
821 #endif
822
823             // get the address of our OpenGL extensions
824     if ( fgGetBool("/sim/rendering/distance-attenuation") )
825     {
826         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
827             glPointParameterIsSupported = true;
828             glPointParameterfPtr = (glPointParameterfProc)
829                                    SGLookupFunction("glPointParameterfEXT");
830             glPointParameterfvPtr = (glPointParameterfvProc)
831                                     SGLookupFunction("glPointParameterfvEXT");
832
833         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
834             glPointParameterIsSupported = true;
835             glPointParameterfPtr = (glPointParameterfProc)
836                                    SGLookupFunction("glPointParameterfARB");
837             glPointParameterfvPtr = (glPointParameterfvProc)
838                                     SGLookupFunction("glPointParameterfvARB");
839         } else
840             glPointParameterIsSupported = false;
841    }
842
843     // based on the requested presets, calculate the true starting
844     // lon, lat
845     fgInitNav();
846     fgInitPosition();
847
848     SGTime *t = fgInitTime();
849     globals->set_time_params( t );
850
851     // Do some quick general initializations
852     if( !fgInitGeneral()) {
853         SG_LOG( SG_GENERAL, SG_ALERT, 
854             "General initializations failed ..." );
855         exit(-1);
856     }
857
858     ////////////////////////////////////////////////////////////////////
859     // Initialize the property-based built-in commands
860     ////////////////////////////////////////////////////////////////////
861     fgInitCommands();
862
863     ////////////////////////////////////////////////////////////////////
864     // Initialize the material manager
865     ////////////////////////////////////////////////////////////////////
866     globals->set_matlib( new SGMaterialLib );
867
868     globals->set_model_lib(new SGModelLib);
869
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 );
877
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();
884
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();
892
893     ////////////////////////////////////////////////////////////////////
894     // Initialize the view manager subsystem.
895     ////////////////////////////////////////////////////////////////////
896     FGViewMgr *viewmgr = new FGViewMgr;
897     globals->set_viewmgr( viewmgr );
898     viewmgr->init();
899     viewmgr->bind();
900
901
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(),
908                    0.0 );
909     globals->set_ephem( ephem );
910
911     // TODO: move to environment mgr
912     thesky = new SGSky;
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);
919     }
920
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() );
925
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,
932                    463.3, 361.8,
933                    globals->get_ephem()->getNumPlanets(), 
934                    globals->get_ephem()->getPlanets(),
935                    globals->get_ephem()->getNumStars(),
936                    globals->get_ephem()->getStars() );
937
938     // Initialize MagVar model
939     SGMagVar *magvar = new SGMagVar();
940     globals->set_mag( magvar );
941
942
943                                 // kludge to initialize mag compass
944                                 // (should only be done for in-flight
945                                 // startup)
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")
952                                 * SG_FEET_TO_METER,
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);
956
957     // airport = new ssgBranch;
958     // airport->setName( "Airport Lighting" );
959     // lighting->addKid( airport );
960
961     // build our custom render states
962     globals->get_renderer()->build_states();
963
964     // pass control off to the master event handler
965     fgOSMainLoop();
966
967     // we never actually get here ... but to avoid compiler warnings,
968     // etc.
969     return false;
970 }
971
972
973 // end of main.cxx