]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
- Added ultra-light traffic is now a separate traffic class that can have its
[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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #ifdef HAVE_STRINGS_H
26 #  include <strings.h>   // bcopy()
27 #else
28 #  include <string.h>    // MSVC doesn't have strings.h
29 #endif
30
31 #include <Main/globals.hxx>
32 #include <Airports/runways.hxx>
33 #include <simgear/math/sg_geodesy.hxx>
34 #include <simgear/debug/logstream.hxx>
35
36 #include "tower.hxx"
37 #include "ATCmgr.hxx"
38 #include "ATCutils.hxx"
39 #include "ATCDialog.hxx"
40 #include "commlist.hxx"
41 #include "AILocalTraffic.hxx"
42
43 SG_USING_STD(cout);
44
45 // TowerPlaneRec
46
47 TowerPlaneRec::TowerPlaneRec() :
48         planePtr(NULL),
49         clearedToLand(false),
50         clearedToLineUp(false),
51         clearedToTakeOff(false),
52         holdShortReported(false),
53         downwindReported(false),
54         longFinalReported(false),
55         longFinalAcknowledged(false),
56         finalReported(false),
57         finalAcknowledged(false),
58         rwyVacatedReported(false),
59         rwyVacatedAcknowledged(false),
60         goAroundReported(false),
61         instructedToGoAround(false),
62         onRwy(false),
63         nextOnRwy(false),
64         vfrArrivalReported(false),
65         vfrArrivalAcknowledged(false),
66         opType(TTT_UNKNOWN),
67         leg(LEG_UNKNOWN),
68         landingType(AIP_LT_UNKNOWN),
69         isUser(false)
70 {
71         plane.callsign = "UNKNOWN";
72 }
73
74 TowerPlaneRec::TowerPlaneRec(const PlaneRec& p) :
75         planePtr(NULL),
76         clearedToLand(false),
77         clearedToLineUp(false),
78         clearedToTakeOff(false),
79         holdShortReported(false),
80         downwindReported(false),
81         longFinalReported(false),
82         longFinalAcknowledged(false),
83         finalReported(false),
84         finalAcknowledged(false),
85         rwyVacatedReported(false),
86         rwyVacatedAcknowledged(false),
87         goAroundReported(false),
88         instructedToGoAround(false),
89         onRwy(false),
90         nextOnRwy(false),
91         vfrArrivalReported(false),
92         vfrArrivalAcknowledged(false),
93         opType(TTT_UNKNOWN),
94         leg(LEG_UNKNOWN),
95         landingType(AIP_LT_UNKNOWN),
96         isUser(false)
97 {
98         plane = p;
99 }
100
101 TowerPlaneRec::TowerPlaneRec(const Point3D& pt) :
102         planePtr(NULL),
103         clearedToLand(false),
104         clearedToLineUp(false),
105         clearedToTakeOff(false),
106         holdShortReported(false),
107         downwindReported(false),
108         longFinalReported(false),
109         longFinalAcknowledged(false),
110         finalReported(false),
111         finalAcknowledged(false),
112         rwyVacatedReported(false),
113         rwyVacatedAcknowledged(false),
114         goAroundReported(false),
115         instructedToGoAround(false),
116         onRwy(false),
117         nextOnRwy(false),
118         vfrArrivalReported(false),
119         vfrArrivalAcknowledged(false),
120         opType(TTT_UNKNOWN),
121         leg(LEG_UNKNOWN),
122         landingType(AIP_LT_UNKNOWN),
123         isUser(false)
124 {
125         plane.callsign = "UNKNOWN";
126         pos = pt;
127 }
128
129 TowerPlaneRec::TowerPlaneRec(const PlaneRec& p, const Point3D& pt) :
130         planePtr(NULL),
131         clearedToLand(false),
132         clearedToLineUp(false),
133         clearedToTakeOff(false),
134         holdShortReported(false),
135         downwindReported(false),
136         longFinalReported(false),
137         longFinalAcknowledged(false),
138         finalReported(false),
139         finalAcknowledged(false),
140         rwyVacatedReported(false),
141         rwyVacatedAcknowledged(false),
142         goAroundReported(false),
143         instructedToGoAround(false),
144         onRwy(false),
145         nextOnRwy(false),
146         vfrArrivalReported(false),
147         vfrArrivalAcknowledged(false),
148         opType(TTT_UNKNOWN),
149         leg(LEG_UNKNOWN),
150         landingType(AIP_LT_UNKNOWN),
151         isUser(false)
152 {
153         plane = p;
154         pos = pt;
155 }
156
157
158 // FGTower
159
160 /*******************************************
161                TODO List
162                            
163 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in. (MAJOR)
164
165 Use track instead of heading to determine what leg of the circuit the user is flying. (MINOR)
166
167 Use altitude as well as position to try to determine if the user has left the circuit. (MEDIUM - other issues as well).
168
169 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and 
170 will break when planes start queueing. (CRITICAL)
171
172 Report-Runway-Vacated is left as only user ATC option following a go-around. (MAJOR)
173
174 Report-Downwind is not added as ATC option when user takes off to fly a circuit. (MAJOR)
175
176 eta of USER can be calculated very wrongly in circuit if flying straight out and turn4 etc are with +ve ortho y. 
177 This can then screw up circuit ordering for other planes (MEDIUM)
178
179 USER leaving circuit needs to be more robustly considered when intentions unknown
180 Currently only considered during climbout and breaks when user turns (MEDIUM).
181
182 GetPos() of the AI planes is called erratically - either too much or not enough. (MINOR)
183
184 GO-AROUND is instructed very late at < 12s to landing - possibly make more dependent on chance of rwy clearing before landing (FEATURE)
185
186 Need to make clear when TowerPlaneRecs do or don't get deleted in RemoveFromCircuitList etc. (MINOR until I misuse it - then CRITICAL!)
187
188 FGTower::RemoveAllUserDialogOptions() really ought to be replaced by an ATCDialog::clear_entries() function. (MINOR - efficiency).
189
190 At the moment planes in the lists are not guaranteed to always have a sensible ETA - it should be set as part of AddList functions, and lists should only be accessed this way. (FAIRLY MAJOR). 
191 *******************************************/
192
193 FGTower::FGTower() {
194         ATCmgr = globals->get_ATC_mgr();
195         
196         _type = TOWER;
197         
198         // Init the property nodes - TODO - need to make sure we're getting surface winds.
199         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
200         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
201         
202         update_count = 0;
203         update_count_max = 15;
204         
205         holdListItr = holdList.begin();
206         appListItr = appList.begin();
207         depListItr = depList.begin();
208         rwyListItr = rwyList.begin();
209         circuitListItr = circuitList.begin();
210         trafficListItr = trafficList.begin();
211         vacatedListItr = vacatedList.begin();
212         
213         freqClear = true;
214         
215         timeSinceLastDeparture = 9999;
216         departed = false;
217         
218         nominal_downwind_leg_pos = 1000.0;
219         nominal_base_leg_pos = -1000.0;
220         // TODO - set nominal crosswind leg pos based on minimum distance from takeoff end of rwy.
221         
222         _departureControlled = false;
223 }
224
225 FGTower::~FGTower() {
226         if(!separateGround) {
227                 delete ground;
228         }
229 }
230
231 void FGTower::Init() {
232         //cout << "Initialising tower " << ident << '\n';
233         
234         // Pointers to user's position
235         user_lon_node = fgGetNode("/position/longitude-deg", true);
236         user_lat_node = fgGetNode("/position/latitude-deg", true);
237         user_elev_node = fgGetNode("/position/altitude-ft", true);
238         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
239         
240         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
241         // I'll punt the startup issue for now though!!!
242         rwyOccupied = false;
243         
244         // Setup the ground control at this airport
245         AirportATC a;
246         //cout << "Tower ident = " << ident << '\n';
247         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
248                 if(a.ground_freq) {             // Ground control
249                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
250                         separateGround = true;
251                         if(ground == NULL) {
252                                 // Something has gone wrong :-(
253                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
254                                 ground = new FGGround(ident);
255                                 separateGround = false;
256                                 ground->Init();
257                                 if(_display) {
258                                         ground->SetDisplay();
259                                 } else {
260                                         ground->SetNoDisplay();
261                                 }
262                         }
263                 } else {
264                         // Initialise ground anyway to do the shortest path stuff!
265                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
266                         ground = new FGGround(ident);
267                         separateGround = false;
268                         ground->Init();
269                         if(_display) {
270                                 ground->SetDisplay();
271                         } else {
272                                 ground->SetNoDisplay();
273                         }
274                 }
275         } else {
276                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
277                 // Initialise ground anyway to avoid segfault later
278                 ground = new FGGround(ident);
279                 separateGround = false;
280                 ground->Init();
281                 if(_display) {
282                         ground->SetDisplay();
283                 } else {
284                         ground->SetNoDisplay();
285                 }
286         }
287         
288         // TODO - attempt to get a departure control pointer to see if we need to hand off departing traffic to departure.
289         
290         // Get the airport elevation
291         aptElev = fgGetAirportElev(ident.c_str());
292         
293         // TODO - this function only assumes one active rwy.
294         DoRwyDetails();
295         
296         // TODO - this currently assumes only one active runway.
297         rwyOccupied = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
298         if(rwyOccupied) {
299                 //cout << "User found on active runway\n";
300                 // Assume the user is started at the threshold ready to take-off
301                 TowerPlaneRec* t = new TowerPlaneRec;
302                 t->plane.callsign = fgGetString("/sim/user/callsign");
303                 t->plane.type = GA_SINGLE;      // FIXME - hardwired!!
304                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
305                 t->landingType = AIP_LT_UNKNOWN;
306                 t->leg = TAKEOFF_ROLL;
307                 t->isUser = true;
308                 t->planePtr = NULL;
309                 t->clearedToTakeOff = true;
310                 rwyList.push_back(t);
311                 rwyListItr = rwyList.begin();
312                 departed = false;
313         } else {
314                 //cout << "User not on active runway\n";
315                 // For now assume that this means the user is not at the airport and is in the air.
316                 // TODO FIXME - this will break when user starts on apron, at hold short, etc.
317                 if(!OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0))) {
318                         //cout << ident << "  ADD 0\n";
319                         current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI miles @CD of the airport for full stop with ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
320                 }
321         }
322 }
323
324 void FGTower::Update(double dt) {
325         //cout << "T" << endl;
326         // Each time step, what do we need to do?
327         // We need to go through the list of outstanding requests and acknowedgements
328         // and process at least one of them.
329         // We need to go through the list of planes under our control and check if
330         // any need to be addressed.
331         // We need to check for planes not under our control coming within our 
332         // control area and address if necessary.
333         
334         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
335         
336         // Sort the arriving planes
337         
338         /*
339         if(ident == "KEMT") {
340                 cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
341         }
342         */
343         //if(ident == "EGNX") cout << display << '\n';
344         
345         if(departed != false) {
346                 timeSinceLastDeparture += dt;
347                 //if(ident == "KEMT") 
348                 //      cout << "  dt = " << dt << "  timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
349         }
350         
351         //cout << ident << " respond = " << respond << " responseReqd = " << responseReqd << '\n'; 
352         if(respond) {
353                 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
354                 Respond();
355                 respond = false;
356                 responseReqd = false;
357         }
358         
359         // Calculate the eta of each plane to the threshold.
360         // For ground traffic this is the fastest they can get there.
361         // For air traffic this is the middle approximation.
362         if(update_count == 1) {
363                 doThresholdETACalc();
364         }
365         
366         // Order the list of traffic as per expected threshold use and flag any conflicts
367         if(update_count == 2) {
368                 //bool conflicts = doThresholdUseOrder();
369                 doThresholdUseOrder();
370         }
371         
372         // sortConficts() !!!
373         
374         if(update_count == 4) {
375                 CheckHoldList(dt);
376         }
377         
378         // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
379         if(rwyList.size()) {
380                 rwyOccupied = true;
381         } else {
382                 rwyOccupied = false;
383         }
384         
385         if(update_count == 5 && rwyOccupied) {
386                 CheckRunwayList(dt);
387         }
388                 
389         if(update_count == 6) {
390                 CheckCircuitList(dt);
391         }
392         
393         if(update_count == 7) {
394                 CheckApproachList(dt);
395         }
396         
397         if(update_count == 8) {
398                 CheckDepartureList(dt);
399         }
400         
401         // TODO - do one plane from the departure list and set departed = false when out of consideration
402         
403         //doCommunication();
404         
405         if(!separateGround) {
406                 // The display stuff might have to get more clever than this when not separate 
407                 // since the tower and ground might try communicating simultaneously even though
408                 // they're mean't to be the same contoller/frequency!!
409                 // We could also get rid of this by overloading FGATC's Set(No)Display() functions.
410                 if(_display) {
411                         ground->SetDisplay();
412                 } else {
413                         ground->SetNoDisplay();
414                 }
415                 ground->Update(dt);
416         }
417         
418         ++update_count;
419         // How big should ii get - ie how long should the update cycle interval stretch?
420         if(update_count >= update_count_max) {
421                 update_count = 0;
422         }
423         
424         // Call the base class update for the response time handling.
425         FGATC::Update(dt);
426
427         /*
428         if(ident == "KEMT") {   
429                 // For AI debugging convienience - may be removed
430                 Point3D user_pos;
431                 user_pos.setlon(user_lon_node->getDoubleValue());
432                 user_pos.setlat(user_lat_node->getDoubleValue());
433                 user_pos.setelev(user_elev_node->getDoubleValue());
434                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
435                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
436                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
437                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
438         }
439         */
440         
441         //cout << "Done T" << endl;
442 }
443
444 void FGTower::ReceiveUserCallback(int code) {
445         if(code == (int)USER_REQUEST_VFR_DEPARTURE) {
446                 //cout << "User requested departure\n";
447         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL) {
448                 VFRArrivalContact("USER");
449         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP) {
450                 VFRArrivalContact("USER", FULL_STOP);
451         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO) {
452                 VFRArrivalContact("USER", TOUCH_AND_GO);
453         } else if(code == (int)USER_REPORT_DOWNWIND) {
454                 ReportDownwind("USER");
455         } else if(code == (int)USER_REPORT_3_MILE_FINAL) {
456                 // For now we'll just call report final instead of report long final to avoid having to alter the response code
457                 ReportFinal("USER");
458         } else if(code == (int)USER_REPORT_RWY_VACATED) {
459                 ReportRunwayVacated("USER");
460         } else if(code == (int)USER_REPORT_GOING_AROUND) {
461                 ReportGoingAround("USER");
462         }
463 }
464
465 // **************** RESPONSE FUNCTIONS ****************
466
467 void FGTower::Respond() {
468         //cout << "\nEntering Respond, responseID = " << responseID << endl;
469         TowerPlaneRec* t = FindPlane(responseID);
470         if(t) {
471                 // This will grow!!!
472                 if(t->vfrArrivalReported && !t->vfrArrivalAcknowledged) {
473                         //cout << "Tower " << ident << " is responding to VFR arrival reported...\n";
474                         // Testing - hardwire straight in for now
475                         string trns = t->plane.callsign;
476                         trns += " ";
477                         trns += name;
478                         trns += " Tower,";
479                         // Should we clear staight in or for downwind entry?
480                         // For now we'll clear straight in if greater than 1km from a line drawn through the threshold perpendicular to the rwy.
481                         // Later on we might check the actual heading and direct some of those to enter on downwind or base.
482                         Point3D op = ortho.ConvertToLocal(t->pos);
483                         if(op.y() < -1000) {
484                                 trns += " Report three mile straight-in runway ";
485                                 t->opType = STRAIGHT_IN;
486                                 if(t->isUser) {
487                                         current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI mile final Runway @RW", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL);
488                                 } else {
489                                         t->planePtr->RegisterTransmission(14);
490                                 }
491                         } else {
492                                 // For now we'll just request reporting downwind.
493                                 // TODO - In real life something like 'report 2 miles southwest right downwind rwy 19R' might be used
494                                 // but I'm not sure how to handle all permutations of which direction to tell to report from yet.
495                                 trns += " Report ";
496                                 //cout << "Responding, rwy.patterDirection is " << rwy.patternDirection << '\n';
497                                 trns += ((rwy.patternDirection == 1) ? "right " : "left ");
498                                 trns += "downwind runway ";
499                                 t->opType = CIRCUIT;
500                                 // leave it in the app list until it gets into pattern though.
501                                 if(t->isUser) {
502                                         current_atcdialog->add_entry(ident, "@AP Tower, @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
503                                 } else {
504                                         t->planePtr->RegisterTransmission(15);
505                                 }
506                         }
507                         trns += ConvertRwyNumToSpokenString(activeRwy);
508                         if(_display) {
509                                 pending_transmission = trns;
510                                 Transmit();
511                         } else {
512                                 //cout << "Not displaying, trns was " << trns << '\n';
513                         }
514                         t->vfrArrivalAcknowledged = true;
515                 } else if(t->downwindReported) {
516                         //cout << "Tower " << ident << " is responding to downwind reported...\n";
517                         ProcessDownwindReport(t);
518                         t->downwindReported = false;
519                 } else if(t->holdShortReported) {
520                         //cout << "Tower " << ident << " is reponding to holdShortReported...\n";
521                         if(t->nextOnRwy) {
522                                 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!!)
523                                         // Do nothing for now - consider acknowloging hold short eventually
524                                 } else {
525                                         ClearHoldingPlane(t);
526                                         t->leg = TAKEOFF_ROLL;
527                                         rwyList.push_back(t);
528                                         rwyListItr = rwyList.begin();
529                                         rwyOccupied = true;
530                                         // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
531                                         // FIXME TODO - FIX THIS!!!
532                                         if(!holdList.empty()) {
533                                                 if(holdListItr == holdList.end()) {
534                                                         holdListItr = holdList.begin();
535                                                 }
536                                                 holdList.erase(holdListItr);
537                                                 holdListItr = holdList.begin();
538                                         }
539                                 }
540                         } else {
541                                 // Tell him to hold and what position he is.
542                                 // Not currently sure under which circumstances we do or don't bother transmitting this.
543                                 string trns = t->plane.callsign;
544                                 trns += " hold position";
545                                 if(_display) {
546                                         pending_transmission = trns;
547                                         Transmit();
548                                 }
549                                 // TODO - add some idea of what traffic is blocking him.
550                         }
551                         t->holdShortReported = false;
552                 } else if(t->finalReported && !(t->finalAcknowledged)) {
553                         //cout << "Tower " << ident << " is responding to finalReported...\n";
554                         bool disp = true;
555                         string trns = t->plane.callsign;
556                         //cout << (t->nextOnRwy ? "Next on rwy " : "Not next!! ");
557                         //cout << (rwyOccupied ? "RWY OCCUPIED!!\n" : "Rwy not occupied\n");
558                         if(t->nextOnRwy && !rwyOccupied && !(t->instructedToGoAround)) {
559                                 if(t->landingType == FULL_STOP) {
560                                         trns += " cleared to land ";
561                                 } else {
562                                         trns += " cleared for the option ";
563                                 }
564                                 // TODO - add winds
565                                 t->clearedToLand = true;
566                                 // Maybe remove report downwind from menu here as well incase user didn't bother to?
567                                 if(t->isUser) {
568                                         //cout << "ADD VACATED B\n";
569                                         // Put going around at the top (and hence default) since that'll be more desperate,
570                                         // or put rwy vacated at the top since that'll be more common?
571                                         current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
572                                         current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
573                                 } else {
574                                         t->planePtr->RegisterTransmission(7);
575                                 }
576                         } else if(t->eta < 20) {
577                                 // Do nothing - we'll be telling it to go around in less than 10 seconds if the
578                                 // runway doesn't clear so no point in calling "continue approach".
579                                 disp = false;
580                         } else {
581                                 trns += " continue approach";
582                                 t->clearedToLand = false;
583                         }
584                         if(_display && disp) {
585                                 pending_transmission = trns;
586                                 Transmit();
587                         }
588                         t->finalAcknowledged = true;
589                 } else if(t->rwyVacatedReported && !(t->rwyVacatedAcknowledged)) {
590                         ProcessRunwayVacatedReport(t);
591                         t->rwyVacatedAcknowledged = true;
592                 }
593         }
594         //freqClear = true;     // FIXME - set this to come true after enough time to render the message
595         _releaseCounter = 0.0;
596         _releaseTime = 5.5;
597         _runReleaseCounter = true;
598         //cout << "Done Respond\n" << endl;
599 }
600
601 void FGTower::ProcessDownwindReport(TowerPlaneRec* t) {
602         int i = 1;
603         int a = 0;      // Count of preceding planes on approach
604         bool cf = false;        // conflicting traffic on final
605         bool cc = false;        // preceding traffic in circuit
606         TowerPlaneRec* tc = NULL;
607         for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
608                 if((*twrItr)->plane.callsign == responseID) break;
609                 tc = *twrItr;
610                 ++i;
611         }
612         if(i > 1) { cc = true; }
613         doThresholdETACalc();
614         TowerPlaneRec* tf = NULL;
615         for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
616                 if((*twrItr)->eta < (t->eta + 45)) {
617                         a++;
618                         tf = *twrItr;
619                         cf = true;
620                         // This should set the flagged plane to be the last conflicting one, and hence the one to follow.
621                         // It ignores the fact that we might have problems slotting into the approach traffic behind it - 
622                         // eventually we'll need some fancy algorithms for that!
623                 }
624         }
625         string trns = t->plane.callsign;
626         trns += " Number ";
627         trns += ConvertNumToSpokenDigits(i + a);
628         // This assumes that the number spoken is landing position, not circuit position, since some of the traffic might be on straight-in final.
629         trns += " ";
630         TowerPlaneRec* tt = NULL;
631         if((i == 1) && rwyList.empty() && (t->nextOnRwy) && (!cf)) {    // Unfortunately nextOnRwy currently doesn't handle circuit/straight-in ordering properly at present, hence the cf check below.
632                 trns += "Cleared to land";      // TODO - clear for the option if appropriate
633                 t->clearedToLand = true;
634                 if(!t->isUser) t->planePtr->RegisterTransmission(7);
635         } else if((i+a) > 1) {
636                 //First set tt to point to the correct preceding plane - final or circuit
637                 if(tc && tf) {
638                         tt = (tf->eta < tc->eta ? tf : tc);
639                 } else if(tc) {
640                         tt = tc;
641                 } else if(tf) {
642                         tt = tf;
643                 } else {
644                         // We should never get here!
645                         SG_LOG(SG_ATC, SG_ALERT, "ALERT - Logic error in FGTower::ProcessDownwindReport");
646                         return;
647                 }
648                 trns += "Follow the ";
649                 string s = tt->plane.callsign;
650                 int p = s.find('-');
651                 s = s.substr(0,p);
652                 trns += s;
653                 if((tt->opType) == CIRCUIT) {
654                         PatternLeg leg;
655                         if(tt->isUser) {
656                                 leg = tt->leg;
657                         } else {
658                                 leg = tt->planePtr->GetLeg();
659                         }
660                         if(leg == FINAL) {
661                                 trns += " on final";
662                         } else if(leg == TURN4) {
663                                 trns += " turning final";
664                         } else if(leg == BASE) {
665                                 trns += " on base";
666                         } else if(leg == TURN3) {
667                                 trns += " turning base";
668                         }
669                 } else {
670                         double miles_out = CalcDistOutMiles(tt);
671                         if(miles_out < 2) {
672                                 trns += " on short final";
673                         } else {
674                                 trns += " on ";
675                                 trns += ConvertNumToSpokenDigits((int)miles_out);
676                                 trns += " mile final";
677                         }
678                 }
679         }
680         if(_display) {
681                 pending_transmission = trns;
682                 Transmit();
683         }
684         if(t->isUser) {
685                 if(t->opType == TTT_UNKNOWN) t->opType = CIRCUIT;
686                 //cout << "ADD VACATED A\n";
687                 // Put going around at the top (and hence default) since that'll be more desperate,
688                 // or put rwy vacated at the top since that'll be more common?
689                 //cout << "ident = " << ident << ", adding go-around option\n";
690                 current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
691                 current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
692         }
693 }
694
695 void FGTower::ProcessRunwayVacatedReport(TowerPlaneRec* t) {
696         //cout << "Processing rwy vacated...\n";
697         if(t->isUser) current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);
698         string trns = t->plane.callsign;
699         if(separateGround) {
700                 trns += " Contact ground on ";
701                 double f = globals->get_ATC_mgr()->GetFrequency(ident, GROUND) / 100.0; 
702                 char buf[10];
703                 sprintf(buf, "%.2f", f);
704                 trns += buf;
705                 trns += " Good Day";
706                 if(!t->isUser) t->planePtr->RegisterTransmission(5);
707         } else {
708                 // Cop-out!!
709                 trns += " cleared for taxi to general aviation parking";
710                 if(!t->isUser) t->planePtr->RegisterTransmission(6);    // TODO - this is a mega-hack!!
711         }
712         //cout << "trns = " << trns << '\n';
713         if(_display) {
714                 pending_transmission = trns;
715                 Transmit();
716         }
717         RemoveFromRwyList(t->plane.callsign);
718         AddToVacatedList(t);
719         // Maybe we should check that the plane really *has* vacated the runway!
720 }
721
722 // *********** END RESPONSE FUNCTIONS *****************
723
724 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land - 
725 // this should be done prior to calling this function.
726 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
727         //cout << "Entering ClearHoldingPlane..." << endl;
728         // Lets Roll !!!!
729         string trns = t->plane.callsign;
730         //if(departed plane < some threshold in time away) {
731         if(0) {         // FIXME
732         //if(timeSinceLastDeparture <= 60.0 && departed == true) {
733                 trns += " line up";
734                 t->clearedToLineUp = true;
735                 t->planePtr->RegisterTransmission(3);   // cleared to line-up
736         //} else if(arriving plane < some threshold away) {
737         } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) {   // Hack - hardwired time
738                 trns += " cleared immediate take-off";
739                 if(trafficList.size()) {
740                         tower_plane_rec_list_iterator trfcItr = trafficList.begin();
741                         trfcItr++;      // At the moment the holding plane should be first in trafficList.
742                         // Note though that this will break if holding planes aren't put in trafficList in the future.
743                         TowerPlaneRec* trfc = *trfcItr;
744                         trns += "... traffic is";
745                         switch(trfc->plane.type) {
746                         case UNKNOWN:
747                                 break;
748                         case GA_SINGLE:
749                                 trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
750                                 break;
751                         case GA_HP_SINGLE:
752                                 trns += " a Piper";
753                                 break;
754                         case GA_TWIN:
755                                 trns += " a King-air";
756                                 break;
757                         case GA_JET:
758                                 trns += " a Learjet";
759                                 break;
760                         case MEDIUM:
761                                 trns += " a Regional";
762                                 break;
763                         case HEAVY:
764                                 trns += " a Heavy";
765                                 break;
766                         case MIL_JET:
767                                 trns += " Military";
768                                 break;
769                         }
770                         //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
771                         if(trfc->opType == STRAIGHT_IN) {
772                                 double miles_out = CalcDistOutMiles(trfc);
773                                 if(miles_out < 2) {
774                                         trns += " on final";
775                                 } else {
776                                         trns += " on ";
777                                         trns += ConvertNumToSpokenDigits((int)miles_out);
778                                         trns += " mile final";
779                                 }
780                         } else if(trfc->opType == CIRCUIT) {
781                                 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
782                                 switch(trfc->leg) {
783                                 case FINAL:
784                                         trns += " on final";
785                                         break;
786                                 case TURN4:
787                                         trns += " turning final";
788                                         break;
789                                 case BASE:
790                                         trns += " on base";
791                                         break;
792                                 case TURN3:
793                                         trns += " turning base";
794                                         break;
795                                 case DOWNWIND:
796                                         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.
797                                         break;
798                                 // And to eliminate compiler warnings...
799                                 case TAKEOFF_ROLL: break;
800                                 case CLIMBOUT:     break;
801                                 case TURN1:        break;
802                                 case CROSSWIND:    break;
803                                 case TURN2:        break;
804                                 case LANDING_ROLL: break;
805                                 case LEG_UNKNOWN:  break;
806                                 }
807                         }
808                 } else {
809                         // By definition there should be some arriving traffic if we're cleared for immediate takeoff
810                         SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
811                 }
812                 t->clearedToTakeOff = true;
813                 t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
814                 departed = false;
815                 timeSinceLastDeparture = 0.0;
816         } else {
817         //} else if(timeSinceLastDeparture > 60.0 || departed == false) {       // Hack - test for timeSinceLastDeparture should be in lineup block eventually
818                 trns += " cleared for take-off";
819                 // TODO - add traffic is... ?
820                 t->clearedToTakeOff = true;
821                 t->planePtr->RegisterTransmission(4);   // cleared to take-off
822                 departed = false;
823                 timeSinceLastDeparture = 0.0;
824         }
825         if(_display) {
826                 pending_transmission = trns;
827                 Transmit();
828         }
829         //cout << "Done ClearHoldingPlane " << endl;
830 }
831
832
833 // ***************************************************************************************
834 // ********** Functions to periodically check what the various traffic is doing **********
835
836 // Do one plane from the hold list
837 void FGTower::CheckHoldList(double dt) {
838         //cout << "Entering CheckHoldList..." << endl;
839         if(!holdList.empty()) {
840                 //cout << "*holdListItr = " << *holdListItr << endl;
841                 if(holdListItr == holdList.end()) {
842                         holdListItr = holdList.begin();
843                 }
844                 //cout << "*holdListItr = " << *holdListItr << endl;
845                 //Process(*holdListItr);
846                 TowerPlaneRec* t = *holdListItr;
847                 //cout << "t = " << t << endl;
848                 if(t->holdShortReported) {
849                         // NO-OP - leave it to the response handler.
850                 } else {        // not responding to report, but still need to clear if clear
851                         if(t->nextOnRwy) {
852                                 //cout << "departed = " << departed << '\n';
853                                 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
854                                 if(rwyOccupied) {
855                                         // Do nothing
856                                 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
857                                         // Do nothing - this is a bit of a hack - should maybe do line up be ready here
858                                 } else {
859                                         ClearHoldingPlane(t);
860                                         t->leg = TAKEOFF_ROLL;
861                                         rwyList.push_back(t);
862                                         rwyListItr = rwyList.begin();
863                                         rwyOccupied = true;
864                                         holdList.erase(holdListItr);
865                                         holdListItr = holdList.begin();
866                                         if (holdList.empty())
867                                           return;
868                                 }
869                         }
870                         // TODO - rationalise the considerable code duplication above!
871                 }
872                 ++holdListItr;
873         }
874         //cout << "Done CheckHoldList" << endl;
875 }
876
877 // do the ciruit list
878 void FGTower::CheckCircuitList(double dt) {
879         //cout << "Entering CheckCircuitList..." << endl;
880         // Clear the constraints - we recalculate here.
881         base_leg_pos = 0.0;
882         downwind_leg_pos = 0.0;
883         crosswind_leg_pos = 0.0;
884         
885         if(!circuitList.empty()) {      // Do one plane from the circuit
886                 if(circuitListItr == circuitList.end()) {
887                         circuitListItr = circuitList.begin();
888                 }
889                 TowerPlaneRec* t = *circuitListItr;
890                 //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
891                 if(t->isUser) {
892                         t->pos.setlon(user_lon_node->getDoubleValue());
893                         t->pos.setlat(user_lat_node->getDoubleValue());
894                         t->pos.setelev(user_elev_node->getDoubleValue());
895                         //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
896                 } else {
897                         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.
898                         t->landingType = t->planePtr->GetLandingOption();
899                         //cout << "AI plane landing option is " << t->landingType << '\n';
900                 }
901                 Point3D tortho = ortho.ConvertToLocal(t->pos);
902                 if(t->isUser) {
903                         // Need to figure out which leg he's on
904                         //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
905                         double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
906                         //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
907                         // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
908                         // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
909                         if(fabs(ho) < 30) {
910                                 // could be either takeoff, climbout or landing - check orthopos.y
911                                 //cout << "tortho.y = " << tortho.y() << '\n';
912                                 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
913                                         t->leg = FINAL;
914                                         //cout << "Final\n";
915                                 } else {
916                                         t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
917                                         //cout << "Climbout\n";
918                                         // If it's the user we may be unsure of his/her intentions.
919                                         // (Hopefully the AI planes won't try confusing the sim!!!)
920                                         //cout << "tortho.y = " << tortho.y() << '\n';
921                                         if(t->opType == TTT_UNKNOWN) {
922                                                 if(tortho.y() > 5000) {
923                                                         // 5 km out from threshold - assume it's a departure
924                                                         t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
925                                                         // Since we are unknown operation we should be in depList already.
926                                                         //cout << ident << " Removing user from circuitList (TTT_UNKNOWN)\n";
927                                                         circuitListItr = circuitList.erase(circuitListItr);
928                                                         RemoveFromTrafficList(t->plane.callsign);
929                                                         if (circuitList.empty())
930                                                             return;
931                                                 }
932                                         } else if(t->opType == CIRCUIT) {
933                                                 if(tortho.y() > 10000) {
934                                                         // 10 km out - assume the user has abandoned the circuit!!
935                                                         t->opType = OUTBOUND;
936                                                         depList.push_back(t);
937                                                         depListItr = depList.begin();
938                                                         //cout << ident << " removing user from circuitList (CIRCUIT)\n";
939                                                         circuitListItr = circuitList.erase(circuitListItr);
940                                                         if (circuitList.empty())
941                                                           return;
942                                                 }
943                                         }
944                                 }
945                         } else if(fabs(ho) < 60) {
946                                 // turn1 or turn 4
947                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
948                                 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
949                                         t->leg = TURN1;
950                                         //cout << "Turn1\n";
951                                 } else {
952                                         t->leg = TURN4;
953                                         //cout << "Turn4\n";
954                                 }
955                         } else if(fabs(ho) < 120) {
956                                 // crosswind or base
957                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
958                                 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
959                                         t->leg = CROSSWIND;
960                                         //cout << "Crosswind\n";
961                                 } else {
962                                         t->leg = BASE;
963                                         //cout << "Base\n";
964                                 }
965                         } else if(fabs(ho) < 150) {
966                                 // turn2 or turn 3
967                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
968                                 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
969                                         t->leg = TURN2;
970                                         //cout << "Turn2\n";
971                                 } else {
972                                         t->leg = TURN3;
973                                         // Probably safe now to assume the user is flying a circuit
974                                         t->opType = CIRCUIT;
975                                         //cout << "Turn3\n";
976                                 }
977                         } else {
978                                 // downwind
979                                 t->leg = DOWNWIND;
980                                 //cout << "Downwind\n";
981                         }
982                         if(t->leg == FINAL) {
983                                 if(OnActiveRunway(t->pos)) {
984                                         t->leg = LANDING_ROLL;
985                                 }
986                         }
987                 } else {
988                         t->leg = t->planePtr->GetLeg();
989                 }
990                 
991                 // Set the constraints IF this is the first plane in the circuit
992                 // 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!!
993                 if(circuitListItr == circuitList.begin()) {
994                         switch(t->leg) {
995                                 case FINAL:
996                                 // 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.
997                                 base_leg_pos = tortho.y();
998                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
999                                 break;
1000                                 case TURN4:
1001                                 // Fall through to base
1002                                 case BASE:
1003                                 base_leg_pos = tortho.y();
1004                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
1005                                 break;
1006                                 case TURN3:
1007                                 // Fall through to downwind
1008                                 case DOWNWIND:
1009                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
1010                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
1011                                 //cout << "base_leg_pos = " << base_leg_pos;
1012                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
1013                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
1014                                 break;
1015                                 case TURN2:
1016                                 // Fall through to crosswind
1017                                 case CROSSWIND:
1018                                 crosswind_leg_pos = tortho.y();
1019                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1020                                 t->instructedToGoAround = false;
1021                                 break;
1022                                 case TURN1:
1023                                 // Fall through to climbout
1024                                 case CLIMBOUT:
1025                                 // Only use current by constraint as largest
1026                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
1027                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1028                                 break;
1029                                 case TAKEOFF_ROLL:
1030                                 break;
1031                                 case LEG_UNKNOWN:
1032                                 break;
1033                                 case LANDING_ROLL:
1034                                 break;
1035                                 default:
1036                                 break;
1037                         }
1038                 }
1039                 
1040                 if(t->leg == FINAL && !(t->instructedToGoAround)) {
1041                         doThresholdETACalc();
1042                         doThresholdUseOrder();
1043                         /*
1044                         if(t->isUser) {
1045                                 cout << "Checking USER on final... ";
1046                                 cout << "eta " << t->eta;
1047                                 if(t->clearedToLand) cout << " cleared to land\n";
1048                         }
1049                         */
1050                         //cout << "YES FINAL, t->eta = " << t->eta << ", rwyList.size() = " << rwyList.size() << '\n';
1051                         if(t->landingType == FULL_STOP) {
1052                                 t->opType = INBOUND;
1053                                 //cout << "\n******** SWITCHING TO INBOUND AT POINT AAA *********\n\n";
1054                         }
1055                         if(t->eta < 12 && rwyList.size()) {
1056                                 // TODO - need to make this more sophisticated 
1057                                 // eg. is the plane accelerating down the runway taking off [OK],
1058                                 // or stationary near the start [V. BAD!!].
1059                                 // For now this should stop the AI plane landing on top of the user.
1060                                 string trns = t->plane.callsign;
1061                                 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1062                                 pending_transmission = trns;
1063                                 ImmediateTransmit();
1064                                 t->instructedToGoAround = true;
1065                                 t->clearedToLand = false;
1066                                 // Assume it complies!!!
1067                                 t->opType = CIRCUIT;
1068                                 t->leg = CLIMBOUT;
1069                                 if(t->planePtr) {
1070                                         //cout << "Registering Go-around transmission with AI plane\n";
1071                                         t->planePtr->RegisterTransmission(13);
1072                                 }
1073                         } else if(!t->clearedToLand) {
1074                                 // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work
1075                                 // TODO - fix this!
1076                                 bool cf = false;
1077                                 for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1078                                         if((*twrItr)->eta < t->eta) {
1079                                                 cf = true;
1080                                         }
1081                                 }
1082                                 if(t->nextOnRwy && !cf) {
1083                                         if(!rwyList.size()) {
1084                                                 string trns = t->plane.callsign;
1085                                                 trns += " Cleared to land";
1086                                                 pending_transmission = trns;
1087                                                 Transmit();
1088                                                 //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
1089                                                 t->clearedToLand = true;
1090                                                 if(!t->isUser) {
1091                                                         t->planePtr->RegisterTransmission(7);
1092                                                 }
1093                                         }
1094                                 } else {
1095                                         //if(t->isUser) cout << "Not next\n";
1096                                 }
1097                         }
1098                 } else if(t->leg == LANDING_ROLL) {
1099                         //cout << t->plane.callsign << " has landed - adding to rwyList\n";
1100                         rwyList.push_front(t);
1101                         // TODO - if(!clearedToLand) shout something!!
1102                         t->clearedToLand = false;
1103                         RemoveFromTrafficList(t->plane.callsign);
1104                         if(t->isUser) {
1105                                 t->opType = TTT_UNKNOWN;
1106                         }       // TODO - allow the user to specify opType via ATC menu
1107                         //cout << ident << " Removing " << t->plane.callsign << " from circuitList..." << endl;
1108                         circuitListItr = circuitList.erase(circuitListItr);
1109                         if(circuitListItr == circuitList.end() ) {
1110                                 circuitListItr = circuitList.begin();
1111                                 // avoid increment of circuitListItr (would increment to second element, or crash if no element left)
1112                                 return;
1113                         }
1114                 }
1115                 ++circuitListItr;
1116         }
1117         //cout << "Done CheckCircuitList" << endl;
1118 }
1119
1120 // 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!!
1121 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
1122 // (However, at the moment there should only be one airplane on the rwy at once, until we
1123 // start allowing planes to line up whilst previous arrival clears the rwy.)
1124 void FGTower::CheckRunwayList(double dt) {
1125         //cout << "Entering CheckRunwayList..." << endl;
1126         if(rwyOccupied) {
1127                 if(!rwyList.size()) {
1128                         rwyOccupied = false;
1129                 } else {
1130                         rwyListItr = rwyList.begin();
1131                         TowerPlaneRec* t = *rwyListItr;
1132                         if(t->isUser) {
1133                                 t->pos.setlon(user_lon_node->getDoubleValue());
1134                                 t->pos.setlat(user_lat_node->getDoubleValue());
1135                                 t->pos.setelev(user_elev_node->getDoubleValue());
1136                         } else {
1137                                 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.
1138                         }
1139                         bool on_rwy = OnActiveRunway(t->pos);
1140                         if(!on_rwy) {
1141                                 // TODO - for all of these we need to check what the user is *actually* doing!
1142                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
1143                                         //cout << "Tower " << ident << " is removing plane " << t->plane.callsign << " from rwy list (vacated)\n";
1144                                         //cout << "Size of rwylist was " << rwyList.size() << '\n';
1145                                         //cout << "Size of vacatedList was " << vacatedList.size() << '\n';
1146                                         RemoveFromRwyList(t->plane.callsign);
1147                                         AddToVacatedList(t);
1148                                         //cout << "Size of rwylist is " << rwyList.size() << '\n';
1149                                         //cout << "Size of vacatedList is " << vacatedList.size() << '\n';
1150                                         // At the moment we wait until Runway Vacated is reported by the plane before telling to contact ground etc.
1151                                         // It's possible we could be a bit more proactive about this.
1152                                 } else if(t->opType == OUTBOUND) {
1153                                         depList.push_back(t);
1154                                         depListItr = depList.begin();
1155                                         rwyList.pop_front();
1156                                         departed = true;
1157                                         timeSinceLastDeparture = 0.0;
1158                                 } else if(t->opType == CIRCUIT) {
1159                                         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1160                                         circuitList.push_back(t);
1161                                         circuitListItr = circuitList.begin();
1162                                         AddToTrafficList(t);
1163                                         rwyList.pop_front();
1164                                         departed = true;
1165                                         timeSinceLastDeparture = 0.0;
1166                                 } else if(t->opType == TTT_UNKNOWN) {
1167                                         depList.push_back(t);
1168                                         depListItr = depList.begin();
1169                                         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1170                                         circuitList.push_back(t);
1171                                         circuitListItr = circuitList.begin();
1172                                         AddToTrafficList(t);
1173                                         rwyList.pop_front();
1174                                         departed = true;
1175                                         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.
1176                                 } else {
1177                                         // HELP - we shouldn't ever get here!!!
1178                                 }
1179                         }
1180                 }
1181         }
1182         //cout << "Done CheckRunwayList" << endl;
1183 }
1184
1185 // Do one plane from the approach list
1186 void FGTower::CheckApproachList(double dt) {
1187         //cout << "CheckApproachList called for " << ident << endl;
1188         //cout << "AppList.size is " << appList.size() << endl;
1189         if(!appList.empty()) {
1190                 if(appListItr == appList.end()) {
1191                         appListItr = appList.begin();
1192                 }
1193                 TowerPlaneRec* t = *appListItr;
1194                 //cout << "t = " << t << endl;
1195                 //cout << "Checking " << t->plane.callsign << endl;
1196                 if(t->isUser) {
1197                         t->pos.setlon(user_lon_node->getDoubleValue());
1198                         t->pos.setlat(user_lat_node->getDoubleValue());
1199                         t->pos.setelev(user_elev_node->getDoubleValue());
1200                 } else {
1201                         // TODO - set/update the position if it's an AI plane
1202                 }
1203                 doThresholdETACalc();   // We need this here because planes in the lists are not guaranteed to *always* have the correct ETA
1204                 //cout << "eta is " << t->eta << ", rwy is " << (rwyList.size() ? "occupied " : "clear ") << '\n';
1205                 if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
1206                         // TODO - need to make this more sophisticated 
1207                         // eg. is the plane accelerating down the runway taking off [OK],
1208                         // or stationary near the start [V. BAD!!].
1209                         // For now this should stop the AI plane landing on top of the user.
1210                         string trns = t->plane.callsign;
1211                         trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1212                         pending_transmission = trns;
1213                         ImmediateTransmit();
1214                         t->instructedToGoAround = true;
1215                         t->clearedToLand = false;
1216                         t->nextOnRwy = false;   // But note this is recalculated so don't rely on it
1217                         // Assume it complies!!!
1218                         t->opType = CIRCUIT;
1219                         t->leg = CLIMBOUT;
1220                         if(!t->isUser) {
1221                                 if(t->planePtr) {
1222                                         //cout << "Registering Go-around transmission with AI plane\n";
1223                                         t->planePtr->RegisterTransmission(13);
1224                                 }
1225                         } else {
1226                                 // TODO - add Go-around ack to comm options,
1227                                 // remove report rwy vacated. (possibly).
1228                         }
1229                 } else if(t->eta < 90 && !t->clearedToLand) {
1230                         //doThresholdETACalc();
1231                         doThresholdUseOrder();
1232                         // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work
1233                         // TODO - fix this!
1234                         bool cf = false;
1235                         for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1236                                 if((*twrItr)->eta < t->eta) {
1237                                         cf = true;
1238                                 }
1239                         }
1240                         if(t->nextOnRwy && !cf) {
1241                                 if(!rwyList.size()) {
1242                                         string trns = t->plane.callsign;
1243                                         trns += " Cleared to land";
1244                                         pending_transmission = trns;
1245                                         Transmit();
1246                                         //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
1247                                         t->clearedToLand = true;
1248                                         if(!t->isUser) {
1249                                                 t->planePtr->RegisterTransmission(7);
1250                                         }
1251                                 }
1252                         } else {
1253                                 //if(t->isUser) cout << "Not next\n";
1254                         }
1255                 }
1256                 
1257                 // Check for landing...
1258                 bool landed = false;
1259                 if(!t->isUser) {
1260                         if(t->planePtr) {
1261                                 if(t->planePtr->GetLeg() == LANDING_ROLL) {
1262                                         landed = true;
1263                                 }
1264                         } else {
1265                                 SG_LOG(SG_ATC, SG_ALERT, "WARNING - not user and null planePtr in CheckApproachList!");
1266                         }
1267                 } else {        // user
1268                         if(OnActiveRunway(t->pos)) {
1269                                 landed = true;
1270                         }
1271                 }
1272                 
1273                 if(landed) {
1274                         // Duplicated in CheckCircuitList - must be able to rationalise this somehow!
1275                         //cout << "A " << t->plane.callsign << " has landed, adding to rwyList...\n";
1276                         rwyList.push_front(t);
1277                         // TODO - if(!clearedToLand) shout something!!
1278                         t->clearedToLand = false;
1279                         RemoveFromTrafficList(t->plane.callsign);
1280                         //if(t->isUser) {
1281                                 //      t->opType = TTT_UNKNOWN;
1282                         //}     // TODO - allow the user to specify opType via ATC menu
1283                         appListItr = appList.erase(appListItr);
1284                         if(appListItr == appList.end() ) {
1285                                 appListItr = appList.begin();
1286                         }
1287                         if (appList.empty())
1288                           return;
1289
1290                 }
1291                 
1292                 ++appListItr;
1293         }
1294         //cout << "Done" << endl;
1295 }
1296
1297 // Do one plane from the departure list
1298 void FGTower::CheckDepartureList(double dt) {
1299         if(!depList.empty()) {
1300                 if(depListItr == depList.end()) {
1301                         depListItr = depList.begin();
1302                 }
1303                 TowerPlaneRec* t = *depListItr;
1304                 //cout << "Dep list, checking " << t->plane.callsign;
1305                 
1306                 double distout; // meters
1307                 if(t->isUser) distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
1308                 else distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), t->planePtr->GetPos());
1309                 //cout << " distout = " << distout << '\n';
1310                 if(distout > 10000) {
1311                         string trns = t->plane.callsign;
1312                         trns += " You are now clear of my airspace, good day";
1313                         pending_transmission = trns;
1314                         Transmit();
1315                         if(t->isUser) {
1316                                 // Change the communication options
1317                                 RemoveAllUserDialogOptions();
1318                                 //cout << "ADD A\n";
1319                                 current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI miles @CD of the airport for full stop with ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
1320                         } else {
1321                                 // Send a clear-of-airspace signal
1322                                 // TODO - implement this once we actually have departing AI traffic (currently all circuits or arrivals).
1323                         }
1324                         RemovePlane(t->plane.callsign);
1325                 } else {
1326                         ++depListItr;
1327                 }
1328         }
1329 }
1330
1331 // ********** End periodic check functions ***********************************************
1332 // ***************************************************************************************
1333
1334
1335 // Remove all dialog options for this tower.
1336 void FGTower::RemoveAllUserDialogOptions() {
1337         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_DEPARTURE, TOWER);
1338         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1339         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1340         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1341         current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1342         current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
1343         current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
1344         current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);        
1345 }
1346
1347 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
1348 // plus the constraint position as a rwy orientated orthopos (meters)
1349 bool FGTower::GetCrosswindConstraint(double& cpos) {
1350         if(crosswind_leg_pos != 0.0) {
1351                 cpos = crosswind_leg_pos;
1352                 return(true);
1353         } else {
1354                 cpos = 0.0;
1355                 return(false);
1356         }
1357 }
1358 bool FGTower::GetDownwindConstraint(double& dpos) {
1359         if(fabs(downwind_leg_pos) > nominal_downwind_leg_pos) {
1360                 dpos = downwind_leg_pos;
1361                 return(true);
1362         } else {
1363                 dpos = 0.0;
1364                 return(false);
1365         }
1366 }
1367 bool FGTower::GetBaseConstraint(double& bpos) {
1368         if(base_leg_pos < nominal_base_leg_pos) {
1369                 bpos = base_leg_pos;
1370                 return(true);
1371         } else {
1372                 bpos = nominal_base_leg_pos;
1373                 return(false);
1374         }
1375 }
1376
1377
1378 // Figure out which runways are active.
1379 // For now we'll just be simple and do one active runway - eventually this will get much more complex
1380 // This is a private function - public interface to the results of this is through GetActiveRunway
1381 void FGTower::DoRwyDetails() {
1382         //cout << "GetRwyDetails called" << endl;
1383         
1384         // Based on the airport-id and wind get the active runway
1385         
1386         //wind
1387         double hdg = wind_from_hdg->getDoubleValue();
1388         double speed = wind_speed_knots->getDoubleValue();
1389         hdg = (speed == 0.0 ? 270.0 : hdg);
1390         //cout << "Heading = " << hdg << '\n';
1391         
1392         FGRunway runway;
1393         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
1394         if(rwyGood) {
1395                 //cout << "RUNWAY GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOD\n";
1396                 activeRwy = runway._rwy_no;
1397                 rwy.rwyID = runway._rwy_no;
1398                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
1399                 
1400                 // Get the threshold position
1401                 double other_way = runway._heading - 180.0;
1402                 while(other_way <= 0.0) {
1403                         other_way += 360.0;
1404                 }
1405         // move to the +l end/center of the runway
1406                 //cout << "Runway center is at " << runway._lon << ", " << runway._lat << '\n';
1407         Point3D origin = Point3D(runway._lon, runway._lat, aptElev);
1408                 Point3D ref = origin;
1409         double tshlon, tshlat, tshr;
1410                 double tolon, tolat, tor;
1411                 rwy.length = runway._length * SG_FEET_TO_METER;
1412                 rwy.width = runway._width * SG_FEET_TO_METER;
1413         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
1414                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
1415         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway._heading, 
1416                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
1417                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
1418                 // now copy what we need out of runway into rwy
1419         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
1420                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
1421                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
1422                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
1423                 rwy.hdg = runway._heading;
1424                 // Set the projection for the local area based on this active runway
1425                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
1426                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
1427                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
1428                 
1429                 // Set the pattern direction
1430                 // TODO - we'll check for a facilities file with this in eventually - for now assume left traffic except
1431                 // for certain circumstances (RH parallel rwy).
1432                 rwy.patternDirection = -1;              // Left
1433                 if(rwy.rwyID.size() == 3) {
1434                         rwy.patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1);
1435                 }
1436                 //cout << "Doing details, rwy.patterDirection is " << rwy.patternDirection << '\n';
1437         } else {
1438                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
1439                 activeRwy = "NN";
1440         }
1441 }
1442
1443
1444 // Figure out if a given position lies on the active runway
1445 // Might have to change when we consider more than one active rwy.
1446 bool FGTower::OnActiveRunway(const Point3D& pt) {
1447         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
1448         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
1449         Point3D xyp = ortho.ConvertToLocal(pt);
1450         
1451         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
1452         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
1453
1454         double rlen = rwy.length/2.0 + 5.0;
1455         double rwidth = rwy.width/2.0;
1456         double ldiff = fabs(xyp.y() - xyc.y());
1457         double wdiff = fabs(xyp.x() - xyc.x());
1458
1459         return((ldiff < rlen) && (wdiff < rwidth));
1460 }       
1461
1462
1463 // Figure out if a given position lies on any runway or not
1464 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
1465 bool FGTower::OnAnyRunway(const Point3D& pt) {
1466         ATCData ad;
1467         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
1468         if(dist < 0.0) {
1469                 return(false);
1470         }
1471         // Based on the airport-id, go through all the runways and check for a point in them
1472         
1473         // TODO - do we actually need to search for the airport - surely we already know our ident and
1474         // can just search runways of our airport???
1475         //cout << "Airport ident is " << ad.ident << '\n';
1476         FGRunway runway;
1477         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
1478         if(!rwyGood) {
1479                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
1480         }
1481         bool on = false;
1482         while(runway._id == ad.ident) {         
1483                 on = OnRunway(pt, runway);
1484                 //cout << "Runway " << runway._rwy_no << ": On = " << (on ? "true\n" : "false\n");
1485                 if(on) return(true);
1486                 globals->get_runways()->next(&runway);          
1487         }
1488         return(on);
1489 }
1490
1491
1492 // Returns true if successful
1493 bool FGTower::RemoveFromTrafficList(const string& id) {
1494         tower_plane_rec_list_iterator twrItr;
1495         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1496                 TowerPlaneRec* tpr = *twrItr;
1497                 if(tpr->plane.callsign == id) {
1498                         trafficList.erase(twrItr);
1499                         trafficListItr = trafficList.begin();
1500                         return(true);
1501                 }
1502         }       
1503         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
1504         return(false);
1505 }
1506
1507
1508 // Returns true if successful
1509 bool FGTower::RemoveFromAppList(const string& id) {
1510         tower_plane_rec_list_iterator twrItr;
1511         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1512                 TowerPlaneRec* tpr = *twrItr;
1513                 if(tpr->plane.callsign == id) {
1514                         appList.erase(twrItr);
1515                         appListItr = appList.begin();
1516                         return(true);
1517                 }
1518         }       
1519         //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from appList in FGTower");
1520         return(false);
1521 }
1522
1523 // Returns true if successful
1524 bool FGTower::RemoveFromRwyList(const string& id) {
1525         tower_plane_rec_list_iterator twrItr;
1526         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
1527                 TowerPlaneRec* tpr = *twrItr;
1528                 if(tpr->plane.callsign == id) {
1529                         rwyList.erase(twrItr);
1530                         rwyListItr = rwyList.begin();
1531                         return(true);
1532                 }
1533         }       
1534         //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from rwyList in FGTower");
1535         return(false);
1536 }
1537
1538
1539 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
1540 // and set nextOnRwy if so.
1541 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
1542 // For planes holding they are put in the first position with time to go, and the return value is
1543 // true if in the first position (nextOnRwy) and false otherwise.
1544 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
1545 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
1546         //cout << "ADD: " << trafficList.size();
1547         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
1548         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.
1549         double departure_sep_time = 60.0;       // Separation time behind departing airplanes.  Comments above also apply.
1550         bool conflict = false;
1551         double lastETA = 0.0;
1552         bool firstTime = true;
1553         // FIXME - make this more robust for different plane types eg. light following heavy.
1554         tower_plane_rec_list_iterator twrItr;
1555         //twrItr = trafficList.begin();
1556         //while(1) {
1557         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1558                 //if(twrItr == trafficList.end()) {
1559                 //      cout << "  END  ";
1560                 //      trafficList.push_back(t);
1561                 //      return(holding ? firstTime : conflict);
1562                 //} else {
1563                         TowerPlaneRec* tpr = *twrItr;
1564                         if(holding) {
1565                                 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1566                                 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1567                                 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0); 
1568                                 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1569                                 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1570                                 // and if not needs time to clear the rwy anyway.
1571                                 if(tpr->eta  - lastETA > slot_time) {
1572                                         t->nextOnRwy = firstTime;
1573                                         trafficList.insert(twrItr, t);
1574                                         //cout << "\tH\t" << trafficList.size() << '\n';
1575                                         return(firstTime);
1576                                 }
1577                                 firstTime = false;
1578                         } else {
1579                                 if(t->eta < tpr->eta) {
1580                                         // Ugg - this one's tricky.
1581                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1582                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1583                                                 if(tpr->nextOnRwy) {
1584                                                         tpr->nextOnRwy = false;
1585                                                         t->nextOnRwy = true;
1586                                                 }
1587                                                 trafficList.insert(twrItr, t);
1588                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1589                                                 conflict = true;
1590                                                 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1591                                                 if(tpr->nextOnRwy) {
1592                                                         tpr->nextOnRwy = false;
1593                                                         t->nextOnRwy = true;
1594                                                 }
1595                                                 trafficList.insert(twrItr, t);
1596                                         }
1597                                         //cout << "\tC\t" << trafficList.size() << '\n';
1598                                         return(conflict);
1599                                 }
1600                         }
1601                 //}
1602                 //++twrItr;
1603         }
1604         // If we get here we must be at the end of the list, or maybe the list is empty.
1605         if(!trafficList.size()) {
1606                 t->nextOnRwy = true;
1607                 // conflict and firstTime should be false and true respectively in this case anyway.
1608         } else {
1609                 t->nextOnRwy = false;
1610         }
1611         trafficList.push_back(t);
1612         //cout << "\tE\t" << trafficList.size() << endl;
1613         return(holding ? firstTime : conflict);
1614 }
1615
1616 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
1617 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
1618 // Safe to add a plane that is already in - planes with the same callsign are not added.
1619 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
1620         if(!t) {
1621                 //cout << "**********************************************\n";
1622                 //cout << "AddToCircuitList called with NULL pointer!!!!!\n";
1623                 //cout << "**********************************************\n";
1624                 return false;
1625         }
1626         //cout << "ADD: " << circuitList.size();
1627         //cout << ident << " AddToCircuitList called for " << t->plane.callsign << ", currently size = " << circuitList.size() << endl;
1628         double separation_time = 60.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.
1629         bool conflict = false;
1630         tower_plane_rec_list_iterator twrItr;
1631         // First check if the plane is already in the list
1632         //cout << "A" << endl;
1633         //cout << "Checking whether " << t->plane.callsign << " is already in circuit list..." << endl;
1634         //cout << "B" << endl;
1635         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1636                 if((*twrItr)->plane.callsign == t->plane.callsign) {
1637                         //cout << "In list - returning...\n";
1638                         return false;
1639                 }
1640         }
1641         //cout << "Not in list - adding..." << endl;
1642         
1643         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1644                 TowerPlaneRec* tpr = *twrItr;
1645                 //cout << tpr->plane.callsign << " eta is " << tpr->eta << '\n';
1646                 //cout << "New eta is " << t->eta << '\n';              
1647                 if(t->eta < tpr->eta) {
1648                         // Ugg - this one's tricky.
1649                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1650                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1651                                 circuitList.insert(twrItr, t);
1652                                 circuitListItr = circuitList.begin();
1653                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1654                                 conflict = true;
1655                                 // HACK - just add anyway for now and flag conflict.
1656                                 circuitList.insert(twrItr, t);
1657                                 circuitListItr = circuitList.begin();
1658                         }
1659                         //cout << "\tC\t" << circuitList.size() << '\n';
1660                         return(conflict);
1661                 }
1662         }
1663         // If we get here we must be at the end of the list, or maybe the list is empty.
1664         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1665         circuitList.push_back(t);       // TODO - check the separation with the preceding plane for the conflict flag.
1666         circuitListItr = circuitList.begin();
1667         //cout << "\tE\t" << circuitList.size() << endl;
1668         return(conflict);
1669 }
1670
1671 // Add to vacated list only if not already present
1672 void FGTower::AddToVacatedList(TowerPlaneRec* t) {
1673         tower_plane_rec_list_iterator twrItr;
1674         bool found = false;
1675         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
1676                 if((*twrItr)->plane.callsign == t->plane.callsign) {
1677                         found = true;
1678                 }
1679         }
1680         if(found) return;
1681         vacatedList.push_back(t);
1682 }
1683
1684
1685 // Calculate the eta of a plane to the threshold.
1686 // For ground traffic this is the fastest they can get there.
1687 // For air traffic this is the middle approximation.
1688 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1689         // For now we'll be very crude and hardwire expected speeds to C172-like values
1690         // The speeds below are specified in knots IAS and then converted to m/s
1691         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
1692         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
1693         double final_ias = 70.0 * 0.514444;             // Speed during final approach
1694         
1695         //if(printout) {
1696         //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1697         //cout << (tpr->isUser ? "USER\n" : "AI\n");
1698         //cout << flush;
1699         //}
1700         
1701         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1702         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1703         
1704         Point3D op = ortho.ConvertToLocal(tpr->pos);
1705         //if(printout) {
1706         //if(!tpr->isUser) cout << "Orthopos is " << op.x() << ", " << op.y() << ' ';
1707         //cout << "opType is " << tpr->opType << '\n';
1708         //}
1709         double dist_out_m = op.y();
1710         double dist_across_m = fabs(op.x());    // The fabs is a hack to cope with the fact that we don't know the circuit direction yet
1711         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1712         
1713         if(tpr->opType == STRAIGHT_IN || tpr->opType == INBOUND) {
1714                 //cout << "CASE 1\n";
1715                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1716                 if(dist_to_go_m < 1000) {
1717                         tpr->eta = dist_to_go_m / final_ias;
1718                 } else {
1719                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1720                 }
1721         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1722                 //cout << "CASE 2\n";
1723                 // It's complicated - depends on if base leg is delayed or not
1724                 //if(printout) {
1725                 //cout << "Leg = " << tpr->leg << '\n';
1726                 //}
1727                 if(tpr->leg == LANDING_ROLL) {
1728                         tpr->eta = 0;
1729                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1730                         //cout << "dist_out_m = " << dist_out_m << '\n';
1731                         tpr->eta = fabs(dist_out_m) / final_ias;
1732                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1733                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1734                 } else {
1735                         // Need to calculate where base leg is likely to be
1736                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1737                         // 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
1738                         double nominal_base_dist_out_m = -1000;
1739                         double current_base_dist_out_m;
1740                         if(!GetBaseConstraint(current_base_dist_out_m)) {
1741                                 current_base_dist_out_m = nominal_base_dist_out_m;
1742                         }
1743                         //cout << "current_base_dist_out_m = " << current_base_dist_out_m << '\n';
1744                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
1745                         double current_dist_across_m;
1746                         if(!GetDownwindConstraint(current_dist_across_m)) {
1747                                 current_dist_across_m = nominal_dist_across_m;
1748                         }
1749                         double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 700ft agl.
1750                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
1751                         //cout << "a = " << tpr->eta << '\n';
1752                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1753                                 tpr->eta += dist_across_m / circuit_ias;
1754                                 //cout << "b = " << tpr->eta << '\n';
1755                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1756                                 //cout << "c = " << tpr->eta << '\n';
1757                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1758                                 //cout << "CROSSWIND calc: ";
1759                                 //cout << tpr->eta << ' ';
1760                                 if(dist_across_m > nominal_dist_across_m) {
1761                                         tpr->eta += dist_across_m / circuit_ias;
1762                                         //cout << "a ";
1763                                 } else {
1764                                         tpr->eta += nominal_dist_across_m / circuit_ias;
1765                                         //cout << "b ";
1766                                 }
1767                                 //cout << tpr->eta << ' ';
1768                                 // should we use the dist across of the previous plane if there is previous still on downwind?
1769                                 //if(printout) cout << "bb = " << tpr->eta << '\n';
1770                                 if(dist_out_m > nominal_cross_dist_out_m) {
1771                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1772                                         //cout << "c ";
1773                                 } else {
1774                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1775                                         //cout << "d ";
1776                                 }
1777                                 //cout << tpr->eta << ' ';
1778                                 //if(printout) cout << "cc = " << tpr->eta << '\n';
1779                                 if(nominal_dist_across_m > dist_across_m) {
1780                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1781                                         //cout << "e ";
1782                                 } else {
1783                                         // Nothing to add
1784                                         //cout << "f ";
1785                                 }
1786                                 //cout << tpr->eta << '\n';
1787                                 //if(printout) cout << "dd = " << tpr->eta << '\n';
1788                         } else {
1789                                 // We've only just started - why not use a generic estimate?
1790                                 tpr->eta = 240.0;
1791                         }
1792                 }
1793                 //if(printout) {
1794                 //      cout << "ETA = " << tpr->eta << '\n';
1795                 //}
1796                 //if(!tpr->isUser) cout << tpr->plane.callsign << '\t' << tpr->eta << '\n';
1797         } else {
1798                 tpr->eta = 99999;
1799         }       
1800 }
1801
1802
1803 // Calculate the distance of a plane to the threshold in meters
1804 // TODO - Modify to calculate flying distance of a plane in the circuit
1805 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1806         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1807 }
1808
1809
1810 // Calculate the distance of a plane to the threshold in miles
1811 // TODO - Modify to calculate flying distance of a plane in the circuit
1812 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1813         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
1814 }
1815
1816
1817 // Iterate through all the lists, update the position of, and call CalcETA for all the planes.
1818 void FGTower::doThresholdETACalc() {
1819         //cout << "Entering doThresholdETACalc..." << endl;
1820         tower_plane_rec_list_iterator twrItr;
1821         // Do the approach list first
1822         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1823                 TowerPlaneRec* tpr = *twrItr;
1824                 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1825                 //cout << "APP: ";
1826                 CalcETA(tpr);
1827         }       
1828         // Then the circuit list
1829         //cout << "Circuit list size is " << circuitList.size() << '\n';
1830         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1831                 TowerPlaneRec* tpr = *twrItr;
1832                 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1833                 //cout << "CIRC: ";
1834                 CalcETA(tpr);
1835         }
1836         //cout << "Done doThresholdETCCalc" << endl;
1837 }
1838                 
1839
1840 // Check that the planes in traffic list are correctly ordered,
1841 // that the nearest (timewise) is flagged next on rwy, and return
1842 // true if any threshold use conflicts are detected, false otherwise.
1843 bool FGTower::doThresholdUseOrder() {
1844         //cout << "Entering doThresholdUseOrder..." << endl;
1845         bool conflict = false;
1846         
1847         // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1848         // Here's the rather simplistic assumptions we're using:
1849         // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1850         // In order of priority for runway use:
1851         // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1852         // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1853         // and holding planes until a space.
1854         // When calculating if a holding plane can use the runway, time clearance from last departure
1855         // as well as time clearance to next arrival must be considered.
1856         
1857         trafficList.clear();
1858         
1859         tower_plane_rec_list_iterator twrItr;
1860         // Do the approach list first
1861         //if(ident == "KRHV") cout << "A" << flush;
1862         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1863                 TowerPlaneRec* tpr = *twrItr;
1864                 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1865                 conflict = AddToTrafficList(tpr);
1866         }       
1867         // Then the circuit list
1868         //if(ident == "KRHV") cout << "C" << flush;
1869         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1870                 TowerPlaneRec* tpr = *twrItr;
1871                 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1872                 conflict = AddToTrafficList(tpr);
1873         }
1874         // And finally the hold list
1875         //cout << "H" << endl;
1876         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1877                 TowerPlaneRec* tpr = *twrItr;
1878                 AddToTrafficList(tpr, true);
1879         }
1880         
1881         
1882         if(0) {
1883         //if(ident == "KRHV") {
1884                 cout << "T\n";
1885                 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1886                         TowerPlaneRec* tpr = *twrItr;
1887                         cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1888                 }
1889                 cout << endl;
1890         }
1891         
1892         //cout << "Done doThresholdUseOrder" << endl;
1893         return(conflict);
1894 }
1895
1896
1897 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1898 // i.e. list_pos = 1 implies next to use runway.
1899 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1900         if(trafficList.size() < list_pos) {
1901                 return(99999);
1902         }
1903
1904         tower_plane_rec_list_iterator twrItr;
1905         twrItr = trafficList.begin();
1906         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1907         TowerPlaneRec* tpr = *twrItr;
1908         CalcETA(tpr, printout);
1909         //cout << "ETA returned = " << tpr->eta << '\n';
1910         return(tpr->eta);
1911 }
1912         
1913
1914 void FGTower::ContactAtHoldShort(const PlaneRec& plane, FGAIPlane* requestee, tower_traffic_type operation) {
1915         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1916         TowerPlaneRec* t = new TowerPlaneRec;
1917         t->plane = plane;
1918         t->planePtr = requestee;
1919         t->holdShortReported = true;
1920         t->clearedToLineUp = false;
1921         t->clearedToTakeOff = false;
1922         t->opType = operation;
1923         t->pos = requestee->GetPos();
1924         
1925         //cout << "Hold Short reported by " << plane.callsign << '\n';
1926         SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign);
1927
1928 /*      
1929         bool next = AddToTrafficList(t, true);
1930         if(next) {
1931                 double teta = GetTrafficETA(2);
1932                 if(teta < 150.0) {
1933                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1934                         //cout << "Reducing response time to request due imminent traffic\n";
1935                 }
1936         } else {
1937         }
1938 */
1939         // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1940
1941         holdList.push_back(t);
1942         
1943         responseReqd = true;
1944 }
1945
1946 // Register the presence of an AI plane at a point where contact would already have been made in real life
1947 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
1948 void FGTower::RegisterAIPlane(const PlaneRec& plane, FGAIPlane* ai, const tower_traffic_type& op, const PatternLeg& lg) {
1949         // At the moment this is only going to be tested with inserting an AI plane on downwind
1950         TowerPlaneRec* t = new TowerPlaneRec;
1951         t->plane = plane;
1952         t->planePtr = ai;
1953         t->opType = op;
1954         t->leg = lg;
1955         t->pos = ai->GetPos();
1956         
1957         CalcETA(t);
1958         
1959         if(op == CIRCUIT && lg != LEG_UNKNOWN) {
1960                 AddToCircuitList(t);
1961         } else {
1962                 // FLAG A WARNING
1963         }
1964         
1965         doThresholdUseOrder();
1966 }
1967
1968 void FGTower::DeregisterAIPlane(const string& id) {
1969         RemovePlane(id);
1970 }
1971
1972 // Contact tower for VFR approach
1973 // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo"
1974 // This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec.
1975 // opt defaults to AIP_LT_UNKNOWN
1976 void FGTower::VFRArrivalContact(const string& ID, const LandingType& opt) {
1977         //cout << "USER Request Landing Clearance called for ID " << ID << '\n';
1978         
1979         // For now we'll assume that the user is a light plane and can get him/her to join the circuit if necessary.
1980
1981         TowerPlaneRec* t;       
1982         string usercall = fgGetString("/sim/user/callsign");
1983         if(ID == "USER" || ID == usercall) {
1984                 t = FindPlane(usercall);
1985                 if(!t) {
1986                         //cout << "NOT t\n";
1987                         t = new TowerPlaneRec;
1988                         t->isUser = true;
1989                         t->pos.setlon(user_lon_node->getDoubleValue());
1990                         t->pos.setlat(user_lat_node->getDoubleValue());
1991                         t->pos.setelev(user_elev_node->getDoubleValue());
1992                 } else {
1993                         //cout << "IS t\n";
1994                         // Oops - the plane is already registered with this tower - maybe we took off and flew a giant circuit without
1995                         // quite getting out of tower airspace - just ignore for now and treat as new arrival.
1996                         // TODO - Maybe should remove from departure and circuit list if in there though!!
1997                 }
1998         } else {
1999                 // Oops - something has gone wrong - put out a warning
2000                 cout << "WARNING - FGTower::VFRContact(string ID, LandingType lt) called with ID " << ID << " which does not appear to be the user.\n";
2001                 return;
2002         }
2003                 
2004         
2005         // TODO
2006         // Calculate where the plane is in relation to the active runway and it's circuit
2007         // and set the op-type as appropriate.
2008         
2009         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
2010         t->opType = STRAIGHT_IN;
2011         
2012         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
2013         t->plane.callsign = usercall;
2014         
2015         t->vfrArrivalReported = true;
2016         responseReqd = true;
2017         
2018         appList.push_back(t);   // Not necessarily permanent
2019         appListItr = appList.begin();
2020         AddToTrafficList(t);
2021         
2022         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
2023         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
2024         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
2025 }
2026
2027 // landingType defaults to AIP_LT_UNKNOWN
2028 void FGTower::VFRArrivalContact(const PlaneRec& plane, FGAIPlane* requestee, const LandingType& lt) {
2029         //cout << "VFRArrivalContact called for plane " << plane.callsign << " at " << ident << '\n';
2030         // Possible hack - assume this plane is new for now - TODO - should check really
2031         TowerPlaneRec* t = new TowerPlaneRec;
2032         t->plane = plane;
2033         t->planePtr = requestee;
2034         t->landingType = lt;
2035         t->pos = requestee->GetPos();
2036         
2037         //cout << "Hold Short reported by " << plane.callsign << '\n';
2038         SG_LOG(SG_ATC, SG_BULK, "VFR arrival contact made by " << plane.callsign);
2039         //cout << "VFR arrival contact made by " << plane.callsign << '\n';
2040
2041         // HACK - to get up and running I'm going to assume a staight-in final for now.
2042         t->opType = STRAIGHT_IN;
2043         
2044         t->vfrArrivalReported = true;
2045         responseReqd = true;
2046         
2047         //cout << "Before adding, appList.size = " << appList.size() << " at " << ident << '\n';
2048         appList.push_back(t);   // Not necessarily permanent
2049         appListItr = appList.begin();
2050         //cout << "After adding, appList.size = " << appList.size() << " at " << ident << '\n';
2051         AddToTrafficList(t);
2052 }
2053
2054 void FGTower::RequestDepartureClearance(const string& ID) {
2055         //cout << "Request Departure Clearance called...\n";
2056 }
2057         
2058 void FGTower::ReportFinal(const string& ID) {
2059         //cout << "Report Final Called at tower " << ident << " by plane " << ID << '\n';
2060         string uid=ID;
2061         if(ID == "USER") {
2062                 uid = fgGetString("/sim/user/callsign");
2063                 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
2064         }
2065         TowerPlaneRec* t = FindPlane(uid);
2066         if(t) {
2067                 t->finalReported = true;
2068                 t->finalAcknowledged = false;
2069                 if(!(t->clearedToLand)) {
2070                         responseReqd = true;
2071                 } else {
2072                         // possibly respond with wind even if already cleared to land?
2073                         t->finalReported = false;
2074                         t->finalAcknowledged = true;
2075                         // HACK!! - prevents next reporting being misinterpreted as this one.
2076                 }
2077         } else {
2078                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
2079         }
2080 }
2081
2082 void FGTower::ReportLongFinal(const string& ID) {
2083         string uid=ID;
2084         if(ID == "USER") {
2085                 uid = fgGetString("/sim/user/callsign");
2086                 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
2087         }
2088         TowerPlaneRec* t = FindPlane(uid);
2089         if(t) {
2090                 t->longFinalReported = true;
2091                 t->longFinalAcknowledged = false;
2092                 if(!(t->clearedToLand)) {
2093                         responseReqd = true;
2094                 } // possibly respond with wind even if already cleared to land?
2095         } else {
2096                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportLongFinal(...)");
2097         }
2098 }
2099
2100 //void FGTower::ReportOuterMarker(string ID);
2101 //void FGTower::ReportMiddleMarker(string ID);
2102 //void FGTower::ReportInnerMarker(string ID);
2103
2104 void FGTower::ReportRunwayVacated(const string& ID) {
2105         //cout << "Report Runway Vacated Called at tower " << ident << " by plane " << ID << '\n';
2106         string uid=ID;
2107         if(ID == "USER") {
2108                 uid = fgGetString("/sim/user/callsign");
2109                 current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
2110         }
2111         TowerPlaneRec* t = FindPlane(uid);
2112         if(t) {
2113                 //cout << "Found it...\n";
2114                 t->rwyVacatedReported = true;
2115                 responseReqd = true;
2116         } else {
2117                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2118                 SG_LOG(SG_ATC, SG_ALERT, "A WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2119                 //cout << "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)\n";
2120         }
2121 }
2122
2123 TowerPlaneRec* FGTower::FindPlane(const string& ID) {
2124         //cout << "FindPlane called for " << ID << "...\n";
2125         tower_plane_rec_list_iterator twrItr;
2126         // Do the approach list first
2127         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
2128                 //cout << "appList callsign is " << (*twrItr)->plane.callsign << '\n';
2129                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2130         }       
2131         // Then the circuit list
2132         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
2133                 //cout << "circuitList callsign is " << (*twrItr)->plane.callsign << '\n';
2134                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2135         }
2136         // Then the runway list
2137         //cout << "rwyList.size() is " << rwyList.size() << '\n';
2138         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
2139                 //cout << "rwyList callsign is " << (*twrItr)->plane.callsign << '\n';
2140                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2141         }
2142         // The hold list
2143         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
2144                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2145         }
2146         // And finally the vacated list
2147         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
2148                 //cout << "vacatedList callsign is " << (*twrItr)->plane.callsign << '\n';
2149                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2150         }
2151         SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
2152         //exit(-1);
2153         return(NULL);
2154 }
2155
2156 void FGTower::RemovePlane(const string& ID) {
2157         //cout << ident << " RemovePlane called for " << ID << '\n';
2158         // We have to be careful here - we want to erase the plane from all lists it is in,
2159         // but we can only delete it once, AT THE END.
2160         TowerPlaneRec* t = NULL;
2161         tower_plane_rec_list_iterator twrItr;
2162         for(twrItr = appList.begin(); twrItr != appList.end();) {
2163                 if((*twrItr)->plane.callsign == ID) {
2164                         t = *twrItr;
2165                         twrItr = appList.erase(twrItr);
2166                         appListItr = appList.begin();
2167                         // HACK: aircraft are sometimes more than once in a list, so we need to
2168                         // remove them all before we can delete the TowerPlaneRec class
2169                         //break;
2170                 } else
2171                         ++twrItr;
2172         }
2173         for(twrItr = depList.begin(); twrItr != depList.end();) {
2174                 if((*twrItr)->plane.callsign == ID) {
2175                         t = *twrItr;
2176                         twrItr = depList.erase(twrItr);
2177                         depListItr = depList.begin();
2178                 } else
2179                         ++twrItr;
2180         }
2181         for(twrItr = circuitList.begin(); twrItr != circuitList.end();) {
2182                 if((*twrItr)->plane.callsign == ID) {
2183                         t = *twrItr;
2184                         twrItr = circuitList.erase(twrItr);
2185                         circuitListItr = circuitList.begin();
2186                 } else
2187                         ++twrItr;
2188         }
2189         for(twrItr = holdList.begin(); twrItr != holdList.end();) {
2190                 if((*twrItr)->plane.callsign == ID) {
2191                         t = *twrItr;
2192                         twrItr = holdList.erase(twrItr);
2193                         holdListItr = holdList.begin();
2194                 } else
2195                         ++twrItr;
2196         }
2197         for(twrItr = rwyList.begin(); twrItr != rwyList.end();) {
2198                 if((*twrItr)->plane.callsign == ID) {
2199                         t = *twrItr;
2200                         twrItr = rwyList.erase(twrItr);
2201                         rwyListItr = rwyList.begin();
2202                 } else
2203                         ++twrItr;
2204         }
2205         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end();) {
2206                 if((*twrItr)->plane.callsign == ID) {
2207                         t = *twrItr;
2208                         twrItr = vacatedList.erase(twrItr);
2209                         vacatedListItr = vacatedList.begin();
2210                 } else
2211                         ++twrItr;
2212         }
2213         for(twrItr = trafficList.begin(); twrItr != trafficList.end();) {
2214                 if((*twrItr)->plane.callsign == ID) {
2215                         t = *twrItr;
2216                         twrItr = trafficList.erase(twrItr);
2217                         trafficListItr = trafficList.begin();
2218                 } else
2219                         ++twrItr;
2220         }
2221         // And finally, delete the record.
2222         delete t;
2223 }
2224
2225 void FGTower::ReportDownwind(const string& ID) {
2226         //cout << "ReportDownwind(...) called\n";
2227         string uid=ID;
2228         if(ID == "USER") {
2229                 uid = fgGetString("/sim/user/callsign");
2230                 current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
2231         }
2232         TowerPlaneRec* t = FindPlane(uid);
2233         if(t) {
2234                 t->downwindReported = true;
2235                 responseReqd = true;
2236                 // If the plane is in the app list, remove it and put it in the circuit list instead.
2237                 // Ideally we might want to do this at the 2 mile report prior to 45 deg entry, but at
2238                 // the moment that would b&gg?r up the constraint position calculations.
2239                 RemoveFromAppList(ID);
2240                 t->leg = DOWNWIND;
2241                 if(t->isUser) {
2242                         t->pos.setlon(user_lon_node->getDoubleValue());
2243                         t->pos.setlat(user_lat_node->getDoubleValue());
2244                         t->pos.setelev(user_elev_node->getDoubleValue());
2245                 } else {
2246                         // ASSERT(t->planePtr != NULL);
2247                         t->pos = t->planePtr->GetPos();
2248                 }
2249                 CalcETA(t);
2250                 AddToCircuitList(t);
2251         } else {
2252                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2253         }
2254 }
2255
2256 void FGTower::ReportGoingAround(const string& ID) {
2257         string uid=ID;
2258         if(ID == "USER") {
2259                 uid = fgGetString("/sim/user/callsign");
2260                 RemoveAllUserDialogOptions();   // TODO - it would be much more efficient if ATCDialog simply had a clear() function!!!
2261                 current_atcdialog->add_entry(ident, "@AP Tower, @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
2262         }
2263         TowerPlaneRec* t = FindPlane(uid);
2264         if(t) {
2265                 //t->goAroundReported = true;  // No need to set this until we start responding to it.
2266                 responseReqd = false;   // might change in the future but for now we'll not distract them during the go-around.
2267                 // If the plane is in the app list, remove it and put it in the circuit list instead.
2268                 RemoveFromAppList(ID);
2269                 t->leg = CLIMBOUT;
2270                 if(t->isUser) {
2271                         t->pos.setlon(user_lon_node->getDoubleValue());
2272                         t->pos.setlat(user_lat_node->getDoubleValue());
2273                         t->pos.setelev(user_elev_node->getDoubleValue());
2274                 } else {
2275                         // ASSERT(t->planePtr != NULL);
2276                         t->pos = t->planePtr->GetPos();
2277                 }
2278                 CalcETA(t);
2279                 AddToCircuitList(t);
2280         } else {
2281                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2282         }
2283 }
2284
2285 string FGTower::GenText(const string& m, int c) {
2286         const int cmax = 300;
2287         //string message;
2288         char tag[4];
2289         char crej = '@';
2290         char mes[cmax];
2291         char dum[cmax];
2292         //char buf[10];
2293         char *pos;
2294         int len;
2295         //FGTransmission t;
2296         string usercall = fgGetString("/sim/user/callsign");
2297         
2298         //transmission_list_type     tmissions = transmissionlist_station[station];
2299         //transmission_list_iterator current   = tmissions.begin();
2300         //transmission_list_iterator last      = tmissions.end();
2301         
2302         //for ( ; current != last ; ++current ) {
2303         //      if ( current->get_code().c1 == code.c1 &&  
2304         //              current->get_code().c2 == code.c2 &&
2305         //          current->get_code().c3 == code.c3 ) {
2306                         
2307                         //if ( ttext ) message = current->get_transtext();
2308                         //else message = current->get_menutext();
2309                         strcpy( &mes[0], m.c_str() ); 
2310                         
2311                         // Replace all the '@' parameters with the actual text.
2312                         int check = 0;  // If mes gets overflowed the while loop can go infinite
2313                         while ( strchr(&mes[0], crej) != NULL  ) {      // ie. loop until no more occurances of crej ('@') found
2314                                 pos = strchr( &mes[0], crej );
2315                                 memmove(&tag[0], pos, 3);
2316                                 tag[3] = '\0';
2317                                 int i;
2318                                 len = 0;
2319                                 for ( i=0; i<cmax; i++ ) {
2320                                         if ( mes[i] == crej ) {
2321                                                 len = i; 
2322                                                 break;
2323                                         }
2324                                 }
2325                                 strncpy( &dum[0], &mes[0], len );
2326                                 dum[len] = '\0';
2327                                 
2328                                 if ( strcmp ( tag, "@ST" ) == 0 )
2329                                         //strcat( &dum[0], tpars.station.c_str() );
2330                                         strcat(&dum[0], ident.c_str());
2331                                 else if ( strcmp ( tag, "@AP" ) == 0 )
2332                                         //strcat( &dum[0], tpars.airport.c_str() );
2333                                         strcat(&dum[0], name.c_str());
2334                                 else if ( strcmp ( tag, "@CS" ) == 0 ) 
2335                                         //strcat( &dum[0], tpars.callsign.c_str() );
2336                                         strcat(&dum[0], usercall.c_str());
2337                                 else if ( strcmp ( tag, "@TD" ) == 0 ) {
2338                                         /*
2339                                         if ( tpars.tdir == 1 ) {
2340                                                 char buf[] = "left";
2341                                                 strcat( &dum[0], &buf[0] );
2342                                         }
2343                                         else {
2344                                                 char buf[] = "right";
2345                                                 strcat( &dum[0], &buf[0] );
2346                                         }
2347                                         */
2348                                 }
2349                                 else if ( strcmp ( tag, "@HE" ) == 0 ) {
2350                                         /*
2351                                         char buf[10];
2352                                         sprintf( buf, "%i", (int)(tpars.heading) );
2353                                         strcat( &dum[0], &buf[0] );
2354                                         */
2355                                 }
2356                                 else if ( strcmp ( tag, "@VD" ) == 0 ) {
2357                                         /*
2358                                         if ( tpars.VDir == 1 ) {
2359                                                 char buf[] = "Descend and maintain";
2360                                                 strcat( &dum[0], &buf[0] );
2361                                         }
2362                                         else if ( tpars.VDir == 2 ) {
2363                                                 char buf[] = "Maintain";
2364                                                 strcat( &dum[0], &buf[0] );
2365                                         }
2366                                         else if ( tpars.VDir == 3 ) {
2367                                                 char buf[] = "Climb and maintain";
2368                                                 strcat( &dum[0], &buf[0] );
2369                                         } 
2370                                         */
2371                                 }
2372                                 else if ( strcmp ( tag, "@AL" ) == 0 ) {
2373                                         /*
2374                                         char buf[10];
2375                                         sprintf( buf, "%i", (int)(tpars.alt) );
2376                                         strcat( &dum[0], &buf[0] );
2377                                         */
2378                                 }
2379                                 else if ( strcmp ( tag, "@MI" ) == 0 ) {
2380                                         char buf[10];
2381                                         //sprintf( buf, "%3.1f", tpars.miles );
2382                                         int dist_miles = (int)dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())) / 1600;
2383                                         sprintf(buf, "%i", dist_miles);
2384                                         strcat( &dum[0], &buf[0] );
2385                                 }
2386                                 else if ( strcmp ( tag, "@FR" ) == 0 ) {
2387                                         /*
2388                                         char buf[10];
2389                                         sprintf( buf, "%6.2f", tpars.freq );
2390                                         strcat( &dum[0], &buf[0] );
2391                                         */
2392                                 }
2393                                 else if ( strcmp ( tag, "@RW" ) == 0 ) {
2394                                         strcat(&dum[0], ConvertRwyNumToSpokenString(activeRwy).c_str());
2395                                 } else if(strcmp(tag, "@CD") == 0) {    // @CD = compass direction
2396                                         double h = GetHeadingFromTo(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
2397                                         while(h < 0.0) h += 360.0;
2398                                         while(h > 360.0) h -= 360.0;
2399                                         if(h < 22.5 || h > 337.5) {
2400                                                 strcat(&dum[0], "North");
2401                                         } else if(h < 67.5) {
2402                                                 strcat(&dum[0], "North-East");
2403                                         } else if(h < 112.5) {
2404                                                 strcat(&dum[0], "East");
2405                                         } else if(h < 157.5) {
2406                                                 strcat(&dum[0], "South-East");
2407                                         } else if(h < 202.5) {
2408                                                 strcat(&dum[0], "South");
2409                                         } else if(h < 247.5) {
2410                                                 strcat(&dum[0], "South-West");
2411                                         } else if(h < 292.5) {
2412                                                 strcat(&dum[0], "West");
2413                                         } else {
2414                                                 strcat(&dum[0], "North-West");
2415                                         }
2416                                 } else {
2417                                         cout << "Tag " << tag << " not found" << endl;
2418                                         break;
2419                                 }
2420                                 strcat( &dum[0], &mes[len+3] );
2421                                 strcpy( &mes[0], &dum[0] );
2422                                 
2423                                 ++check;
2424                                 if(check > 10) {
2425                                         SG_LOG(SG_ATC, SG_WARN, "WARNING: Possibly endless loop terminated in FGTransmissionlist::gen_text(...)"); 
2426                                         break;
2427                                 }
2428                         }
2429                         
2430                         //cout << mes  << endl;  
2431                         //break;
2432                 //}
2433         //}
2434         if ( mes != "" ) return mes;
2435         else return "No transmission found";
2436 }
2437
2438 ostream& operator << (ostream& os, tower_traffic_type ttt) {
2439         switch(ttt) {
2440         case(CIRCUIT):      return(os << "CIRCUIT");
2441         case(INBOUND):      return(os << "INBOUND");
2442         case(OUTBOUND):     return(os << "OUTBOUND");
2443         case(TTT_UNKNOWN):  return(os << "UNKNOWN");
2444         case(STRAIGHT_IN):  return(os << "STRAIGHT_IN");
2445         }
2446         return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");
2447 }
2448