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