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