1 // dclgps.hxx - a class to extend the operation of FG's current GPS
2 // code, and provide support for a KLN89-specific instrument. It
3 // is envisioned that eventually this file and class will be split
4 // up between current FG code and new KLN89-specific code and removed.
6 // Written by David Luff, started 2005.
8 // Copyright (C) 2005 - David C Luff: daveluff --AT-- ntlworld --D0T-- com
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
29 #include "render_area_2d.hxx"
35 #include <simgear/structure/subsystem_mgr.hxx>
36 #include <simgear/props/props.hxx>
37 #include <simgear/props/tiedpropertylist.hxx>
38 #include <Navaids/positioned.hxx>
48 // --------------------- Waypoint / Flightplan stuff -----------------------------
49 // This should be merged with other similar stuff in FG at some point.
51 // NOTE - ORDERING IS IMPORTANT HERE - it matches the Bendix-King page ordering!
58 GPS_WP_VIRT // Used for virtual waypoints, such as the start of DTO operation.
62 GPS_IAF, // Initial approach fix
63 GPS_IAP, // Waypoint on approach sequence that isn't any of the others.
64 GPS_FAF, // Final approach fix
65 GPS_MAP, // Missed approach point
66 GPS_MAHP, // Initial missed approach holding point.
67 GPS_HDR, // A virtual 'waypoint' to represent the approach header in the fpl page
68 GPS_FENCE, // A virtual 'waypoint' to represent the NO WPT SEQ fence.
69 GPS_APP_NONE // Not part of the approach sequence - the default.
72 std::ostream& operator << (std::ostream& os, GPSAppWpType type);
77 GPSWaypoint(const std::string& aIdent, float lat, float lon, GPSWpType aType);
79 static GPSWaypoint* createFromPositioned(const FGPositioned* aFix);
82 std::string GetAprId(); // Returns the id with i, f, m or h added if appropriate. (Initial approach fix, final approach fix, etc)
87 GPSAppWpType appType; // only used for waypoints that are part of an approach sequence
90 typedef std::vector < GPSWaypoint* > gps_waypoint_array;
91 typedef gps_waypoint_array::iterator gps_waypoint_array_iterator;
92 typedef std::map < std::string, gps_waypoint_array > gps_waypoint_map;
93 typedef gps_waypoint_map::iterator gps_waypoint_map_iterator;
94 typedef gps_waypoint_map::const_iterator gps_waypoint_map_const_iterator;
98 std::vector<GPSWaypoint*> waypoints;
99 inline bool IsEmpty() { return(waypoints.size() == 0); }
102 // TODO - probably de-public the internals of the next 2 classes and add some methods!
103 // Instrument approach procedure base class
107 virtual ~FGIAP() = 0;
110 std::string _aptIdent; // The ident of the airport this approach is for
111 std::string _ident; // The approach ident.
112 std::string _name; // The full approach name.
113 std::string _rwyStr; // The string used to specify the rwy - eg "B" in this instance.
114 bool _precision; // True for precision approach, false for non-precision.
117 // Non-precision instrument approach procedure
118 class FGNPIAP : public FGIAP {
124 std::vector<GPSFlightPlan*> _approachRoutes; // The approach route(s) from the IAF(s) to the IF.
125 // NOTE: It is an assumption in the code that uses this that there is a unique IAF per approach route.
126 std::vector<GPSWaypoint*> _IAP; // The compulsory waypoints of the approach procedure (may duplicate one of the above).
127 // _IAP includes the FAF and MAF, and the missed approach waypoints.
130 typedef std::vector < FGIAP* > iap_list_type;
131 typedef std::map < std::string, iap_list_type > iap_map_type;
132 typedef iap_map_type::iterator iap_map_iterator;
134 // A class to encapsulate hr:min representation of time.
139 ClockTime(int hr, int min);
141 inline void set_hr(int hr) { _hr = hr; }
142 inline int hr() const { return(_hr); }
143 inline void set_min(int min) { _min = min; }
144 inline int min() const { return(_min); }
146 ClockTime operator+ (const ClockTime& t) {
147 int cumMin = _hr * 60 + _min + t.hr() * 60 + t.min();
148 ClockTime t2(cumMin / 60, cumMin % 60);
151 // Operator - has a max difference of 23:59,
152 // and assumes the day has wrapped if the second operand
153 // is larger that the first.
154 // eg. 2:59 - 3:00 = 23:59
155 ClockTime operator- (const ClockTime& t) {
156 int diff = (_hr * 60 + _min) - (t.hr() * 60 + t.min());
157 if(diff < 0) { diff += 24 * 60; }
158 ClockTime t2(diff / 60, diff % 60);
161 friend std::ostream& operator<< (std::ostream& out, const ClockTime& t);
168 // ------------------------------------------------------------------------------
170 // TODO - merge generic GPS functions instead and split out KLN specific stuff.
171 class DCLGPS : public SGSubsystem {
174 DCLGPS(RenderArea2D* instrument);
175 virtual ~DCLGPS() = 0;
177 virtual void draw(osg::State& state);
181 virtual void unbind();
182 virtual void update(double dt);
184 // Expand a SIAP ident to the full procedure name.
185 std::string ExpandSIAPIdent(const std::string& ident);
187 // Render string s in display field field at position x, y
188 // WHERE POSITION IS IN CHARACTER UNITS!
190 virtual void DrawText(const std::string& s, int field, int px, int py, bool bold = false);
192 // Render a char at a given position as above
193 virtual void DrawChar(char c, int field, int px, int py, bool bold = false);
195 virtual void ToggleOBSMode();
197 // Set the number of fields
198 inline void SetNumFields(int n) { _nFields = (n > _maxFields ? _maxFields : (n < 1 ? 1 : n)); }
200 // It is expected that specific GPS units will override these functions.
201 // Increase the CDI full-scale deflection (ie. increase the nm per dot) one (GPS unit dependent) increment. Wraps if necessary (GPS unit dependent).
202 virtual void CDIFSDIncrease();
203 // Ditto for decrease the distance per dot
204 virtual void CDIFSDDecrease();
207 ////inline void SetOverlays(Overlays* overlays) { _overlays = overlays; }
209 virtual void CreateDefaultFlightPlans();
211 void SetOBSFromWaypoint();
213 GPSWaypoint* GetActiveWaypoint();
214 // Get the (zero-based) position of the active waypoint in the active flightplan
215 // Returns -1 if no active waypoint.
216 int GetActiveWaypointIndex();
217 // Ditto for an arbitrary waypoint id
218 int GetWaypointIndex(const std::string& id);
221 float GetDistToActiveWaypoint();
222 // Returns degrees (magnetic)
223 float GetHeadingToActiveWaypoint();
224 // Returns degrees (magnetic)
225 float GetHeadingFromActiveWaypoint();
226 // Get the time to the active waypoint in seconds.
227 // Returns -1 if groundspeed < 30 kts
228 double GetTimeToActiveWaypoint();
229 // Get the time to the final waypoint in seconds.
230 // Returns -1 if groundspeed < 30 kts
232 // Get the time to a given waypoint (spec'd by ID) in seconds.
233 // returns -1 if groundspeed is less than 30kts.
234 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
235 // otherwise it will be a direct-to time.
236 double GetTimeToWaypoint(const std::string& id);
238 // Return true if waypoint alerting is occuring
239 inline bool GetWaypointAlert() const { return(_waypointAlert); }
240 // Return true if in OBS mode
241 inline bool GetOBSMode() const { return(_obsMode); }
242 // Return true if in Leg mode
243 inline bool GetLegMode() const { return(!_obsMode); }
245 // Clear a flightplan
246 void ClearFlightPlan(int n);
247 void ClearFlightPlan(GPSFlightPlan* fp);
249 // Returns true if an approach is loaded/armed/active in the active flight plan
250 inline bool ApproachLoaded() const { return(_approachLoaded); }
251 inline bool GetApproachArm() const { return(_approachArm); }
252 inline bool GetApproachActive() const { return(_approachActive); }
253 double GetCDIDeflection() const;
254 inline bool GetToFlag() const { return(_headingBugTo); }
256 // Initiate Direct To operation to the supplied ID.
257 virtual void DtoInitiate(const std::string& id);
258 // Cancel Direct To operation
262 // Maximum number of display fields for this device
264 // Current number of on-screen fields
270 // Lower (y) border per field
271 int _yFieldBorder[4];
272 // Left (x) border per field
273 int _xFieldBorder[4];
274 // Field start in x dir (border is part of field since it is the normal char border - sometimes map mode etc draws in it)
276 // Field start in y dir (for completeness - KLN89 only has vertical divider.
279 // The number of pages on the cyclic knob control
280 unsigned int _nPages;
281 // The current page we're on (Not sure how this ties in with extra pages such as direct or nearest).
282 unsigned int _curPage;
285 RenderArea2D* _instrument;
287 // CDI full-scale deflection, specified either as an index into a vector of values (standard values) or as a double precision float (intermediate values).
288 // This will influence how an externally driven CDI will display as well as the NAV1 page.
289 // Hence the variables are located here, not in the nav page class.
290 std::vector<float> _cdiScales;
291 unsigned int _currentCdiScaleIndex;
292 bool _cdiScaleTransition; // Set true when the floating CDI value is used during transitions
293 double _currentCdiScale; // The floating value to use.
294 unsigned int _targetCdiScaleIndex; // The target indexed value to attain during a transition.
295 unsigned int _sourceCdiScaleIndex; // The source indexed value during a transition - so we know which way we're heading!
296 // Timers to handle the transitions - not sure if we need these.
297 double _apprArmTimer;
298 double _apprActvTimer;
299 double _cdiTransitionTime; // Time for transition to occur in - normally 30sec but may be quicker if time to FAF < 30sec?
302 // Data and lookup functions
306 void LoadApproachData();
308 // Find first of any type of waypoint by id. (TODO - Possibly we should return multiple waypoints here).
309 GPSWaypoint* FindFirstById(const std::string& id) const;
310 GPSWaypoint* FindFirstByExactId(const std::string& id) const;
312 FGNavRecord* FindFirstVorById(const std::string& id, bool &multi, bool exact = false);
313 FGNavRecord* FindFirstNDBById(const std::string& id, bool &multi, bool exact = false);
314 const FGAirport* FindFirstAptById(const std::string& id, bool &multi, bool exact = false);
315 const FGFix* FindFirstIntById(const std::string& id, bool &multi, bool exact = false);
316 // Find the closest VOR to a position in RADIANS.
317 FGNavRecord* FindClosestVor(double lat_rad, double lon_rad);
319 // helper to implement the above FindFirstXXX methods
320 FGPositioned* FindTypedFirstById(const std::string& id, FGPositioned::Type ty, bool &multi, bool exact);
322 // Position, orientation and velocity.
323 // These should be read from FG's built-in GPS logic if possible.
324 // Use the property node pointers below to do this.
325 SGPropertyNode_ptr _lon_node;
326 SGPropertyNode_ptr _lat_node;
327 SGPropertyNode_ptr _alt_node;
328 SGPropertyNode_ptr _grnd_speed_node;
329 SGPropertyNode_ptr _true_track_node;
330 SGPropertyNode_ptr _mag_track_node;
331 // Present position. (Radians)
333 // Present altitude (ft). (Yuk! but it saves converting ft->m->ft every update).
335 // Reported position as measured by GPS. For now this is the same
336 // as present position, but in the future we might want to model
337 // GPS lat and lon errors.
338 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
339 // gps code and not our own.
340 double _gpsLat, _gpsLon; //(Radians)
341 // Hack - it seems that the GPS gets initialised before FG's initial position is properly set.
342 // By checking for abnormal slew in the position we can force a re-initialisation of active flight
343 // plan leg and anything else that might be affected.
344 // TODO - sort FlightGear's initialisation order properly!!!
345 double _checkLat, _checkLon; // (Radians)
346 double _groundSpeed_ms; // filtered groundspeed (m/s)
347 double _groundSpeed_kts; // ditto in knots
348 double _track; // filtered true track (degrees)
349 double _magTrackDeg; // magnetic track in degrees calculated from true track above
351 // _navFlagged is set true when GPS navigation is either not possible or not logical.
352 // This includes not receiving adequate signals, and not having an active flightplan entered.
355 // Positional functions copied from ATCutils that might get replaced
356 // INPUT in RADIANS, returns DEGREES!
358 double GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB);
360 //double GetHeadingFromTo(double latA, double lonA, double latB, double lonB);
362 // Given two positions (lat & lon in RADIANS), get the HORIZONTAL separation (in meters)
363 //double GetHorizontalSeparation(double lat1, double lon1, double lat2, double lon2);
365 // Proper great circle positional functions from The Aviation Formulary
366 // Returns distance in Nm, input in RADIANS.
367 double GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const;
369 // Input in RADIANS, output in DEGREES.
371 double GetGreatCircleCourse(double lat1, double lon1, double lat2, double lon2) const;
373 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
374 // Note that d should be less that 1/4 Earth diameter!
375 GPSWaypoint GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h);
377 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
378 // Note that d should be less that 1/4 Earth diameter!
379 GPSWaypoint GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h);
381 // Calculate the current cross-track deviation in nm.
382 // Returns zero if a sensible value cannot be calculated.
383 double CalcCrossTrackDeviation() const;
385 // Calculate the cross-track deviation between 2 arbitrary waypoints in nm.
386 // Returns zero if a sensible value cannot be calculated.
387 double CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const;
390 // GPS can have up to _maxFlightPlans flightplans stored, PLUS an active FP which may or my not be one of the stored ones.
391 // This is from KLN89, but is probably not far off the mark for most if not all GPS.
392 std::vector<GPSFlightPlan*> _flightPlans;
393 unsigned int _maxFlightPlans;
394 GPSFlightPlan* _activeFP;
396 // Modes of operation.
397 // This is currently somewhat Bendix-King specific, but probably applies fundamentally to other units as well
398 // Mode defaults to leg, but is OBS if _obsMode is true.
400 // _dto is set true for DTO operation
402 // In leg mode, we need to know if we are displaying a from and to waypoint, or just the to waypoint (eg. when OBS mode is cancelled).
404 // In OBS mode we need to know the set OBS heading
407 // Operational variables
408 GPSWaypoint _activeWaypoint;
409 GPSWaypoint _fromWaypoint;
411 float _crosstrackDist; // UNITS ??????????
412 double _eta; // ETA in SECONDS to active waypoint.
413 // Desired track for active leg, true and magnetic, in degrees
414 double _dtkTrue, _dtkMag;
415 bool _headingBugTo; // Set true when the heading bug is TO, false when FROM.
416 bool _waypointAlert; // Set true when waypoint alerting is happening. (This is a variable NOT a user-setting).
417 bool _departed; // Set when groundspeed first exceeds 30kts.
418 std::string _departureTimeString; // Ditto.
419 double _elapsedTime; // Elapsed time in seconds since departure
420 ClockTime _powerOnTime; // Time (hr:min) of unit power-up.
421 bool _powerOnTimerSet; // Indicates that we have set the above following power-up.
422 void SetPowerOnTimer();
424 void ResetPowerOnTimer();
425 // Set the alarm to go off at a given time.
426 inline void SetAlarm(int hr, int min) {
427 _alarmTime.set_hr(hr);
428 _alarmTime.set_min(min);
432 ClockTime _alarmTime;
435 // Configuration that affects flightplan operation
436 bool _turnAnticipationEnabled;
438 // Magvar stuff. Might get some of this stuff (such as time) from FG in future.
441 std::list<std::string> _messageStack;
443 virtual void CreateFlightPlan(GPSFlightPlan* fp, std::vector<std::string> ids, std::vector<GPSWpType> wps);
445 // Orientate the GPS unit to a flightplan - ie. figure out from current position
446 // and possibly orientation which leg of the FP we are on.
447 virtual void OrientateToFlightPlan(GPSFlightPlan* fp);
449 // Ditto for active fp. Probably all we need really!
450 virtual void OrientateToActiveFlightPlan();
452 int _cleanUpPage; // -1 => no cleanup required.
455 iap_map_type _np_iap; // Non-precision approaches
456 iap_map_type _pr_iap; // Precision approaches
457 bool _approachLoaded; // Set true when an approach is loaded in the active flightplan
458 bool _approachArm; // Set true when in approach-arm mode
459 bool _approachReallyArmed; // Apparently, approach-arm mode can be set from an external GPS-APR switch outside 30nm from airport,
460 // but the CDI scale change doesn't happen until 30nm from airport. Bizarre that it can be armed without
461 // the scale change, but it's in the manual...
462 bool _approachActive; // Set true when in approach-active mode
463 GPSFlightPlan* _approachFP; // Current approach - not necessarily loaded.
464 std::string _approachID; // ID of the airport we have an approach loaded for - bit of a hack that can hopefully be removed in future.
465 // More hackery since we aren't actually storing an approach class... Doh!
466 std::string _approachAbbrev;
467 std::string _approachRwyStr;
469 simgear::TiedPropertyList _tiedProperties;
472 #endif // _DCLGPS_HXX