]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
5a0e7ef8640f3ef1229891d4092a0d5c53a5f984
[flightgear.git] / src / ATC / tower.cxx
1 // FGTower - a class to provide tower control at towered airports.
2 //
3 // Written by David Luff, started March 2002.
4 //
5 // Copyright (C) 2002  David C. Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #include <Main/globals.hxx>
22 #include <Airports/runways.hxx>
23 #include <simgear/math/sg_geodesy.hxx>
24 #include <simgear/debug/logstream.hxx>
25
26 #include "tower.hxx"
27 #include "ATCdisplay.hxx"
28 #include "ATCmgr.hxx"
29 #include "ATCutils.hxx"
30 #include "commlist.hxx"
31 #include "AILocalTraffic.hxx"
32
33 SG_USING_STD(cout);
34
35 // TowerPlaneRec
36
37 TowerPlaneRec::TowerPlaneRec() :
38 clearedToLand(false),
39 clearedToLineUp(false),
40 clearedToTakeOff(false),
41 holdShortReported(false),
42 downwindReported(false),
43 longFinalReported(false),
44 longFinalAcknowledged(false),
45 finalReported(false),
46 finalAcknowledged(false),
47 onRwy(false),
48 nextOnRwy(false),
49 opType(TTT_UNKNOWN),
50 leg(LEG_UNKNOWN),
51 landingType(AIP_LT_UNKNOWN),
52 isUser(false)
53 {
54         plane.callsign = "UNKNOWN";
55 }
56
57 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
58 clearedToLand(false),
59 clearedToLineUp(false),
60 clearedToTakeOff(false),
61 holdShortReported(false),
62 downwindReported(false),
63 longFinalReported(false),
64 longFinalAcknowledged(false),
65 finalReported(false),
66 finalAcknowledged(false),
67 onRwy(false),
68 nextOnRwy(false),
69 opType(TTT_UNKNOWN),
70 leg(LEG_UNKNOWN),
71 landingType(AIP_LT_UNKNOWN),
72 isUser(false)
73 {
74         plane = p;
75 }
76
77 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
78 clearedToLand(false),
79 clearedToLineUp(false),
80 clearedToTakeOff(false),
81 holdShortReported(false),
82 downwindReported(false),
83 longFinalReported(false),
84 longFinalAcknowledged(false),
85 finalReported(false),
86 finalAcknowledged(false),
87 onRwy(false),
88 nextOnRwy(false),
89 opType(TTT_UNKNOWN),
90 leg(LEG_UNKNOWN),
91 landingType(AIP_LT_UNKNOWN),
92 isUser(false)
93 {
94         plane.callsign = "UNKNOWN";
95         pos = pt;
96 }
97
98 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
99 clearedToLand(false),
100 clearedToLineUp(false),
101 clearedToTakeOff(false),
102 holdShortReported(false),
103 downwindReported(false),
104 longFinalReported(false),
105 longFinalAcknowledged(false),
106 finalReported(false),
107 finalAcknowledged(false),
108 onRwy(false),
109 nextOnRwy(false),
110 opType(TTT_UNKNOWN),
111 leg(LEG_UNKNOWN),
112 landingType(AIP_LT_UNKNOWN),
113 isUser(false)
114 {
115         plane = p;
116         pos = pt;
117 }
118
119
120 // FGTower
121
122 FGTower::FGTower() {
123         ATCmgr = globals->get_ATC_mgr();
124         
125         // Init the property nodes - TODO - need to make sure we're getting surface winds.
126         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
127         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
128         
129         update_count = 0;
130         update_count_max = 15;
131         
132         holdListItr = holdList.begin();
133         appListItr = appList.begin();
134         depListItr = depList.begin();
135         rwyListItr = rwyList.begin();
136         circuitListItr = circuitList.begin();
137         trafficListItr = trafficList.begin();
138         
139         freqClear = true;
140         
141         timeSinceLastDeparture = 9999;
142         departed = false;
143 }
144
145 FGTower::~FGTower() {
146         if(!separateGround) {
147                 delete ground;
148         }
149 }
150
151 void FGTower::Init() {
152     display = false;
153         
154         // Pointers to user's position
155         user_lon_node = fgGetNode("/position/longitude-deg", true);
156         user_lat_node = fgGetNode("/position/latitude-deg", true);
157         user_elev_node = fgGetNode("/position/altitude-ft", true);
158         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
159         
160         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
161         // I'll punt the startup issue for now though!!!
162         rwyOccupied = false;
163         
164         // Setup the ground control at this airport
165         AirportATC a;
166         //cout << "Tower ident = " << ident << '\n';
167         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
168                 if(a.ground_freq) {             // Ground control
169                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
170                         separateGround = true;
171                         if(ground == NULL) {
172                                 // Something has gone wrong :-(
173                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
174                                 ground = new FGGround(ident);
175                                 separateGround = false;
176                                 ground->Init();
177                                 if(display) {
178                                         ground->SetDisplay();
179                                 } else {
180                                         ground->SetNoDisplay();
181                                 }
182                         }
183                 } else {
184                         // Initialise ground anyway to do the shortest path stuff!
185                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
186                         ground = new FGGround(ident);
187                         separateGround = false;
188                         ground->Init();
189                         if(display) {
190                                 ground->SetDisplay();
191                         } else {
192                                 ground->SetNoDisplay();
193                         }
194                 }
195         } else {
196                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
197                 // Initialise ground anyway to avoid segfault later
198                 ground = new FGGround(ident);
199                 separateGround = false;
200                 ground->Init();
201                 if(display) {
202                         ground->SetDisplay();
203                 } else {
204                         ground->SetNoDisplay();
205                 }
206         }
207         
208         // Get the airport elevation
209         aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
210         
211         DoRwyDetails();
212         
213         // FIXME - this currently assumes use of the active rwy by the user.
214         rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
215         if(rwyOccupied) {
216                 // Assume the user is started at the threshold ready to take-off
217                 TowerPlaneRec* t = new TowerPlaneRec;
218                 t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
219                 t->plane.type = GA_SINGLE;
220                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
221                 t->landingType = AIP_LT_UNKNOWN;
222                 t->leg = TAKEOFF_ROLL;
223                 t->isUser = true;
224                 t->planePtr = NULL;
225                 t->clearedToTakeOff = true;
226                 rwyList.push_back(t);
227                 departed = false;
228         }
229 }
230
231 void FGTower::Update(double dt) {
232         //cout << "T" << endl;
233         // Each time step, what do we need to do?
234         // We need to go through the list of outstanding requests and acknowedgements
235         // and process at least one of them.
236         // We need to go through the list of planes under our control and check if
237         // any need to be addressed.
238         // We need to check for planes not under our control coming within our 
239         // control area and address if necessary.
240         
241         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
242         
243         // Sort the arriving planes
244         
245         /*
246         if(ident == "KEMT") {
247                 cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
248         }
249         */
250         
251         if(departed != false) {
252                 timeSinceLastDeparture += dt;
253                 //if(ident == "KEMT") 
254                 //      cout << "  dt = " << dt << "  timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
255         }
256         
257         if(respond) {
258                 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
259                 Respond();
260                 respond = false;
261                 responseReqd = false;
262         }
263         
264         // Calculate the eta of each plane to the threshold.
265         // For ground traffic this is the fastest they can get there.
266         // For air traffic this is the middle approximation.
267         if(update_count == 1) {
268                 doThresholdETACalc();
269         }
270         
271         // Order the list of traffic as per expected threshold use and flag any conflicts
272         if(update_count == 2) {
273                 //bool conflicts = doThresholdUseOrder();
274                 doThresholdUseOrder();
275         }
276         
277         // sortConficts() !!!
278         
279         if(update_count == 4) {
280                 CheckHoldList(dt);
281         }
282         
283         // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
284         if(rwyList.size()) {
285                 rwyOccupied = true;
286         } else {
287                 rwyOccupied = false;
288         }
289         
290         if(update_count == 5 && rwyOccupied) {
291                 CheckRunwayList(dt);
292         }
293                 
294         if(update_count == 6) {
295                 CheckCircuitList(dt);
296         }
297         
298         if(update_count == 7) {
299                 CheckApproachList(dt);
300         }
301         
302         // TODO - do one plane from the departure list and set departed = false when out of consideration
303         
304         //doCommunication();
305         
306         if(!separateGround) {
307                 // The display stuff might have to get more clever than this when not separate 
308                 // since the tower and ground might try communicating simultaneously even though
309                 // they're mean't to be the same contoller/frequency!!
310                 if(display) {
311                         ground->SetDisplay();
312                 } else {
313                         ground->SetNoDisplay();
314                 }
315                 ground->Update(dt);
316         }
317         
318         ++update_count;
319         // How big should ii get - ie how long should the update cycle interval stretch?
320         if(update_count >= update_count_max) {
321                 update_count = 0;
322         }
323         
324         // Call the base class update for the response time handling.
325         FGATC::Update(dt);
326
327         if(ident == "KEMT") {   
328                 // For AI debugging convienience - may be removed
329                 Point3D user_pos;
330                 user_pos.setlon(user_lon_node->getDoubleValue());
331                 user_pos.setlat(user_lat_node->getDoubleValue());
332                 user_pos.setelev(user_elev_node->getDoubleValue());
333                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
334                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
335                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
336                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
337         }
338         
339         //cout << "Done T" << endl;
340 }
341
342 void FGTower::Respond() {
343         //cout << "Entering Respond..." << endl;
344         TowerPlaneRec* t = FindPlane(responseID);
345         if(t) {
346                 // This will grow!!!
347                 if(t->downwindReported) {
348                         t->downwindReported = false;
349                         int i = 1;
350                         for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
351                                 if((*twrItr)->plane.callsign == responseID) break;
352                                 ++i;
353                         }                       
354                         string trns = "Number ";
355                         trns += ConvertNumToSpokenDigits(i);
356                         trns += " ";
357                         trns += t->plane.callsign;
358                         if(display) {
359                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
360                         }
361                         if(t->isUser && t->opType == TTT_UNKNOWN) {
362                                 t->opType = CIRCUIT;
363                         }
364                 } else if(t->holdShortReported) {
365                         if(t->nextOnRwy) {
366                                 if(rwyOccupied) {       // TODO - ought to add a sanity check that it isn't this plane only on the runway (even though it shouldn't be!!)
367                                         // Do nothing for now - consider acknowloging hold short eventually
368                                 } else {
369                                         ClearHoldingPlane(t);
370                                         t->leg = TAKEOFF_ROLL;
371                                         rwyList.push_back(t);
372                                         rwyOccupied = true;
373                                         // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
374                                         // FIXME TODO - FIX THIS!!!
375                                         if(holdList.size()) {
376                                                 if(holdListItr == holdList.end()) {
377                                                         holdListItr = holdList.begin();
378                                                 }
379                                                 holdList.erase(holdListItr);
380                                                 holdListItr = holdList.begin();
381                                         }
382                                 }
383                         } else {
384                                 // Tell him to hold and what position he is.
385                                 // Not currently sure under which circumstances we do or don't bother transmitting this.
386                                 string trns = t->plane.callsign;
387                                 trns += " hold position";
388                                 if(display) {
389                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
390                                 }
391                                 // TODO - add some idea of what traffic is blocking him.
392                         }
393                         t->holdShortReported = false;
394                 }
395         }
396         freqClear = true;       // FIXME - set this to come true after enough time to render the message
397         //cout << "Done Respond" << endl;
398 }
399
400 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land - 
401 // this should be done prior to calling this function.
402 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
403         //cout << "Entering ClearHoldingPlane..." << endl;
404         // Lets Roll !!!!
405         string trns = t->plane.callsign;
406         //if(departed plane < some threshold in time away) {
407         if(0) {         // FIXME
408         //if(timeSinceLastDeparture <= 60.0 && departed == true) {
409                 trns += " line up";
410                 t->clearedToLineUp = true;
411                 t->planePtr->RegisterTransmission(3);   // cleared to line-up
412         //} else if(arriving plane < some threshold away) {
413         } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) {   // Hack - hardwired time
414                 trns += " cleared immediate take-off";
415                 if(trafficList.size()) {
416                         tower_plane_rec_list_iterator trfcItr = trafficList.begin();
417                         trfcItr++;      // At the moment the holding plane should be first in trafficList.
418                         // Note though that this will break if holding planes aren't put in trafficList in the future.
419                         TowerPlaneRec* trfc = *trfcItr;
420                         trns += "... traffic is";
421                         switch(trfc->plane.type) {
422                         case UNKNOWN:
423                                 break;
424                         case GA_SINGLE:
425                                 trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
426                                 break;
427                         case GA_HP_SINGLE:
428                                 trns += " a Piper";
429                                 break;
430                         case GA_TWIN:
431                                 trns += " a King-air";
432                                 break;
433                         case GA_JET:
434                                 trns += " a Learjet";
435                                 break;
436                         case MEDIUM:
437                                 trns += " a Regional";
438                                 break;
439                         case HEAVY:
440                                 trns += " a Heavy";
441                                 break;
442                         case MIL_JET:
443                                 trns += " Military";
444                                 break;
445                         }
446                         //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
447                         if(trfc->opType == STRAIGHT_IN) {
448                                 double miles_out = CalcDistOutMiles(trfc);
449                                 if(miles_out < 2) {
450                                         trns += " on final";
451                                 } else {
452                                         trns += " on ";
453                                         trns += ConvertNumToSpokenDigits((int)miles_out);
454                                         trns += " mile final";
455                                 }
456                         } else if(trfc->opType == CIRCUIT) {
457                                 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
458                                 switch(trfc->leg) {
459                                 case FINAL:
460                                         trns += " on final";
461                                         break;
462                                 case TURN4:
463                                         trns += " turning final";
464                                         break;
465                                 case BASE:
466                                         trns += " on base";
467                                         break;
468                                 case TURN3:
469                                         trns += " turning base";
470                                         break;
471                                 case DOWNWIND:
472                                         trns += " in circuit";  // At the moment the user plane is generally flagged as unknown opType when downwind incase its a downwind departure which means we won't get here.
473                                         break;
474                                 // And to eliminate compiler warnings...
475                                 case TAKEOFF_ROLL: break;
476                                 case CLIMBOUT:     break;
477                                 case TURN1:        break;
478                                 case CROSSWIND:    break;
479                                 case TURN2:        break;
480                                 case LANDING_ROLL: break;
481                                 case LEG_UNKNOWN:  break;
482                                 }
483                         }
484                 } else {
485                         // By definition there should be some arriving traffic if we're cleared for immediate takeoff
486                         SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
487                 }
488                 t->clearedToTakeOff = true;
489                 t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
490                 departed = false;
491                 timeSinceLastDeparture = 0.0;
492         } else {
493         //} else if(timeSinceLastDeparture > 60.0 || departed == false) {       // Hack - test for timeSinceLastDeparture should be in lineup block eventually
494                 trns += " cleared for take-off";
495                 // TODO - add traffic is... ?
496                 t->clearedToTakeOff = true;
497                 t->planePtr->RegisterTransmission(4);   // cleared to take-off
498                 departed = false;
499                 timeSinceLastDeparture = 0.0;
500         }
501         if(display) {
502                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
503         }
504         //cout << "Done ClearHoldingPlane " << endl;
505 }
506
507 // Do one plane from the hold list
508 void FGTower::CheckHoldList(double dt) {
509         //cout << "Entering CheckHoldList..." << endl;
510         if(holdList.size()) {
511                 //cout << "*holdListItr = " << *holdListItr << endl;
512                 if(holdListItr == holdList.end()) {
513                         holdListItr = holdList.begin();
514                 }
515                 //cout << "*holdListItr = " << *holdListItr << endl;
516                 //Process(*holdListItr);
517                 TowerPlaneRec* t = *holdListItr;
518                 //cout << "t = " << t << endl;
519                 if(t->holdShortReported) {
520                         // NO-OP - leave it to the response handler.
521                 } else {        // not responding to report, but still need to clear if clear
522                         if(t->nextOnRwy) {
523                                 //cout << "departed = " << departed << '\n';
524                                 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
525                                 if(rwyOccupied) {
526                                         // Do nothing
527                                 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
528                                         // Do nothing - this is a bit of a hack - should maybe do line up be ready here
529                                 } else {
530                                         ClearHoldingPlane(t);
531                                         t->leg = TAKEOFF_ROLL;
532                                         rwyList.push_back(t);
533                                         rwyOccupied = true;
534                                         holdList.erase(holdListItr);
535                                         holdListItr = holdList.begin();
536                                 }
537                         }
538                         // TODO - rationalise the considerable code duplication above!
539                 }
540                 ++holdListItr;
541         }
542         //cout << "Done CheckHoldList" << endl;
543 }
544
545 // do the ciruit list
546 void FGTower::CheckCircuitList(double dt) {
547         //cout << "Entering CheckCircuitList..." << endl;
548         // Clear the constraints - we recalculate here.
549         base_leg_pos = 0.0;
550         downwind_leg_pos = 0.0;
551         crosswind_leg_pos = 0.0;
552         
553         if(circuitList.size()) {        // Do one plane from the circuit
554                 if(circuitListItr == circuitList.end()) {
555                         circuitListItr = circuitList.begin();
556                 }
557                 TowerPlaneRec* t = *circuitListItr;
558                 if(t->isUser) {
559                         t->pos.setlon(user_lon_node->getDoubleValue());
560                         t->pos.setlat(user_lat_node->getDoubleValue());
561                         t->pos.setelev(user_elev_node->getDoubleValue());
562                 } else {
563                         t->pos = t->planePtr->GetPos();         // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this.
564                         t->landingType = t->planePtr->GetLandingOption();
565                         //cout << "AI plane landing option is " << t->landingType << '\n';
566                 }
567                 Point3D tortho = ortho.ConvertToLocal(t->pos);
568                 if(t->isUser) {
569                         // Need to figure out which leg he's on
570                         //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
571                         double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
572                         //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
573                         // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
574                         // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
575                         if(abs(ho) < 30) {
576                                 // could be either takeoff, climbout or landing - check orthopos.y
577                                 //cout << "tortho.y = " << tortho.y() << '\n';
578                                 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
579                                         t->leg = FINAL;
580                                         //cout << "Final\n";
581                                 } else {
582                                         t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
583                                         //cout << "Climbout\n";
584                                         // If it's the user we may be unsure of his/her intentions.
585                                         // (Hopefully the AI planes won't try confusing the sim!!!)
586                                         if(t->opType == TTT_UNKNOWN) {
587                                                 if(tortho.y() > 5000) {
588                                                         // 5 km out from threshold - assume it's a departure
589                                                         t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
590                                                         // Since we are unknown operation we should be in depList already.
591                                                         circuitList.erase(circuitListItr);
592                                                         RemoveFromTrafficList(t->plane.callsign);
593                                                         circuitListItr = circuitList.begin();
594                                                 }
595                                         } else if(t->opType == CIRCUIT) {
596                                                 if(tortho.y() > 10000) {
597                                                         // 10 km out - assume the user has abandoned the circuit!!
598                                                         t->opType = OUTBOUND;
599                                                         depList.push_back(t);
600                                                         circuitList.erase(circuitListItr);
601                                                         circuitListItr = circuitList.begin();
602                                                 }
603                                         }
604                                 }
605                         } else if(abs(ho) < 60) {
606                                 // turn1 or turn 4
607                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
608                                 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
609                                         t->leg = TURN1;
610                                         //cout << "Turn1\n";
611                                 } else {
612                                         t->leg = TURN4;
613                                         //cout << "Turn4\n";
614                                 }
615                         } else if(abs(ho) < 120) {
616                                 // crosswind or base
617                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
618                                 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
619                                         t->leg = CROSSWIND;
620                                         //cout << "Crosswind\n";
621                                 } else {
622                                         t->leg = BASE;
623                                         //cout << "Base\n";
624                                 }
625                         } else if(abs(ho) < 150) {
626                                 // turn2 or turn 3
627                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
628                                 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
629                                         t->leg = TURN2;
630                                         //cout << "Turn2\n";
631                                 } else {
632                                         t->leg = TURN3;
633                                         // Probably safe now to assume the user is flying a circuit
634                                         t->opType = CIRCUIT;
635                                         //cout << "Turn3\n";
636                                 }
637                         } else {
638                                 // downwind
639                                 t->leg = DOWNWIND;
640                                 //cout << "Downwind\n";
641                         }
642                         if(t->leg == FINAL) {
643                                 if(OnActiveRunway(t->pos)) {
644                                         t->leg = LANDING_ROLL;
645                                 }
646                         }
647                 } else {
648                         t->leg = t->planePtr->GetLeg();
649                 }
650                 
651                 // Set the constraints IF this is the first plane in the circuit
652                 // TODO - at the moment we're constraining plane 2 based on plane 1 - this won't (or might not) work for 3 planes in the circuit!!
653                 if(circuitListItr == circuitList.begin()) {
654                         switch(t->leg) {
655                         case FINAL:
656                                 // Base leg must be at least as far out as the plane is - actually possibly not necessary for separation, but we'll use that for now.
657                                 base_leg_pos = tortho.y();
658                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
659                                 break;
660                         case TURN4:
661                                 // Fall through to base
662                         case BASE:
663                                 base_leg_pos = tortho.y();
664                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
665                                 break;
666                         case TURN3:
667                                 // Fall through to downwind
668                         case DOWNWIND:
669                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
670                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
671                                 //cout << "base_leg_pos = " << base_leg_pos;
672                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
673                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
674                                 break;
675                         case TURN2:
676                                 // Fall through to crosswind
677                         case CROSSWIND:
678                                 crosswind_leg_pos = tortho.y();
679                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
680                                 break;
681                         case TURN1:
682                                 // Fall through to climbout
683                         case CLIMBOUT:
684                                 // Only use current by constraint as largest
685                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
686                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
687                                 break;
688                         case TAKEOFF_ROLL:
689                                 break;
690                         case LEG_UNKNOWN:
691                                 break;
692                         case LANDING_ROLL:
693                                 break;
694                         default:
695                                 break;
696                         }
697                 }
698                 
699                 if(t->leg == FINAL) {
700                         if(t->landingType == FULL_STOP) t->opType = INBOUND;
701                 } else if(t->leg == LANDING_ROLL) {
702                         rwyList.push_front(t);
703                         RemoveFromTrafficList(t->plane.callsign);
704                         if(t->isUser) {
705                                 t->opType = TTT_UNKNOWN;
706                         }       // TODO - allow the user to specify opType via ATC menu
707                         circuitListItr = circuitList.erase(circuitListItr);
708                         if(circuitListItr == circuitList.end() ) {
709                                 circuitListItr = circuitList.begin();
710                         }
711                 }
712                 ++circuitListItr;
713         }
714         //cout << "Done CheckCircuitList" << endl;
715 }
716
717 // Do the runway list - we'll do the whole runway list since it's important and there'll never be many planes on the rwy at once!!
718 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
719 // (However, at the moment there should only be one airplane on the rwy at once, until we
720 // start allowing planes to line up whilst previous arrival clears the rwy.)
721 void FGTower::CheckRunwayList(double dt) {
722         //cout << "Entering CheckRunwayList..." << endl;
723         if(rwyOccupied) {
724                 if(!rwyList.size()) {
725                         rwyOccupied = false;
726                 } else {
727                         rwyListItr = rwyList.begin();
728                         TowerPlaneRec* t = *rwyListItr;
729                         if(t->isUser) {
730                                 t->pos.setlon(user_lon_node->getDoubleValue());
731                                 t->pos.setlat(user_lat_node->getDoubleValue());
732                                 t->pos.setelev(user_elev_node->getDoubleValue());
733                         } else {
734                                 t->pos = t->planePtr->GetPos();         // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this.
735                         }
736                         bool on_rwy = OnActiveRunway(t->pos);
737                         if(!on_rwy) {
738                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
739                                         rwyList.pop_front();
740                                         delete t;
741                                         // TODO - tell it to taxi / contact ground / don't delete it etc!
742                                 } else if(t->opType == OUTBOUND) {
743                                         depList.push_back(t);
744                                         rwyList.pop_front();
745                                         departed = true;
746                                         timeSinceLastDeparture = 0.0;
747                                 } else if(t->opType == CIRCUIT) {
748                                         circuitList.push_back(t);
749                                         AddToTrafficList(t);
750                                         rwyList.pop_front();
751                                         departed = true;
752                                         timeSinceLastDeparture = 0.0;
753                                 } else if(t->opType == TTT_UNKNOWN) {
754                                         depList.push_back(t);
755                                         circuitList.push_back(t);
756                                         AddToTrafficList(t);
757                                         rwyList.pop_front();
758                                         departed = true;
759                                         timeSinceLastDeparture = 0.0;   // TODO - we need to take into account that the user might taxi-in when flagged opType UNKNOWN - check speed/altitude etc to make decision as to what user is up to.
760                                 } else {
761                                         // HELP - we shouldn't ever get here!!!
762                                 }
763                         }
764                 }
765         }
766         //cout << "Done CheckRunwayList" << endl;
767 }
768
769 // Do one plane from the approach list
770 void FGTower::CheckApproachList(double dt) {
771         if(appList.size()) {
772                 if(appListItr == appList.end()) {
773                         appListItr = appList.begin();
774                 }
775                 TowerPlaneRec* t = *appListItr;
776                 //cout << "t = " << t << endl;
777                 if(t->isUser) {
778                         t->pos.setlon(user_lon_node->getDoubleValue());
779                         t->pos.setlat(user_lat_node->getDoubleValue());
780                         t->pos.setelev(user_elev_node->getDoubleValue());
781                 } else {
782                         // TODO - set/update the position if it's an AI plane
783                 }                               
784                 if(t->nextOnRwy && !(t->clearedToLand)) {
785                         // check distance away and whether runway occupied
786                         // and schedule transmission if necessary
787                 }                               
788                 ++appListItr;
789         }
790 }
791
792 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
793 // plus the constraint position as a rwy orientated orthopos (meters)
794 bool FGTower::GetCrosswindConstraint(double& cpos) {
795         if(crosswind_leg_pos != 0.0) {
796                 cpos = crosswind_leg_pos;
797                 return(true);
798         } else {
799                 cpos = 0.0;
800                 return(false);
801         }
802 }
803 bool FGTower::GetDownwindConstraint(double& dpos) {
804         if(downwind_leg_pos != 0.0) {
805                 dpos = downwind_leg_pos;
806                 return(true);
807         } else {
808                 dpos = 0.0;
809                 return(false);
810         }
811 }
812 bool FGTower::GetBaseConstraint(double& bpos) {
813         if(base_leg_pos != 0.0) {
814                 bpos = base_leg_pos;
815                 return(true);
816         } else {
817                 bpos = 0.0;
818                 return(false);
819         }
820 }
821
822
823 // Figure out which runways are active.
824 // For now we'll just be simple and do one active runway - eventually this will get much more complex
825 // This is a private function - public interface to the results of this is through GetActiveRunway
826 void FGTower::DoRwyDetails() {
827         //cout << "GetRwyDetails called" << endl;
828         
829         // Based on the airport-id and wind get the active runway
830         
831         //wind
832         double hdg = wind_from_hdg->getDoubleValue();
833         double speed = wind_speed_knots->getDoubleValue();
834         hdg = (speed == 0.0 ? 270.0 : hdg);
835         //cout << "Heading = " << hdg << '\n';
836         
837         FGRunway runway;
838         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
839         if(rwyGood) {
840                 activeRwy = runway.rwy_no;
841                 rwy.rwyID = runway.rwy_no;
842                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
843                 
844                 // Get the threshold position
845                 double other_way = runway.heading - 180.0;
846                 while(other_way <= 0.0) {
847                         other_way += 360.0;
848                 }
849         // move to the +l end/center of the runway
850                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
851         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
852                 Point3D ref = origin;
853         double tshlon, tshlat, tshr;
854                 double tolon, tolat, tor;
855                 rwy.length = runway.length * SG_FEET_TO_METER;
856                 rwy.width = runway.width * SG_FEET_TO_METER;
857         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
858                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
859         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
860                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
861                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
862                 // now copy what we need out of runway into rwy
863         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
864                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
865                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
866                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
867                 rwy.hdg = runway.heading;
868                 // Set the projection for the local area based on this active runway
869                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
870                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
871                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
872         } else {
873                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
874                 activeRwy = "NN";
875         }
876 }
877
878
879 // Figure out if a given position lies on the active runway
880 // Might have to change when we consider more than one active rwy.
881 bool FGTower::OnActiveRunway(Point3D pt) {
882         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
883         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
884         Point3D xyp = ortho.ConvertToLocal(pt);
885         
886         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
887         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
888
889         double rlen = rwy.length/2.0 + 5.0;
890         double rwidth = rwy.width/2.0;
891         double ldiff = fabs(xyp.y() - xyc.y());
892         double wdiff = fabs(xyp.x() - xyc.x());
893
894         return((ldiff < rlen) && (wdiff < rwidth));
895 }       
896
897
898 // Figure out if a given position lies on any runway or not
899 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
900 bool FGTower::OnAnyRunway(Point3D pt) {
901         ATCData ad;
902         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
903         if(dist < 0.0) {
904                 return(false);
905         }
906         // Based on the airport-id, go through all the runways and check for a point in them
907         
908         // TODO - do we actually need to search for the airport - surely we already know our ident and
909         // can just search runways of our airport???
910         //cout << "Airport ident is " << ad.ident << '\n';
911         FGRunway runway;
912         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
913         if(!rwyGood) {
914                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
915         }
916         bool on = false;
917         while(runway.id == ad.ident) {          
918                 on = OnRunway(pt, runway);
919                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
920                 if(on) return(true);
921                 globals->get_runways()->next(&runway);          
922         }
923         return(on);
924 }
925
926
927 // Returns true if successful
928 bool FGTower::RemoveFromTrafficList(string id) {
929         tower_plane_rec_list_iterator twrItr;
930         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
931                 TowerPlaneRec* tpr = *twrItr;
932                 if(tpr->plane.callsign == id) {
933                         trafficList.erase(twrItr);
934                         return(true);
935                 }
936         }       
937         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
938         return(false);
939 }
940
941
942 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
943 // and set nextOnRwy if so.
944 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
945 // For planes holding they are put in the first position with time to go, and the return value is
946 // true if in the first position (nextOnRwy) and false otherwise.
947 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
948 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
949         //cout << "ADD: " << trafficList.size();
950         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
951         double separation_time = 90.0;  // seconds - this is currently a guess for light plane separation, and includes a few seconds for a holding plane to taxi onto the rwy.
952         double departure_sep_time = 60.0;       // Separation time behind departing airplanes.  Comments above also apply.
953         bool conflict = false;
954         double lastETA = 0.0;
955         bool firstTime = true;
956         // FIXME - make this more robust for different plane types eg. light following heavy.
957         tower_plane_rec_list_iterator twrItr;
958         //twrItr = trafficList.begin();
959         //while(1) {
960         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
961                 //if(twrItr == trafficList.end()) {
962                 //      cout << "  END  ";
963                 //      trafficList.push_back(t);
964                 //      return(holding ? firstTime : conflict);
965                 //} else {
966                         TowerPlaneRec* tpr = *twrItr;
967                         if(holding) {
968                                 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
969                                 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
970                                 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0); 
971                                 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
972                                 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
973                                 // and if not needs time to clear the rwy anyway.
974                                 if(tpr->eta  - lastETA > slot_time) {
975                                         t->nextOnRwy = firstTime;
976                                         trafficList.insert(twrItr, t);
977                                         //cout << "\tH\t" << trafficList.size() << '\n';
978                                         return(firstTime);
979                                 }
980                                 firstTime = false;
981                         } else {
982                                 if(t->eta < tpr->eta) {
983                                         // Ugg - this one's tricky.
984                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
985                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
986                                                 if(tpr->nextOnRwy) {
987                                                         tpr->nextOnRwy = false;
988                                                         t->nextOnRwy = true;
989                                                 }
990                                                 trafficList.insert(twrItr, t);
991                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
992                                                 conflict = true;
993                                                 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
994                                                 if(tpr->nextOnRwy) {
995                                                         tpr->nextOnRwy = false;
996                                                         t->nextOnRwy = true;
997                                                 }
998                                                 trafficList.insert(twrItr, t);
999                                         }
1000                                         //cout << "\tC\t" << trafficList.size() << '\n';
1001                                         return(conflict);
1002                                 }
1003                         }
1004                 //}
1005                 //++twrItr;
1006         }
1007         // If we get here we must be at the end of the list, or maybe the list is empty.
1008         if(!trafficList.size()) {
1009                 t->nextOnRwy = true;
1010                 // conflict and firstTime should be false and true respectively in this case anyway.
1011         }
1012         trafficList.push_back(t);
1013         //cout << "\tE\t" << trafficList.size() << endl;
1014         return(holding ? firstTime : conflict);
1015 }
1016
1017
1018 // Calculate the eta of a plane to the threshold.
1019 // For ground traffic this is the fastest they can get there.
1020 // For air traffic this is the middle approximation.
1021 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1022         // For now we'll be very crude and hardwire expected speeds to C172-like values
1023         // The speeds below are specified in knots IAS and then converted to m/s
1024         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
1025         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
1026         double final_ias = 70.0 * 0.514444;             // Speed during final approach
1027         
1028         //if(printout) {
1029         //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1030         //cout << (tpr->isUser ? "USER\n" : "AI\n");
1031         //cout << flush;
1032         //}
1033         
1034         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1035         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1036         
1037         Point3D op = ortho.ConvertToLocal(tpr->pos);
1038         //if(printout) {
1039         //      cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1040         //      cout << "opType is " << tpr->opType << '\n';
1041         //}
1042         double dist_out_m = op.y();
1043         double dist_across_m = fabs(op.x());    // FIXME = the fabs is a hack to cope with the fact that we don't know the circuit direction yet
1044         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1045         
1046         if(tpr->opType == STRAIGHT_IN) {
1047                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1048                 if(dist_to_go_m < 1000) {
1049                         tpr->eta = dist_to_go_m / final_ias;
1050                 } else {
1051                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1052                 }
1053         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1054                 // It's complicated - depends on if base leg is delayed or not
1055                 //if(printout) {
1056                 //      cout << "Leg = " << tpr->leg << '\n';
1057                 //}
1058                 if(tpr->leg == LANDING_ROLL) {
1059                         tpr->eta = 0;
1060                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1061                         tpr->eta = fabs(dist_out_m) / final_ias;
1062                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1063                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1064                 } else {
1065                         // Need to calculate where base leg is likely to be
1066                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1067                         // TODO - as a matter of design - AILocalTraffic should get the nominal no-traffic base turn distance from Tower, since in real life the published pattern might differ from airport to airport
1068                         double nominal_base_dist_out_m = -1000;
1069                         double current_base_dist_out_m;
1070                         if(!GetBaseConstraint(current_base_dist_out_m)) {
1071                                 current_base_dist_out_m = nominal_base_dist_out_m;
1072                         }
1073                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
1074                         double current_dist_across_m;
1075                         if(!GetDownwindConstraint(current_dist_across_m)) {
1076                                 current_dist_across_m = nominal_dist_across_m;
1077                         }
1078                         double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1079                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
1080                         //if(printout) cout << "a = " << tpr->eta << '\n';
1081                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1082                                 tpr->eta += dist_across_m / circuit_ias;
1083                                 //if(printout) cout << "b = " << tpr->eta << '\n';
1084                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1085                                 //if(printout) cout << "c = " << tpr->eta << '\n';
1086                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1087                                 if(dist_across_m > nominal_dist_across_m) {
1088                                         tpr->eta += dist_across_m / circuit_ias;
1089                                 } else {
1090                                         tpr->eta += nominal_dist_across_m / circuit_ias;
1091                                 }
1092                                 // should we use the dist across of the previous plane if there is previous still on downwind?
1093                                 //if(printout) cout << "bb = " << tpr->eta << '\n';
1094                                 if(dist_out_m > nominal_cross_dist_out_m) {
1095                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1096                                 } else {
1097                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1098                                 }
1099                                 //if(printout) cout << "cc = " << tpr->eta << '\n';
1100                                 if(nominal_dist_across_m > dist_across_m) {
1101                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1102                                 } else {
1103                                         // Nothing to add
1104                                 }
1105                                 //if(printout) cout << "dd = " << tpr->eta << '\n';
1106                         } else {
1107                                 // We've only just started - why not use a generic estimate?
1108                                 tpr->eta = 240.0;
1109                         }
1110                 }
1111                 //if(printout) {
1112                 //      cout << "ETA = " << tpr->eta << '\n';
1113                 //}
1114         } else {
1115                 tpr->eta = 99999;
1116         }       
1117 }
1118
1119
1120 // Calculate the distance of a plane to the threshold in meters
1121 // TODO - Modify to calculate flying distance of a plane in the circuit
1122 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1123         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1124 }
1125
1126
1127 // Calculate the distance of a plane to the threshold in miles
1128 // TODO - Modify to calculate flying distance of a plane in the circuit
1129 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1130         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
1131 }
1132
1133
1134 // Iterate through all the lists and call CalcETA for all the planes.
1135 void FGTower::doThresholdETACalc() {
1136         //cout << "Entering doThresholdETACalc..." << endl;
1137         tower_plane_rec_list_iterator twrItr;
1138         // Do the approach list first
1139         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1140                 TowerPlaneRec* tpr = *twrItr;
1141                 CalcETA(tpr);
1142         }       
1143         // Then the circuit list
1144         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1145                 TowerPlaneRec* tpr = *twrItr;
1146                 CalcETA(tpr);
1147         }
1148         //cout << "Done doThresholdETCCalc" << endl;
1149 }
1150                 
1151
1152 // Check that the planes in traffic list are correctly ordered,
1153 // that the nearest (timewise) is flagged next on rwy, and return
1154 // true if any threshold use conflicts are detected, false otherwise.
1155 bool FGTower::doThresholdUseOrder() {
1156         //cout << "Entering doThresholdUseOrder..." << endl;
1157         bool conflict = false;
1158         
1159         // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1160         // Here's the rather simplistic assumptions we're using:
1161         // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1162         // In order of priority for runway use:
1163         // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1164         // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1165         // and holding planes until a space.
1166         // When calculating if a holding plane can use the runway, time clearance from last departure
1167         // as well as time clearance to next arrival must be considered.
1168         
1169         trafficList.clear();
1170         
1171         tower_plane_rec_list_iterator twrItr;
1172         // Do the approach list first
1173         //cout << "A" << flush;
1174         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1175                 TowerPlaneRec* tpr = *twrItr;
1176                 conflict = AddToTrafficList(tpr);
1177         }       
1178         // Then the circuit list
1179         //cout << "C" << flush;
1180         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1181                 TowerPlaneRec* tpr = *twrItr;
1182                 conflict = AddToTrafficList(tpr);
1183         }
1184         // And finally the hold list
1185         //cout << "H" << endl;
1186         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1187                 TowerPlaneRec* tpr = *twrItr;
1188                 AddToTrafficList(tpr, true);
1189         }
1190         
1191         if(0) {
1192         //if(ident == "KEMT") {
1193                 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1194                         TowerPlaneRec* tpr = *twrItr;
1195                         cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1196                 }
1197                 cout << endl;
1198         }
1199         
1200         //cout << "Done doThresholdUseOrder" << endl;
1201         return(conflict);
1202 }
1203
1204
1205 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1206 // i.e. list_pos = 1 implies next to use runway.
1207 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1208         if(trafficList.size() < list_pos) {
1209                 return(99999);
1210         }
1211
1212         tower_plane_rec_list_iterator twrItr;
1213         twrItr = trafficList.begin();
1214         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1215         TowerPlaneRec* tpr = *twrItr;
1216         CalcETA(tpr, printout);
1217         //cout << "ETA returned = " << tpr->eta << '\n';
1218         return(tpr->eta);
1219 }
1220         
1221
1222 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1223         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1224         TowerPlaneRec* t = new TowerPlaneRec;
1225         t->plane = plane;
1226         t->planePtr = requestee;
1227         t->holdShortReported = true;
1228         t->clearanceCounter = 0;
1229         t->clearedToLineUp = false;
1230         t->clearedToTakeOff = false;
1231         t->opType = operation;
1232         
1233         //cout << "Hold Short reported by " << plane.callsign << '\n';
1234
1235 /*      
1236         bool next = AddToTrafficList(t, true);
1237         if(next) {
1238                 double teta = GetTrafficETA(2);
1239                 if(teta < 150.0) {
1240                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1241                         //cout << "Reducing response time to request due imminent traffic\n";
1242                 }
1243         } else {
1244         }
1245 */
1246         // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1247
1248         holdList.push_back(t);
1249         
1250         responseReqd = true;
1251 }
1252
1253 void FGTower::RequestLandingClearance(string ID) {
1254         //cout << "Request Landing Clearance called...\n";
1255         
1256         // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1257         // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1258         
1259         TowerPlaneRec* t = new TowerPlaneRec;
1260         t->isUser = true;
1261         t->clearedToLand = false;
1262         t->pos.setlon(user_lon_node->getDoubleValue());
1263         t->pos.setlat(user_lat_node->getDoubleValue());
1264         t->pos.setelev(user_elev_node->getDoubleValue());
1265         
1266         // TODO
1267         // Calculate where the user is in relation to the active runway and it's circuit
1268         // and set the op-type as appropriate.
1269         
1270         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1271         t->opType = STRAIGHT_IN;
1272         
1273         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
1274         t->plane.callsign = ID;
1275         
1276         appList.push_back(t);   // Not necessarily permanent
1277         AddToTrafficList(t);
1278 }
1279
1280 void FGTower::RequestDepartureClearance(string ID) {
1281         //cout << "Request Departure Clearance called...\n";
1282 }       
1283 //void FGTower::ReportFinal(string ID);
1284 //void FGTower::ReportLongFinal(string ID);
1285 //void FGTower::ReportOuterMarker(string ID);
1286 //void FGTower::ReportMiddleMarker(string ID);
1287 //void FGTower::ReportInnerMarker(string ID);
1288 //void FGTower::ReportGoingAround(string ID);
1289 void FGTower::ReportRunwayVacated(string ID) {
1290         //cout << "Report Runway Vacated Called...\n";
1291 }
1292
1293 TowerPlaneRec* FGTower::FindPlane(string ID) {
1294         tower_plane_rec_list_iterator twrItr;
1295         // Do the approach list first
1296         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1297                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1298         }       
1299         // Then the circuit list
1300         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1301                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1302         }
1303         // And finally the hold list
1304         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1305                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1306         }
1307         SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
1308         return(NULL);
1309 }
1310
1311 void FGTower::ReportDownwind(string ID) {
1312         //cout << "ReportDownwind(...) called\n";
1313         // Tell the plane reporting what number she is in the circuit
1314         TowerPlaneRec* t = FindPlane(ID);
1315         if(t) {
1316                 t->downwindReported = true;
1317                 responseReqd = true;
1318         } else {
1319                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
1320         }
1321 }
1322
1323 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1324         switch(ttt) {
1325         case(CIRCUIT):      return(os << "CIRCUIT");
1326         case(INBOUND):      return(os << "INBOUND");
1327         case(OUTBOUND):     return(os << "OUTBOUND");
1328         case(TTT_UNKNOWN):  return(os << "UNKNOWN");
1329         case(STRAIGHT_IN):  return(os << "STRAIGHT_IN");
1330         }
1331         return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");
1332 }
1333