]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
9fb7cee0233257b8a3be48ae59c066d138339990
[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  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 //
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 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>             // strcmp()
37
38
39 #if defined( unix ) || defined( __CYGWIN__ )
40 #  include <unistd.h>           // for gethostname()
41 #endif
42
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
45 #ifdef linux
46 #  define _G_NO_EXTERN_TEMPLATES
47 #endif
48
49 #include <simgear/compiler.h>
50
51 #include STL_STRING
52
53 #include <simgear/constants.h>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/event_mgr.hxx>
57 #include <simgear/math/point3d.hxx>
58 #include <simgear/math/polar3d.hxx>
59 #include <simgear/math/sg_geodesy.hxx>
60 #include <simgear/misc/sg_path.hxx>
61 #include <simgear/misc/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/timing/sg_time.hxx>
64 #include <simgear/timing/lowleveltime.h>
65
66 #include <Aircraft/aircraft.hxx>
67 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
68 #include <Airports/apt_loader.hxx>
69 #include <Airports/runways.hxx>
70 #include <Airports/simple.hxx>
71 #include <AIModel/AIManager.hxx>
72 #include <ATC/ATCdisplay.hxx>
73 #include <ATC/ATCmgr.hxx>
74 #include <ATC/AIMgr.hxx>
75 #include <Autopilot/auto_gui.hxx>
76 #include <Autopilot/route_mgr.hxx>
77 #include <Autopilot/xmlauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
81 #ifdef ENABLE_SP_FMDS
82 #include <FDM/SP/ADA.hxx>
83 #include <FDM/SP/ACMS.hxx>
84 #endif
85 #include <FDM/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/MagicCarpet.hxx>
91 #include <FDM/UFO.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <Include/general.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <AIModel/submodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/navdb.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Replay/replay.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/fg_fx.hxx>
108 #include <Sound/beacon.hxx>
109 #include <Sound/morse.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/sunpos.hxx>
113 #include <Time/sunsolver.hxx>
114 #include <Time/tmp.hxx>
115 #include <Traffic/TrafficMgr.hxx>
116
117 #ifdef FG_MPLAYER_AS
118 #include <MultiPlayer/multiplaytxmgr.hxx>
119 #include <MultiPlayer/multiplayrxmgr.hxx>
120 #endif
121
122 #include <Environment/environment_mgr.hxx>
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
140 class Sound;
141 extern const char *default_root;
142 float init_volume;
143
144
145 // Scan the command line options for the specified option and return
146 // the value.
147 static string fgScanForOption( const string& option, int argc, char **argv ) {
148     int i = 1;
149
150     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
151
152     int len = option.length();
153
154     while ( i < argc ) {
155         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
156
157         string arg = argv[i];
158         if ( arg.find( option ) == 0 ) {
159             return arg.substr( len );
160         }
161
162         i++;
163     }
164
165     return "";
166 }
167
168
169 // Scan the user config files for the specified option and return
170 // the value.
171 static string fgScanForOption( const string& option, const string& path ) {
172     sg_gzifstream in( path );
173     if ( !in.is_open() ) {
174         return "";
175     }
176
177     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
178
179     int len = option.length();
180
181     in >> skipcomment;
182 #ifndef __MWERKS__
183     while ( ! in.eof() ) {
184 #else
185     char c = '\0';
186     while ( in.get(c) && c != '\0' ) {
187         in.putback(c);
188 #endif
189         string line;
190
191 #if defined( macintosh )
192         getline( in, line, '\r' );
193 #else
194         getline( in, line, '\n' );
195 #endif
196
197         // catch extraneous (DOS) line ending character
198         if ( line[line.length() - 1] < 32 ) {
199             line = line.substr( 0, line.length()-1 );
200         }
201
202         if ( line.find( option ) == 0 ) {
203             return line.substr( len );
204         }
205
206         in >> skipcomment;
207     }
208
209     return "";
210 }
211
212
213 // Read in configuration (files and command line options) but only set
214 // fg_root
215 bool fgInitFGRoot ( int argc, char **argv ) {
216     string root;
217     char* envp;
218
219     // First parse command line options looking for --fg-root=, this
220     // will override anything specified in a config file
221     root = fgScanForOption( "--fg-root=", argc, argv);
222
223 #if defined( unix ) || defined( __CYGWIN__ )
224     // Next check home directory for .fgfsrc.hostname file
225     if ( root.empty() ) {
226         envp = ::getenv( "HOME" );
227         if ( envp != NULL ) {
228             SGPath config( envp );
229             config.append( ".fgfsrc" );
230             char name[256];
231             gethostname( name, 256 );
232             config.concat( "." );
233             config.concat( name );
234             root = fgScanForOption( "--fg-root=", config.str() );
235         }
236     }
237 #endif
238
239     // Next check home directory for .fgfsrc file
240     if ( root.empty() ) {
241         envp = ::getenv( "HOME" );
242         if ( envp != NULL ) {
243             SGPath config( envp );
244             config.append( ".fgfsrc" );
245             root = fgScanForOption( "--fg-root=", config.str() );
246         }
247     }
248     
249     // Next check if fg-root is set as an env variable
250     if ( root.empty() ) {
251         envp = ::getenv( "FG_ROOT" );
252         if ( envp != NULL ) {
253             root = envp;
254         }
255     }
256
257     // Otherwise, default to a random compiled-in location if we can't
258     // find fg-root any other way.
259     if ( root.empty() ) {
260 #if defined( __CYGWIN__ )
261         root = "/FlightGear";
262 #elif defined( WIN32 )
263         root = "\\FlightGear";
264 #elif defined(OSX_BUNDLE) 
265         /* the following code looks for the base package directly inside
266             the application bundle. This can be changed fairly easily by
267             fiddling with the code below. And yes, I know it's ugly and verbose.
268         */
269         CFBundleRef appBundle = CFBundleGetMainBundle();
270         CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
271         CFRelease(appBundle);
272
273         // look for a 'data' subdir directly inside the bundle : is there
274         // a better place? maybe in Resources? I don't know ...
275         CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
276
277         // now convert down to a path, and the a c-string
278         CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
279         root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
280
281         // tidy up.
282         CFRelease(appBundle);
283         CFRelease(dataDir);
284         CFRelease(path);
285 #else
286         root = PKGLIBDIR;
287 #endif
288     }
289
290     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
291     globals->set_fg_root(root);
292
293     return true;
294 }
295
296
297 // Read in configuration (files and command line options) but only set
298 // aircraft
299 bool fgInitFGAircraft ( int argc, char **argv ) {
300     string aircraft;
301     char* envp;
302
303     // First parse command line options looking for --aircraft=, this
304     // will override anything specified in a config file
305     aircraft = fgScanForOption( "--aircraft=", argc, argv );
306
307 #if defined( unix ) || defined( __CYGWIN__ )
308     // Next check home directory for .fgfsrc.hostname file
309     if ( aircraft.empty() ) {
310         envp = ::getenv( "HOME" );
311         if ( envp != NULL ) {
312             SGPath config( envp );
313             config.append( ".fgfsrc" );
314             char name[256];
315             gethostname( name, 256 );
316             config.concat( "." );
317             config.concat( name );
318             aircraft = fgScanForOption( "--aircraft=", config.str() );
319         }
320     }
321 #endif
322
323     // Next check home directory for .fgfsrc file
324     if ( aircraft.empty() ) {
325         envp = ::getenv( "HOME" );
326         if ( envp != NULL ) {
327             SGPath config( envp );
328             config.append( ".fgfsrc" );
329             aircraft = fgScanForOption( "--aircraft=", config.str() );
330         }
331     }
332
333     if ( aircraft.empty() ) {
334         // Check for $fg_root/system.fgfsrc
335         SGPath sysconf( globals->get_fg_root() );
336         sysconf.append( "system.fgfsrc" );
337         aircraft = fgScanForOption( "--aircraft=", sysconf.str() );
338     }
339     // if an aircraft was specified, set the property name
340     if ( !aircraft.empty() ) {
341         SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
342         fgSetString("/sim/aircraft", aircraft.c_str() );
343     } else {
344         SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
345     }
346
347     return true;
348 }
349
350
351 // Return the current base package version
352 string fgBasePackageVersion() {
353     SGPath base_path( globals->get_fg_root() );
354     base_path.append("version");
355
356     sg_gzifstream in( base_path.str() );
357     if ( !in.is_open() ) {
358         SGPath old_path( globals->get_fg_root() );
359         old_path.append( "Thanks" );
360         sg_gzifstream old( old_path.str() );
361         if ( !old.is_open() ) {
362             return "[none]";
363         } else {
364             return "[old version]";
365         }
366     }
367
368     string version;
369     in >> version;
370
371     return version;
372 }
373
374
375 // Initialize the localization
376 SGPropertyNode *fgInitLocale(const char *language) {
377    SGPropertyNode *c_node = NULL, *d_node = NULL;
378    SGPropertyNode *intl = fgGetNode("/sim/intl");
379
380    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
381
382    // localization not defined
383    if (!intl)
384       return NULL;
385
386    //
387    // Select the proper language from the list
388    //
389    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
390    for (unsigned int i = 0; i < locale.size(); i++) {
391
392       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
393       for (unsigned int j = 0; j < lang.size(); j++) {
394
395          if (!strcmp(lang[j]->getStringValue(), language)) {
396             c_node = locale[i];
397             break;
398          }
399       }
400    }
401
402
403    // Get the defaults
404    d_node = intl->getChild("locale");
405    if (!c_node)
406       c_node = d_node;
407
408    // Check for localized font
409    SGPropertyNode *font_n = c_node->getNode("font", true);
410    if ( !strcmp(font_n->getStringValue(), "") )
411       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
412
413
414    //
415    // Load the default strings
416    //
417    SGPath d_path( globals->get_fg_root() );
418
419    const char *d_path_str = d_node->getStringValue("strings");
420    if (!d_path_str) {
421       SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
422       return NULL;
423    }
424
425    d_path.append(d_path_str);
426    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
427                                   << d_path.str());
428
429    SGPropertyNode *strings = c_node->getNode("strings");
430    try {
431       readProperties(d_path.str(), strings);
432    } catch (const sg_exception &e) {
433       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
434       return NULL;
435    }
436
437    //
438    // Load the language specific strings
439    //
440    if (c_node != d_node) {
441       SGPath c_path( globals->get_fg_root() );
442
443       const char *c_path_str = c_node->getStringValue("strings");
444       if (!c_path_str) {
445          SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
446          return NULL;
447       }
448
449       c_path.append(c_path_str);
450       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
451                                      << c_path.str());
452
453       try {
454          readProperties(c_path.str(), strings);
455       } catch (const sg_exception &e) {
456          SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
457          return NULL;
458       }
459    }
460
461    return c_node;
462 }
463
464
465
466 // Initialize the localization routines
467 bool fgDetectLanguage() {
468     char *language = ::getenv("LANG");
469
470     if (language == NULL) {
471         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
472         language = "C";
473     }
474
475     SGPropertyNode *locale = fgInitLocale(language);
476     if (!locale) {
477        SG_LOG(SG_GENERAL, SG_ALERT,
478               "No internationalization settings specified in preferences.xml" );
479
480        return false;
481     }
482
483     globals->set_locale( locale );
484
485     return true;
486 }
487
488 // Attempt to locate and parse the various non-XML config files in order
489 // from least precidence to greatest precidence
490 static void
491 do_options (int argc, char ** argv)
492 {
493     // Check for $fg_root/system.fgfsrc
494     SGPath config( globals->get_fg_root() );
495     config.append( "system.fgfsrc" );
496     fgParseOptions(config.str());
497
498 #if defined( unix ) || defined( __CYGWIN__ )
499     char name[256];
500     // Check for $fg_root/system.fgfsrc.hostname
501     gethostname( name, 256 );
502     config.concat( "." );
503     config.concat( name );
504     fgParseOptions(config.str());
505 #endif
506
507     // Check for ~/.fgfsrc
508     char* envp = ::getenv( "HOME" );
509     if ( envp != NULL ) {
510         config.set( envp );
511         config.append( ".fgfsrc" );
512         fgParseOptions(config.str());
513     }
514
515 #if defined( unix ) || defined( __CYGWIN__ )
516     // Check for ~/.fgfsrc.hostname
517     gethostname( name, 256 );
518     config.concat( "." );
519     config.concat( name );
520     fgParseOptions(config.str());
521 #endif
522
523     // Parse remaining command line options
524     // These will override anything specified in a config file
525     fgParseArgs(argc, argv);
526 }
527
528
529 static string fgFindAircraftPath( const SGPath &path, const string &aircraft ) {
530     ulDirEnt* dire;
531     ulDir *dirp = ulOpenDir(path.str().c_str());
532     if (dirp == NULL) {
533         cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
534         exit(-1);
535     }
536
537     while ((dire = ulReadDir(dirp)) != NULL) {
538         if (dire->d_isdir) {
539             if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
540                  && strcmp("..", dire->d_name) )
541             {
542                 SGPath next = path;
543                 next.append(dire->d_name);
544
545                 string result = fgFindAircraftPath( next, aircraft );
546                 if ( ! result.empty() ) {
547                     return result;
548                 }
549             }
550         } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
551             return path.str();
552         }
553     }
554
555     ulCloseDir(dirp);
556
557     return "";
558 }
559
560
561 // Read in configuration (file and command line)
562 bool fgInitConfig ( int argc, char **argv ) {
563
564     // First, set some sane default values
565     fgSetDefaults();
566
567     // Read global preferences from $FG_ROOT/preferences.xml
568     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
569     fgLoadProps("preferences.xml", globals->get_props());
570     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
571
572     // Detect the required language as early as possible
573     if ( !fgDetectLanguage() ) {
574         return false;
575     }
576
577     // Scan user config files and command line for a specified aircraft.
578     fgInitFGAircraft(argc, argv);
579
580     string aircraft = fgGetString( "/sim/aircraft", "" );
581     if ( aircraft.size() > 0 ) {
582         SGPath aircraft_search( globals->get_fg_root() );
583         aircraft_search.append( "Aircraft" );
584
585         string aircraft_set = aircraft + "-set.xml";
586
587         string result = fgFindAircraftPath( aircraft_search, aircraft_set );
588         if ( !result.empty() ) {
589             fgSetString( "/sim/aircraft-dir", result.c_str() );
590             SGPath full_name( result );
591             full_name.append( aircraft_set );
592
593             SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
594                    << " from " << full_name.str());
595             try {
596                 readProperties( full_name.str(), globals->get_props() );
597             } catch ( const sg_exception &e ) {
598                 string message = "Error reading default aircraft: ";
599                 message += e.getFormattedMessage();
600                 SG_LOG(SG_INPUT, SG_ALERT, message);
601                 exit(2);
602             }
603         } else {
604             SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
605                     << aircraft );
606             return false;
607         }
608
609     } else {
610         SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
611     }
612
613     // parse options after loading aircraft to ensure any user
614     // overrides of defaults are honored.
615     do_options(argc, argv);
616
617     return true;
618 }
619
620
621 // find basic airport location info from airport database
622 bool fgFindAirportID( const string& id, FGAirport *a ) {
623     const FGAirport* result;
624     if ( id.length() ) {
625         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
626
627         result = globals->get_airports()->search( id );
628
629         if ( result == NULL ) {
630             SG_LOG( SG_GENERAL, SG_ALERT,
631                     "Failed to find " << id << " in apt.dat.gz" );
632             return false;
633         }
634     } else {
635         return false;
636     }
637
638     *a = *result;
639
640     SG_LOG( SG_GENERAL, SG_INFO,
641             "Position for " << id << " is ("
642             << a->getLongitude() << ", "
643             << a->getLatitude() << ")" );
644
645     return true;
646 }
647
648
649 // get airport elevation
650 static double fgGetAirportElev( const string& id ) {
651     FGAirport a;
652     // double lon, lat;
653
654     SG_LOG( SG_GENERAL, SG_INFO,
655             "Finding elevation for airport: " << id );
656
657     if ( fgFindAirportID( id, &a ) ) {
658         return a.getElevation();
659     } else {
660         return -9999.0;
661     }
662 }
663
664
665 #if 0 
666   // 
667   // This function is never used, but maybe useful in the future ???
668   //
669
670 // Preset lon/lat given an airport id
671 static bool fgSetPosFromAirportID( const string& id ) {
672     FGAirport a;
673     // double lon, lat;
674
675     SG_LOG( SG_GENERAL, SG_INFO,
676             "Attempting to set starting position from airport code " << id );
677
678     if ( fgFindAirportID( id, &a ) ) {
679         // presets
680         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
681         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
682
683         // other code depends on the actual postition being set so set
684         // that as well
685         fgSetDouble("/position/longitude-deg", a.longitude );
686         fgSetDouble("/position/latitude-deg", a.latitude );
687
688         SG_LOG( SG_GENERAL, SG_INFO,
689                 "Position for " << id << " is (" << a.longitude
690                 << ", " << a.latitude << ")" );
691
692         return true;
693     } else {
694         return false;
695     }
696 }
697 #endif
698
699
700 // Set current tower position lon/lat given an airport id
701 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
702     FGAirport a;
703     // tower height hard coded for now...
704     float towerheight=50.0f;
705
706     // make a little off the heading for 1 runway airports...
707     float fudge_lon = fabs(sin(hdg)) * .003f;
708     float fudge_lat = .003f - fudge_lon;
709
710     if ( fgFindAirportID( id, &a ) ) {
711         fgSetDouble("/sim/tower/longitude-deg",  a.getLongitude() + fudge_lon);
712         fgSetDouble("/sim/tower/latitude-deg",  a.getLatitude() + fudge_lat);
713         fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
714         return true;
715     } else {
716         return false;
717     }
718
719 }
720
721
722 // Set current_options lon/lat given an airport id and heading (degrees)
723 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
724     FGRunway r;
725
726     if ( id.length() ) {
727         // set initial position from runway and heading
728
729         SG_LOG( SG_GENERAL, SG_INFO,
730                 "Attempting to set starting position from airport code "
731                 << id << " heading " << tgt_hdg );
732                 
733         if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
734             SG_LOG( SG_GENERAL, SG_ALERT,
735                     "Failed to find a good runway for " << id << '\n' );
736             return false;
737         }       
738     } else {
739         return false;
740     }
741
742     double lat2, lon2, az2;
743     double heading = r._heading;
744     double azimuth = heading + 180.0;
745     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
746
747     SG_LOG( SG_GENERAL, SG_INFO,
748             "runway =  " << r._lon << ", " << r._lat
749             << " length = " << r._length * SG_FEET_TO_METER 
750             << " heading = " << azimuth );
751             
752     geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, 
753                         r._length * SG_FEET_TO_METER * 0.5 - 5.0,
754                         &lat2, &lon2, &az2 );
755
756     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
757         double olat, olon;
758         double odist = fgGetDouble("/sim/presets/offset-distance");
759         odist *= SG_NM_TO_METER;
760         double oaz = azimuth;
761         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
762             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
763             heading = tgt_hdg;
764         }
765         while ( oaz >= 360.0 ) { oaz -= 360.0; }
766         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
767         lat2=olat;
768         lon2=olon;
769     }
770
771     // presets
772     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
773     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
774     fgSetDouble("/sim/presets/heading-deg", heading );
775
776     // other code depends on the actual values being set ...
777     fgSetDouble("/position/longitude-deg",  lon2 );
778     fgSetDouble("/position/latitude-deg",  lat2 );
779     fgSetDouble("/orientation/heading-deg", heading );
780
781     SG_LOG( SG_GENERAL, SG_INFO,
782             "Position for " << id << " is ("
783             << lon2 << ", "
784             << lat2 << ") new heading is "
785             << heading );
786             
787     return true;
788 }
789
790
791 // Set current_options lon/lat given an airport id and runway number
792 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
793     FGRunway r;
794
795     if ( id.length() ) {
796         // set initial position from airport and runway number
797
798         SG_LOG( SG_GENERAL, SG_INFO,
799                 "Attempting to set starting position for "
800                 << id << ":" << rwy );
801
802         if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
803             SG_LOG( SG_GENERAL, SG_ALERT,
804                     "Failed to find runway " << rwy << 
805                     " at airport " << id );
806             return false;
807         }
808     } else {
809         return false;
810     }
811
812     double lat2, lon2, az2;
813     double heading = r._heading;
814     double azimuth = heading + 180.0;
815     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
816     
817     SG_LOG( SG_GENERAL, SG_INFO,
818     "runway =  " << r._lon << ", " << r._lat
819     << " length = " << r._length * SG_FEET_TO_METER 
820     << " heading = " << azimuth );
821     
822     geo_direct_wgs_84 ( 0, r._lat, r._lon, 
823     azimuth,
824     r._length * SG_FEET_TO_METER * 0.5 - 5.0,
825     &lat2, &lon2, &az2 );
826     
827     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
828     {
829         double olat, olon;
830         double odist = fgGetDouble("/sim/presets/offset-distance");
831         odist *= SG_NM_TO_METER;
832         double oaz = azimuth;
833         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
834         {
835             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
836             heading = fgGetDouble("/sim/presets/heading-deg");
837         }
838         while ( oaz >= 360.0 ) { oaz -= 360.0; }
839         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
840         lat2=olat;
841         lon2=olon;
842     }
843     
844     // presets
845     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
846     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
847     fgSetDouble("/sim/presets/heading-deg", heading );
848     
849     // other code depends on the actual values being set ...
850     fgSetDouble("/position/longitude-deg",  lon2 );
851     fgSetDouble("/position/latitude-deg",  lat2 );
852     fgSetDouble("/orientation/heading-deg", heading );
853     
854     SG_LOG( SG_GENERAL, SG_INFO,
855     "Position for " << id << " is ("
856     << lon2 << ", "
857     << lat2 << ") new heading is "
858     << heading );
859     
860     return true;
861 }
862
863
864 static void fgSetDistOrAltFromGlideSlope() {
865     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
866     string apt_id = fgGetString("/sim/presets/airport-id");
867     double gs = fgGetDouble("/sim/presets/glideslope-deg")
868         * SG_DEGREES_TO_RADIANS ;
869     double od = fgGetDouble("/sim/presets/offset-distance");
870     double alt = fgGetDouble("/sim/presets/altitude-ft");
871
872     double apt_elev = 0.0;
873     if ( ! apt_id.empty() ) {
874         apt_elev = fgGetAirportElev( apt_id );
875         if ( apt_elev < -9990.0 ) {
876             apt_elev = 0.0;
877         }
878     } else {
879         apt_elev = 0.0;
880     }
881
882     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
883         // set altitude from glideslope and offset-distance
884         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
885         alt = fabs(od*tan(gs)) + apt_elev;
886         fgSetDouble("/sim/presets/altitude-ft", alt);
887         fgSetBool("/sim/presets/onground", false);
888         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
889                 << alt  << " ft" );
890     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
891         // set offset-distance from glideslope and altitude
892         od  = (alt - apt_elev) / tan(gs);
893         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
894         fgSetDouble("/sim/presets/offset-distance", od);
895         fgSetBool("/sim/presets/onground", false);
896         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
897                 << od  << " nm" );
898     } else if( fabs(gs) > 0.01 ) {
899         SG_LOG( SG_GENERAL, SG_ALERT,
900                 "Glideslope given but not altitude or offset-distance." );
901         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
902         fgSetDouble("/sim/presets/glideslope-deg", 0);
903         fgSetBool("/sim/presets/onground", true);
904     }                              
905 }
906
907
908 // Set current_options lon/lat given an airport id and heading (degrees)
909 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
910     FGNavRecord *nav
911         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
912
913     // set initial position from runway and heading
914     if ( nav != NULL ) {
915         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
916                 << id << ":" << freq );
917
918         double lon = nav->get_lon();
919         double lat = nav->get_lat();
920
921         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
922         {
923             double odist = fgGetDouble("/sim/presets/offset-distance")
924                 * SG_NM_TO_METER;
925             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
926                 + 180.0;
927             while ( oaz >= 360.0 ) { oaz -= 360.0; }
928             double olat, olon, az2;
929             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
930
931             lat = olat;
932             lon = olon;
933         }
934
935         // presets
936         fgSetDouble("/sim/presets/longitude-deg",  lon );
937         fgSetDouble("/sim/presets/latitude-deg",  lat );
938
939         // other code depends on the actual values being set ...
940         fgSetDouble("/position/longitude-deg",  lon );
941         fgSetDouble("/position/latitude-deg",  lat );
942         fgSetDouble("/orientation/heading-deg", 
943                     fgGetDouble("/sim/presets/heading-deg") );
944
945         SG_LOG( SG_GENERAL, SG_INFO,
946                 "Position for " << id << ":" << freq << " is ("
947                 << lon << ", "<< lat << ")" );
948
949         return true;
950     } else {
951         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
952                 << id << ":" << freq );
953         return false;
954     }
955 }
956
957 // Set current_options lon/lat given an aircraft carrier id
958 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
959
960     // set initial position from runway and heading
961     Point3D geodPos;
962     double heading;
963     sgdVec3 uvw;
964     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
965         double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
966         double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
967         double alt = geodPos.elev() * SG_METER_TO_FEET;
968
969         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
970                 << carrier << " at lat = " << lat << ", lon = " << lon
971                 << ", alt = " << alt << ", heading = " << heading);
972
973         fgSetDouble("/sim/presets/longitude-deg",  lon);
974         fgSetDouble("/sim/presets/latitude-deg",  lat);
975         fgSetDouble("/sim/presets/altitude-ft", alt);
976         fgSetDouble("/sim/presets/heading-deg", heading);
977         fgSetDouble("/position/longitude-deg",  lon);
978         fgSetDouble("/position/latitude-deg",  lat);
979         fgSetDouble("/position/altitude-ft", alt);
980         fgSetDouble("/orientation/heading-deg", heading);
981
982         fgSetString("/sim/presets/speed-set", "UVW");
983         fgSetDouble("/velocities/uBody-fps", uvw[0]);
984         fgSetDouble("/velocities/vBody-fps", uvw[1]);
985         fgSetDouble("/velocities/wBody-fps", uvw[2]);
986         fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
987         fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
988         fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
989
990         fgSetBool("/sim/presets/onground", true);
991
992         return true;
993     } else {
994         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carroer = "
995                 << carrier );
996         return false;
997     }
998 }
999  
1000 // Set current_options lon/lat given an airport id and heading (degrees)
1001 static bool fgSetPosFromFix( const string& id ) {
1002     FGFix fix;
1003
1004     // set initial position from runway and heading
1005     if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1006         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1007                 << id );
1008
1009         double lon = fix.get_lon();
1010         double lat = fix.get_lat();
1011
1012         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1013         {
1014             double odist = fgGetDouble("/sim/presets/offset-distance")
1015                 * SG_NM_TO_METER;
1016             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1017                 + 180.0;
1018             while ( oaz >= 360.0 ) { oaz -= 360.0; }
1019             double olat, olon, az2;
1020             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1021
1022             lat = olat;
1023             lon = olon;
1024         }
1025
1026         // presets
1027         fgSetDouble("/sim/presets/longitude-deg",  lon );
1028         fgSetDouble("/sim/presets/latitude-deg",  lat );
1029
1030         // other code depends on the actual values being set ...
1031         fgSetDouble("/position/longitude-deg",  lon );
1032         fgSetDouble("/position/latitude-deg",  lat );
1033         fgSetDouble("/orientation/heading-deg", 
1034                     fgGetDouble("/sim/presets/heading-deg") );
1035
1036         SG_LOG( SG_GENERAL, SG_INFO,
1037                 "Position for " << id << " is ("
1038                 << lon << ", "<< lat << ")" );
1039
1040         return true;
1041     } else {
1042         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1043                 << id );
1044         return false;
1045     }
1046 }
1047  
1048 static void parseWaypoints() {
1049     string_list *waypoints = globals->get_initial_waypoints();
1050     if (waypoints) {
1051         vector<string>::iterator i;
1052         for (i = waypoints->begin(); 
1053              i  != waypoints->end();
1054              i++)
1055         {
1056             NewWaypoint(*i);
1057         }
1058         // Now were done using the way points we can deallocate the
1059         // memory they used
1060         while (waypoints->begin() != waypoints->end()) {
1061             waypoints->pop_back();
1062         }
1063         delete waypoints;
1064         globals->set_initial_waypoints(0);
1065     }
1066 }
1067
1068  
1069  
1070
1071
1072 /**
1073  * Initialize vor/ndb/ils/fix list management and query systems (as
1074  * well as simple airport db list)
1075  */
1076 bool
1077 fgInitNav ()
1078 {
1079     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1080
1081     SGPath aptdb( globals->get_fg_root() );
1082     aptdb.append( "Airports/apt.dat" );
1083
1084     SGPath p_metar( globals->get_fg_root() );
1085     p_metar.append( "Airports/metar.dat" );
1086
1087     FGAirportList *airports = new FGAirportList();
1088     globals->set_airports( airports );
1089     FGRunwayList *runways = new FGRunwayList();
1090     globals->set_runways( runways );
1091
1092     fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1093
1094     FGNavList *navlist = new FGNavList;
1095     FGNavList *loclist = new FGNavList;
1096     FGNavList *gslist = new FGNavList;
1097     FGNavList *dmelist = new FGNavList;
1098     FGNavList *mkrlist = new FGNavList;
1099
1100     globals->set_navlist( navlist );
1101     globals->set_loclist( loclist );
1102     globals->set_gslist( gslist );
1103     globals->set_dmelist( dmelist );
1104     globals->set_mkrlist( mkrlist );
1105
1106     if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist) ) {
1107         SG_LOG( SG_GENERAL, SG_ALERT,
1108                 "Problems loading one or more navigational database" );
1109     }
1110
1111     if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1112         // align all the localizers with their corresponding runways
1113         // since data sources are good for cockpit navigation
1114         // purposes, but not always to the error tolerances needed to
1115         // exactly place these items.
1116         double threshold
1117             = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1118                            5.0 );
1119         fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1120     }
1121
1122     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1123     SGPath p_fix( globals->get_fg_root() );
1124     p_fix.append( "Navaids/fix.dat" );
1125     FGFixList *fixlist = new FGFixList;
1126     fixlist->init( p_fix );
1127     globals->set_fixlist( fixlist );
1128
1129     return true;
1130 }
1131
1132
1133 // Set the initial position based on presets (or defaults)
1134 bool fgInitPosition() {
1135     // cout << "fgInitPosition()" << endl;
1136     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1137         * SG_DEGREES_TO_RADIANS ;
1138     double od = fgGetDouble("/sim/presets/offset-distance");
1139     double alt = fgGetDouble("/sim/presets/altitude-ft");
1140
1141     bool set_pos = false;
1142
1143     // If glideslope is specified, then calculate offset-distance or
1144     // altitude relative to glide slope if either of those was not
1145     // specified.
1146     if ( fabs( gs ) > 0.01 ) {
1147         fgSetDistOrAltFromGlideSlope();
1148     }
1149
1150
1151     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1152     // If not, check for an airport-id and use that.
1153     // If not, default to the middle of the KSFO field.
1154     // The default values for lon/lat are deliberately out of range
1155     // so that the airport-id can take effect; valid lon/lat will
1156     // override airport-id, however.
1157     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1158     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1159     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1160          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1161     {
1162         set_pos = true;
1163     }
1164
1165     string apt = fgGetString("/sim/presets/airport-id");
1166     string rwy_no = fgGetString("/sim/presets/runway");
1167     double hdg = fgGetDouble("/sim/presets/heading-deg");
1168     string vor = fgGetString("/sim/presets/vor-id");
1169     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1170     string ndb = fgGetString("/sim/presets/ndb-id");
1171     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1172     string carrier = fgGetString("/sim/presets/carrier");
1173     string parkpos = fgGetString("/sim/presets/parkpos");
1174     string fix = fgGetString("/sim/presets/fix");
1175
1176     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1177         // An airport + runway is requested
1178         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1179             // set tower position (a little off the heading for single
1180             // runway airports)
1181             fgSetTowerPosFromAirportID( apt, hdg );
1182             set_pos = true;
1183         }
1184     }
1185
1186     if ( !set_pos && !apt.empty() ) {
1187         // An airport is requested (find runway closest to hdg)
1188         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1189             // set tower position (a little off the heading for single
1190             // runway airports)
1191             fgSetTowerPosFromAirportID( apt, hdg );
1192             set_pos = true;
1193         }
1194     }
1195
1196     if ( !set_pos && !vor.empty() ) {
1197         // a VOR is requested
1198         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1199             set_pos = true;
1200         }
1201     }
1202
1203     if ( !set_pos && !ndb.empty() ) {
1204         // an NDB is requested
1205         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1206             set_pos = true;
1207         }
1208     }
1209
1210     if ( !set_pos && !carrier.empty() ) {
1211         // an aircraft carrier is requested
1212         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1213             set_pos = true;
1214         }
1215     }
1216
1217     if ( !set_pos && !fix.empty() ) {
1218         // a Fix is requested
1219         if ( fgSetPosFromFix( fix ) ) {
1220             set_pos = true;
1221         }
1222     }
1223
1224     if ( !set_pos ) {
1225         // No lon/lat specified, no airport specified, default to
1226         // middle of KSFO field.
1227         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1228         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1229     }
1230
1231     fgSetDouble( "/position/longitude-deg",
1232                  fgGetDouble("/sim/presets/longitude-deg") );
1233     fgSetDouble( "/position/latitude-deg",
1234                  fgGetDouble("/sim/presets/latitude-deg") );
1235     fgSetDouble( "/orientation/heading-deg",
1236                  fgGetDouble("/sim/presets/heading-deg") );
1237
1238     // determine if this should be an on-ground or in-air start
1239     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1240         fgSetBool("/sim/presets/onground", false);
1241     } else {
1242         fgSetBool("/sim/presets/onground", true);
1243     }                              
1244
1245     return true;
1246 }
1247
1248
1249 // General house keeping initializations
1250 bool fgInitGeneral() {
1251     string root;
1252
1253 #if defined(FX) && defined(XMESA)
1254     char *mesa_win_state;
1255 #endif
1256
1257     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1258     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1259
1260     root = globals->get_fg_root();
1261     if ( ! root.length() ) {
1262         // No root path set? Then bail ...
1263         SG_LOG( SG_GENERAL, SG_ALERT,
1264                 "Cannot continue without a path to the base package "
1265                 << "being defined." );
1266         exit(-1);
1267     }
1268     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1269
1270 #if defined(FX) && defined(XMESA)
1271     // initialize full screen flag
1272     globals->set_fullscreen(false);
1273     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1274         // Test for the MESA_GLX_FX env variable
1275         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1276             // test if we are fullscreen mesa/glide
1277             if ( (mesa_win_state[0] == 'f') ||
1278                  (mesa_win_state[0] == 'F') ) {
1279                 globals->set_fullscreen(true);
1280             }
1281         }
1282     }
1283 #endif
1284
1285     return true;
1286 }
1287
1288
1289 // Initialize the flight model subsystem.  This just creates the
1290 // object.  The actual fdm initialization is delayed until we get a
1291 // proper scenery elevation hit.  This is checked for in main.cxx
1292
1293 void fgInitFDM() {
1294
1295     if ( cur_fdm_state ) {
1296         delete cur_fdm_state;
1297         cur_fdm_state = 0;
1298     }
1299
1300     double dt = 1.0 / fgGetInt("/sim/model-hz");
1301     aircraft_dir = fgGetString("/sim/aircraft-dir");
1302     const string &model = fgGetString("/sim/flight-model");
1303
1304     try {
1305         if ( model == "larcsim" ) {
1306             cur_fdm_state = new FGLaRCsim( dt );
1307         } else if ( model == "jsb" ) {
1308             cur_fdm_state = new FGJSBsim( dt );
1309 #ifdef ENABLE_SP_FMDS
1310         } else if ( model == "ada" ) {
1311             cur_fdm_state = new FGADA( dt );
1312         } else if ( model == "acms" ) {
1313             cur_fdm_state = new FGACMS( dt );
1314 #endif
1315         } else if ( model == "balloon" ) {
1316             cur_fdm_state = new FGBalloonSim( dt );
1317         } else if ( model == "magic" ) {
1318             cur_fdm_state = new FGMagicCarpet( dt );
1319         } else if ( model == "ufo" ) {
1320             cur_fdm_state = new FGUFO( dt );
1321         } else if ( model == "external" ) {
1322             // external is a synonym for "--fdm=null" and is
1323             // maintained here for backwards compatibility
1324             cur_fdm_state = new FGNullFDM( dt );
1325         } else if ( model.find("network") == 0 ) {
1326             string host = "localhost";
1327             int port1 = 5501;
1328             int port2 = 5502;
1329             int port3 = 5503;
1330             string net_options = model.substr(8);
1331             string::size_type begin, end;
1332             begin = 0;
1333             // host
1334             end = net_options.find( ",", begin );
1335             if ( end != string::npos ) {
1336                 host = net_options.substr(begin, end - begin);
1337                 begin = end + 1;
1338             }
1339             // port1
1340             end = net_options.find( ",", begin );
1341             if ( end != string::npos ) {
1342                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1343                 begin = end + 1;
1344             }
1345             // port2
1346             end = net_options.find( ",", begin );
1347             if ( end != string::npos ) {
1348                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1349                 begin = end + 1;
1350             }
1351             // port3
1352             end = net_options.find( ",", begin );
1353             if ( end != string::npos ) {
1354                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1355                 begin = end + 1;
1356             }
1357             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1358         } else if ( model.find("pipe") == 0 ) {
1359             // /* old */ string pipe_path = model.substr(5);
1360             // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1361             string pipe_path = "";
1362             string pipe_protocol = "";
1363             string pipe_options = model.substr(5);
1364             string::size_type begin, end;
1365             begin = 0;
1366             // pipe file path
1367             end = pipe_options.find( ",", begin );
1368             if ( end != string::npos ) {
1369                 pipe_path = pipe_options.substr(begin, end - begin);
1370                 begin = end + 1;
1371             }
1372             // protocol (last option)
1373             pipe_protocol = pipe_options.substr(begin);
1374             cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1375         } else if ( model == "null" ) {
1376             cur_fdm_state = new FGNullFDM( dt );
1377         } else if ( model == "yasim" ) {
1378             cur_fdm_state = new YASim( dt );
1379         } else {
1380             SG_LOG(SG_GENERAL, SG_ALERT,
1381                    "Unrecognized flight model '" << model
1382                    << "', cannot init flight dynamics model.");
1383             exit(-1);
1384         }
1385     } catch ( ... ) {
1386         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1387         exit(-1);
1388     }
1389 }
1390
1391 static void printMat(const sgVec4 *mat, char *name="")
1392 {
1393     int i;
1394     SG_LOG(SG_GENERAL, SG_BULK, name );
1395     for(i=0; i<4; i++) {
1396         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1397                                     << " " << mat[i][2] << " " << mat[i][3] );
1398     }
1399 }
1400
1401 // Initialize view parameters
1402 void fgInitView() {
1403   // force update of model so that viewer can get some data...
1404   globals->get_aircraft_model()->update(0);
1405   // run update for current view so that data is current...
1406   globals->get_viewmgr()->update(0);
1407
1408   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1409   printMat(globals->get_current_view()->get_UP(),"UP");
1410   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1411   
1412 }
1413
1414
1415 SGTime *fgInitTime() {
1416     // Initialize time
1417     static const SGPropertyNode *longitude
1418         = fgGetNode("/position/longitude-deg");
1419     static const SGPropertyNode *latitude
1420         = fgGetNode("/position/latitude-deg");
1421     static const SGPropertyNode *cur_time_override
1422         = fgGetNode("/sim/time/cur-time-override", true);
1423
1424     SGPath zone( globals->get_fg_root() );
1425     zone.append( "Timezone" );
1426     SGTime *t = new SGTime( longitude->getDoubleValue()
1427                               * SGD_DEGREES_TO_RADIANS,
1428                             latitude->getDoubleValue()
1429                               * SGD_DEGREES_TO_RADIANS,
1430                             zone.str(),
1431                             cur_time_override->getLongValue() );
1432
1433     globals->set_warp_delta( 0 );
1434
1435     t->update( 0.0, 0.0,
1436                cur_time_override->getLongValue(),
1437                globals->get_warp() );
1438
1439     return t;
1440 }
1441
1442
1443 // set up a time offset (aka warp) if one is specified
1444 void fgInitTimeOffset() {
1445     static const SGPropertyNode *longitude
1446         = fgGetNode("/position/longitude-deg");
1447     static const SGPropertyNode *latitude
1448         = fgGetNode("/position/latitude-deg");
1449     static const SGPropertyNode *cur_time_override
1450         = fgGetNode("/sim/time/cur-time-override", true);
1451
1452     // Handle potential user specified time offsets
1453     int orig_warp = globals->get_warp();
1454     SGTime *t = globals->get_time_params();
1455     time_t cur_time = t->get_cur_time();
1456     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1457     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1458     time_t aircraftLocalTime = 
1459         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1460
1461     // Okay, we now have several possible scenarios
1462     int offset = fgGetInt("/sim/startup/time-offset");
1463     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1464
1465     int warp = 0;
1466     if ( offset_type == "real" ) {
1467         warp = 0;
1468     } else if ( offset_type == "dawn" ) {
1469         warp = fgTimeSecondsUntilSunAngle( cur_time,
1470                                            longitude->getDoubleValue()
1471                                              * SGD_DEGREES_TO_RADIANS,
1472                                            latitude->getDoubleValue()
1473                                              * SGD_DEGREES_TO_RADIANS,
1474                                            90.0, true ); 
1475     } else if ( offset_type == "morning" ) {
1476         warp = fgTimeSecondsUntilSunAngle( cur_time,
1477                                            longitude->getDoubleValue()
1478                                              * SGD_DEGREES_TO_RADIANS,
1479                                            latitude->getDoubleValue()
1480                                              * SGD_DEGREES_TO_RADIANS,
1481                                            75.0, true ); 
1482     } else if ( offset_type == "noon" ) {
1483         warp = fgTimeSecondsUntilSunAngle( cur_time,
1484                                            longitude->getDoubleValue()
1485                                              * SGD_DEGREES_TO_RADIANS,
1486                                            latitude->getDoubleValue()
1487                                              * SGD_DEGREES_TO_RADIANS,
1488                                            0.0, true ); 
1489     } else if ( offset_type == "afternoon" ) {
1490         warp = fgTimeSecondsUntilSunAngle( cur_time,
1491                                            longitude->getDoubleValue()
1492                                              * SGD_DEGREES_TO_RADIANS,
1493                                            latitude->getDoubleValue()
1494                                              * SGD_DEGREES_TO_RADIANS,
1495                                            60.0, false ); 
1496      } else if ( offset_type == "dusk" ) {
1497         warp = fgTimeSecondsUntilSunAngle( cur_time,
1498                                            longitude->getDoubleValue()
1499                                              * SGD_DEGREES_TO_RADIANS,
1500                                            latitude->getDoubleValue()
1501                                              * SGD_DEGREES_TO_RADIANS,
1502                                            90.0, false ); 
1503      } else if ( offset_type == "evening" ) {
1504         warp = fgTimeSecondsUntilSunAngle( cur_time,
1505                                            longitude->getDoubleValue()
1506                                              * SGD_DEGREES_TO_RADIANS,
1507                                            latitude->getDoubleValue()
1508                                              * SGD_DEGREES_TO_RADIANS,
1509                                            100.0, false ); 
1510     } else if ( offset_type == "midnight" ) {
1511         warp = fgTimeSecondsUntilSunAngle( cur_time,
1512                                            longitude->getDoubleValue()
1513                                              * SGD_DEGREES_TO_RADIANS,
1514                                            latitude->getDoubleValue()
1515                                              * SGD_DEGREES_TO_RADIANS,
1516                                            180.0, false ); 
1517     } else if ( offset_type == "system-offset" ) {
1518         warp = offset;
1519     } else if ( offset_type == "gmt-offset" ) {
1520         warp = offset - (currGMT - systemLocalTime);
1521     } else if ( offset_type == "latitude-offset" ) {
1522         warp = offset - (aircraftLocalTime - systemLocalTime);
1523     } else if ( offset_type == "system" ) {
1524         warp = offset - cur_time;
1525     } else if ( offset_type == "gmt" ) {
1526         warp = offset - currGMT;
1527     } else if ( offset_type == "latitude" ) {
1528         warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time; 
1529     } else {
1530         SG_LOG( SG_GENERAL, SG_ALERT,
1531                 "FG_TIME::Unsupported offset type " << offset_type );
1532         exit( -1 );
1533     }
1534     globals->set_warp( orig_warp + warp );
1535     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1536                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1537                cur_time_override->getLongValue(),
1538                globals->get_warp() );
1539
1540     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1541             << globals->get_warp() );
1542 }
1543
1544
1545 // This is the top level init routine which calls all the other
1546 // initialization routines.  If you are adding a subsystem to flight
1547 // gear, its initialization call should located in this routine.
1548 // Returns non-zero if a problem encountered.
1549 bool fgInitSubsystems() {
1550     // static const SGPropertyNode *longitude
1551     //     = fgGetNode("/sim/presets/longitude-deg");
1552     // static const SGPropertyNode *latitude
1553     //     = fgGetNode("/sim/presets/latitude-deg");
1554     // static const SGPropertyNode *altitude
1555     //     = fgGetNode("/sim/presets/altitude-ft");
1556
1557     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1558     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1559
1560     ////////////////////////////////////////////////////////////////////
1561     // Initialize the event manager subsystem.
1562     ////////////////////////////////////////////////////////////////////
1563
1564     globals->get_event_mgr()->init();
1565     globals->get_event_mgr()->setFreezeProperty(fgGetNode("/sim/freeze/clock"));
1566
1567     ////////////////////////////////////////////////////////////////////
1568     // Initialize the property interpolator subsystem
1569     ////////////////////////////////////////////////////////////////////
1570     globals->add_subsystem("interpolator", new SGInterpolator);
1571
1572
1573     ////////////////////////////////////////////////////////////////////
1574     // Add the FlightGear property utilities.
1575     ////////////////////////////////////////////////////////////////////
1576     globals->add_subsystem("properties", new FGProperties);
1577
1578     ////////////////////////////////////////////////////////////////////
1579     // Initialize the material property subsystem.
1580     ////////////////////////////////////////////////////////////////////
1581
1582     SGPath mpath( globals->get_fg_root() );
1583     mpath.append( "materials.xml" );
1584     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1585         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1586         exit(-1);
1587     }
1588
1589
1590     ////////////////////////////////////////////////////////////////////
1591     // Initialize the scenery management subsystem.
1592     ////////////////////////////////////////////////////////////////////
1593
1594     if ( globals->get_tile_mgr()->init() ) {
1595         // Load the local scenery data
1596         double visibility_meters = fgGetDouble("/environment/visibility-m");
1597                 
1598         globals->get_tile_mgr()->update( visibility_meters );
1599     } else {
1600         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1601         exit(-1);
1602     }
1603
1604     // cause refresh of viewer scenery timestamps every 15 seconds...
1605     globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1606                                        globals->get_tile_mgr(),
1607                                        &FGTileMgr::refresh_view_timestamps,
1608                                        15 );
1609
1610
1611     ////////////////////////////////////////////////////////////////////
1612     // Initialize the flight model subsystem.
1613     ////////////////////////////////////////////////////////////////////
1614
1615     fgInitFDM();
1616         
1617     // allocates structures so must happen before any of the flight
1618     // model or control parameters are set
1619     fgAircraftInit();   // In the future this might not be the case.
1620
1621
1622     ////////////////////////////////////////////////////////////////////
1623     // Initialize the XML Autopilot subsystem.
1624     ////////////////////////////////////////////////////////////////////
1625
1626     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1627     globals->add_subsystem( "route-manager", new FGRouteMgr );
1628
1629   
1630     ////////////////////////////////////////////////////////////////////
1631     // Initialize the view manager subsystem.
1632     ////////////////////////////////////////////////////////////////////
1633
1634     fgInitView();
1635
1636     ////////////////////////////////////////////////////////////////////
1637     // Create and register the logger.
1638     ////////////////////////////////////////////////////////////////////
1639     
1640     globals->add_subsystem("logger", new FGLogger);
1641
1642     ////////////////////////////////////////////////////////////////////
1643     // Create and register the XML GUI.
1644     ////////////////////////////////////////////////////////////////////
1645
1646     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1647
1648
1649     ////////////////////////////////////////////////////////////////////
1650     // Initialize the local time subsystem.
1651     ////////////////////////////////////////////////////////////////////
1652
1653     // update the current timezone each 30 minutes
1654     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1655                                        &fgUpdateLocalTime, 30*60 );
1656     fgInitTimeOffset();         // the environment subsystem needs this
1657
1658
1659     ////////////////////////////////////////////////////////////////////
1660     // Initialize the weather subsystem.
1661     ////////////////////////////////////////////////////////////////////
1662
1663     // Initialize the weather modeling subsystem
1664     globals->add_subsystem("environment", new FGEnvironmentMgr);
1665
1666
1667     ////////////////////////////////////////////////////////////////////
1668     // Initialize the lighting subsystem.
1669     ////////////////////////////////////////////////////////////////////
1670
1671     globals->add_subsystem("lighting", new FGLight);
1672
1673     //////////////////////////////////////////////////////////////////////
1674     // Initialize the 2D cloud subsystem.
1675     ////////////////////////////////////////////////////////////////////
1676     fgGetBool("/sim/rendering/bump-mapping", false);
1677
1678 #ifdef ENABLE_AUDIO_SUPPORT
1679     ////////////////////////////////////////////////////////////////////
1680     // Initialize the sound subsystem.
1681     ////////////////////////////////////////////////////////////////////
1682
1683     init_volume = fgGetFloat("/sim/sound/volume");
1684     fgSetFloat("/sim/sound/volume", 0.0f);
1685     globals->set_soundmgr(new SGSoundMgr);
1686     globals->get_soundmgr()->init();
1687     globals->get_soundmgr()->bind();
1688
1689
1690     ////////////////////////////////////////////////////////////////////
1691     // Initialize the sound-effects subsystem.
1692     ////////////////////////////////////////////////////////////////////
1693
1694     globals->add_subsystem("fx", new FGFX);
1695     
1696 #endif
1697
1698     ////////////////////////////////////////////////////////////////////
1699     // Initialise ATC display system
1700     ////////////////////////////////////////////////////////////////////
1701
1702     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1703     globals->set_ATC_display(new FGATCDisplay);
1704     globals->get_ATC_display()->init(); 
1705
1706     ////////////////////////////////////////////////////////////////////
1707     // Initialise the ATC Manager 
1708     ////////////////////////////////////////////////////////////////////
1709
1710     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1711     globals->set_ATC_mgr(new FGATCMgr);
1712     globals->get_ATC_mgr()->init(); 
1713     
1714     ////////////////////////////////////////////////////////////////////
1715     // Initialise the AI Manager 
1716     ////////////////////////////////////////////////////////////////////
1717
1718     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1719     globals->set_AI_mgr(new FGAIMgr);
1720     globals->get_AI_mgr()->init();
1721
1722     ////////////////////////////////////////////////////////////////////
1723     // Initialise the AI Model Manager
1724     ////////////////////////////////////////////////////////////////////
1725     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1726     globals->add_subsystem("ai_model", new FGAIManager);
1727     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1728
1729
1730      // It's probably a good idea to initialize the top level traffic manager
1731      // After the AI and ATC systems have been initialized properly.
1732      // AI Traffic manager
1733      globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1734              FGTrafficManager *dispatcher = 
1735              (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1736              SGPath path = globals->get_fg_root();
1737              path.append("/Traffic/fgtraffic.xml");
1738      readXML(path.str(),
1739         *dispatcher);
1740              //globals->get_subsystem("Traffic Manager")->init();
1741
1742     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1743     globals->add_subsystem("systems", new FGSystemMgr);
1744
1745
1746
1747     ////////////////////////////////////////////////////////////////////
1748     // Initialize the cockpit subsystem
1749     ////////////////////////////////////////////////////////////////////
1750     if( fgCockpitInit( &current_aircraft )) {
1751         // Cockpit initialized ok.
1752     } else {
1753         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1754         exit(-1);
1755     }
1756
1757
1758     ////////////////////////////////////////////////////////////////////
1759     // Initialize the autopilot subsystem.
1760     ////////////////////////////////////////////////////////////////////
1761
1762                                 // FIXME: these should go in the
1763                                 // GUI initialization code, not here.
1764     // fgAPAdjustInit();
1765     NewTgtAirportInit();
1766     NewHeadingInit();
1767     NewAltitudeInit();
1768
1769     ////////////////////////////////////////////////////////////////////
1770     // Initialize I/O subsystem.
1771     ////////////////////////////////////////////////////////////////////
1772
1773     globals->get_io()->init();
1774     globals->get_io()->bind();
1775
1776
1777     ////////////////////////////////////////////////////////////////////
1778     // Add a new 2D panel.
1779     ////////////////////////////////////////////////////////////////////
1780
1781     string panel_path = fgGetString("/sim/panel/path",
1782                                     "Panels/Default/default.xml");
1783
1784     globals->set_current_panel( fgReadPanel(panel_path) );
1785     if (globals->get_current_panel() == 0) {
1786         SG_LOG( SG_INPUT, SG_ALERT, 
1787                 "Error reading new panel from " << panel_path );
1788     } else {
1789         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1790         globals->get_current_panel()->init();
1791         globals->get_current_panel()->bind();
1792     }
1793
1794     
1795     ////////////////////////////////////////////////////////////////////
1796     // Initialize the controls subsystem.
1797     ////////////////////////////////////////////////////////////////////
1798
1799     globals->get_controls()->init();
1800     globals->get_controls()->bind();
1801
1802
1803     ////////////////////////////////////////////////////////////////////
1804     // Initialize the input subsystem.
1805     ////////////////////////////////////////////////////////////////////
1806
1807     globals->add_subsystem("input", new FGInput);
1808
1809
1810     ////////////////////////////////////////////////////////////////////
1811     // Initialize the replay subsystem
1812     ////////////////////////////////////////////////////////////////////
1813     globals->add_subsystem("replay", new FGReplay);
1814
1815     ////////////////////////////////////////////////////////////////////
1816     // Bind and initialize subsystems.
1817     ////////////////////////////////////////////////////////////////////
1818
1819     globals->get_subsystem_mgr()->bind();
1820     globals->get_subsystem_mgr()->init();
1821
1822 #ifdef FG_MPLAYER_AS
1823     ////////////////////////////////////////////////////////////////////
1824     // Initialize multiplayer subsystem
1825     ////////////////////////////////////////////////////////////////////
1826
1827     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1828     globals->get_multiplayer_tx_mgr()->init();
1829
1830     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1831     globals->get_multiplayer_rx_mgr()->init();
1832 #endif
1833
1834     ////////////////////////////////////////////////////////////////////////
1835     // Initialize the Nasal interpreter.
1836     // Do this last, so that the loaded scripts see initialized state
1837     ////////////////////////////////////////////////////////////////////////
1838     FGNasalSys* nasal = new FGNasalSys();
1839     globals->add_subsystem("nasal", nasal);
1840     nasal->init();
1841
1842     ////////////////////////////////////////////////////////////////////
1843     // At this point we could try and parse the waypoint options
1844     ///////////////////////////////////////////////////////////////////
1845     parseWaypoints();
1846
1847     // initialize methods that depend on other subsystems.
1848     globals->get_subsystem_mgr()->postinit();
1849
1850     ////////////////////////////////////////////////////////////////////////
1851     // End of subsystem initialization.
1852     ////////////////////////////////////////////////////////////////////
1853
1854     SG_LOG( SG_GENERAL, SG_INFO, endl);
1855
1856                                 // Save the initial state for future
1857                                 // reference.
1858     globals->saveInitialState();
1859
1860     return true;
1861 }
1862
1863
1864 void fgReInitSubsystems()
1865 {
1866     // static const SGPropertyNode *longitude
1867     //     = fgGetNode("/sim/presets/longitude-deg");
1868     // static const SGPropertyNode *latitude
1869     //     = fgGetNode("/sim/presets/latitude-deg");
1870     static const SGPropertyNode *altitude
1871         = fgGetNode("/sim/presets/altitude-ft");
1872     static const SGPropertyNode *master_freeze
1873         = fgGetNode("/sim/freeze/master");
1874
1875     SG_LOG( SG_GENERAL, SG_INFO,
1876             "fgReInitSubsystems(): /position/altitude = "
1877             << altitude->getDoubleValue() );
1878
1879     bool freeze = master_freeze->getBoolValue();
1880     if ( !freeze ) {
1881         fgSetBool("/sim/freeze/master", true);
1882     }
1883     fgSetBool("/sim/crashed", false);
1884
1885     // Force reupdating the positions of the ai 3d models. They are used for
1886     // initializing ground level for the FDM.
1887     globals->get_subsystem("ai_model")->reinit();
1888
1889     // Initialize the FDM
1890     fgInitFDM();
1891     
1892     // allocates structures so must happen before any of the flight
1893     // model or control parameters are set
1894     fgAircraftInit();   // In the future this might not be the case.
1895
1896     // reload offsets from config defaults
1897     globals->get_viewmgr()->reinit();
1898
1899     fgInitView();
1900
1901     globals->get_controls()->reset_all();
1902
1903     fgUpdateLocalTime();
1904
1905     // re-init to proper time of day setting
1906     fgInitTimeOffset();
1907
1908     if ( !freeze ) {
1909         fgSetBool("/sim/freeze/master", false);
1910     }
1911     fgSetBool("/sim/sceneryloaded",false);
1912 }
1913