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