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