]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
65c52b1e356f41a887ede947cb63ab025b6b578c
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
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 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #ifdef HAVE_WINDOWS_H
35 #  include <windows.h>
36 #endif
37
38 #include <GL/glut.h>
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>             // strcmp()
43
44
45 #if defined( unix ) || defined( __CYGWIN__ )
46 #  include <unistd.h>           // for gethostname()
47 #endif
48
49 // work around a stdc++ lib bug in some versions of linux, but doesn't
50 // seem to hurt to have this here for all versions of Linux.
51 #ifdef linux
52 #  define _G_NO_EXTERN_TEMPLATES
53 #endif
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/exception.hxx>
57
58 #include STL_STRING
59
60 #include <simgear/constants.h>
61 #include <simgear/debug/logstream.hxx>
62 #include <simgear/math/point3d.hxx>
63 #include <simgear/math/polar3d.hxx>
64 #include <simgear/math/sg_geodesy.hxx>
65 #include <simgear/misc/sg_path.hxx>
66 #include <simgear/sky/clouds3d/SkySceneLoader.hpp>
67 #include <simgear/sky/clouds3d/SkyUtil.hpp>
68 #include <simgear/timing/sg_time.hxx>
69 #include <simgear/timing/lowleveltime.h>
70
71 #include <Aircraft/aircraft.hxx>
72 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
73 #include <Airports/runways.hxx>
74 #include <Airports/simple.hxx>
75 #include <ATC/ATCdisplay.hxx>
76 #include <ATC/ATCmgr.hxx>
77 #include <ATC/atislist.hxx>
78 #include <ATC/towerlist.hxx>
79 #include <ATC/approachlist.hxx>
80 #include <ATC/AIMgr.hxx>
81 #include <Autopilot/auto_gui.hxx>
82 #include <Autopilot/newauto.hxx>
83 #include <Cockpit/cockpit.hxx>
84 #include <Cockpit/radiostack.hxx>
85 #include <Cockpit/steam.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
88 #include <FDM/ADA.hxx>
89 #include <FDM/Balloon.h>
90 #include <FDM/ExternalNet/ExternalNet.hxx>
91 #include <FDM/JSBSim/JSBSim.hxx>
92 #include <FDM/LaRCsim.hxx>
93 #include <FDM/MagicCarpet.hxx>
94 #include <FDM/UFO.hxx>
95 #include <FDM/NullFDM.hxx>
96 #include <FDM/YASim/YASim.hxx>
97 #include <Include/general.hxx>
98 #include <Input/input.hxx>
99 #include <Instrumentation/instrument_mgr.hxx>
100 // #include <Joystick/joystick.hxx>
101 #include <Objects/matlib.hxx>
102 #include <Model/acmodel.hxx>
103 #include <Navaids/fixlist.hxx>
104 #include <Navaids/ilslist.hxx>
105 #include <Navaids/mkrbeacons.hxx>
106 #include <Navaids/navlist.hxx>
107 #include <Scenery/scenery.hxx>
108 #include <Scenery/tilemgr.hxx>
109 #include <Sound/fg_fx.hxx>
110 #include <Sound/soundmgr.hxx>
111 #include <Systems/system_mgr.hxx>
112 #include <Time/FGEventMgr.hxx>
113 #include <Time/light.hxx>
114 #include <Time/sunpos.hxx>
115 #include <Time/moonpos.hxx>
116 #include <Time/tmp.hxx>
117
118 #ifdef FG_WEATHERCM
119 #  include <WeatherCM/FGLocalWeatherDatabase.h>
120 #else
121 #  include <Environment/environment_mgr.hxx>
122 #endif
123
124 #include "fg_init.hxx"
125 #include "fg_io.hxx"
126 #include "fg_commands.hxx"
127 #include "fg_props.hxx"
128 #include "options.hxx"
129 #include "globals.hxx"
130 #include "logger.hxx"
131 #include "viewmgr.hxx"
132
133 #if defined(FX) && defined(XMESA)
134 #include <GL/xmesa.h>
135 #endif
136
137 SG_USING_STD(string);
138
139 extern const char *default_root;
140
141 SkySceneLoader *sgCloud3d;
142
143 // Read in configuration (file and command line) and just set fg_root
144 bool fgInitFGRoot ( int argc, char **argv ) {
145     string root;
146     char* envp;
147
148     // First parse command line options looking for fg-root, this will
149     // override anything specified in a config file
150     root = fgScanForRoot(argc, argv);
151
152 #if defined( unix ) || defined( __CYGWIN__ )
153     // Next check home directory for .fgfsrc.hostname file
154     if ( root.empty() ) {
155         envp = ::getenv( "HOME" );
156         if ( envp != NULL ) {
157             SGPath config( envp );
158             config.append( ".fgfsrc" );
159             char name[256];
160             gethostname( name, 256 );
161             config.concat( "." );
162             config.concat( name );
163             root = fgScanForRoot(config.str());
164         }
165     }
166 #endif
167
168     // Next check home directory for .fgfsrc file
169     if ( root.empty() ) {
170         envp = ::getenv( "HOME" );
171         if ( envp != NULL ) {
172             SGPath config( envp );
173             config.append( ".fgfsrc" );
174             root = fgScanForRoot(config.str());
175         }
176     }
177     
178     // Next check if fg-root is set as an env variable
179     if ( root.empty() ) {
180         envp = ::getenv( "FG_ROOT" );
181         if ( envp != NULL ) {
182             root = envp;
183         }
184     }
185
186     // Otherwise, default to a random compiled-in location if we can't
187     // find fg-root any other way.
188     if ( root.empty() ) {
189 #if defined( __CYGWIN__ )
190         root = "/FlightGear";
191 #elif defined( WIN32 )
192         root = "\\FlightGear";
193 #elif defined( macintosh )
194         root = "";
195 #else
196         root = PKGLIBDIR;
197 #endif
198     }
199
200     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
201     globals->set_fg_root(root);
202
203     return true;
204 }
205
206
207 // Return the current base package version
208 string fgBasePackageVersion() {
209     SGPath base_path( globals->get_fg_root() );
210     base_path.append("version");
211
212     sg_gzifstream in( base_path.str() );
213     if ( !in.is_open() ) {
214         SGPath old_path( globals->get_fg_root() );
215         old_path.append( "Thanks" );
216         sg_gzifstream old( old_path.str() );
217         if ( !old.is_open() ) {
218             return "[none]";
219         } else {
220             return "[old version]";
221         }
222     }
223
224     string version;
225     in >> version;
226
227     return version;
228 }
229
230
231 // Initialize the localization
232 SGPropertyNode *fgInitLocale(const char *language) {
233    SGPropertyNode *c_node = NULL, *d_node = NULL;
234    SGPropertyNode *intl = fgGetNode("/sim/intl");
235
236    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
237
238    // localization not defined
239    if (!intl)
240       return NULL;
241
242    //
243    // Select the proper language from the list
244    //
245    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
246    for (unsigned int i = 0; i < locale.size(); i++) {
247
248       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
249       for (unsigned int j = 0; j < lang.size(); j++) {
250
251          if (!strcmp(lang[j]->getStringValue(), language)) {
252             c_node = locale[i];
253             break;
254          }
255       }
256    }
257
258
259    // Get the defaults
260    d_node = intl->getChild("locale");
261    if (!c_node)
262       c_node = d_node;
263
264    // Check for localized font
265    SGPropertyNode *font_n = c_node->getNode("font", true);
266    if ( !strcmp(font_n->getStringValue(), "") )
267       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
268
269
270    //
271    // Load the default strings
272    //
273    SGPath d_path( globals->get_fg_root() );
274
275    const char *d_path_str = d_node->getStringValue("strings");
276    if (!d_path_str) {
277       SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
278       return NULL;
279    }
280
281    d_path.append(d_path_str);
282    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
283                                   << d_path.str());
284
285    SGPropertyNode *strings = c_node->getNode("strings");
286    try {
287       readProperties(d_path.str(), strings);
288    } catch (const sg_exception &e) {
289       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
290       return NULL;
291    }
292
293    //
294    // Load the language specific strings
295    //
296    if (c_node != d_node) {
297       SGPath c_path( globals->get_fg_root() );
298
299       const char *c_path_str = c_node->getStringValue("strings");
300       if (!c_path_str) {
301          SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
302          return NULL;
303       }
304
305       c_path.append(c_path_str);
306       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
307                                      << c_path.str());
308
309       try {
310          readProperties(c_path.str(), strings);
311       } catch (const sg_exception &e) {
312          SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
313          return NULL;
314       }
315    }
316
317    return c_node;
318 }
319
320
321
322 // Initialize the localization routines
323 bool fgDetectLanguage() {
324     char *language = ::getenv("LANG");
325
326     if (language == NULL) {
327         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
328         language = "C";
329     }
330
331     SGPropertyNode *locale = fgInitLocale(language);
332     if (!locale) {
333        cerr << "No internationalization settings specified in preferences.xml"
334             << endl;
335
336        return false;
337     }
338
339     globals->set_locale( locale );
340
341     return true;
342 }
343
344 // Attempt to locate and parse the various non-XML config files in order
345 // from least precidence to greatest precidence
346 static void
347 do_options (int argc, char ** argv)
348 {
349     // Check for $fg_root/system.fgfsrc
350     SGPath config( globals->get_fg_root() );
351     config.append( "system.fgfsrc" );
352     fgParseOptions(config.str());
353
354 #if defined( unix ) || defined( __CYGWIN__ )
355     char name[256];
356     // Check for $fg_root/system.fgfsrc.hostname
357     gethostname( name, 256 );
358     config.concat( "." );
359     config.concat( name );
360     fgParseOptions(config.str());
361 #endif
362
363     // Check for ~/.fgfsrc
364     char* envp = ::getenv( "HOME" );
365     if ( envp != NULL ) {
366         config.set( envp );
367         config.append( ".fgfsrc" );
368         fgParseOptions(config.str());
369     }
370
371 #if defined( unix ) || defined( __CYGWIN__ )
372     // Check for ~/.fgfsrc.hostname
373     gethostname( name, 256 );
374     config.concat( "." );
375     config.concat( name );
376     fgParseOptions(config.str());
377 #endif
378
379     // Parse remaining command line options
380     // These will override anything specified in a config file
381     fgParseArgs(argc, argv);
382 }
383
384
385 // Read in configuration (file and command line)
386 bool fgInitConfig ( int argc, char **argv ) {
387
388                                 // First, set some sane default values
389     fgSetDefaults();
390
391     // Read global preferences from $FG_ROOT/preferences.xml
392     SGPath props_path(globals->get_fg_root());
393     props_path.append("preferences.xml");
394     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
395     readProperties(props_path.str(), globals->get_props());
396     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
397
398     // Detect the required language as early as possible
399     if (fgDetectLanguage() != true)
400        return false;
401
402     // Read the default aircraft config file.
403     do_options(argc, argv);     // preparse options for default aircraft
404     string aircraft = fgGetString("/sim/aircraft", "");
405     if (aircraft.size() > 0) {
406       SGPath aircraft_path(globals->get_fg_root());
407       aircraft_path.append("Aircraft");
408       aircraft_path.append(aircraft);
409       aircraft_path.concat("-set.xml");
410       SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
411              << " from " << aircraft_path.str());
412       try {
413         readProperties(aircraft_path.str(), globals->get_props());
414       } catch (const sg_exception &e) {
415         string message = "Error reading default aircraft: ";
416         message += e.getFormattedMessage();
417         SG_LOG(SG_INPUT, SG_ALERT, message);
418         exit(2);
419       }
420     } else {
421       SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
422     }
423
424     do_options(argc, argv);
425
426     return true;
427 }
428
429
430 // find basic airport location info from airport database
431 bool fgFindAirportID( const string& id, FGAirport *a ) {
432     if ( id.length() ) {
433         SGPath path( globals->get_fg_root() );
434         path.append( "Airports" );
435         path.append( "simple.mk4" );
436         FGAirports airports( path.c_str() );
437
438         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
439
440         if ( ! airports.search( id, a ) ) {
441             SG_LOG( SG_GENERAL, SG_ALERT,
442                     "Failed to find " << id << " in " << path.str() );
443             return false;
444         }
445     } else {
446         return false;
447     }
448
449     SG_LOG( SG_GENERAL, SG_INFO,
450             "Position for " << id << " is ("
451             << a->longitude << ", "
452             << a->latitude << ")" );
453
454     return true;
455 }
456
457
458 // Set current_options lon/lat given an airport id
459 bool fgSetPosFromAirportID( const string& id ) {
460     FGAirport a;
461     // double lon, lat;
462
463     SG_LOG( SG_GENERAL, SG_INFO,
464             "Attempting to set starting position from airport code " << id );
465
466     if ( fgFindAirportID( id, &a ) ) {
467         fgSetDouble("/position/longitude-deg",  a.longitude );
468         fgSetDouble("/position/latitude-deg",  a.latitude );
469         SG_LOG( SG_GENERAL, SG_INFO,
470                 "Position for " << id << " is ("
471                 << a.longitude << ", "
472                 << a.latitude << ")" );
473
474         return true;
475     } else {
476         return false;
477     }
478
479 }
480
481
482
483 // Set current tower position lon/lat given an airport id
484 bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
485     FGAirport a;
486     // tower height hard coded for now...
487     float towerheight=50.0f;
488
489     // make a little off the heading for 1 runway airports...
490     float fudge_lon = fabs(sin(hdg)) * .003f;
491     float fudge_lat = .003f - fudge_lon;
492
493     if ( fgFindAirportID( id, &a ) ) {
494         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
495         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
496         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
497         return true;
498     } else {
499         return false;
500     }
501
502 }
503
504
505 // Set current_options lon/lat given an airport id and heading (degrees)
506 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
507     FGRunway r;
508     FGRunway found_r;
509     double found_dir = 0.0;
510
511     if ( id.length() ) {
512         // set initial position from runway and heading
513
514         SGPath path( globals->get_fg_root() );
515         path.append( "Airports" );
516         path.append( "runways.mk4" );
517         FGRunways runways( path.c_str() );
518
519         SG_LOG( SG_GENERAL, SG_INFO,
520                 "Attempting to set starting position from runway code "
521                 << id << " heading " << tgt_hdg );
522
523         // SGPath inpath( globals->get_fg_root() );
524         // inpath.append( "Airports" );
525         // inpath.append( "apt_simple" );
526         // airports.load( inpath.c_str() );
527
528         // SGPath outpath( globals->get_fg_root() );
529         // outpath.append( "Airports" );
530         // outpath.append( "simple.gdbm" );
531         // airports.dump_gdbm( outpath.c_str() );
532
533         if ( ! runways.search( id, &r ) ) {
534             SG_LOG( SG_GENERAL, SG_ALERT,
535                     "Failed to find " << id << " in database." );
536             return false;
537         }
538
539         double diff;
540         double min_diff = 360.0;
541
542         while ( r.id == id ) {
543             // forward direction
544             diff = tgt_hdg - r.heading;
545             while ( diff < -180.0 ) { diff += 360.0; }
546             while ( diff >  180.0 ) { diff -= 360.0; }
547             diff = fabs(diff);
548             SG_LOG( SG_GENERAL, SG_INFO,
549                     "Runway " << r.rwy_no << " heading = " << r.heading <<
550                     " diff = " << diff );
551             if ( diff < min_diff ) {
552                 min_diff = diff;
553                 found_r = r;
554                 found_dir = 0;
555             }
556
557             // reverse direction
558             diff = tgt_hdg - r.heading - 180.0;
559             while ( diff < -180.0 ) { diff += 360.0; }
560             while ( diff >  180.0 ) { diff -= 360.0; }
561             diff = fabs(diff);
562             SG_LOG( SG_GENERAL, SG_INFO,
563                     "Runway -" << r.rwy_no << " heading = " <<
564                     r.heading + 180.0 <<
565                     " diff = " << diff );
566             if ( diff < min_diff ) {
567                 min_diff = diff;
568                 found_r = r;
569                 found_dir = 180.0;
570             }
571
572             runways.next( &r );
573         }
574
575         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
576                 << " + " << found_dir );
577
578     } else {
579         return false;
580     }
581
582     double heading = found_r.heading + found_dir;
583     while ( heading >= 360.0 ) { heading -= 360.0; }
584
585     double lat2, lon2, az2;
586     double azimuth = found_r.heading + found_dir + 180.0;
587     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
588
589     SG_LOG( SG_GENERAL, SG_INFO,
590             "runway =  " << found_r.lon << ", " << found_r.lat
591             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
592             << " heading = " << azimuth );
593     
594     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
595                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
596                         &lat2, &lon2, &az2 );
597
598     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > SG_EPSILON ) {
599         double olat, olon;
600         double odist = fgGetDouble("/sim/startup/offset-distance");
601         odist *= SG_NM_TO_METER;
602         double oaz = azimuth;
603         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > SG_EPSILON ) {
604             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
605         }
606         while ( oaz >= 360.0 ) { oaz -= 360.0; }
607         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
608         lat2=olat;
609         lon2=olon;
610     }
611         
612     fgSetDouble("/position/longitude-deg",  lon2 );
613     fgSetDouble("/position/latitude-deg",  lat2 );
614     fgSetDouble("/orientation/heading-deg", heading );
615
616     SG_LOG( SG_GENERAL, SG_INFO,
617             "Position for " << id << " is ("
618             << lon2 << ", "
619             << lat2 << ") new heading is "
620             << heading );
621
622     return true;
623 }
624
625
626 void fgSetPosFromGlideSlope(void) {
627     double gs = fgGetDouble("/velocities/glideslope");
628     double od = fgGetDouble("/sim/startup/offset-distance");
629     double alt = fgGetDouble("/position/altitude-ft");
630     
631     //if glideslope and offset-distance are set and altitude is
632     //not, calculate the initial altitude
633     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
634         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
635         alt = fabs(od*tan(gs));
636         fgSetDouble("/position/altitude-ft",alt);
637         fgSetBool("/sim/startup/onground", false);
638         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
639     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
640         od  = alt/tan(gs);
641         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
642         fgSetDouble("/sim/startup/offset-distance",od);
643         SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
644                                        << od  << " nm");
645     } else if( fabs(gs) > 0.01 ) {
646         SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
647                                   << " or offset-distance.  Resetting"
648                                   << " glideslope to zero" );
649         fgSetDouble("/velocities/glideslope",0);                                  
650     }                              
651                                       
652 }                       
653
654 // General house keeping initializations
655 bool fgInitGeneral( void ) {
656     string root;
657
658 #if defined(FX) && defined(XMESA)
659     char *mesa_win_state;
660 #endif
661
662     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
663     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
664
665     root = globals->get_fg_root();
666     if ( ! root.length() ) {
667         // No root path set? Then bail ...
668         SG_LOG( SG_GENERAL, SG_ALERT,
669                 "Cannot continue without a path to the base package "
670                 << "being defined." );
671         exit(-1);
672     }
673     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
674
675 #if defined(FX) && defined(XMESA)
676     // initialize full screen flag
677     globals->set_fullscreen(false);
678     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
679         // Test for the MESA_GLX_FX env variable
680         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
681             // test if we are fullscreen mesa/glide
682             if ( (mesa_win_state[0] == 'f') ||
683                  (mesa_win_state[0] == 'F') ) {
684                 globals->set_fullscreen(true);
685             }
686         }
687     }
688 #endif
689
690     return true;
691 }
692
693
694 // Initialize the flight model subsystem.  This just creates the
695 // object.  The actual fdm initialization is delayed until we get a
696 // proper scenery elevation hit.  This is checked for in main.cxx
697
698 void fgInitFDM() {
699
700     if ( cur_fdm_state ) {
701         delete cur_fdm_state;
702         cur_fdm_state = 0;
703     }
704
705     double dt = 1.0 / fgGetInt("/sim/model-hz");
706     aircraft_dir = fgGetString("/sim/aircraft-dir");
707     const string &model = fgGetString("/sim/flight-model");
708
709     try {
710         if ( model == "larcsim" ) {
711             cur_fdm_state = new FGLaRCsim( dt );
712         } else if ( model == "jsb" ) {
713             cur_fdm_state = new FGJSBsim( dt );
714         } else if ( model == "ada" ) {
715             cur_fdm_state = new FGADA( dt );
716         } else if ( model == "balloon" ) {
717             cur_fdm_state = new FGBalloonSim( dt );
718         } else if ( model == "magic" ) {
719             cur_fdm_state = new FGMagicCarpet( dt );
720         } else if ( model == "ufo" ) {
721             cur_fdm_state = new FGUFO( dt );
722         } else if ( model == "external" ) {
723             // external is a synonym for "--fdm=null" and is
724             // maintained here for backwards compatibility
725             cur_fdm_state = new FGNullFDM( dt );
726         } else if ( model.find("network") == 0 ) {
727             string host = "localhost";
728             int port1 = 5501;
729             int port2 = 5502;
730             int port3 = 5503;
731             string net_options = model.substr(8);
732             string::size_type begin, end;
733             begin = 0;
734             // host
735             end = net_options.find( ",", begin );
736             if ( end != string::npos ) {
737                 host = net_options.substr(begin, end - begin);
738                 begin = end + 1;
739             }
740             // port1
741             end = net_options.find( ",", begin );
742             if ( end != string::npos ) {
743                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
744                 begin = end + 1;
745             }
746             // port2
747             end = net_options.find( ",", begin );
748             if ( end != string::npos ) {
749                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
750                 begin = end + 1;
751             }
752             // port3
753             end = net_options.find( ",", begin );
754             if ( end != string::npos ) {
755                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
756                 begin = end + 1;
757             }
758             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
759         } else if ( model == "null" ) {
760             cur_fdm_state = new FGNullFDM( dt );
761         } else if ( model == "yasim" ) {
762             cur_fdm_state = new YASim( dt );
763         } else {
764             SG_LOG(SG_GENERAL, SG_ALERT,
765                    "Unrecognized flight model '" << model
766                    << "', cannot init flight dynamics model.");
767             exit(-1);
768         }
769     } catch ( ... ) {
770         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
771         exit(-1);
772     }
773 }
774
775 static void printMat(const sgVec4 *mat, char *name="")
776 {
777     int i;
778     cout << name << endl;
779     for(i=0; i<4; i++) {
780         cout <<"  "<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<" "<<mat[i][3]<<endl;
781     }
782     cout << endl;
783 }
784
785 // Initialize view parameters
786 void fgInitView() {
787   // force update of model so that viewer can get some data...
788   globals->get_aircraft_model()->update(0);
789   // run update for current view so that data is current...
790   globals->get_viewmgr()->update(0);
791
792   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
793   printMat(globals->get_current_view()->get_UP(),"UP");
794   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
795   
796 }
797
798
799 SGTime *fgInitTime() {
800     // Initialize time
801     static const SGPropertyNode *longitude
802         = fgGetNode("/position/longitude-deg");
803     static const SGPropertyNode *latitude
804         = fgGetNode("/position/latitude-deg");
805     static const SGPropertyNode *cur_time_override
806         = fgGetNode("/sim/time/cur-time-override", true);
807
808     SGPath zone( globals->get_fg_root() );
809     zone.append( "Timezone" );
810     SGTime *t = new SGTime( longitude->getDoubleValue()
811                               * SGD_DEGREES_TO_RADIANS,
812                             latitude->getDoubleValue()
813                               * SGD_DEGREES_TO_RADIANS,
814                             zone.str(),
815                             cur_time_override->getLongValue() );
816
817     // Handle potential user specified time offsets
818     time_t cur_time = t->get_cur_time();
819     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
820     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
821     time_t aircraftLocalTime = 
822         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
823
824     // Okay, we now have six possible scenarios
825     int offset = fgGetInt("/sim/startup/time-offset");
826     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
827     if (offset_type == "system-offset") {
828         globals->set_warp( offset );
829     } else if (offset_type == "gmt-offset") {
830         globals->set_warp( offset - (currGMT - systemLocalTime) );
831     } else if (offset_type == "latitude-offset") {
832         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
833     } else if (offset_type == "system") {
834         globals->set_warp( offset - cur_time );
835     } else if (offset_type == "gmt") {
836         globals->set_warp( offset - currGMT );
837     } else if (offset_type == "latitude") {
838         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
839                            cur_time ); 
840     } else {
841         SG_LOG( SG_GENERAL, SG_ALERT,
842                 "FG_TIME::Unsupported offset type " << offset_type );
843         exit( -1 );
844     }
845
846     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
847             << globals->get_warp() );
848
849     globals->set_warp_delta( 0 );
850
851     t->update( 0.0, 0.0,
852                cur_time_override->getLongValue(),
853                globals->get_warp() );
854
855     return t;
856 }
857
858
859 // This is the top level init routine which calls all the other
860 // initialization routines.  If you are adding a subsystem to flight
861 // gear, its initialization call should located in this routine.
862 // Returns non-zero if a problem encountered.
863 bool fgInitSubsystems( void ) {
864     static const SGPropertyNode *longitude
865         = fgGetNode("/position/longitude-deg");
866     static const SGPropertyNode *latitude
867         = fgGetNode("/position/latitude-deg");
868     static const SGPropertyNode *altitude
869         = fgGetNode("/position/altitude-ft");
870
871     fgLIGHT *l = &cur_light_params;
872
873     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
874     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
875
876
877     ////////////////////////////////////////////////////////////////////
878     // Initialize the material property subsystem.
879     ////////////////////////////////////////////////////////////////////
880
881     SGPath mpath( globals->get_fg_root() );
882     mpath.append( "materials.xml" );
883     if ( ! material_lib.load( mpath.str() ) ) {
884         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
885         exit(-1);
886     }
887
888     ////////////////////////////////////////////////////////////////////
889     // Initialize the event manager subsystem.
890     ////////////////////////////////////////////////////////////////////
891
892     global_events.init();
893
894     // Output event stats every 60 seconds
895     global_events.Register( "FGEventMgr::print_stats()",
896                             &global_events, &FGEventMgr::print_stats,
897                             60000 );
898
899
900     ////////////////////////////////////////////////////////////////////
901     // Initialize the scenery management subsystem.
902     ////////////////////////////////////////////////////////////////////
903
904     if ( global_tile_mgr.init() ) {
905         // Load the local scenery data
906         double visibility_meters = fgGetDouble("/environment/visibility-m");
907                 
908         global_tile_mgr.update( longitude->getDoubleValue(),
909                                 latitude->getDoubleValue(),
910                                 visibility_meters );
911     } else {
912         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
913         exit(-1);
914     }
915
916     // cause refresh of viewer scenery timestamps every 15 seconds...
917     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
918                             &global_tile_mgr, &FGTileMgr::refresh_view_timestamps,
919                             15000 );
920
921     SG_LOG( SG_GENERAL, SG_DEBUG,
922             "Current terrain elevation after tile mgr init " <<
923             globals->get_scenery()->get_cur_elev() );
924
925
926     ////////////////////////////////////////////////////////////////////
927     // Initialize the flight model subsystem.
928     ////////////////////////////////////////////////////////////////////
929
930     fgInitFDM();
931         
932     // allocates structures so must happen before any of the flight
933     // model or control parameters are set
934     fgAircraftInit();   // In the future this might not be the case.
935
936
937     ////////////////////////////////////////////////////////////////////
938     // Initialize the view manager subsystem.
939     ////////////////////////////////////////////////////////////////////
940
941     fgInitView();
942
943
944     ////////////////////////////////////////////////////////////////////
945     // Initialize the lighting subsystem.
946     ////////////////////////////////////////////////////////////////////
947
948     // fgUpdateSunPos() needs a few position and view parameters set
949     // so it can calculate local relative sun angle and a few other
950     // things for correctly orienting the sky.
951     fgUpdateSunPos();
952     fgUpdateMoonPos();
953     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
954                             60000);
955     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
956                             60000);
957
958     // Initialize Lighting interpolation tables
959     l->Init();
960
961     // force one lighting update to make it right to start with...
962     l->Update();
963     // update the lighting parameters (based on sun angle)
964     global_events.Register( "fgLight::Update()",
965                             &cur_light_params, &fgLIGHT::Update,
966                             30000 );
967
968
969     ////////////////////////////////////////////////////////////////////
970     // Initialize the logger.
971     ////////////////////////////////////////////////////////////////////
972     
973     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
974                                       "logger",
975                                       new FGLogger);
976
977
978     ////////////////////////////////////////////////////////////////////
979     // Initialize the local time subsystem.
980     ////////////////////////////////////////////////////////////////////
981
982     // update the current timezone each 30 minutes
983     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
984                             30*60*1000 );
985
986
987     ////////////////////////////////////////////////////////////////////
988     // Initialize the weather subsystem.
989     ////////////////////////////////////////////////////////////////////
990
991     // Initialize the weather modeling subsystem
992 #ifdef FG_WEATHERCM
993     // Initialize the WeatherDatabase
994     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
995     sgVec3 position;
996     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
997                current_aircraft.fdm_state->get_Longitude(),
998                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
999     double init_vis = fgGetDouble("/environment/visibility-m");
1000
1001     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1002
1003     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1004     {
1005       working_type = FGLocalWeatherDatabase::use_internet;
1006     } else {
1007       working_type = FGLocalWeatherDatabase::default_mode;
1008     }
1009     
1010     if ( init_vis > 0 ) {
1011       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1012         new FGLocalWeatherDatabase( position,
1013                                     globals->get_fg_root(),
1014                                     working_type,
1015                                     init_vis );
1016     } else {
1017       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1018         new FGLocalWeatherDatabase( position,
1019                                     globals->get_fg_root(),
1020                                     working_type );
1021     }
1022
1023     // cout << theFGLocalWeatherDatabase << endl;
1024     // cout << "visibility = " 
1025     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1026
1027     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1028
1029     // register the periodic update of the weather
1030     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1031                             30000);
1032 #else
1033     globals->get_environment_mgr()->init();
1034     globals->get_environment_mgr()->bind();
1035 #endif
1036
1037     ////////////////////////////////////////////////////////////////////
1038     // Initialize the 3D cloud subsystem.
1039     ////////////////////////////////////////////////////////////////////
1040     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1041         SGPath cloud_path(globals->get_fg_root());
1042         cloud_path.append("large.sky");
1043         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1044         if ( !sgCloud3d->Load( cloud_path.str(),
1045                                latitude->getDoubleValue(),
1046                                longitude->getDoubleValue()) )
1047         {
1048             fgSetBool("/sim/rendering/clouds3d", false);
1049             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1050         }
1051         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1052     }
1053
1054     ////////////////////////////////////////////////////////////////////
1055     // Initialize vor/ndb/ils/fix list management and query systems
1056     ////////////////////////////////////////////////////////////////////
1057
1058     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
1059
1060     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
1061     current_navlist = new FGNavList;
1062     SGPath p_nav( globals->get_fg_root() );
1063     p_nav.append( "Navaids/default.nav" );
1064     current_navlist->init( p_nav );
1065
1066     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
1067     current_beacons = new FGMarkerBeacons;
1068     current_beacons->init();
1069     current_ilslist = new FGILSList;
1070     SGPath p_ils( globals->get_fg_root() );
1071     p_ils.append( "Navaids/default.ils" );
1072     current_ilslist->init( p_ils );
1073
1074     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1075     current_fixlist = new FGFixList;
1076     SGPath p_fix( globals->get_fg_root() );
1077     p_fix.append( "Navaids/default.fix" );
1078     current_fixlist->init( p_fix );
1079
1080     ////////////////////////////////////////////////////////////////////
1081     // Initialize ATC list management and query systems
1082     ////////////////////////////////////////////////////////////////////
1083
1084     SG_LOG(SG_GENERAL, SG_INFO, "  ATIS");
1085     current_atislist = new FGATISList;
1086     SGPath p_atis( globals->get_fg_root() );
1087     p_atis.append( "ATC/default.atis" );
1088     current_atislist->init( p_atis );
1089
1090     SG_LOG(SG_GENERAL, SG_INFO, "  Tower");
1091     current_towerlist = new FGTowerList;
1092     SGPath p_tower( globals->get_fg_root() );
1093     p_tower.append( "ATC/default.tower" );
1094     current_towerlist->init( p_tower );
1095
1096     SG_LOG(SG_GENERAL, SG_INFO, "  Approach");
1097     current_approachlist = new FGApproachList;
1098     SGPath p_approach( globals->get_fg_root() );
1099     p_approach.append( "ATC/default.approach" );
1100     current_approachlist->init( p_approach );
1101
1102     ////////////////////////////////////////////////////////////////////
1103     // Initialise ATC display system
1104     ////////////////////////////////////////////////////////////////////
1105
1106     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1107     globals->set_ATC_display(new FGATCDisplay);
1108     globals->get_ATC_display()->init(); 
1109
1110     ////////////////////////////////////////////////////////////////////
1111     // Initialise the ATC Manager 
1112     ////////////////////////////////////////////////////////////////////
1113
1114     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1115     globals->set_ATC_mgr(new FGATCMgr);
1116     globals->get_ATC_mgr()->init(); 
1117     
1118     ////////////////////////////////////////////////////////////////////
1119     // Initialise the AI Manager 
1120     ////////////////////////////////////////////////////////////////////
1121
1122     if (fgGetBool("/sim/ai-traffic/enabled")) {
1123         SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1124         globals->set_AI_mgr(new FGAIMgr);
1125         globals->get_AI_mgr()->init();
1126     }
1127
1128     ////////////////////////////////////////////////////////////////////
1129     // Initialize the built-in commands.
1130     ////////////////////////////////////////////////////////////////////
1131     fgInitCommands();
1132
1133
1134 #ifdef ENABLE_AUDIO_SUPPORT
1135     ////////////////////////////////////////////////////////////////////
1136     // Initialize the sound subsystem.
1137     ////////////////////////////////////////////////////////////////////
1138
1139     globals->set_soundmgr(new FGSoundMgr);
1140     globals->get_soundmgr()->init();
1141     globals->get_soundmgr()->bind();
1142
1143
1144     ////////////////////////////////////////////////////////////////////
1145     // Initialize the sound-effects subsystem.
1146     ////////////////////////////////////////////////////////////////////
1147
1148     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1149                                       "fx",
1150                                       new FGFX);
1151     
1152
1153 #endif
1154
1155     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1156                                       "instrumentation",
1157                                       new FGInstrumentMgr);
1158     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1159                                       "systems",
1160                                       new FGSystemMgr);
1161
1162     ////////////////////////////////////////////////////////////////////
1163     // Initialize the radio stack subsystem.
1164     ////////////////////////////////////////////////////////////////////
1165
1166                                 // A textbook example of how FGSubsystem
1167                                 // should work...
1168     current_radiostack = new FGRadioStack;
1169     current_radiostack->init();
1170     current_radiostack->bind();
1171
1172
1173     ////////////////////////////////////////////////////////////////////
1174     // Initialize the cockpit subsystem
1175     ////////////////////////////////////////////////////////////////////
1176
1177     if( fgCockpitInit( &current_aircraft )) {
1178         // Cockpit initialized ok.
1179     } else {
1180         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1181         exit(-1);
1182     }
1183
1184
1185     ////////////////////////////////////////////////////////////////////
1186     // Initialize the autopilot subsystem.
1187     ////////////////////////////////////////////////////////////////////
1188
1189     globals->set_autopilot(new FGAutopilot);
1190     globals->get_autopilot()->init();
1191     globals->get_autopilot()->bind();
1192
1193                                 // FIXME: these should go in the
1194                                 // GUI initialization code, not here.
1195     fgAPAdjustInit();
1196     NewTgtAirportInit();
1197     NewHeadingInit();
1198     NewAltitudeInit();
1199
1200     ////////////////////////////////////////////////////////////////////
1201     // Initialize I/O subsystem.
1202     ////////////////////////////////////////////////////////////////////
1203
1204     globals->get_io()->init();
1205     globals->get_io()->bind();
1206
1207     // Initialize the 2D panel.
1208     string panel_path = fgGetString("/sim/panel/path",
1209                                     "Panels/Default/default.xml");
1210     current_panel = fgReadPanel(panel_path);
1211     if (current_panel == 0) {
1212         SG_LOG( SG_INPUT, SG_ALERT, 
1213                 "Error reading new panel from " << panel_path );
1214     } else {
1215         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1216         current_panel->init();
1217         current_panel->bind();
1218     }
1219
1220     
1221     ////////////////////////////////////////////////////////////////////
1222     // Initialize the default (kludged) properties.
1223     ////////////////////////////////////////////////////////////////////
1224
1225     fgInitProps();
1226
1227
1228     ////////////////////////////////////////////////////////////////////
1229     // Initialize the controls subsystem.
1230     ////////////////////////////////////////////////////////////////////
1231
1232     globals->get_controls()->init();
1233     globals->get_controls()->bind();
1234
1235
1236     ////////////////////////////////////////////////////////////////////
1237     // Initialize the steam subsystem.
1238     ////////////////////////////////////////////////////////////////////
1239
1240     globals->get_steam()->init();
1241     globals->get_steam()->bind();
1242
1243
1244     ////////////////////////////////////////////////////////////////////
1245     // Initialize the input subsystem.
1246     ////////////////////////////////////////////////////////////////////
1247
1248     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1249                                       "input",
1250                                       new FGInput);
1251
1252
1253     ////////////////////////////////////////////////////////////////////
1254     // Bind and initialize subsystems.
1255     ////////////////////////////////////////////////////////////////////
1256
1257     globals->get_subsystem_mgr()->bind();
1258     globals->get_subsystem_mgr()->init();
1259
1260
1261     ////////////////////////////////////////////////////////////////////////
1262     // End of subsystem initialization.
1263     ////////////////////////////////////////////////////////////////////
1264
1265     SG_LOG( SG_GENERAL, SG_INFO, endl);
1266
1267                                 // Save the initial state for future
1268                                 // reference.
1269     globals->saveInitialState();
1270
1271     return true;
1272 }
1273
1274
1275 void fgReInitSubsystems( void )
1276 {
1277     static const SGPropertyNode *longitude
1278         = fgGetNode("/position/longitude-deg");
1279     static const SGPropertyNode *latitude
1280         = fgGetNode("/position/latitude-deg");
1281     static const SGPropertyNode *altitude
1282         = fgGetNode("/position/altitude-ft");
1283     static const SGPropertyNode *master_freeze
1284         = fgGetNode("/sim/freeze/master");
1285
1286     SG_LOG( SG_GENERAL, SG_INFO,
1287             "fgReInitSubsystems(): /position/altitude = "
1288             << altitude->getDoubleValue() );
1289
1290     bool freeze = master_freeze->getBoolValue();
1291     if ( !freeze ) {
1292         fgSetBool("/sim/freeze/master", true);
1293     }
1294     
1295     // Initialize the Scenery Management subsystem
1296     // FIXME, what really needs to get initialized here, at the time
1297     // this was commented out, scenery.init() was a noop
1298     // scenery.init();
1299
1300     fgInitFDM();
1301     
1302     // allocates structures so must happen before any of the flight
1303     // model or control parameters are set
1304     fgAircraftInit();   // In the future this might not be the case.
1305
1306     // copy viewer settings into current-view path
1307     globals->get_viewmgr()->copyToCurrent();
1308
1309     fgInitView();
1310
1311     globals->get_controls()->reset_all();
1312     globals->get_autopilot()->reset();
1313
1314     fgUpdateSunPos();
1315     fgUpdateMoonPos();
1316     cur_light_params.Update();
1317     fgUpdateLocalTime();
1318
1319     if ( !freeze ) {
1320         fgSetBool("/sim/freeze/master", false);
1321     }
1322 }
1323