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