]> git.mxchange.org Git - flightgear.git/blob - src/Main/positioninit.cxx
Restructure positional finalisation for sim-reset.
[flightgear.git] / src / Main / positioninit.cxx
1 // positioninit.cxx - helpers relating to setting initial aircraft position
2 //
3 // Copyright (C) 2012 James Turner  zakalawe@mac.com
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #include "positioninit.hxx"
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 // simgear
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29
30 #include "globals.hxx"
31 #include "fg_props.hxx"
32
33 #include <Navaids/navlist.hxx>
34 #include <Airports/runways.hxx>
35 #include <Airports/simple.hxx>
36 #include <Airports/dynamics.hxx>
37 #include <AIModel/AIManager.hxx>
38
39 using std::endl;
40
41 namespace flightgear
42 {
43     
44 /// to avoid blocking when metar-fetch is enabled, but the network is
45 /// unresponsive, we need a timeout value. This value is reset on initPosition,
46 /// and tracked through each call to finalizePosition.
47 static SGTimeStamp global_finalizeTime;
48 static bool global_callbackRegistered = false;
49
50 static void finalizePosition();
51   
52 // Set current tower position lon/lat given an airport id
53 static bool fgSetTowerPosFromAirportID( const string& id) {
54   const FGAirport *a = fgFindAirportID( id);
55   if (a) {
56     SGGeod tower = a->getTowerLocation();
57     fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
58     fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
59     fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
60     return true;
61   } else {
62     return false;
63   }
64   
65 }
66
67 struct FGTowerLocationListener : SGPropertyChangeListener {
68   void valueChanged(SGPropertyNode* node) {
69     string id(node->getStringValue());
70     if (fgGetBool("/sim/tower/auto-position",true))
71     {
72       // enforce using closest airport when auto-positioning is enabled
73       const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
74       if (closest_airport && (id != closest_airport))
75       {
76         id = closest_airport;
77         node->setStringValue(id);
78       }
79     }
80     fgSetTowerPosFromAirportID(id);
81   }
82 };
83
84 struct FGClosestTowerLocationListener : SGPropertyChangeListener
85 {
86   void valueChanged(SGPropertyNode* )
87   {
88     // closest airport has changed
89     if (fgGetBool("/sim/tower/auto-position",true))
90     {
91       // update tower position
92       const char* id = fgGetString("/sim/airport/closest-airport-id", "");
93       if (id && *id!=0)
94         fgSetString("/sim/tower/airport-id", id);
95     }
96   }
97 };
98
99 void initTowerLocationListener() {
100   fgGetNode("/sim/tower/airport-id",  true)
101   ->addChangeListener( new FGTowerLocationListener(), true );
102   FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
103   fgGetNode("/sim/airport/closest-airport-id", true)
104   ->addChangeListener(ntcl , true );
105   fgGetNode("/sim/tower/auto-position", true)
106   ->addChangeListener(ntcl, true );
107 }
108
109 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
110 {
111   SGGeod startPos(aStartPos);
112   if (aTargetHeading == HUGE_VAL) {
113     aTargetHeading = aHeading;
114   }
115   
116   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
117     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
118     offsetDistance *= SG_NM_TO_METER;
119     double offsetAzimuth = aHeading;
120     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
121       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
122       aHeading = aTargetHeading;
123     }
124     
125     SGGeod offset;
126     double az2; // dummy
127     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
128     startPos = offset;
129   }
130   
131   // presets
132   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
133   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
134   fgSetDouble("/sim/presets/heading-deg", aHeading );
135   
136   // other code depends on the actual values being set ...
137   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
138   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
139   fgSetDouble("/orientation/heading-deg", aHeading );
140 }
141
142 // Set current_options lon/lat given an airport id and heading (degrees)
143 static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
144   if ( id.empty() )
145     return false;
146   
147   // set initial position from runway and heading
148   SG_LOG( SG_GENERAL, SG_INFO,
149          "Attempting to set starting position from airport code "
150          << id << " heading " << tgt_hdg );
151   
152   const FGAirport* apt = fgFindAirportID(id);
153   if (!apt) return false;
154   FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
155   fgSetString("/sim/atc/runway", r->ident().c_str());
156   
157   SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
158   fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
159   return true;
160 }
161
162 // Set current_options lon/lat given an airport id and parkig position name
163 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos )
164 {
165   if ( id.empty() )
166     return false;
167   
168   // can't see an easy way around this const_cast at the moment
169   FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
170   if (!apt) {
171     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
172     return false;
173   }
174   FGAirportDynamics* dcs = apt->getDynamics();
175   if (!dcs) {
176     SG_LOG( SG_GENERAL, SG_ALERT,
177            "Airport " << id << "does not appear to have parking information available");
178     return false;
179   }
180   
181   ParkingAssignment pka;
182   double radius = fgGetDouble("/sim/dimensions/radius-m");
183   if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
184     string fltType;
185     string acOperator;
186     SGPath acData;
187     try {
188       acData = globals->get_fg_home();
189       acData.append("aircraft-data");
190       string acfile = fgGetString("/sim/aircraft") + string(".xml");
191       acData.append(acfile);
192       SGPropertyNode root;
193       readProperties(acData.str(), &root);
194       SGPropertyNode * node = root.getNode("sim");
195       fltType    = node->getStringValue("aircraft-class", "NONE"     );
196       acOperator = node->getStringValue("aircraft-operator", "NONE"     );
197     } catch (const sg_exception &) {
198       SG_LOG(SG_GENERAL, SG_INFO,
199              "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
200       
201       // cout << path.str() << endl;
202     }
203     if (fltType.empty() || fltType == "NONE") {
204       SG_LOG(SG_GENERAL, SG_INFO,
205              "Aircraft type information not found in: " << acData.str() << ". Using default value");
206       fltType = fgGetString("/sim/aircraft-class"   );
207     }
208     if (acOperator.empty() || fltType == "NONE") {
209       SG_LOG(SG_GENERAL, SG_INFO,
210              "Aircraft operator information not found in: " << acData.str() << ". Using default value");
211       acOperator = fgGetString("/sim/aircraft-operator"   );
212     }
213     
214     string acType; // Currently not used by findAvailable parking, so safe to leave empty.
215     pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
216     if (pka.isValid()) {
217       fgGetString("/sim/presets/parkpos");
218       fgSetString("/sim/presets/parkpos", pka.parking()->getName());
219     } else {
220       SG_LOG( SG_GENERAL, SG_ALERT,
221              "Failed to find a suitable parking at airport " << id );
222       return false;
223     }
224   } else {
225     pka = dcs->getParkingByName(parkpos);
226     if (!pka.isValid()) {
227       SG_LOG( SG_GENERAL, SG_ALERT,
228                "Failed to find a parking at airport " << id << ":" << parkpos);
229       return false;
230     }
231   }
232   
233   fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
234   return true;
235 }
236
237
238 // Set current_options lon/lat given an airport id and runway number
239 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
240   if ( id.empty() )
241     return false;
242   
243   // set initial position from airport and runway number
244   SG_LOG( SG_GENERAL, SG_INFO,
245          "Attempting to set starting position for "
246          << id << ":" << rwy );
247   
248   const FGAirport* apt = fgFindAirportID(id);
249   if (!apt) {
250     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
251     return false;
252   }
253   
254   if (!apt->hasRunwayWithIdent(rwy)) {
255     SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
256            "Failed to find runway " << rwy <<
257            " at airport " << id << ". Using default runway." );
258     return false;
259   }
260   
261   FGRunway* r(apt->getRunwayByIdent(rwy));
262   fgSetString("/sim/atc/runway", r->ident().c_str());
263   SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
264   fgApplyStartOffset(startPos, r->headingDeg());
265   return true;
266 }
267
268
269 static void fgSetDistOrAltFromGlideSlope() {
270   // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
271   string apt_id = fgGetString("/sim/presets/airport-id");
272   double gs = fgGetDouble("/sim/presets/glideslope-deg")
273   * SG_DEGREES_TO_RADIANS ;
274   double od = fgGetDouble("/sim/presets/offset-distance-nm");
275   double alt = fgGetDouble("/sim/presets/altitude-ft");
276   
277   double apt_elev = 0.0;
278   if ( ! apt_id.empty() ) {
279     apt_elev = fgGetAirportElev( apt_id );
280     if ( apt_elev < -9990.0 ) {
281       apt_elev = 0.0;
282     }
283   } else {
284     apt_elev = 0.0;
285   }
286   
287   if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
288     // set altitude from glideslope and offset-distance
289     od *= SG_NM_TO_METER * SG_METER_TO_FEET;
290     alt = fabs(od*tan(gs)) + apt_elev;
291     fgSetDouble("/sim/presets/altitude-ft", alt);
292     fgSetBool("/sim/presets/onground", false);
293     SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
294            << alt  << " ft" );
295   } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
296     // set offset-distance from glideslope and altitude
297     od  = (alt - apt_elev) / tan(gs);
298     od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
299     fgSetDouble("/sim/presets/offset-distance-nm", od);
300     fgSetBool("/sim/presets/onground", false);
301     SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
302            << od  << " nm" );
303   } else if( fabs(gs) > 0.01 ) {
304     SG_LOG( SG_GENERAL, SG_ALERT,
305            "Glideslope given but not altitude or offset-distance." );
306     SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
307     fgSetDouble("/sim/presets/glideslope-deg", 0);
308     fgSetBool("/sim/presets/onground", true);
309   }
310 }
311
312
313 // Set current_options lon/lat given an airport id and heading (degrees)
314 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type )
315 {
316   FGNavList::TypeFilter filter(type);
317   const nav_list_type navlist = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
318   
319   if (navlist.size() == 0 ) {
320     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
321            << id << ":" << freq );
322     return false;
323   }
324   
325   if( navlist.size() > 1 ) {
326     std::ostringstream buf;
327     buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
328     for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
329       // NDB stored in kHz, VOR stored in MHz * 100 :-P
330       double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
331       string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
332       buf << (*it)->ident() << " "
333       << std::setprecision(5) << (double)((*it)->get_freq() * factor) << " "
334       << (*it)->get_lat() << "/" << (*it)->get_lon()
335       << endl;
336     }
337     
338     SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
339     return false;
340   }
341   
342   FGNavRecord *nav = navlist[0];
343   fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
344   return true;
345 }
346
347 // Set current_options lon/lat given an aircraft carrier id
348 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
349   
350   // set initial position from runway and heading
351   SGGeod geodPos;
352   double heading;
353   SGVec3d uvw;
354   if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
355     double lon = geodPos.getLongitudeDeg();
356     double lat = geodPos.getLatitudeDeg();
357     double alt = geodPos.getElevationFt();
358     
359     SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
360            << carrier << " at lat = " << lat << ", lon = " << lon
361            << ", alt = " << alt << ", heading = " << heading);
362     
363     fgSetDouble("/sim/presets/longitude-deg",  lon);
364     fgSetDouble("/sim/presets/latitude-deg",  lat);
365     fgSetDouble("/sim/presets/altitude-ft", alt);
366     fgSetDouble("/sim/presets/heading-deg", heading);
367     fgSetDouble("/position/longitude-deg",  lon);
368     fgSetDouble("/position/latitude-deg",  lat);
369     fgSetDouble("/position/altitude-ft", alt);
370     fgSetDouble("/orientation/heading-deg", heading);
371     
372     fgSetString("/sim/presets/speed-set", "UVW");
373     fgSetDouble("/velocities/uBody-fps", uvw(0));
374     fgSetDouble("/velocities/vBody-fps", uvw(1));
375     fgSetDouble("/velocities/wBody-fps", uvw(2));
376     fgSetDouble("/sim/presets/uBody-fps", uvw(0));
377     fgSetDouble("/sim/presets/vBody-fps", uvw(1));
378     fgSetDouble("/sim/presets/wBody-fps", uvw(2));
379     
380     fgSetBool("/sim/presets/onground", true);
381     
382     return true;
383   } else {
384     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
385            << carrier );
386     return false;
387   }
388 }
389
390 // Set current_options lon/lat given an airport id and heading (degrees)
391 static bool fgSetPosFromFix( const string& id )
392 {
393   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
394   FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
395   if (!fix) {
396     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
397     return false;
398   }
399   
400   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
401   return true;
402 }
403
404 // Set the initial position based on presets (or defaults)
405 bool initPosition()
406 {
407   global_finalizeTime = SGTimeStamp(); // reset to invalid
408   if (!global_callbackRegistered) {
409     globals->get_event_mgr()->addTask("finalizePosition", &finalizePosition, 0.1);
410     global_callbackRegistered = true;
411   }
412     
413   double gs = fgGetDouble("/sim/presets/glideslope-deg")
414   * SG_DEGREES_TO_RADIANS ;
415   double od = fgGetDouble("/sim/presets/offset-distance-nm");
416   double alt = fgGetDouble("/sim/presets/altitude-ft");
417   
418   bool set_pos = false;
419   
420   // If glideslope is specified, then calculate offset-distance or
421   // altitude relative to glide slope if either of those was not
422   // specified.
423   if ( fabs( gs ) > 0.01 ) {
424     fgSetDistOrAltFromGlideSlope();
425   }
426   
427   
428   // If we have an explicit, in-range lon/lat, don't change it, just use it.
429   // If not, check for an airport-id and use that.
430   // If not, default to the middle of the KSFO field.
431   // The default values for lon/lat are deliberately out of range
432   // so that the airport-id can take effect; valid lon/lat will
433   // override airport-id, however.
434   double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
435   double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
436   if ( lon_deg >= -180.0 && lon_deg <= 180.0
437       && lat_deg >= -90.0 && lat_deg <= 90.0 )
438   {
439     set_pos = true;
440   }
441   
442   string apt = fgGetString("/sim/presets/airport-id");
443   string rwy_no = fgGetString("/sim/presets/runway");
444   bool rwy_req = fgGetBool("/sim/presets/runway-requested");
445   string vor = fgGetString("/sim/presets/vor-id");
446   double vor_freq = fgGetDouble("/sim/presets/vor-freq");
447   string ndb = fgGetString("/sim/presets/ndb-id");
448   double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
449   string carrier = fgGetString("/sim/presets/carrier");
450   string parkpos = fgGetString("/sim/presets/parkpos");
451   string fix = fgGetString("/sim/presets/fix");
452   SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
453   double hdg = hdg_preset->getDoubleValue();
454   
455   // save some start parameters, so that we can later say what the
456   // user really requested. TODO generalize that and move it to options.cxx
457   static bool start_options_saved = false;
458   if (!start_options_saved) {
459     start_options_saved = true;
460     SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
461     
462     opt->setDoubleValue("latitude-deg", lat_deg);
463     opt->setDoubleValue("longitude-deg", lon_deg);
464     opt->setDoubleValue("heading-deg", hdg);
465     opt->setStringValue("airport", apt.c_str());
466     opt->setStringValue("runway", rwy_no.c_str());
467   }
468   
469   if (hdg > 9990.0)
470     hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
471   
472   if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
473     // An airport + parking position is requested
474     if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
475       // set tower position
476       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
477       fgSetString("/sim/tower/airport-id",  apt.c_str());
478       set_pos = true;
479     }
480   }
481   
482   if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
483     // An airport + runway is requested
484     if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
485       // set tower position (a little off the heading for single
486       // runway airports)
487       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
488       fgSetString("/sim/tower/airport-id",  apt.c_str());
489       set_pos = true;
490     }
491   }
492   
493   if ( !set_pos && !apt.empty() ) {
494     // An airport is requested (find runway closest to hdg)
495     if ( setPosFromAirportIDandHdg( apt, hdg ) ) {
496       // set tower position (a little off the heading for single
497       // runway airports)
498       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
499       fgSetString("/sim/tower/airport-id",  apt.c_str());
500       set_pos = true;
501     }
502   }
503   
504   if (hdg_preset->getDoubleValue() > 9990.0)
505     hdg_preset->setDoubleValue(hdg);
506   
507   if ( !set_pos && !vor.empty() ) {
508     // a VOR is requested
509     if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
510       set_pos = true;
511     }
512   }
513   
514   if ( !set_pos && !ndb.empty() ) {
515     // an NDB is requested
516     if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
517       set_pos = true;
518     }
519   }
520   
521   if ( !set_pos && !carrier.empty() ) {
522     // an aircraft carrier is requested
523     if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
524       set_pos = true;
525     }
526   }
527   
528   if ( !set_pos && !fix.empty() ) {
529     // a Fix is requested
530     if ( fgSetPosFromFix( fix ) ) {
531       set_pos = true;
532     }
533   }
534   
535   if ( !set_pos ) {
536     // No lon/lat specified, no airport specified, default to
537     // middle of KSFO field.
538     fgSetDouble("/sim/presets/longitude-deg", -122.374843);
539     fgSetDouble("/sim/presets/latitude-deg", 37.619002);
540   }
541   
542   fgSetDouble( "/position/longitude-deg",
543               fgGetDouble("/sim/presets/longitude-deg") );
544   fgSetDouble( "/position/latitude-deg",
545               fgGetDouble("/sim/presets/latitude-deg") );
546   fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
547   
548   // determine if this should be an on-ground or in-air start
549   if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
550     fgSetBool("/sim/presets/onground", false);
551   } else {
552     fgSetBool("/sim/presets/onground", true);
553   }
554   
555   fgSetBool("/sim/position-finalized", false);
556     
557   return true;
558 }
559   
560 bool finalizeMetar()
561 {
562   double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
563   string apt = fgGetString( "/sim/startup/options/airport" );
564   string rwy = fgGetString( "/sim/startup/options/runway" );
565   double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
566   string parkpos = fgGetString( "/sim/presets/parkpos" );
567   bool onground = fgGetBool( "/sim/presets/onground", false );
568   // this logic is taken from former startup.nas
569   bool needMetar = (hdg < 360.0) && !apt.empty() && (strthdg > 360.0) &&
570   rwy.empty() && onground && parkpos.empty();
571   
572   if (needMetar) {
573     // timeout so we don't spin forever if the network is down
574     if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 10000)) {
575       SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch");
576       return true;
577     }
578     
579     if (!fgGetBool( "/environment/metar/valid" )) {
580       // bit hacky - run these two subsystems. We can't run the whole
581       // lot since some view things aren't initialised and hence FGLight
582       // crashes.
583       globals->get_subsystem("http")->update(0.0);
584       globals->get_subsystem("environment")->update(0.0);
585       return false;
586     }
587     
588     SG_LOG(SG_ENVIRONMENT, SG_INFO,
589            "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
590     setPosFromAirportIDandHdg( apt, hdg );
591     // fall through to return true
592   } // of need-metar case
593   
594   return true;
595 }
596   
597 void finalizePosition()
598 {
599   // first call to finalize after an initPosition call
600   if (global_finalizeTime.get_usec() == 0) {
601     global_finalizeTime = SGTimeStamp::now();
602   }
603   
604   bool done = true;
605   
606     /* Scenarios require Nasal, so FGAIManager loads the scenarios,
607      * including its models such as a/c carriers, in its 'postinit',
608      * which is the very last thing we do.
609      * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
610      * one of the first things we do, long before scenarios/carriers are
611      * loaded. => When requested "initial preset position" relates to a
612      * carrier, recalculate the 'initial' position here 
613      */
614     std::string carrier = fgGetString("/sim/presets/carrier","");
615     if (!carrier.empty())
616     {
617         SG_LOG(SG_GENERAL, SG_INFO, "finalizePositioned: re-init-ing position on carrier");
618         // clear preset location and re-trigger position setup
619         fgSetDouble("/sim/presets/longitude-deg", 9999);
620         fgSetDouble("/sim/presets/latitude-deg", 9999);
621         initPosition();
622     } else {
623         done = finalizeMetar();
624     }
625   
626     fgSetBool("/sim/position-finalized", done);
627     if (done) {
628         globals->get_event_mgr()->removeTask("finalizePosition");
629         global_callbackRegistered = false;
630     }
631 }
632     
633 } // of namespace flightgear