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