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 <Navaids/positioned.hxx>
46 enum GPSDistanceUnits {
47 GPS_DIST_UNITS_NM = 0,
56 enum GPSAltitudeUnits {
61 enum GPSPressureUnits {
62 GPS_PRES_UNITS_IN = 1,
67 // --------------------- Waypoint / Flightplan stuff -----------------------------
68 // This should be merged with other similar stuff in FG at some point.
70 // NOTE - ORDERING IS IMPORTANT HERE - it matches the Bendix-King page ordering!
77 GPS_WP_VIRT // Used for virtual waypoints, such as the start of DTO operation.
81 GPS_IAF, // Initial approach fix
82 GPS_IAP, // Waypoint on approach sequence that isn't any of the others.
83 GPS_FAF, // Final approach fix
84 GPS_MAP, // Missed approach point
85 GPS_MAHP, // Initial missed approach holding point.
86 GPS_HDR, // A virtual 'waypoint' to represent the approach header in the fpl page
87 GPS_FENCE, // A virtual 'waypoint' to represent the NO WPT SEQ fence.
88 GPS_APP_NONE // Not part of the approach sequence - the default.
91 ostream& operator << (ostream& os, GPSAppWpType type);
96 GPSWaypoint(const std::string& aIdent, float lat, float lon, GPSWpType aType);
98 static GPSWaypoint* createFromPositioned(const FGPositioned* aFix);
101 string GetAprId(); // Returns the id with i, f, m or h added if appropriate. (Initial approach fix, final approach fix, etc)
103 float lat; // Radians
104 float lon; // Radians
106 GPSAppWpType appType; // only used for waypoints that are part of an approach sequence
109 typedef vector < GPSWaypoint* > gps_waypoint_array;
110 typedef gps_waypoint_array::iterator gps_waypoint_array_iterator;
111 typedef map < string, gps_waypoint_array > gps_waypoint_map;
112 typedef gps_waypoint_map::iterator gps_waypoint_map_iterator;
113 typedef gps_waypoint_map::const_iterator gps_waypoint_map_const_iterator;
115 class GPSFlightPlan {
117 vector<GPSWaypoint*> waypoints;
118 inline bool IsEmpty() { return(waypoints.size() == 0); }
121 // TODO - probably de-public the internals of the next 2 classes and add some methods!
122 // Instrument approach procedure base class
126 virtual ~FGIAP() = 0;
129 string _aptIdent; // The ident of the airport this approach is for
130 string _ident; // The approach ident.
131 string _name; // The full approach name.
132 string _rwyStr; // The string used to specify the rwy - eg "B" in this instance.
133 bool _precision; // True for precision approach, false for non-precision.
136 // Non-precision instrument approach procedure
137 class FGNPIAP : public FGIAP {
143 vector<GPSFlightPlan*> _approachRoutes; // The approach route(s) from the IAF(s) to the IF.
144 // NOTE: It is an assumption in the code that uses this that there is a unique IAF per approach route.
145 vector<GPSWaypoint*> _IAP; // The compulsory waypoints of the approach procedure (may duplicate one of the above).
146 // _IAP includes the FAF and MAF.
147 vector<GPSWaypoint*> _MAP; // The missed approach procedure (doesn't include the MAF).
150 typedef vector < FGIAP* > iap_list_type;
151 typedef map < string, iap_list_type > iap_map_type;
152 typedef iap_map_type::iterator iap_map_iterator;
154 // A class to encapsulate hr:min representation of time.
159 ClockTime(int hr, int min);
161 inline void set_hr(int hr) { _hr = hr; }
162 inline int hr() const { return(_hr); }
163 inline void set_min(int min) { _min = min; }
164 inline int min() const { return(_min); }
166 ClockTime operator+ (const ClockTime& t) {
167 int cumMin = _hr * 60 + _min + t.hr() * 60 + t.min();
168 ClockTime t2(cumMin / 60, cumMin % 60);
171 // Operator - has a max difference of 23:59,
172 // and assumes the day has wrapped if the second operand
173 // is larger that the first.
174 // eg. 2:59 - 3:00 = 23:59
175 ClockTime operator- (const ClockTime& t) {
176 int diff = (_hr * 60 + _min) - (t.hr() * 60 + t.min());
177 if(diff < 0) { diff += 24 * 60; }
178 ClockTime t2(diff / 60, diff % 60);
181 friend ostream& operator<< (ostream& out, const ClockTime& t);
188 // ------------------------------------------------------------------------------
190 // TODO - merge generic GPS functions instead and split out KLN specific stuff.
191 class DCLGPS : public SGSubsystem {
194 DCLGPS(RenderArea2D* instrument);
195 virtual ~DCLGPS() = 0;
197 virtual void draw(osg::State& state);
201 virtual void unbind();
202 virtual void update(double dt);
204 // Expand a SIAP ident to the full procedure name.
205 string ExpandSIAPIdent(const string& ident);
207 // Render string s in display field field at position x, y
208 // WHERE POSITION IS IN CHARACTER UNITS!
210 virtual void DrawText(const string& s, int field, int px, int py, bool bold = false);
212 // Render a char at a given position as above
213 virtual void DrawChar(char c, int field, int px, int py, bool bold = false);
215 virtual void ToggleOBSMode();
217 // Set the number of fields
218 inline void SetNumFields(int n) { _nFields = (n > _maxFields ? _maxFields : (n < 1 ? 1 : n)); }
221 // m if true, ft if false
222 inline void SetAltUnitsSI(bool b) { _altUnits = (b ? GPS_ALT_UNITS_M : GPS_ALT_UNITS_FT); }
223 // Returns true if alt units are SI (m), false if ft
224 inline bool GetAltUnitsSI() { return(_altUnits == GPS_ALT_UNITS_M ? true : false); }
225 // km and k/h if true, nm and kt if false
226 inline void SetDistVelUnitsSI(bool b) { _distUnits = (b ? GPS_DIST_UNITS_KM : GPS_DIST_UNITS_NM); _velUnits = (b ? GPS_VEL_UNITS_KPH : GPS_VEL_UNITS_KT); }
227 // Returns true if dist/vel units are SI
228 inline bool GetDistVelUnitsSI() { return(_distUnits == GPS_DIST_UNITS_KM && _velUnits == GPS_VEL_UNITS_KPH ? true : false); }
229 // Set baro units - 1 = in, 2 = mB, 3 = hP Wrapping if for the convienience of the GPS setter.
230 void SetBaroUnits(int n, bool wrap = false);
231 // Get baro units: 1 = in, 2 = mB, 3 = hP
232 inline int GetBaroUnits() { return((int)_baroUnits); }
234 // It is expected that specific GPS units will override these functions.
235 // Increase the CDI full-scale deflection (ie. increase the nm per dot) one (GPS unit dependent) increment. Wraps if necessary (GPS unit dependent).
236 virtual void CDIFSDIncrease();
237 // Ditto for decrease the distance per dot
238 virtual void CDIFSDDecrease();
241 ////inline void SetOverlays(Overlays* overlays) { _overlays = overlays; }
243 virtual void CreateDefaultFlightPlans();
245 void SetOBSFromWaypoint();
247 GPSWaypoint* GetActiveWaypoint();
248 // Get the (zero-based) position of the active waypoint in the active flightplan
249 // Returns -1 if no active waypoint.
250 int GetActiveWaypointIndex();
251 // Ditto for an arbitrary waypoint id
252 int GetWaypointIndex(const string& id);
255 float GetDistToActiveWaypoint();
256 // Returns degrees (magnetic)
257 float GetHeadingToActiveWaypoint();
258 // Returns degrees (magnetic)
259 float GetHeadingFromActiveWaypoint();
260 // Get the time to the active waypoint in seconds.
261 // Returns -1 if groundspeed < 30 kts
262 double GetTimeToActiveWaypoint();
263 // Get the time to the final waypoint in seconds.
264 // Returns -1 if groundspeed < 30 kts
266 // Get the time to a given waypoint (spec'd by ID) in seconds.
267 // returns -1 if groundspeed is less than 30kts.
268 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
269 // otherwise it will be a direct-to time.
270 double GetTimeToWaypoint(const string& id);
272 // Return true if waypoint alerting is occuring
273 inline bool GetWaypointAlert() const { return(_waypointAlert); }
274 // Return true if in OBS mode
275 inline bool GetOBSMode() const { return(_obsMode); }
276 // Return true if in Leg mode
277 inline bool GetLegMode() const { return(!_obsMode); }
279 // Clear a flightplan
280 void ClearFlightPlan(int n);
281 void ClearFlightPlan(GPSFlightPlan* fp);
283 // Returns true if an approach is loaded/armed/active in the active flight plan
284 inline bool ApproachLoaded() const { return(_approachLoaded); }
285 inline bool GetApproachArm() const { return(_approachArm); }
286 inline bool GetApproachActive() const { return(_approachActive); }
287 double GetCDIDeflection() const;
288 inline bool GetToFlag() const { return(_headingBugTo); }
290 // Initiate Direct To operation to the supplied ID.
291 void DtoInitiate(const string& id);
292 // Cancel Direct To operation
296 // Maximum number of display fields for this device
298 // Current number of on-screen fields
304 // Lower (y) border per field
305 int _yFieldBorder[4];
306 // Left (x) border per field
307 int _xFieldBorder[4];
308 // Field start in x dir (border is part of field since it is the normal char border - sometimes map mode etc draws in it)
310 // Field start in y dir (for completeness - KLN89 only has vertical divider.
313 // The number of pages on the cyclic knob control
314 unsigned int _nPages;
315 // The current page we're on (Not sure how this ties in with extra pages such as direct or nearest).
316 unsigned int _curPage;
319 RenderArea2D* _instrument;
322 GPSSpeedUnits _velUnits;
323 GPSDistanceUnits _distUnits;
324 GPSPressureUnits _baroUnits;
325 GPSAltitudeUnits _altUnits;
327 // CDI full-scale deflection, specified either as an index into a vector of values (standard values) or as a double precision float (intermediate values).
328 // This will influence how an externally driven CDI will display as well as the NAV1 page.
329 // Hence the variables are located here, not in the nav page class.
330 vector<float> _cdiScales;
331 unsigned int _currentCdiScaleIndex;
332 bool _cdiScaleTransition; // Set true when the floating CDI value is used during transitions
333 double _currentCdiScale; // The floating value to use.
334 unsigned int _targetCdiScaleIndex; // The target indexed value to attain during a transition.
335 unsigned int _sourceCdiScaleIndex; // The source indexed value during a transition - so we know which way we're heading!
336 // Timers to handle the transitions - not sure if we need these.
337 double _apprArmTimer;
338 double _apprActvTimer;
339 double _cdiTransitionTime; // Time for transition to occur in - normally 30sec but may be quicker if time to FAF < 30sec?
342 // Data and lookup functions
346 // Find first of any type of waypoint by id. (TODO - Possibly we should return multiple waypoints here).
347 GPSWaypoint* FindFirstById(const string& id) const;
348 GPSWaypoint* FindFirstByExactId(const string& id) const;
350 FGNavRecord* FindFirstVorById(const string& id, bool &multi, bool exact = false);
351 FGNavRecord* FindFirstNDBById(const string& id, bool &multi, bool exact = false);
352 const FGAirport* FindFirstAptById(const string& id, bool &multi, bool exact = false);
353 const FGFix* FindFirstIntById(const string& id, bool &multi, bool exact = false);
354 // Find the closest VOR to a position in RADIANS.
355 FGNavRecord* FindClosestVor(double lat_rad, double lon_rad);
357 // helper to implement the above FindFirstXXX methods
358 FGPositioned* FindTypedFirstById(const std::string& id, FGPositioned::Type ty, bool &multi, bool exact);
360 // Position, orientation and velocity.
361 // These should be read from FG's built-in GPS logic if possible.
362 // Use the property node pointers below to do this.
363 SGPropertyNode_ptr _lon_node;
364 SGPropertyNode_ptr _lat_node;
365 SGPropertyNode_ptr _alt_node;
366 SGPropertyNode_ptr _grnd_speed_node;
367 SGPropertyNode_ptr _true_track_node;
368 SGPropertyNode_ptr _mag_track_node;
369 // Present position. (Radians)
371 // Present altitude (ft). (Yuk! but it saves converting ft->m->ft every update).
373 // Reported position as measured by GPS. For now this is the same
374 // as present position, but in the future we might want to model
375 // GPS lat and lon errors.
376 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
377 // gps code and not our own.
378 double _gpsLat, _gpsLon; //(Radians)
379 // Hack - it seems that the GPS gets initialised before FG's initial position is properly set.
380 // By checking for abnormal slew in the position we can force a re-initialisation of active flight
381 // plan leg and anything else that might be affected.
382 // TODO - sort FlightGear's initialisation order properly!!!
383 double _checkLat, _checkLon; // (Radians)
384 double _groundSpeed_ms; // filtered groundspeed (m/s)
385 double _groundSpeed_kts; // ditto in knots
386 double _track; // filtered true track (degrees)
387 double _magTrackDeg; // magnetic track in degrees calculated from true track above
389 // _navFlagged is set true when GPS navigation is either not possible or not logical.
390 // This includes not receiving adequate signals, and not having an active flightplan entered.
393 // Positional functions copied from ATCutils that might get replaced
394 // INPUT in RADIANS, returns DEGREES!
396 double GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB);
398 //double GetHeadingFromTo(double latA, double lonA, double latB, double lonB);
400 // Given two positions (lat & lon in RADIANS), get the HORIZONTAL separation (in meters)
401 //double GetHorizontalSeparation(double lat1, double lon1, double lat2, double lon2);
403 // Proper great circle positional functions from The Aviation Formulary
404 // Returns distance in Nm, input in RADIANS.
405 double GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const;
407 // Input in RADIANS, output in DEGREES.
409 double GetGreatCircleCourse(double lat1, double lon1, double lat2, double lon2) const;
411 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
412 // Note that d should be less that 1/4 Earth diameter!
413 GPSWaypoint GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h);
415 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
416 // Note that d should be less that 1/4 Earth diameter!
417 GPSWaypoint GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h);
419 // Calculate the current cross-track deviation in nm.
420 // Returns zero if a sensible value cannot be calculated.
421 double CalcCrossTrackDeviation() const;
423 // Calculate the cross-track deviation between 2 arbitrary waypoints in nm.
424 // Returns zero if a sensible value cannot be calculated.
425 double CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const;
428 // GPS can have up to _maxFlightPlans flightplans stored, PLUS an active FP which may or my not be one of the stored ones.
429 // This is from KLN89, but is probably not far off the mark for most if not all GPS.
430 vector<GPSFlightPlan*> _flightPlans;
431 unsigned int _maxFlightPlans;
432 GPSFlightPlan* _activeFP;
434 // Modes of operation.
435 // This is currently somewhat Bendix-King specific, but probably applies fundamentally to other units as well
436 // Mode defaults to leg, but is OBS if _obsMode is true.
438 // _dto is set true for DTO operation
440 // 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).
442 // In OBS mode we need to know the set OBS heading
445 // Operational variables
446 GPSWaypoint _activeWaypoint;
447 GPSWaypoint _fromWaypoint;
449 float _crosstrackDist; // UNITS ??????????
450 double _eta; // ETA in SECONDS to active waypoint.
451 // Desired track for active leg, true and magnetic, in degrees
452 double _dtkTrue, _dtkMag;
453 bool _headingBugTo; // Set true when the heading bug is TO, false when FROM.
454 bool _waypointAlert; // Set true when waypoint alerting is happening. (This is a variable NOT a user-setting).
455 bool _departed; // Set when groundspeed first exceeds 30kts.
456 string _departureTimeString; // Ditto.
457 double _elapsedTime; // Elapsed time in seconds since departure
458 ClockTime _powerOnTime; // Time (hr:min) of unit power-up.
459 bool _powerOnTimerSet; // Indicates that we have set the above following power-up.
460 void SetPowerOnTimer();
462 void ResetPowerOnTimer();
463 // Set the alarm to go off at a given time.
464 inline void SetAlarm(int hr, int min) {
465 _alarmTime.set_hr(hr);
466 _alarmTime.set_min(min);
470 ClockTime _alarmTime;
473 // Configuration that affects flightplan operation
474 bool _turnAnticipationEnabled;
476 // Configuration that affects general operation
477 bool _suaAlertEnabled; // Alert user to potential SUA entry
478 bool _altAlertEnabled; // Alert user to min safe alt violation
480 // Magvar stuff. Might get some of this stuff (such as time) from FG in future.
483 list<string> _messageStack;
485 virtual void CreateFlightPlan(GPSFlightPlan* fp, vector<string> ids, vector<GPSWpType> wps);
487 // Orientate the GPS unit to a flightplan - ie. figure out from current position
488 // and possibly orientation which leg of the FP we are on.
489 virtual void OrientateToFlightPlan(GPSFlightPlan* fp);
491 // Ditto for active fp. Probably all we need really!
492 virtual void OrientateToActiveFlightPlan();
494 int _cleanUpPage; // -1 => no cleanup required.
497 iap_map_type _np_iap; // Non-precision approaches
498 iap_map_type _pr_iap; // Precision approaches
499 bool _approachLoaded; // Set true when an approach is loaded in the active flightplan
500 bool _approachArm; // Set true when in approach-arm mode
501 bool _approachReallyArmed; // Apparently, approach-arm mode can be set from an external GPS-APR switch outside 30nm from airport,
502 // but the CDI scale change doesn't happen until 30nm from airport. Bizarre that it can be armed without
503 // the scale change, but it's in the manual...
504 bool _approachActive; // Set true when in approach-active mode
505 GPSFlightPlan* _approachFP; // Current approach - not necessarily loaded.
506 string _approachID; // ID of the airport we have an approach loaded for - bit of a hack that can hopefully be removed in future.
507 // More hackery since we aren't actually storing an approach class... Doh!
508 string _approachAbbrev;
509 string _approachRwyStr;
512 #endif // _DCLGPS_HXX