Debian Codegraph @

src/Instrumentation/dclgps.hxx

raw symbols SCIP
1 /*
2 * SPDX-License-Identifier: GPL-2.0+
3 * SPDX-FileCopyrightText: 2005 (C) David C Luff: daveluff --AT-- ntlworld --D0T-- com
4 *
5 * dclgps.hxx - a class to extend the operation of FG's current GPS
6 * code, and provide support for a KLN89-specific instrument. It
7 * is envisioned that eventually this file and class will be split
8 * up between current FG code and new KLN89-specific code and removed
9 *
10 * Written by David Luff, started 2005.
11 *
12 * Copyright (C) 2005 - David C Luff: daveluff --AT-- ntlworld --D0T-- com
13 *
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 *
28 * $Id$
29 */
30
31 #pragma once
32
33 #include <Cockpit/render_area_2d.hxx>
34
35 #include <string>
36 #include <list>
37 #include <vector>
38 #include <map>
39
40 #include <simgear/structure/subsystem_mgr.hxx>
41 #include <simgear/props/props.hxx>
42 #include <simgear/props/tiedpropertylist.hxx>
43 #include <Navaids/positioned.hxx>
44
45 class SGTime;
46 class FGPositioned;
47
48 // XXX fix me
49 class FGNavRecord;
50 class FGAirport;
51 class FGFix;
52
53 // --------------------- Waypoint / Flightplan stuff -----------------------------
54 // This should be merged with other similar stuff in FG at some point.
55
56 // NOTE - ORDERING IS IMPORTANT HERE - it matches the Bendix-King page ordering!
57 enum GPSWpType {
58 GPS_WP_APT = 0,
59 GPS_WP_VOR,
60 GPS_WP_NDB,
61 GPS_WP_INT,
62 GPS_WP_USR,
63 GPS_WP_VIRT // Used for virtual waypoints, such as the start of DTO operation.
64 };
65
66 enum GPSAppWpType {
67 GPS_IAF, // Initial approach fix
68 GPS_IAP, // Waypoint on approach sequence that isn't any of the others.
69 GPS_FAF, // Final approach fix
70 GPS_MAP, // Missed approach point
71 GPS_MAHP, // Initial missed approach holding point.
72 GPS_HDR, // A virtual 'waypoint' to represent the approach header in the fpl page
73 GPS_FENCE, // A virtual 'waypoint' to represent the NO WPT SEQ fence.
74 GPS_APP_NONE // Not part of the approach sequence - the default.
75 };
76
77 std::ostream& operator << (std::ostream& os, GPSAppWpType type);
78
79 struct GPSWaypoint {
80 GPSWaypoint();
81
82 GPSWaypoint(const std::string& aIdent, float lat, float lon, GPSWpType aType);
83
84 static GPSWaypoint* createFromPositioned(const FGPositioned* aFix);
85
86 ~GPSWaypoint();
87 std::string GetAprId(); // Returns the id with i, f, m or h added if appropriate. (Initial approach fix, final approach fix, etc)
88 std::string id;
89 float lat; // Radians
90 float lon; // Radians
91 GPSWpType type;
92 GPSAppWpType appType; // only used for waypoints that are part of an approach sequence
93 };
94
95 typedef std::vector < GPSWaypoint* > gps_waypoint_array;
96 typedef gps_waypoint_array::iterator gps_waypoint_array_iterator;
97 typedef std::map < std::string, gps_waypoint_array > gps_waypoint_map;
98 typedef gps_waypoint_map::iterator gps_waypoint_map_iterator;
99 typedef gps_waypoint_map::const_iterator gps_waypoint_map_const_iterator;
100
101 class GPSFlightPlan
102 {
103 public:
104 std::vector<GPSWaypoint*> waypoints;
105 inline bool IsEmpty() { return waypoints.empty(); }
106 };
107
108 // TODO: probably de-public the internals of the next 2 classes and add some methods!
109 // Instrument approach procedure base class
110 class FGIAP
111 {
112 public:
113 FGIAP();
114 virtual ~FGIAP() = 0;
115
116 //protected:
117 std::string _aptIdent; // The ident of the airport this approach is for
118 std::string _ident; // The approach ident.
119 std::string _name; // The full approach name.
120 std::string _rwyStr; // The string used to specify the rwy - eg "B" in this instance.
121 bool _precision; // True for precision approach, false for non-precision.
122 };
123
124 // Non-precision instrument approach procedure
125 class FGNPIAP : public FGIAP
126 {
127 public:
128 FGNPIAP();
129 ~FGNPIAP();
130
131 //private:
132 public:
133 std::vector<GPSFlightPlan*> _approachRoutes; // The approach route(s) from the IAF(s) to the IF.
134 // NOTE: It is an assumption in the code that uses this that there is a unique IAF per approach route.
135 std::vector<GPSWaypoint*> _IAP; // The compulsory waypoints of the approach procedure (may duplicate one of the above).
136 // _IAP includes the FAF and MAF, and the missed approach waypoints.
137 };
138
139 typedef std::vector < FGIAP* > iap_list_type;
140 typedef std::map < std::string, iap_list_type > iap_map_type;
141 typedef iap_map_type::iterator iap_map_iterator;
142
143 // A class to encapsulate hr:min representation of time.
144 class ClockTime
145 {
146 public:
147 ClockTime();
148 ClockTime(int hr, int min);
149 ~ClockTime();
150 inline void set_hr(int hr) { _hr = hr; }
151 inline int hr() const { return(_hr); }
152 inline void set_min(int min) { _min = min; }
153 inline int min() const { return(_min); }
154
155 ClockTime operator+ (const ClockTime& t) {
156 int cumMin = _hr * 60 + _min + t.hr() * 60 + t.min();
157 ClockTime t2(cumMin / 60, cumMin % 60);
158 return(t2);
159 }
160 // Operator - has a max difference of 23:59,
161 // and assumes the day has wrapped if the second operand
162 // is larger that the first.
163 // eg. 2:59 - 3:00 = 23:59
164 ClockTime operator- (const ClockTime& t) {
165 int diff = (_hr * 60 + _min) - (t.hr() * 60 + t.min());
166 if(diff < 0) { diff += 24 * 60; }
167 ClockTime t2(diff / 60, diff % 60);
168 return(t2);
169 }
170 friend std::ostream& operator<< (std::ostream& out, const ClockTime& t);
171
172 private:
173 int _hr;
174 int _min;
175 };
176
177 // AlignedProjection - a class to project an area local to a runway onto an orthogonal co-ordinate system
178 // with the origin at the threshold and the runway aligned with the y axis.
179 class AlignedProjection
180 {
181 public:
182 AlignedProjection();
183 AlignedProjection(const SGGeod& centre, double heading);
184 ~AlignedProjection();
185
186 void Init(const SGGeod& centre, double heading);
187
188 // Convert a lat/lon co-ordinate (degrees) to the local projection (meters)
189 SGVec3d ConvertToLocal(const SGGeod& pt);
190
191 // Convert a local projection co-ordinate (meters) to lat/lon (degrees)
192 SGGeod ConvertFromLocal(const SGVec3d& pt);
193
194 private:
195 SGGeod _origin; // lat/lon of local area origin (the threshold)
196 double _theta; // the rotation angle for alignment in radians
197 double _correction_factor; // Reduction in surface distance per degree of longitude due to latitude. Saves having to do a cos() every call.
198 };
199
200 // ------------------------------------------------------------------------------
201
202 // TODO: merge generic GPS functions instead and split out KLN specific stuff.
203 class DCLGPS : public SGSubsystem
204 {
205 public:
206 DCLGPS(RenderArea2D* instrument);
207 virtual ~DCLGPS() = 0;
208
209 // Subsystem API.
210 void bind() override;
211 void init() override;
212 void unbind() override;
213 void update(double dt) override;
214
215 virtual void draw(osg::State& state);
216
217 // Expand a SIAP ident to the full procedure name.
218 std::string ExpandSIAPIdent(const std::string& ident);
219
220 // Render string s in display field field at position x, y
221 // WHERE POSITION IS IN CHARACTER UNITS!
222 // zero y at bottom?
223 virtual void DrawText(const std::string& s, int field, int px, int py, bool bold = false);
224
225 // Render a char at a given position as above
226 virtual void DrawChar(char c, int field, int px, int py, bool bold = false);
227
228 virtual void ToggleOBSMode();
229
230 // Set the number of fields
231 inline void SetNumFields(int n) { _nFields = (n > _maxFields ? _maxFields : (n < 1 ? 1 : n)); }
232
233 // It is expected that specific GPS units will override these functions.
234 // Increase the CDI full-scale deflection (ie. increase the nm per dot) one (GPS unit dependent) increment. Wraps if necessary (GPS unit dependent).
235 virtual void CDIFSDIncrease();
236 // Ditto for decrease the distance per dot
237 virtual void CDIFSDDecrease();
238
239 // Host specifc
240 ////inline void SetOverlays(Overlays* overlays) { _overlays = overlays; }
241
242 virtual void CreateDefaultFlightPlans();
243
244 void SetOBSFromWaypoint();
245
246 GPSWaypoint* GetActiveWaypoint();
247 // Get the (zero-based) position of the active waypoint in the active flightplan
248 // Returns -1 if no active waypoint.
249 int GetActiveWaypointIndex();
250 // Ditto for an arbitrary waypoint id
251 int GetWaypointIndex(const std::string& id);
252
253 // Returns meters
254 float GetDistToActiveWaypoint();
255 // Returns degrees (magnetic)
256 float GetHeadingToActiveWaypoint();
257 // Returns degrees (magnetic)
258 float GetHeadingFromActiveWaypoint();
259 // Get the time to the active waypoint in seconds.
260 // Returns -1 if groundspeed < 30 kts
261 double GetTimeToActiveWaypoint();
262 // Get the time to the final waypoint in seconds.
263 // Returns -1 if groundspeed < 30 kts
264 double GetETE();
265 // Get the time to a given waypoint (spec'd by ID) in seconds.
266 // returns -1 if groundspeed is less than 30kts.
267 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
268 // otherwise it will be a direct-to time.
269 double GetTimeToWaypoint(const std::string& id);
270
271 // Return true if waypoint alerting is occuring
272 inline bool GetWaypointAlert() const { return(_waypointAlert); }
273 // Return true if in OBS mode
274 inline bool GetOBSMode() const { return(_obsMode); }
275 // Return true if in Leg mode
276 inline bool GetLegMode() const { return(!_obsMode); }
277
278 // Clear a flightplan
279 void ClearFlightPlan(int n);
280 void ClearFlightPlan(GPSFlightPlan* fp);
281
282 // Returns true if an approach is loaded/armed/active in the active flight plan
283 inline bool ApproachLoaded() const { return(_approachLoaded); }
284 inline bool GetApproachArm() const { return(_approachArm); }
285 inline bool GetApproachActive() const { return(_approachActive); }
286 double GetCDIDeflection() const;
287 inline bool GetToFlag() const { return(_headingBugTo); }
288
289 // Initiate Direct To operation to the supplied ID.
290 virtual void DtoInitiate(const std::string& id);
291 // Cancel Direct To operation
292 void DtoCancel();
293
294 protected:
295 // Maximum number of display fields for this device
296 int _maxFields;
297 // Current number of on-screen fields
298 int _nFields;
299 // Full x border
300 int _xBorder;
301 // Full y border
302 int _yBorder;
303 // Lower (y) border per field
304 int _yFieldBorder[4];
305 // Left (x) border per field
306 int _xFieldBorder[4];
307 // Field start in x dir (border is part of field since it is the normal char border - sometimes map mode etc draws in it)
308 int _xFieldStart[4];
309 // Field start in y dir (for completeness - KLN89 only has vertical divider.
310 int _yFieldStart[4];
311
312 // The number of pages on the cyclic knob control
313 unsigned int _nPages;
314 // The current page we're on (Not sure how this ties in with extra pages such as direct or nearest).
315 unsigned int _curPage;
316
317 // 2D rendering area
318 RenderArea2D* _instrument;
319
320 // CDI full-scale deflection, specified either as an index into a vector of values (standard values) or as a double precision float (intermediate values).
321 // This will influence how an externally driven CDI will display as well as the NAV1 page.
322 // Hence the variables are located here, not in the nav page class.
323 std::vector<float> _cdiScales;
324 unsigned int _currentCdiScaleIndex;
325 bool _cdiScaleTransition; // Set true when the floating CDI value is used during transitions
326 double _currentCdiScale; // The floating value to use.
327 unsigned int _targetCdiScaleIndex; // The target indexed value to attain during a transition.
328 unsigned int _sourceCdiScaleIndex; // The source indexed value during a transition - so we know which way we're heading!
329 // Timers to handle the transitions - not sure if we need these.
330 double _apprArmTimer;
331 double _apprActvTimer;
332 double _cdiTransitionTime; // Time for transition to occur in - normally 30sec but may be quicker if time to FAF < 30sec?
333 //
334
335 // Data and lookup functions
336
337 protected:
338 void LoadApproachData();
339
340 // Find first of any type of waypoint by id. (TODO: Possibly we should return multiple waypoints here).
341 GPSWaypoint* FindFirstById(const std::string& id) const;
342 GPSWaypoint* FindFirstByExactId(const std::string& id) const;
343
344 FGNavRecord* FindFirstVorById(const std::string& id, bool &multi, bool exact = false);
345 FGNavRecord* FindFirstNDBById(const std::string& id, bool &multi, bool exact = false);
346 const FGAirport* FindFirstAptById(const std::string& id, bool &multi, bool exact = false);
347 const FGFix* FindFirstIntById(const std::string& id, bool &multi, bool exact = false);
348 // Find the closest VOR to a position in RADIANS.
349 FGNavRecord* FindClosestVor(double lat_rad, double lon_rad);
350
351 // helper to implement the above FindFirstXXX methods
352 FGPositioned* FindTypedFirstById(const std::string& id, FGPositioned::Type ty, bool &multi, bool exact);
353
354 // Position, orientation and velocity.
355 // These should be read from FG's built-in GPS logic if possible.
356 // Use the property node pointers below to do this.
357 SGPropertyNode_ptr _lon_node;
358 SGPropertyNode_ptr _lat_node;
359 SGPropertyNode_ptr _alt_node;
360 SGPropertyNode_ptr _grnd_speed_node;
361 SGPropertyNode_ptr _true_track_node;
362 SGPropertyNode_ptr _mag_track_node;
363 // Present position. (Radians)
364 double _lat, _lon;
365 // Present altitude (ft). (Yuk! but it saves converting ft->m->ft every update).
366 double _alt;
367 // Reported position as measured by GPS. For now this is the same
368 // as present position, but in the future we might want to model
369 // GPS lat and lon errors.
370 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
371 // gps code and not our own.
372 double _gpsLat, _gpsLon; //(Radians)
373 // Hack - it seems that the GPS gets initialised before FG's initial position is properly set.
374 // By checking for abnormal slew in the position we can force a re-initialisation of active flight
375 // plan leg and anything else that might be affected.
376 // TODO: sort FlightGear's initialisation order properly!!!
377 double _checkLat, _checkLon; // (Radians)
378 double _groundSpeed_ms; // filtered groundspeed (m/s)
379 double _groundSpeed_kts; // ditto in knots
380 double _track; // filtered true track (degrees)
381 double _magTrackDeg; // magnetic track in degrees calculated from true track above
382
383 // _navFlagged is set true when GPS navigation is either not possible or not logical.
384 // This includes not receiving adequate signals, and not having an active flightplan entered.
385 bool _navFlagged;
386
387 // Positional functions copied from ATCutils that might get replaced
388 // INPUT in RADIANS, returns DEGREES!
389 // Magnetic
390 double GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB);
391 // True
392 //double GetHeadingFromTo(double latA, double lonA, double latB, double lonB);
393
394 // Given two positions (lat & lon in RADIANS), get the HORIZONTAL separation (in meters)
395 //double GetHorizontalSeparation(double lat1, double lon1, double lat2, double lon2);
396
397 // Proper great circle positional functions from The Aviation Formulary
398 // Returns distance in Nm, input in RADIANS.
399 double GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const;
400
401 // Input in RADIANS, output in DEGREES.
402 // True
403 double GetGreatCircleCourse(double lat1, double lon1, double lat2, double lon2) const;
404
405 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
406 // Note that d should be less that 1/4 Earth diameter!
407 GPSWaypoint GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h);
408
409 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
410 // Note that d should be less that 1/4 Earth diameter!
411 GPSWaypoint GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h);
412
413 // Calculate the current cross-track deviation in nm.
414 // Returns zero if a sensible value cannot be calculated.
415 double CalcCrossTrackDeviation() const;
416
417 // Calculate the cross-track deviation between 2 arbitrary waypoints in nm.
418 // Returns zero if a sensible value cannot be calculated.
419 double CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const;
420
421 // Flightplans
422 // GPS can have up to _maxFlightPlans flightplans stored, PLUS an active FP which may or my not be one of the stored ones.
423 // This is from KLN89, but is probably not far off the mark for most if not all GPS.
424 std::vector<GPSFlightPlan*> _flightPlans;
425 unsigned int _maxFlightPlans;
426 GPSFlightPlan* _activeFP;
427
428 // Modes of operation.
429 // This is currently somewhat Bendix-King specific, but probably applies fundamentally to other units as well
430 // Mode defaults to leg, but is OBS if _obsMode is true.
431 bool _obsMode;
432 // _dto is set true for DTO operation
433 bool _dto;
434 // 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).
435 bool _fullLegMode;
436 // In OBS mode we need to know the set OBS heading
437 int _obsHeading;
438
439 // Operational variables
440 GPSWaypoint _activeWaypoint;
441 GPSWaypoint _fromWaypoint;
442 float _dist2Act;
443 float _crosstrackDist; // UNITS ??????????
444 double _eta; // ETA in SECONDS to active waypoint.
445 // Desired track for active leg, true and magnetic, in degrees
446 double _dtkTrue, _dtkMag;
447 bool _headingBugTo; // Set true when the heading bug is TO, false when FROM.
448 bool _waypointAlert; // Set true when waypoint alerting is happening. (This is a variable NOT a user-setting).
449 bool _departed; // Set when groundspeed first exceeds 30kts.
450 std::string _departureTimeString; // Ditto.
451 double _elapsedTime; // Elapsed time in seconds since departure
452 ClockTime _powerOnTime; // Time (hr:min) of unit power-up.
453 bool _powerOnTimerSet; // Indicates that we have set the above following power-up.
454 void SetPowerOnTimer();
455
456 public:
457 void ResetPowerOnTimer();
458 // Set the alarm to go off at a given time.
459 inline void SetAlarm(int hr, int min) {
460 _alarmTime.set_hr(hr);
461 _alarmTime.set_min(min);
462 _alarmSet = true;
463 }
464
465 protected:
466 ClockTime _alarmTime;
467 bool _alarmSet;
468
469 // Configuration that affects flightplan operation
470 bool _turnAnticipationEnabled;
471
472 std::list<std::string> _messageStack;
473
474 virtual void CreateFlightPlan(GPSFlightPlan* fp, std::vector<std::string> ids, std::vector<GPSWpType> wps);
475
476 // Orientate the GPS unit to a flightplan - ie. figure out from current position
477 // and possibly orientation which leg of the FP we are on.
478 virtual void OrientateToFlightPlan(GPSFlightPlan* fp);
479
480 // Ditto for active fp. Probably all we need really!
481 virtual void OrientateToActiveFlightPlan();
482
483 int _cleanUpPage; // -1 => no cleanup required.
484
485 // IAP stuff
486 iap_map_type _np_iap; // Non-precision approaches
487 iap_map_type _pr_iap; // Precision approaches
488 bool _approachLoaded; // Set true when an approach is loaded in the active flightplan
489 bool _approachArm; // Set true when in approach-arm mode
490 bool _approachReallyArmed; // Apparently, approach-arm mode can be set from an external GPS-APR switch outside 30nm from airport,
491 // but the CDI scale change doesn't happen until 30nm from airport. Bizarre that it can be armed without
492 // the scale change, but it's in the manual...
493 bool _approachActive; // Set true when in approach-active mode
494 GPSFlightPlan* _approachFP; // Current approach - not necessarily loaded.
495 std::string _approachID; // ID of the airport we have an approach loaded for - bit of a hack that can hopefully be removed in future.
496 // More hackery since we aren't actually storing an approach class... Doh!
497 std::string _approachAbbrev;
498 std::string _approachRwyStr;
499
500 private:
501 simgear::TiedPropertyList _tiedProperties;
502 };