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