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