]> git.mxchange.org Git - flightgear.git/blobdiff - src/Main/fg_init.cxx
Exposed the fg_commands though the httpd interface.
[flightgear.git] / src / Main / fg_init.cxx
index 91c7d082d44a17b8c948eb97b6e1006b9460f976..ec7e640e12191ba1fba5018d89d01a23a411bb02 100644 (file)
@@ -141,14 +141,84 @@ extern const char *default_root;
 
 SkySceneLoader *sgCloud3d;
 
-// Read in configuration (file and command line) and just set fg_root
+
+// Scan the command line options for the specified option and return
+// the value.
+static string fgScanForOption( const string& option, int argc, char **argv ) {
+    int i = 1;
+
+    SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
+
+    int len = option.length();
+
+    while ( i < argc ) {
+       SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
+
+       string arg = argv[i];
+       if ( arg.find( option ) == 0 ) {
+           return arg.substr( len );
+       }
+
+       i++;
+    }
+
+    return "";
+}
+
+
+// Scan the user config files for the specified option and return
+// the value.
+static string fgScanForOption( const string& option, const string& path ) {
+    sg_gzifstream in( path );
+    if ( !in.is_open() ) {
+        return "";
+    }
+
+    SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
+
+    int len = option.length();
+
+    in >> skipcomment;
+#ifndef __MWERKS__
+    while ( ! in.eof() ) {
+#else
+    char c = '\0';
+    while ( in.get(c) && c != '\0' ) {
+       in.putback(c);
+#endif
+       string line;
+
+#if defined( macintosh )
+        getline( in, line, '\r' );
+#else
+       getline( in, line, '\n' );
+#endif
+
+        // catch extraneous (DOS) line ending character
+        if ( line[line.length() - 1] < 32 ) {
+            line = line.substr( 0, line.length()-1 );
+        }
+
+       if ( line.find( option ) == 0 ) {
+           return line.substr( len );
+       }
+
+       in >> skipcomment;
+    }
+
+    return "";
+}
+
+
+// Read in configuration (files and command line options) but only set
+// fg_root
 bool fgInitFGRoot ( int argc, char **argv ) {
     string root;
     char* envp;
 
-    // First parse command line options looking for fg-root, this will
-    // override anything specified in a config file
-    root = fgScanForRoot(argc, argv);
+    // First parse command line options looking for --fg-root=, this
+    // will override anything specified in a config file
+    root = fgScanForOption( "--fg-root=", argc, argv);
 
 #if defined( unix ) || defined( __CYGWIN__ )
     // Next check home directory for .fgfsrc.hostname file
@@ -161,7 +231,7 @@ bool fgInitFGRoot ( int argc, char **argv ) {
             gethostname( name, 256 );
             config.concat( "." );
             config.concat( name );
-            root = fgScanForRoot(config.str());
+            root = fgScanForOption( "--fg-root=", config.str() );
         }
     }
 #endif
@@ -172,7 +242,7 @@ bool fgInitFGRoot ( int argc, char **argv ) {
         if ( envp != NULL ) {
             SGPath config( envp );
             config.append( ".fgfsrc" );
-            root = fgScanForRoot(config.str());
+            root = fgScanForOption( "--fg-root=", config.str() );
         }
     }
     
@@ -205,6 +275,54 @@ bool fgInitFGRoot ( int argc, char **argv ) {
 }
 
 
+// Read in configuration (files and command line options) but only set
+// aircraft
+bool fgInitFGAircraft ( int argc, char **argv ) {
+    string aircraft;
+    char* envp;
+
+    // First parse command line options looking for --aircraft=, this
+    // will override anything specified in a config file
+    aircraft = fgScanForOption( "--aircraft=", argc, argv );
+
+#if defined( unix ) || defined( __CYGWIN__ )
+    // Next check home directory for .fgfsrc.hostname file
+    if ( aircraft.empty() ) {
+        envp = ::getenv( "HOME" );
+        if ( envp != NULL ) {
+            SGPath config( envp );
+            config.append( ".fgfsrc" );
+            char name[256];
+            gethostname( name, 256 );
+            config.concat( "." );
+            config.concat( name );
+            aircraft = fgScanForOption( "--aircraft=", config.str() );
+        }
+    }
+#endif
+
+    // Next check home directory for .fgfsrc file
+    if ( aircraft.empty() ) {
+        envp = ::getenv( "HOME" );
+        if ( envp != NULL ) {
+            SGPath config( envp );
+            config.append( ".fgfsrc" );
+            aircraft = fgScanForOption( "--aircraft=", config.str() );
+        }
+    }
+
+    // if an aircraft was specified, set the property name
+    if ( !aircraft.empty() ) {
+        SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
+        fgSetString("/sim/aircraft", aircraft.c_str() );
+    } else {
+        SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
+    }
+
+    return true;
+}
+
+
 // Return the current base package version
 string fgBasePackageVersion() {
     SGPath base_path( globals->get_fg_root() );
@@ -386,7 +504,7 @@ do_options (int argc, char ** argv)
 // Read in configuration (file and command line)
 bool fgInitConfig ( int argc, char **argv ) {
 
-                                // First, set some sane default values
+    // First, set some sane default values
     fgSetDefaults();
 
     // Read global preferences from $FG_ROOT/preferences.xml
@@ -395,31 +513,35 @@ bool fgInitConfig ( int argc, char **argv ) {
     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
 
     // Detect the required language as early as possible
-    if (fgDetectLanguage() != true)
-       return false;
+    if ( !fgDetectLanguage() ) {
+        return false;
+    }
+
+    // Scan user config files and command line for a specified aircraft.
+    fgInitFGAircraft(argc, argv);
 
-    // Read the default aircraft config file.
-    do_options(argc, argv);     // preparse options for default aircraft
     string aircraft = fgGetString("/sim/aircraft", "");
-    if (aircraft.size() > 0) {
-      SGPath aircraft_path(globals->get_fg_root());
-      aircraft_path.append("Aircraft");
-      aircraft_path.append(aircraft);
-      aircraft_path.concat("-set.xml");
-      SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
-             << " from " << aircraft_path.str());
-      try {
-        readProperties(aircraft_path.str(), globals->get_props());
-      } catch (const sg_exception &e) {
-        string message = "Error reading default aircraft: ";
-        message += e.getFormattedMessage();
-        SG_LOG(SG_INPUT, SG_ALERT, message);
-        exit(2);
-      }
+    if ( aircraft.size() > 0 ) {
+        SGPath aircraft_path(globals->get_fg_root());
+        aircraft_path.append("Aircraft");
+        aircraft_path.append(aircraft);
+        aircraft_path.concat("-set.xml");
+        SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
+               << " from " << aircraft_path.str());
+        try {
+            readProperties(aircraft_path.str(), globals->get_props());
+        } catch (const sg_exception &e) {
+            string message = "Error reading default aircraft: ";
+            message += e.getFormattedMessage();
+            SG_LOG(SG_INPUT, SG_ALERT, message);
+            exit(2);
+        }
     } else {
-      SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
+        SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
     }
 
+    // parse options after loading aircraft to ensure any user
+    // overrides of defaults are honored.
     do_options(argc, argv);
 
     return true;
@@ -454,8 +576,24 @@ bool fgFindAirportID( const string& id, FGAirport *a ) {
 }
 
 
+// get airport elevation
+static double fgGetAirportElev( const string& id ) {
+    FGAirport a;
+    // double lon, lat;
+
+    SG_LOG( SG_GENERAL, SG_INFO,
+            "Finding elevation for airport: " << id );
+
+    if ( fgFindAirportID( id, &a ) ) {
+        return a.elevation;
+    } else {
+        return -9999.0;
+    }
+}
+
+
 // Preset lon/lat given an airport id
-bool fgSetPosFromAirportID( const string& id ) {
+static bool fgSetPosFromAirportID( const string& id ) {
     FGAirport a;
     // double lon, lat;
 
@@ -480,13 +618,11 @@ bool fgSetPosFromAirportID( const string& id ) {
     } else {
         return false;
     }
-
 }
 
 
-
 // Set current tower position lon/lat given an airport id
-bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
+static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
     FGAirport a;
     // tower height hard coded for now...
     float towerheight=50.0f;
@@ -508,7 +644,7 @@ bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
 
 
 // Set current_options lon/lat given an airport id and heading (degrees)
-bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
+static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
     FGRunway r;
     FGRunway found_r;
     double found_dir = 0.0;
@@ -525,16 +661,6 @@ bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
                 "Attempting to set starting position from runway code "
                 << id << " heading " << tgt_hdg );
 
-        // SGPath inpath( globals->get_fg_root() );
-        // inpath.append( "Airports" );
-        // inpath.append( "apt_simple" );
-        // airports.load( inpath.c_str() );
-
-        // SGPath outpath( globals->get_fg_root() );
-        // outpath.append( "Airports" );
-        // outpath.append( "simple.gdbm" );
-        // airports.dump_gdbm( outpath.c_str() );
-
         if ( ! runways.search( id, &r ) ) {
             SG_LOG( SG_GENERAL, SG_ALERT,
                     "Failed to find " << id << " in database." );
@@ -634,36 +760,262 @@ bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
 }
 
 
-void fgSetPosFromGlideSlope(void) {
-    double gs = fgGetDouble("/velocities/glideslope");
+// Set current_options lon/lat given an airport id and heading (degrees)
+static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
+    FGRunway r;
+    FGRunway found_r;
+    double heading = 0.0;
+    string runway;
+    bool match = false;
+
+    // standardize input number
+    string tmp = rwy.substr(1, 1);
+    if ( tmp == "L" || tmp == "R" || tmp == "C" ) {
+        runway = "0";
+        runway += rwy;
+    } else {
+        runway = rwy;
+    }
+
+    if ( id.length() ) {
+        // set initial position from runway and heading
+
+        SGPath path( globals->get_fg_root() );
+        path.append( "Airports" );
+        path.append( "runways.mk4" );
+        FGRunways runways( path.c_str() );
+
+        SG_LOG( SG_GENERAL, SG_INFO,
+                "Attempting to set starting position for "
+                << id << ":" << runway );
+
+        if ( ! runways.search( id, &r ) ) {
+            SG_LOG( SG_GENERAL, SG_ALERT,
+                    "Failed to find " << id << " in database." );
+            return false;
+        }
+
+        while ( r.id == id ) {
+            // forward direction
+            if ( r.rwy_no == runway ) {
+                found_r = r;
+                heading = r.heading;
+                match = true;
+                SG_LOG( SG_GENERAL, SG_INFO,
+                        "Runway " << r.rwy_no << " heading = " << heading );
+            }
+
+            // calculate reciprocal runway number
+            string snum = r.rwy_no;
+            int len = snum.length();
+            string letter = "";
+            string rev_letter = "";
+            int i;
+            for ( i = 0; i < len; ++i ) {
+                string tmp = snum.substr(i, 1);
+                if ( tmp == "L" ) {
+                    letter = "L";
+                    rev_letter = "R";
+                } else if ( tmp == "R" ) {
+                    letter = "R";
+                    rev_letter = "L";
+                } else if ( tmp == "C" ) {
+                    letter == "C";
+                    rev_letter = "C";
+                }
+            }
+            for ( i = 0; i < len; ++i ) {
+                string tmp = snum.substr(i, 1);
+                if ( tmp == "L" || tmp == "R" || tmp == "C" || tmp == " " ) {
+                    snum = snum.substr(0, i);
+                }
+            }
+            SG_LOG(SG_GENERAL, SG_DEBUG, "Runway num = '" << snum << "'");
+            int num = atoi( snum.c_str() ) + 18;
+            while ( num > 36 ) { num -= 36; }
+            while ( num <= 0 ) { num += 36; }
+
+            char recip_no[10];
+            snprintf( recip_no, 10, "%02d%s", num, rev_letter.c_str() );
+
+            // reverse direction
+            if ( (string)recip_no == runway ) {
+                found_r = r;
+                heading = r.heading + 180;
+                while ( heading > 360.0 ) { heading -= 360; }
+                match = true;
+                SG_LOG( SG_GENERAL, SG_INFO,
+                        "Runway " << r.rwy_no << " heading = " << heading );
+            }
+
+            runways.next( &r );
+        }
+    } else {
+        return false;
+    }
+
+    if ( match ) {
+        double lat2, lon2, az2;
+        double azimuth = heading + 180.0;
+        while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
+
+        SG_LOG( SG_GENERAL, SG_INFO,
+                "runway =  " << found_r.lon << ", " << found_r.lat
+                << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
+                << " heading = " << azimuth );
+    
+        geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
+                            azimuth,
+                            found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
+                            &lat2, &lon2, &az2 );
+
+        if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
+        {
+            double olat, olon;
+            double odist = fgGetDouble("/sim/presets/offset-distance");
+            odist *= SG_NM_TO_METER;
+            double oaz = azimuth;
+            if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
+            {
+                oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
+            }
+            while ( oaz >= 360.0 ) { oaz -= 360.0; }
+            geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
+            lat2=olat;
+            lon2=olon;
+        }
+
+        // presets
+        fgSetDouble("/sim/presets/longitude-deg",  lon2 );
+        fgSetDouble("/sim/presets/latitude-deg",  lat2 );
+        fgSetDouble("/sim/presets/heading-deg", heading );
+
+        // other code depends on the actual values being set ...
+        fgSetDouble("/position/longitude-deg",  lon2 );
+        fgSetDouble("/position/latitude-deg",  lat2 );
+        fgSetDouble("/orientation/heading-deg", heading );
+
+        SG_LOG( SG_GENERAL, SG_INFO,
+                "Position for " << id << " is ("
+                << lon2 << ", "
+                << lat2 << ") new heading is "
+                << heading );
+
+        return true;
+    } else {
+        return false;
+    }
+}
+
+
+static void fgSetDistOrAltFromGlideSlope() {
+    string apt_id = fgGetString("/sim/presets/airport-id");
+    double gs = fgGetDouble("/sim/presets/glideslope-deg")
+        * SG_DEGREES_TO_RADIANS ;
     double od = fgGetDouble("/sim/presets/offset-distance");
     double alt = fgGetDouble("/sim/presets/altitude-ft");
-    
-    //if glideslope and offset-distance are set and altitude is
-    //not, calculate the initial altitude
+
+    double apt_elev = 0.0;
+    if ( ! apt_id.empty() ) {
+        apt_elev = fgGetAirportElev( apt_id );
+        if ( apt_elev < -9990.0 ) {
+            apt_elev = 0.0;
+        }
+    } else {
+        apt_elev = 0.0;
+    }
+
     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
+        // set altitude from glideslope and offset-distance
         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
-        alt = fabs(od*tan(gs));
-        fgSetDouble("/sim/presets/altitude-ft",alt);
+        alt = fabs(od*tan(gs)) + apt_elev;
+        fgSetDouble("/sim/presets/altitude-ft", alt);
         fgSetBool("/sim/presets/onground", false);
         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
-        od  = alt/tan(gs);
+        // set offset-distance from glideslope and altitude
+        od  = (alt - apt_elev) / tan(gs);
         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
-        fgSetDouble("/sim/presets/offset-distance",od);
-        SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
+        fgSetDouble("/sim/presets/offset-distance", od);
+        SG_LOG(SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
                                        << od  << " nm");
     } else if( fabs(gs) > 0.01 ) {
-        SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
-                                  << " or offset-distance.  Resetting"
-                                  << " glideslope to zero" );
-        fgSetDouble("/velocities/glideslope",0);                                  
+        SG_LOG( SG_GENERAL, SG_ALERT,
+                "Glideslope given but not altitude or offset-distance." );
+        SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
+        fgSetDouble("/sim/presets/glideslope-deg", 0);
+        fgSetBool("/sim/presets/onground", true);
     }                              
-                                      
 }                       
 
+
+// Set the initial position based on presets (or defaults)
+bool fgInitPosition() {
+    bool set_pos = false;
+
+    // If glideslope is specified, then calculate offset-distance or
+    // altitude relative to glide slope if either of those was not
+    // specified.
+    fgSetDistOrAltFromGlideSlope();
+
+    // If we have an explicit, in-range lon/lat, don't change it, just use it.
+    // If not, check for an airport-id and use that.
+    // If not, default to the middle of the KSFO field.
+    // The default values for lon/lat are deliberately out of range
+    // so that the airport-id can take effect; valid lon/lat will
+    // override airport-id, however.
+    double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
+    double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
+    if ( lon_deg >= -180.0 && lon_deg <= 180.0
+         && lat_deg >= -90.0 && lat_deg <= 90.0 )
+    {
+        set_pos = true;
+    }
+
+    string apt = fgGetString("/sim/presets/airport-id");
+    string rwy_no = fgGetString("/sim/presets/runway");
+    double hdg = fgGetDouble("/sim/presets/heading-deg");
+    if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
+        // An airport + runway is requested
+        if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
+            // set tower position (a little off the heading for single
+            // runway airports)
+            fgSetTowerPosFromAirportID( apt, hdg );
+
+            set_pos = true;
+        }
+    }
+
+    if ( !set_pos && !apt.empty() ) {
+        if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
+            // set tower position (a little off the heading for single
+            // runway airports)
+            fgSetTowerPosFromAirportID( apt, hdg );
+
+            set_pos = true;
+        }
+    }
+
+    if ( !set_pos ) {
+        // No lon/lat specified, no airport specified, default to
+        // middle of KSFO field.
+        fgSetDouble("/sim/presets/longitude-deg", -122.374843);
+        fgSetDouble("/sim/presets/latitude-deg", 37.619002);
+    }
+
+    fgSetDouble( "/position/longitude-deg",
+                 fgGetDouble("/sim/presets/longitude-deg") );
+    fgSetDouble( "/position/latitude-deg",
+                 fgGetDouble("/sim/presets/latitude-deg") );
+    fgSetDouble( "/orientation/heading-deg",
+                 fgGetDouble("/sim/presets/heading-deg") );
+
+    return true;
+}
+
+
 // General house keeping initializations
-bool fgInitGeneral( void ) {
+bool fgInitGeneral() {
     string root;
 
 #if defined(FX) && defined(XMESA)
@@ -871,7 +1223,7 @@ SGTime *fgInitTime() {
 // initialization routines.  If you are adding a subsystem to flight
 // gear, its initialization call should located in this routine.
 // Returns non-zero if a problem encountered.
-bool fgInitSubsystems( void ) {
+bool fgInitSubsystems() {
     static const SGPropertyNode *longitude
         = fgGetNode("/sim/presets/longitude-deg");
     static const SGPropertyNode *latitude
@@ -916,9 +1268,7 @@ bool fgInitSubsystems( void ) {
         // Load the local scenery data
         double visibility_meters = fgGetDouble("/environment/visibility-m");
                 
-        global_tile_mgr.update( longitude->getDoubleValue(),
-                                latitude->getDoubleValue(),
-                                visibility_meters );
+        global_tile_mgr.update( visibility_meters );
     } else {
         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
         exit(-1);
@@ -1286,7 +1636,7 @@ bool fgInitSubsystems( void ) {
 }
 
 
-void fgReInitSubsystems( void )
+void fgReInitSubsystems()
 {
     static const SGPropertyNode *longitude
         = fgGetNode("/sim/presets/longitude-deg");
@@ -1305,12 +1655,8 @@ void fgReInitSubsystems( void )
     if ( !freeze ) {
         fgSetBool("/sim/freeze/master", true);
     }
-    
-    // Initialize the Scenery Management subsystem
-    // FIXME, what really needs to get initialized here, at the time
-    // this was commented out, scenery.init() was a noop
-    // scenery.init();
 
+    // Initialize the FDM
     fgInitFDM();
     
     // allocates structures so must happen before any of the flight