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