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