]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Al MacLeod: fix typo
[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 carrier = "
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     FGNavList *tacanlist = new FGNavList;
1100     FGNavList *carrierlist = new FGNavList;
1101     FGTACANList *channellist = new FGTACANList;
1102
1103     globals->set_navlist( navlist );
1104     globals->set_loclist( loclist );
1105     globals->set_gslist( gslist );
1106     globals->set_dmelist( dmelist );
1107     globals->set_mkrlist( mkrlist );
1108     globals->set_tacanlist( tacanlist );
1109     globals->set_carrierlist( carrierlist );
1110     globals->set_channellist( channellist );
1111
1112     if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1113         SG_LOG( SG_GENERAL, SG_ALERT,
1114                 "Problems loading one or more navigational database" );
1115     }
1116
1117     if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1118         // align all the localizers with their corresponding runways
1119         // since data sources are good for cockpit navigation
1120         // purposes, but not always to the error tolerances needed to
1121         // exactly place these items.
1122         double threshold
1123             = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1124                            5.0 );
1125         fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1126     }
1127
1128     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1129     SGPath p_fix( globals->get_fg_root() );
1130     p_fix.append( "Navaids/fix.dat" );
1131     FGFixList *fixlist = new FGFixList;
1132     fixlist->init( p_fix );
1133     globals->set_fixlist( fixlist );
1134
1135     return true;
1136 }
1137
1138
1139 // Set the initial position based on presets (or defaults)
1140 bool fgInitPosition() {
1141     // cout << "fgInitPosition()" << endl;
1142     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1143         * SG_DEGREES_TO_RADIANS ;
1144     double od = fgGetDouble("/sim/presets/offset-distance");
1145     double alt = fgGetDouble("/sim/presets/altitude-ft");
1146
1147     bool set_pos = false;
1148
1149     // If glideslope is specified, then calculate offset-distance or
1150     // altitude relative to glide slope if either of those was not
1151     // specified.
1152     if ( fabs( gs ) > 0.01 ) {
1153         fgSetDistOrAltFromGlideSlope();
1154     }
1155
1156
1157     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1158     // If not, check for an airport-id and use that.
1159     // If not, default to the middle of the KSFO field.
1160     // The default values for lon/lat are deliberately out of range
1161     // so that the airport-id can take effect; valid lon/lat will
1162     // override airport-id, however.
1163     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1164     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1165     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1166          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1167     {
1168         set_pos = true;
1169     }
1170
1171     string apt = fgGetString("/sim/presets/airport-id");
1172     string rwy_no = fgGetString("/sim/presets/runway");
1173     double hdg = fgGetDouble("/sim/presets/heading-deg");
1174     string vor = fgGetString("/sim/presets/vor-id");
1175     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1176     string ndb = fgGetString("/sim/presets/ndb-id");
1177     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1178     string carrier = fgGetString("/sim/presets/carrier");
1179     string parkpos = fgGetString("/sim/presets/parkpos");
1180     string fix = fgGetString("/sim/presets/fix");
1181
1182     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1183         // An airport + runway is requested
1184         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1185             // set tower position (a little off the heading for single
1186             // runway airports)
1187             fgSetTowerPosFromAirportID( apt, hdg );
1188             set_pos = true;
1189         }
1190     }
1191
1192     if ( !set_pos && !apt.empty() ) {
1193         // An airport is requested (find runway closest to hdg)
1194         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1195             // set tower position (a little off the heading for single
1196             // runway airports)
1197             fgSetTowerPosFromAirportID( apt, hdg );
1198             set_pos = true;
1199         }
1200     }
1201
1202     if ( !set_pos && !vor.empty() ) {
1203         // a VOR is requested
1204         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1205             set_pos = true;
1206         }
1207     }
1208
1209     if ( !set_pos && !ndb.empty() ) {
1210         // an NDB is requested
1211         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1212             set_pos = true;
1213         }
1214     }
1215
1216     if ( !set_pos && !carrier.empty() ) {
1217         // an aircraft carrier is requested
1218         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1219             set_pos = true;
1220         }
1221     }
1222
1223     if ( !set_pos && !fix.empty() ) {
1224         // a Fix is requested
1225         if ( fgSetPosFromFix( fix ) ) {
1226             set_pos = true;
1227         }
1228     }
1229
1230     if ( !set_pos ) {
1231         // No lon/lat specified, no airport specified, default to
1232         // middle of KSFO field.
1233         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1234         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1235     }
1236
1237     fgSetDouble( "/position/longitude-deg",
1238                  fgGetDouble("/sim/presets/longitude-deg") );
1239     fgSetDouble( "/position/latitude-deg",
1240                  fgGetDouble("/sim/presets/latitude-deg") );
1241     fgSetDouble( "/orientation/heading-deg",
1242                  fgGetDouble("/sim/presets/heading-deg") );
1243
1244     // determine if this should be an on-ground or in-air start
1245     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1246         fgSetBool("/sim/presets/onground", false);
1247     } else {
1248         fgSetBool("/sim/presets/onground", true);
1249     }                              
1250
1251     return true;
1252 }
1253
1254
1255 // General house keeping initializations
1256 bool fgInitGeneral() {
1257     string root;
1258
1259 #if defined(FX) && defined(XMESA)
1260     char *mesa_win_state;
1261 #endif
1262
1263     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1264     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1265
1266     root = globals->get_fg_root();
1267     if ( ! root.length() ) {
1268         // No root path set? Then bail ...
1269         SG_LOG( SG_GENERAL, SG_ALERT,
1270                 "Cannot continue without a path to the base package "
1271                 << "being defined." );
1272         exit(-1);
1273     }
1274     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1275
1276 #if defined(FX) && defined(XMESA)
1277     // initialize full screen flag
1278     globals->set_fullscreen(false);
1279     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1280         // Test for the MESA_GLX_FX env variable
1281         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1282             // test if we are fullscreen mesa/glide
1283             if ( (mesa_win_state[0] == 'f') ||
1284                  (mesa_win_state[0] == 'F') ) {
1285                 globals->set_fullscreen(true);
1286             }
1287         }
1288     }
1289 #endif
1290
1291     return true;
1292 }
1293
1294
1295 // Initialize the flight model subsystem.  This just creates the
1296 // object.  The actual fdm initialization is delayed until we get a
1297 // proper scenery elevation hit.  This is checked for in main.cxx
1298
1299 void fgInitFDM() {
1300
1301     if ( cur_fdm_state ) {
1302         delete cur_fdm_state;
1303         cur_fdm_state = 0;
1304     }
1305
1306     double dt = 1.0 / fgGetInt("/sim/model-hz");
1307     aircraft_dir = fgGetString("/sim/aircraft-dir");
1308     const string &model = fgGetString("/sim/flight-model");
1309
1310     try {
1311         if ( model == "larcsim" ) {
1312             cur_fdm_state = new FGLaRCsim( dt );
1313         } else if ( model == "jsb" ) {
1314             cur_fdm_state = new FGJSBsim( dt );
1315 #ifdef ENABLE_SP_FMDS
1316         } else if ( model == "ada" ) {
1317             cur_fdm_state = new FGADA( dt );
1318         } else if ( model == "acms" ) {
1319             cur_fdm_state = new FGACMS( dt );
1320 #endif
1321         } else if ( model == "balloon" ) {
1322             cur_fdm_state = new FGBalloonSim( dt );
1323         } else if ( model == "magic" ) {
1324             cur_fdm_state = new FGMagicCarpet( dt );
1325         } else if ( model == "ufo" ) {
1326             cur_fdm_state = new FGUFO( dt );
1327         } else if ( model == "external" ) {
1328             // external is a synonym for "--fdm=null" and is
1329             // maintained here for backwards compatibility
1330             cur_fdm_state = new FGNullFDM( dt );
1331         } else if ( model.find("network") == 0 ) {
1332             string host = "localhost";
1333             int port1 = 5501;
1334             int port2 = 5502;
1335             int port3 = 5503;
1336             string net_options = model.substr(8);
1337             string::size_type begin, end;
1338             begin = 0;
1339             // host
1340             end = net_options.find( ",", begin );
1341             if ( end != string::npos ) {
1342                 host = net_options.substr(begin, end - begin);
1343                 begin = end + 1;
1344             }
1345             // port1
1346             end = net_options.find( ",", begin );
1347             if ( end != string::npos ) {
1348                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1349                 begin = end + 1;
1350             }
1351             // port2
1352             end = net_options.find( ",", begin );
1353             if ( end != string::npos ) {
1354                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1355                 begin = end + 1;
1356             }
1357             // port3
1358             end = net_options.find( ",", begin );
1359             if ( end != string::npos ) {
1360                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1361                 begin = end + 1;
1362             }
1363             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1364         } else if ( model.find("pipe") == 0 ) {
1365             // /* old */ string pipe_path = model.substr(5);
1366             // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1367             string pipe_path = "";
1368             string pipe_protocol = "";
1369             string pipe_options = model.substr(5);
1370             string::size_type begin, end;
1371             begin = 0;
1372             // pipe file path
1373             end = pipe_options.find( ",", begin );
1374             if ( end != string::npos ) {
1375                 pipe_path = pipe_options.substr(begin, end - begin);
1376                 begin = end + 1;
1377             }
1378             // protocol (last option)
1379             pipe_protocol = pipe_options.substr(begin);
1380             cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1381         } else if ( model == "null" ) {
1382             cur_fdm_state = new FGNullFDM( dt );
1383         } else if ( model == "yasim" ) {
1384             cur_fdm_state = new YASim( dt );
1385         } else {
1386             SG_LOG(SG_GENERAL, SG_ALERT,
1387                    "Unrecognized flight model '" << model
1388                    << "', cannot init flight dynamics model.");
1389             exit(-1);
1390         }
1391     } catch ( ... ) {
1392         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1393         exit(-1);
1394     }
1395 }
1396
1397 static void printMat(const sgVec4 *mat, char *name="")
1398 {
1399     int i;
1400     SG_LOG(SG_GENERAL, SG_BULK, name );
1401     for(i=0; i<4; i++) {
1402         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1403                                     << " " << mat[i][2] << " " << mat[i][3] );
1404     }
1405 }
1406
1407 // Initialize view parameters
1408 void fgInitView() {
1409   // force update of model so that viewer can get some data...
1410   globals->get_aircraft_model()->update(0);
1411   // run update for current view so that data is current...
1412   globals->get_viewmgr()->update(0);
1413
1414   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1415   printMat(globals->get_current_view()->get_UP(),"UP");
1416   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1417   
1418 }
1419
1420
1421 SGTime *fgInitTime() {
1422     // Initialize time
1423     static const SGPropertyNode *longitude
1424         = fgGetNode("/position/longitude-deg");
1425     static const SGPropertyNode *latitude
1426         = fgGetNode("/position/latitude-deg");
1427     static const SGPropertyNode *cur_time_override
1428         = fgGetNode("/sim/time/cur-time-override", true);
1429
1430     SGPath zone( globals->get_fg_root() );
1431     zone.append( "Timezone" );
1432     SGTime *t = new SGTime( longitude->getDoubleValue()
1433                               * SGD_DEGREES_TO_RADIANS,
1434                             latitude->getDoubleValue()
1435                               * SGD_DEGREES_TO_RADIANS,
1436                             zone.str(),
1437                             cur_time_override->getLongValue() );
1438
1439     globals->set_warp_delta( 0 );
1440
1441     t->update( 0.0, 0.0,
1442                cur_time_override->getLongValue(),
1443                globals->get_warp() );
1444
1445     return t;
1446 }
1447
1448
1449 // set up a time offset (aka warp) if one is specified
1450 void fgInitTimeOffset() {
1451     static const SGPropertyNode *longitude
1452         = fgGetNode("/position/longitude-deg");
1453     static const SGPropertyNode *latitude
1454         = fgGetNode("/position/latitude-deg");
1455     static const SGPropertyNode *cur_time_override
1456         = fgGetNode("/sim/time/cur-time-override", true);
1457
1458     // Handle potential user specified time offsets
1459     int orig_warp = globals->get_warp();
1460     SGTime *t = globals->get_time_params();
1461     time_t cur_time = t->get_cur_time();
1462     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1463     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1464     time_t aircraftLocalTime = 
1465         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1466
1467     // Okay, we now have several possible scenarios
1468     int offset = fgGetInt("/sim/startup/time-offset");
1469     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1470
1471     int warp = 0;
1472     if ( offset_type == "real" ) {
1473         warp = 0;
1474     } else if ( offset_type == "dawn" ) {
1475         warp = fgTimeSecondsUntilSunAngle( cur_time,
1476                                            longitude->getDoubleValue()
1477                                              * SGD_DEGREES_TO_RADIANS,
1478                                            latitude->getDoubleValue()
1479                                              * SGD_DEGREES_TO_RADIANS,
1480                                            90.0, true ); 
1481     } else if ( offset_type == "morning" ) {
1482         warp = fgTimeSecondsUntilSunAngle( cur_time,
1483                                            longitude->getDoubleValue()
1484                                              * SGD_DEGREES_TO_RADIANS,
1485                                            latitude->getDoubleValue()
1486                                              * SGD_DEGREES_TO_RADIANS,
1487                                            75.0, true ); 
1488     } else if ( offset_type == "noon" ) {
1489         warp = fgTimeSecondsUntilSunAngle( cur_time,
1490                                            longitude->getDoubleValue()
1491                                              * SGD_DEGREES_TO_RADIANS,
1492                                            latitude->getDoubleValue()
1493                                              * SGD_DEGREES_TO_RADIANS,
1494                                            0.0, true ); 
1495     } else if ( offset_type == "afternoon" ) {
1496         warp = fgTimeSecondsUntilSunAngle( cur_time,
1497                                            longitude->getDoubleValue()
1498                                              * SGD_DEGREES_TO_RADIANS,
1499                                            latitude->getDoubleValue()
1500                                              * SGD_DEGREES_TO_RADIANS,
1501                                            60.0, false ); 
1502      } else if ( offset_type == "dusk" ) {
1503         warp = fgTimeSecondsUntilSunAngle( cur_time,
1504                                            longitude->getDoubleValue()
1505                                              * SGD_DEGREES_TO_RADIANS,
1506                                            latitude->getDoubleValue()
1507                                              * SGD_DEGREES_TO_RADIANS,
1508                                            90.0, false ); 
1509      } else if ( offset_type == "evening" ) {
1510         warp = fgTimeSecondsUntilSunAngle( cur_time,
1511                                            longitude->getDoubleValue()
1512                                              * SGD_DEGREES_TO_RADIANS,
1513                                            latitude->getDoubleValue()
1514                                              * SGD_DEGREES_TO_RADIANS,
1515                                            100.0, false ); 
1516     } else if ( offset_type == "midnight" ) {
1517         warp = fgTimeSecondsUntilSunAngle( cur_time,
1518                                            longitude->getDoubleValue()
1519                                              * SGD_DEGREES_TO_RADIANS,
1520                                            latitude->getDoubleValue()
1521                                              * SGD_DEGREES_TO_RADIANS,
1522                                            180.0, false ); 
1523     } else if ( offset_type == "system-offset" ) {
1524         warp = offset;
1525     } else if ( offset_type == "gmt-offset" ) {
1526         warp = offset - (currGMT - systemLocalTime);
1527     } else if ( offset_type == "latitude-offset" ) {
1528         warp = offset - (aircraftLocalTime - systemLocalTime);
1529     } else if ( offset_type == "system" ) {
1530         warp = offset - cur_time;
1531     } else if ( offset_type == "gmt" ) {
1532         warp = offset - currGMT;
1533     } else if ( offset_type == "latitude" ) {
1534         warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time; 
1535     } else {
1536         SG_LOG( SG_GENERAL, SG_ALERT,
1537                 "FG_TIME::Unsupported offset type " << offset_type );
1538         exit( -1 );
1539     }
1540     globals->set_warp( orig_warp + warp );
1541     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1542                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1543                cur_time_override->getLongValue(),
1544                globals->get_warp() );
1545
1546     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1547             << globals->get_warp() );
1548 }
1549
1550
1551 // This is the top level init routine which calls all the other
1552 // initialization routines.  If you are adding a subsystem to flight
1553 // gear, its initialization call should located in this routine.
1554 // Returns non-zero if a problem encountered.
1555 bool fgInitSubsystems() {
1556     // static const SGPropertyNode *longitude
1557     //     = fgGetNode("/sim/presets/longitude-deg");
1558     // static const SGPropertyNode *latitude
1559     //     = fgGetNode("/sim/presets/latitude-deg");
1560     // static const SGPropertyNode *altitude
1561     //     = fgGetNode("/sim/presets/altitude-ft");
1562
1563     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1564     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1565
1566     ////////////////////////////////////////////////////////////////////
1567     // Initialize the event manager subsystem.
1568     ////////////////////////////////////////////////////////////////////
1569
1570     globals->get_event_mgr()->init();
1571     globals->get_event_mgr()->setFreezeProperty(fgGetNode("/sim/freeze/clock"));
1572
1573     ////////////////////////////////////////////////////////////////////
1574     // Initialize the property interpolator subsystem
1575     ////////////////////////////////////////////////////////////////////
1576     globals->add_subsystem("interpolator", new SGInterpolator);
1577
1578
1579     ////////////////////////////////////////////////////////////////////
1580     // Add the FlightGear property utilities.
1581     ////////////////////////////////////////////////////////////////////
1582     globals->add_subsystem("properties", new FGProperties);
1583
1584     ////////////////////////////////////////////////////////////////////
1585     // Initialize the material property subsystem.
1586     ////////////////////////////////////////////////////////////////////
1587
1588     SGPath mpath( globals->get_fg_root() );
1589     mpath.append( "materials.xml" );
1590     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1591         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1592         exit(-1);
1593     }
1594
1595
1596     ////////////////////////////////////////////////////////////////////
1597     // Initialize the scenery management subsystem.
1598     ////////////////////////////////////////////////////////////////////
1599
1600     if ( globals->get_tile_mgr()->init() ) {
1601         // Load the local scenery data
1602         double visibility_meters = fgGetDouble("/environment/visibility-m");
1603                 
1604         globals->get_tile_mgr()->update( visibility_meters );
1605     } else {
1606         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1607         exit(-1);
1608     }
1609
1610     // cause refresh of viewer scenery timestamps every 15 seconds...
1611     globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1612                                        globals->get_tile_mgr(),
1613                                        &FGTileMgr::refresh_view_timestamps,
1614                                        15 );
1615
1616
1617     ////////////////////////////////////////////////////////////////////
1618     // Initialize the flight model subsystem.
1619     ////////////////////////////////////////////////////////////////////
1620
1621     fgInitFDM();
1622         
1623     // allocates structures so must happen before any of the flight
1624     // model or control parameters are set
1625     fgAircraftInit();   // In the future this might not be the case.
1626
1627
1628     ////////////////////////////////////////////////////////////////////
1629     // Initialize the XML Autopilot subsystem.
1630     ////////////////////////////////////////////////////////////////////
1631
1632     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1633     globals->add_subsystem( "route-manager", new FGRouteMgr );
1634
1635   
1636     ////////////////////////////////////////////////////////////////////
1637     // Initialize the view manager subsystem.
1638     ////////////////////////////////////////////////////////////////////
1639
1640     fgInitView();
1641
1642     ////////////////////////////////////////////////////////////////////
1643     // Create and register the logger.
1644     ////////////////////////////////////////////////////////////////////
1645     
1646     globals->add_subsystem("logger", new FGLogger);
1647
1648     ////////////////////////////////////////////////////////////////////
1649     // Create and register the XML GUI.
1650     ////////////////////////////////////////////////////////////////////
1651
1652     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1653
1654
1655     ////////////////////////////////////////////////////////////////////
1656     // Initialize the local time subsystem.
1657     ////////////////////////////////////////////////////////////////////
1658
1659     // update the current timezone each 30 minutes
1660     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1661                                        &fgUpdateLocalTime, 30*60 );
1662     fgInitTimeOffset();         // the environment subsystem needs this
1663
1664
1665     ////////////////////////////////////////////////////////////////////
1666     // Initialize the weather subsystem.
1667     ////////////////////////////////////////////////////////////////////
1668
1669     // Initialize the weather modeling subsystem
1670     globals->add_subsystem("environment", new FGEnvironmentMgr);
1671
1672
1673     ////////////////////////////////////////////////////////////////////
1674     // Initialize the lighting subsystem.
1675     ////////////////////////////////////////////////////////////////////
1676
1677     globals->add_subsystem("lighting", new FGLight);
1678
1679     //////////////////////////////////////////////////////////////////////
1680     // Initialize the 2D cloud subsystem.
1681     ////////////////////////////////////////////////////////////////////
1682     fgGetBool("/sim/rendering/bump-mapping", false);
1683
1684 #ifdef ENABLE_AUDIO_SUPPORT
1685     ////////////////////////////////////////////////////////////////////
1686     // Initialize the sound subsystem.
1687     ////////////////////////////////////////////////////////////////////
1688
1689     init_volume = fgGetFloat("/sim/sound/volume");
1690     fgSetFloat("/sim/sound/volume", 0.0f);
1691     globals->set_soundmgr(new SGSoundMgr);
1692     globals->get_soundmgr()->init();
1693     globals->get_soundmgr()->bind();
1694
1695
1696     ////////////////////////////////////////////////////////////////////
1697     // Initialize the sound-effects subsystem.
1698     ////////////////////////////////////////////////////////////////////
1699
1700     globals->add_subsystem("fx", new FGFX);
1701     
1702 #endif
1703
1704     ////////////////////////////////////////////////////////////////////
1705     // Initialise ATC display system
1706     ////////////////////////////////////////////////////////////////////
1707
1708     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1709     globals->set_ATC_display(new FGATCDisplay);
1710     globals->get_ATC_display()->init(); 
1711
1712     ////////////////////////////////////////////////////////////////////
1713     // Initialise the ATC Manager 
1714     ////////////////////////////////////////////////////////////////////
1715
1716     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1717     globals->set_ATC_mgr(new FGATCMgr);
1718     globals->get_ATC_mgr()->init(); 
1719     
1720     ////////////////////////////////////////////////////////////////////
1721     // Initialise the AI Manager 
1722     ////////////////////////////////////////////////////////////////////
1723
1724     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1725     globals->set_AI_mgr(new FGAIMgr);
1726     globals->get_AI_mgr()->init();
1727
1728     ////////////////////////////////////////////////////////////////////
1729     // Initialise the AI Model Manager
1730     ////////////////////////////////////////////////////////////////////
1731     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1732     globals->add_subsystem("ai_model", new FGAIManager);
1733     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1734
1735
1736      // It's probably a good idea to initialize the top level traffic manager
1737      // After the AI and ATC systems have been initialized properly.
1738      // AI Traffic manager
1739      globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1740              FGTrafficManager *dispatcher = 
1741              (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1742              SGPath path = globals->get_fg_root();
1743              path.append("/Traffic/fgtraffic.xml");
1744      readXML(path.str(),
1745         *dispatcher);
1746              //globals->get_subsystem("Traffic Manager")->init();
1747
1748     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1749     globals->add_subsystem("systems", new FGSystemMgr);
1750
1751
1752
1753     ////////////////////////////////////////////////////////////////////
1754     // Initialize the cockpit subsystem
1755     ////////////////////////////////////////////////////////////////////
1756     if( fgCockpitInit( &current_aircraft )) {
1757         // Cockpit initialized ok.
1758     } else {
1759         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1760         exit(-1);
1761     }
1762
1763
1764     ////////////////////////////////////////////////////////////////////
1765     // Initialize the autopilot subsystem.
1766     ////////////////////////////////////////////////////////////////////
1767
1768                                 // FIXME: these should go in the
1769                                 // GUI initialization code, not here.
1770     // fgAPAdjustInit();
1771     NewTgtAirportInit();
1772     NewHeadingInit();
1773     NewAltitudeInit();
1774
1775     ////////////////////////////////////////////////////////////////////
1776     // Initialize I/O subsystem.
1777     ////////////////////////////////////////////////////////////////////
1778
1779     globals->get_io()->init();
1780     globals->get_io()->bind();
1781
1782
1783     ////////////////////////////////////////////////////////////////////
1784     // Add a new 2D panel.
1785     ////////////////////////////////////////////////////////////////////
1786
1787     string panel_path = fgGetString("/sim/panel/path",
1788                                     "Panels/Default/default.xml");
1789
1790     globals->set_current_panel( fgReadPanel(panel_path) );
1791     if (globals->get_current_panel() == 0) {
1792         SG_LOG( SG_INPUT, SG_ALERT, 
1793                 "Error reading new panel from " << panel_path );
1794     } else {
1795         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1796         globals->get_current_panel()->init();
1797         globals->get_current_panel()->bind();
1798     }
1799
1800     
1801     ////////////////////////////////////////////////////////////////////
1802     // Initialize the controls subsystem.
1803     ////////////////////////////////////////////////////////////////////
1804
1805     globals->get_controls()->init();
1806     globals->get_controls()->bind();
1807
1808
1809     ////////////////////////////////////////////////////////////////////
1810     // Initialize the input subsystem.
1811     ////////////////////////////////////////////////////////////////////
1812
1813     globals->add_subsystem("input", new FGInput);
1814
1815
1816     ////////////////////////////////////////////////////////////////////
1817     // Initialize the replay subsystem
1818     ////////////////////////////////////////////////////////////////////
1819     globals->add_subsystem("replay", new FGReplay);
1820
1821     ////////////////////////////////////////////////////////////////////
1822     // Bind and initialize subsystems.
1823     ////////////////////////////////////////////////////////////////////
1824
1825     globals->get_subsystem_mgr()->bind();
1826     globals->get_subsystem_mgr()->init();
1827
1828 #ifdef FG_MPLAYER_AS
1829     ////////////////////////////////////////////////////////////////////
1830     // Initialize multiplayer subsystem
1831     ////////////////////////////////////////////////////////////////////
1832
1833     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1834     globals->get_multiplayer_tx_mgr()->init();
1835
1836     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1837     globals->get_multiplayer_rx_mgr()->init();
1838 #endif
1839
1840     ////////////////////////////////////////////////////////////////////////
1841     // Initialize the Nasal interpreter.
1842     // Do this last, so that the loaded scripts see initialized state
1843     ////////////////////////////////////////////////////////////////////////
1844     FGNasalSys* nasal = new FGNasalSys();
1845     globals->add_subsystem("nasal", nasal);
1846     nasal->init();
1847
1848     ////////////////////////////////////////////////////////////////////
1849     // At this point we could try and parse the waypoint options
1850     ///////////////////////////////////////////////////////////////////
1851     parseWaypoints();
1852
1853     // initialize methods that depend on other subsystems.
1854     globals->get_subsystem_mgr()->postinit();
1855
1856     ////////////////////////////////////////////////////////////////////////
1857     // End of subsystem initialization.
1858     ////////////////////////////////////////////////////////////////////
1859
1860     SG_LOG( SG_GENERAL, SG_INFO, endl);
1861
1862                                 // Save the initial state for future
1863                                 // reference.
1864     globals->saveInitialState();
1865
1866     return true;
1867 }
1868
1869
1870 void fgReInitSubsystems()
1871 {
1872     // static const SGPropertyNode *longitude
1873     //     = fgGetNode("/sim/presets/longitude-deg");
1874     // static const SGPropertyNode *latitude
1875     //     = fgGetNode("/sim/presets/latitude-deg");
1876     static const SGPropertyNode *altitude
1877         = fgGetNode("/sim/presets/altitude-ft");
1878     static const SGPropertyNode *master_freeze
1879         = fgGetNode("/sim/freeze/master");
1880
1881     SG_LOG( SG_GENERAL, SG_INFO,
1882             "fgReInitSubsystems(): /position/altitude = "
1883             << altitude->getDoubleValue() );
1884
1885     bool freeze = master_freeze->getBoolValue();
1886     if ( !freeze ) {
1887         fgSetBool("/sim/freeze/master", true);
1888     }
1889     fgSetBool("/sim/crashed", false);
1890
1891     // Force reupdating the positions of the ai 3d models. They are used for
1892     // initializing ground level for the FDM.
1893     globals->get_subsystem("ai_model")->reinit();
1894
1895     // Initialize the FDM
1896     fgInitFDM();
1897     
1898     // allocates structures so must happen before any of the flight
1899     // model or control parameters are set
1900     fgAircraftInit();   // In the future this might not be the case.
1901
1902     // reload offsets from config defaults
1903     globals->get_viewmgr()->reinit();
1904
1905     fgInitView();
1906
1907     globals->get_controls()->reset_all();
1908
1909     fgUpdateLocalTime();
1910
1911     // re-init to proper time of day setting
1912     fgInitTimeOffset();
1913
1914     if ( !freeze ) {
1915         fgSetBool("/sim/freeze/master", false);
1916     }
1917     fgSetBool("/sim/sceneryloaded",false);
1918 }
1919