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