]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
Refactoring - no actual change
[flightgear.git] / src / ATC / tower.cxx
1 // FGTower - a class to provide tower control at towered airports.
2 //
3 // Written by David Luff, started March 2002.
4 //
5 // Copyright (C) 2002  David C. Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #include <Main/globals.hxx>
22 #include <Airports/runways.hxx>
23 #include <simgear/math/sg_geodesy.hxx>
24 #include <simgear/debug/logstream.hxx>
25
26 #include "tower.hxx"
27 #include "ATCdisplay.hxx"
28 #include "ATCmgr.hxx"
29 #include "ATCutils.hxx"
30 #include "commlist.hxx"
31 #include "AILocalTraffic.hxx"
32
33 SG_USING_STD(cout);
34
35 // TowerPlaneRec
36
37 TowerPlaneRec::TowerPlaneRec() :
38 clearedToLand(false),
39 clearedToLineUp(false),
40 clearedToTakeOff(false),
41 holdShortReported(false),
42 longFinalReported(false),
43 longFinalAcknowledged(false),
44 finalReported(false),
45 finalAcknowledged(false),
46 onRwy(false),
47 nextOnRwy(false),
48 opType(TTT_UNKNOWN),
49 leg(LEG_UNKNOWN),
50 landingType(AIP_LT_UNKNOWN),
51 isUser(false)
52 {
53         plane.callsign = "UNKNOWN";
54 }
55
56 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
57 clearedToLand(false),
58 clearedToLineUp(false),
59 clearedToTakeOff(false),
60 holdShortReported(false),
61 longFinalReported(false),
62 longFinalAcknowledged(false),
63 finalReported(false),
64 finalAcknowledged(false),
65 onRwy(false),
66 nextOnRwy(false),
67 opType(TTT_UNKNOWN),
68 leg(LEG_UNKNOWN),
69 landingType(AIP_LT_UNKNOWN),
70 isUser(false)
71 {
72         plane = p;
73 }
74
75 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
76 clearedToLand(false),
77 clearedToLineUp(false),
78 clearedToTakeOff(false),
79 holdShortReported(false),
80 longFinalReported(false),
81 longFinalAcknowledged(false),
82 finalReported(false),
83 finalAcknowledged(false),
84 onRwy(false),
85 nextOnRwy(false),
86 opType(TTT_UNKNOWN),
87 leg(LEG_UNKNOWN),
88 landingType(AIP_LT_UNKNOWN),
89 isUser(false)
90 {
91         plane.callsign = "UNKNOWN";
92         pos = pt;
93 }
94
95 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
96 clearedToLand(false),
97 clearedToLineUp(false),
98 clearedToTakeOff(false),
99 holdShortReported(false),
100 longFinalReported(false),
101 longFinalAcknowledged(false),
102 finalReported(false),
103 finalAcknowledged(false),
104 onRwy(false),
105 nextOnRwy(false),
106 opType(TTT_UNKNOWN),
107 leg(LEG_UNKNOWN),
108 landingType(AIP_LT_UNKNOWN),
109 isUser(false)
110 {
111         plane = p;
112         pos = pt;
113 }
114
115
116 // FGTower
117
118 FGTower::FGTower() {
119         ATCmgr = globals->get_ATC_mgr();
120         
121         // Init the property nodes - TODO - need to make sure we're getting surface winds.
122         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
123         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
124         
125         update_count = 0;
126         update_count_max = 15;
127         
128         holdListItr = holdList.begin();
129         appListItr = appList.begin();
130         depListItr = depList.begin();
131         rwyListItr = rwyList.begin();
132         circuitListItr = circuitList.begin();
133         trafficListItr = trafficList.begin();
134         
135         freqClear = true;
136         
137         timeSinceLastDeparture = 9999;
138         departed = false;
139 }
140
141 FGTower::~FGTower() {
142         if(!separateGround) {
143                 delete ground;
144         }
145 }
146
147 void FGTower::Init() {
148     display = false;
149         
150         // Pointers to user's position
151         user_lon_node = fgGetNode("/position/longitude-deg", true);
152         user_lat_node = fgGetNode("/position/latitude-deg", true);
153         user_elev_node = fgGetNode("/position/altitude-ft", true);
154         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
155         
156         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
157         // I'll punt the startup issue for now though!!!
158         rwyOccupied = false;
159         
160         // Setup the ground control at this airport
161         AirportATC a;
162         //cout << "Tower ident = " << ident << '\n';
163         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
164                 if(a.ground_freq) {             // Ground control
165                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
166                         separateGround = true;
167                         if(ground == NULL) {
168                                 // Something has gone wrong :-(
169                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
170                                 ground = new FGGround(ident);
171                                 separateGround = false;
172                                 ground->Init();
173                                 if(display) {
174                                         ground->SetDisplay();
175                                 } else {
176                                         ground->SetNoDisplay();
177                                 }
178                         }
179                 } else {
180                         // Initialise ground anyway to do the shortest path stuff!
181                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
182                         ground = new FGGround(ident);
183                         separateGround = false;
184                         ground->Init();
185                         if(display) {
186                                 ground->SetDisplay();
187                         } else {
188                                 ground->SetNoDisplay();
189                         }
190                 }
191         } else {
192                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
193                 // Initialise ground anyway to avoid segfault later
194                 ground = new FGGround(ident);
195                 separateGround = false;
196                 ground->Init();
197                 if(display) {
198                         ground->SetDisplay();
199                 } else {
200                         ground->SetNoDisplay();
201                 }
202         }
203         
204         // Get the airport elevation
205         aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
206         
207         DoRwyDetails();
208         
209         // FIXME - this currently assumes use of the active rwy by the user.
210         rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
211         if(rwyOccupied) {
212                 // Assume the user is started at the threshold ready to take-off
213                 TowerPlaneRec* t = new TowerPlaneRec;
214                 t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
215                 t->plane.type = GA_SINGLE;
216                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
217                 t->landingType = AIP_LT_UNKNOWN;
218                 t->leg = TAKEOFF_ROLL;
219                 t->isUser = true;
220                 t->planePtr = NULL;
221                 t->clearedToTakeOff = true;
222                 rwyList.push_back(t);
223                 departed = false;
224         }
225 }
226
227 void FGTower::Update(double dt) {
228         //cout << "T" << flush;
229         // Each time step, what do we need to do?
230         // We need to go through the list of outstanding requests and acknowedgements
231         // and process at least one of them.
232         // We need to go through the list of planes under our control and check if
233         // any need to be addressed.
234         // We need to check for planes not under our control coming within our 
235         // control area and address if necessary.
236         
237         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
238         
239         // Sort the arriving planes
240         
241         /*
242         if(ident == "KEMT") {
243                 cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
244         }
245         */
246         
247         if(departed != false) {
248                 timeSinceLastDeparture += dt;
249                 //if(ident == "KEMT") 
250                 //      cout << "  dt = " << dt << "  timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
251         }
252         
253         // Calculate the eta of each plane to the threshold.
254         // For ground traffic this is the fastest they can get there.
255         // For air traffic this is the middle approximation.
256         if(update_count == 1) {
257                 doThresholdETACalc();
258         }
259         
260         // Order the list of traffic as per expected threshold use and flag any conflicts
261         if(update_count == 2) {
262                 //bool conflicts = doThresholdUseOrder();
263                 doThresholdUseOrder();
264         }
265         
266         // sortConficts() !!!
267         
268         if(update_count == 4) {
269                 CheckHoldList(dt);
270         }
271         
272         // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
273         if(rwyList.size()) {
274                 rwyOccupied = true;
275         } else {
276                 rwyOccupied = false;
277         }
278         
279         if(update_count == 5 && rwyOccupied) {
280                 CheckRunwayList(dt);
281         }
282                 
283         if(update_count == 6) {
284                 CheckCircuitList(dt);
285         }
286         
287         if(update_count == 7) {
288                 CheckApproachList(dt);
289         }
290         
291         // TODO - do one plane from the departure list and set departed = false when out of consideration
292         
293         //doCommunication();
294         
295         if(!separateGround) {
296                 // The display stuff might have to get more clever than this when not separate 
297                 // since the tower and ground might try communicating simultaneously even though
298                 // they're mean't to be the same contoller/frequency!!
299                 if(display) {
300                         ground->SetDisplay();
301                 } else {
302                         ground->SetNoDisplay();
303                 }
304                 ground->Update(dt);
305         }
306         
307         ++update_count;
308         // How big should ii get - ie how long should the update cycle interval stretch?
309         if(update_count >= update_count_max) {
310                 update_count = 0;
311         }
312         
313         // Call the base class update for the response time handling.
314         FGATC::Update(dt);
315
316         if(ident == "KEMT") {   
317                 // For AI debugging convienience - may be removed
318                 Point3D user_pos;
319                 user_pos.setlon(user_lon_node->getDoubleValue());
320                 user_pos.setlat(user_lat_node->getDoubleValue());
321                 user_pos.setelev(user_elev_node->getDoubleValue());
322                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
323                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
324                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
325                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
326         }
327 }
328
329 // Do one plane from the hold list
330 void FGTower::CheckHoldList(double dt) {
331         //cout << "ug\n";
332         if(holdList.size()) {
333                 //cout << "*holdListItr = " << *holdListItr << endl;
334                 if(holdListItr == holdList.end()) {
335                         holdListItr = holdList.begin();
336                 }
337                 //cout << "*holdListItr = " << *holdListItr << endl;
338                 //Process(*holdListItr);
339                 TowerPlaneRec* t = *holdListItr;
340                 //cout << "t = " << t << endl;
341                 if(t->holdShortReported) {
342                         //cout << "ding\n";
343                         double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
344                         if(t->clearanceCounter > responseTime) {
345                                 if(t->nextOnRwy) {
346                                         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!!)
347                                                 // Do nothing for now - consider acknowloging hold short eventually
348                                         } else {
349                                                 // Lets Roll !!!!
350                                                 string trns = t->plane.callsign;
351                                                 //if(departed plane < some threshold in time away) {
352                                                 if(0) {         // FIXME
353                                                         trns += " line up";
354                                                         t->clearedToLineUp = true;
355                                                         t->planePtr->RegisterTransmission(3);   // cleared to line-up
356                                                         t->leg = TAKEOFF_ROLL;
357                                                 //} else if(arriving plane < some threshold away) {
358                                                 } else if(GetTrafficETA(2) < 150.0) {
359                                                         trns += " cleared immediate take-off";
360                                                         if(trafficList.size()) {
361                                                                 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
362                                                                 trfcItr++;      // At the moment the holding plane should be first in trafficList.
363                                                                 // Note though that this will break if holding planes aren't put in trafficList in the future.
364                                                                 TowerPlaneRec* trfc = *trfcItr;
365                                                                 trns += "... traffic is";
366                                                                 switch(trfc->plane.type) {
367                                                                 case UNKNOWN:
368                                                                         break;
369                                                                 case GA_SINGLE:
370                                                                         trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
371                                                                         break;
372                                                                 case GA_HP_SINGLE:
373                                                                         trns += " a Piper";
374                                                                         break;
375                                                                 case GA_TWIN:
376                                                                         trns += " a King-air";
377                                                                         break;
378                                                                 case GA_JET:
379                                                                         trns += " a Learjet";
380                                                                         break;
381                                                                 case MEDIUM:
382                                                                         trns += " a Regional";
383                                                                         break;
384                                                                 case HEAVY:
385                                                                         trns += " a Heavy";
386                                                                         break;
387                                                                 case MIL_JET:
388                                                                         trns += " Military";
389                                                                         break;
390                                                                 }
391                                                                 if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
392                                                                         double miles_out = CalcDistOutMiles(trfc);
393                                                                         if(miles_out < 2) {
394                                                                                 trns += " on final";
395                                                                         } else {
396                                                                                 trns += " on ";
397                                                                                 trns += ConvertNumToSpokenDigits((int)miles_out);
398                                                                                 trns += " mile final";
399                                                                         }
400                                                                 } else if(trfc->opType == CIRCUIT) {
401                                                                         switch(trfc->leg) {
402                                                                         case FINAL:
403                                                                                 trns += " on final";
404                                                                                 break;
405                                                                         case TURN4:
406                                                                                 trns += " turning final";
407                                                                                 break;
408                                                                         case BASE:
409                                                                                 trns += " on base";
410                                                                                 break;
411                                                                         case TURN3:
412                                                                                 trns += " turning base";
413                                                                                 break;
414                                                                         case DOWNWIND:
415                                                                                 trns += " in circuit";
416                                                                                 break;
417                                                                         // And to eliminate compiler warnings...
418                                                                         case TAKEOFF_ROLL: break;
419                                                                         case CLIMBOUT:     break;
420                                                                         case TURN1:        break;
421                                                                         case CROSSWIND:    break;
422                                                                         case TURN2:        break;
423                                                                         case LANDING_ROLL: break;
424                                                                         case LEG_UNKNOWN:  break;
425                                                                         }
426                                                                 }
427                                                         } else {
428                                                                 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
429                                                                 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
430                                                         }
431                                                         t->clearedToTakeOff = true;
432                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
433                                                         t->leg = TAKEOFF_ROLL;
434                                                         departed = false;
435                                                         timeSinceLastDeparture = 0.0;
436                                                 } else {
437                                                         trns += " cleared for take-off";
438                                                         // TODO - add traffic is... ?
439                                                         t->clearedToTakeOff = true;
440                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off
441                                                         t->leg = TAKEOFF_ROLL;
442                                                         departed = false;
443                                                         timeSinceLastDeparture = 0.0;
444                                                 }
445                                                 if(display) {
446                                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
447                                                 }
448                                                 t->holdShortReported = false;
449                                                 t->clearanceCounter = 0;
450                                                 rwyList.push_back(t);
451                                                 rwyOccupied = true;
452                                                 holdList.erase(holdListItr);
453                                                 holdListItr = holdList.begin();
454                                         }
455                                 } else {
456                                         // Tell him to hold and what position he is.
457                                         // Not currently sure under which circumstances we do or don't bother transmitting this.
458                                         string trns = t->plane.callsign;
459                                         trns += " hold position";
460                                         if(display) {
461                                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
462                                         }
463                                         t->holdShortReported = false;
464                                         t->clearanceCounter = 0;
465                                         // TODO - add some idea of what traffic is blocking him.
466                                 }
467                         } else {
468                                 t->clearanceCounter += (dt * holdList.size() * update_count_max);
469                         }
470                 } else {        // not responding to report, but still need to clear if clear
471                         //cout << "dong\n";
472                         if(t->nextOnRwy) {
473                                 //cout << "departed = " << departed << '\n';
474                                 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
475                                 if(rwyOccupied) {
476                                         // Do nothing for now - consider acknowloging hold short eventually
477                                 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
478                                         // Do nothing - this is a bit of a hack - should maybe do line up be ready here
479                                 } else {
480                                         // Lets Roll !!!!
481                                         string trns = t->plane.callsign;
482                                         //cout << "******************* squaggle\n";
483                                         //cout << "departed = " << departed << '\n';
484                                         //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
485                                         //if(departed plane < some threshold in time away) {
486                                                 if(0) {         // FIXME
487                                                         //cout << "A\n";
488                                                         trns += " line up";
489                                                         t->clearedToLineUp = true;
490                                                         t->planePtr->RegisterTransmission(3);   // cleared to line-up
491                                                         t->leg = TAKEOFF_ROLL;
492                                         //} else if(arriving plane < some threshold away) {
493                                                 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) {   // Hack - hardwired time
494                                                         //cout << "B\n";
495                                                         trns += " cleared immediate take-off";
496                                                         // TODO - add traffic is... ?
497                                                         t->clearedToTakeOff = true;
498                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
499                                                         t->leg = TAKEOFF_ROLL;
500                                                         departed = false;
501                                                         timeSinceLastDeparture = 0.0;
502                                                 } else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
503                                                         //cout << "C\n";
504                                                         trns += " cleared for take-off";
505                                                         // TODO - add traffic is... ?
506                                                         t->clearedToTakeOff = true;
507                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off
508                                                         t->leg = TAKEOFF_ROLL;
509                                                         departed = false;
510                                                         timeSinceLastDeparture = 0.0;
511                                                 } else {
512                                                         //cout << "D\n";
513                                                 }
514                                                 if(display) {
515                                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
516                                                 }
517                                                 rwyList.push_back(t);
518                                                 rwyOccupied = true;
519                                                 holdList.erase(holdListItr);
520                                                 holdListItr = holdList.begin();
521                                 }
522                         }
523                         // TODO - rationalise the considerable code duplication above!
524                 }
525                 ++holdListItr;
526         }
527 }
528
529 // do the ciruit list
530 void FGTower::CheckCircuitList(double dt) {
531         // Clear the constraints - we recalculate here.
532         base_leg_pos = 0.0;
533         downwind_leg_pos = 0.0;
534         crosswind_leg_pos = 0.0;
535         
536         if(circuitList.size()) {        // Do one plane from the circuit
537                 if(circuitListItr == circuitList.end()) {
538                         circuitListItr = circuitList.begin();
539                 }
540                 TowerPlaneRec* t = *circuitListItr;
541                 if(t->isUser) {
542                         t->pos.setlon(user_lon_node->getDoubleValue());
543                         t->pos.setlat(user_lat_node->getDoubleValue());
544                         t->pos.setelev(user_elev_node->getDoubleValue());
545                 } else {
546                         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.
547                         t->landingType = t->planePtr->GetLandingOption();
548                         //cout << "AI plane landing option is " << t->landingType << '\n';
549                 }
550                 Point3D tortho = ortho.ConvertToLocal(t->pos);
551                 if(t->isUser) {
552                         // Need to figure out which leg he's on
553                         //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
554                         double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
555                         //cout << " ho = " << ho << '\n';
556                         // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
557                         // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
558                         if(abs(ho) < 30) {
559                                 // could be either takeoff, climbout or landing - check orthopos.y
560                                 //cout << "tortho.y = " << tortho.y() << '\n';
561                                 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
562                                         t->leg = FINAL;
563                                         //cout << "Final\n";
564                                 } else {
565                                         t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
566                                         //cout << "Climbout\n";
567                                         // If it's the user we may be unsure of his/her intentions.
568                                         // (Hopefully the AI planes won't try confusing the sim!!!)
569                                         if(t->opType == TTT_UNKNOWN) {
570                                                 if(tortho.y() > 5000) {
571                                                         // 5 km out from threshold - assume it's a departure
572                                                         t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
573                                                         // Since we are unknown operation we should be in depList already.
574                                                         circuitList.erase(circuitListItr);
575                                                         RemoveFromTrafficList(t->plane.callsign);
576                                                         circuitListItr = circuitList.begin();
577                                                 }
578                                         } else if(t->opType == CIRCUIT) {
579                                                 if(tortho.y() > 10000) {
580                                                         // 10 km out - assume the user has abandoned the circuit!!
581                                                         t->opType = OUTBOUND;
582                                                         depList.push_back(t);
583                                                         circuitList.erase(circuitListItr);
584                                                         circuitListItr = circuitList.begin();
585                                                 }
586                                         }
587                                 }
588                         } else if(abs(ho) < 60) {
589                                 // turn1 or turn 4
590                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
591                                 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
592                                         t->leg = TURN1;
593                                         //cout << "Turn1\n";
594                                 } else {
595                                         t->leg = TURN4;
596                                         //cout << "Turn4\n";
597                                 }
598                         } else if(abs(ho) < 120) {
599                                 // crosswind or base
600                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
601                                 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
602                                         t->leg = CROSSWIND;
603                                         //cout << "Crosswind\n";
604                                 } else {
605                                         t->leg = BASE;
606                                         //cout << "Base\n";
607                                 }
608                         } else if(abs(ho) < 150) {
609                                 // turn2 or turn 3
610                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
611                                 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
612                                         t->leg = TURN2;
613                                         //cout << "Turn2\n";
614                                 } else {
615                                         t->leg = TURN3;
616                                         // Probably safe now to assume the user is flying a circuit
617                                         t->opType = CIRCUIT;
618                                         //cout << "Turn3\n";
619                                 }
620                         } else {
621                                 // downwind
622                                 t->leg = DOWNWIND;
623                                 //cout << "Downwind\n";
624                         }
625                         if(t->leg == FINAL) {
626                                 if(OnActiveRunway(t->pos)) {
627                                         t->leg = LANDING_ROLL;
628                                 }
629                         }
630                 } else {
631                         t->leg = t->planePtr->GetLeg();
632                 }
633                 
634                 // Set the constraints IF this is the first plane in the circuit
635                 // 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!!
636                 if(circuitListItr == circuitList.begin()) {
637                         switch(t->leg) {
638                         case FINAL:
639                                 // 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.
640                                 base_leg_pos = tortho.y();
641                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
642                                 break;
643                         case TURN4:
644                                 // Fall through to base
645                         case BASE:
646                                 base_leg_pos = tortho.y();
647                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
648                                 break;
649                         case TURN3:
650                                 // Fall through to downwind
651                         case DOWNWIND:
652                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
653                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
654                                 //cout << "base_leg_pos = " << base_leg_pos;
655                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
656                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
657                                 break;
658                         case TURN2:
659                                 // Fall through to crosswind
660                         case CROSSWIND:
661                                 crosswind_leg_pos = tortho.y();
662                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
663                                 break;
664                         case TURN1:
665                                 // Fall through to climbout
666                         case CLIMBOUT:
667                                 // Only use current by constraint as largest
668                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
669                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
670                                 break;
671                         case TAKEOFF_ROLL:
672                                 break;
673                         case LEG_UNKNOWN:
674                                 break;
675                         case LANDING_ROLL:
676                                 break;
677                         default:
678                                 break;
679                         }
680                 }
681                 
682                 if(t->leg == FINAL) {
683                         if(t->landingType == FULL_STOP) t->opType = INBOUND;
684                 } else if(t->leg == LANDING_ROLL) {
685                         rwyList.push_front(t);
686                         RemoveFromTrafficList(t->plane.callsign);
687                         if(t->isUser) {
688                                 t->opType = TTT_UNKNOWN;
689                         }       // TODO - allow the user to specify opType via ATC menu
690                         circuitListItr = circuitList.erase(circuitListItr);
691                         if(circuitListItr == circuitList.end() ) {
692                                 circuitListItr = circuitList.begin();
693                         }
694                 }
695                 ++circuitListItr;
696         }
697 }
698
699 // 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!!
700 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
701 // (However, at the moment there should only be one airplane on the rwy at once, until we
702 // start allowing planes to line up whilst previous arrival clears the rwy.)
703 void FGTower::CheckRunwayList(double dt) {
704         if(rwyOccupied) {
705                 if(!rwyList.size()) {
706                         rwyOccupied = false;
707                 } else {
708                         rwyListItr = rwyList.begin();
709                         TowerPlaneRec* t = *rwyListItr;
710                         if(t->isUser) {
711                                 t->pos.setlon(user_lon_node->getDoubleValue());
712                                 t->pos.setlat(user_lat_node->getDoubleValue());
713                                 t->pos.setelev(user_elev_node->getDoubleValue());
714                         } else {
715                                 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.
716                         }
717                         bool on_rwy = OnActiveRunway(t->pos);
718                         if(!on_rwy) {
719                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
720                                         rwyList.pop_front();
721                                         delete t;
722                                         // TODO - tell it to taxi / contact ground / don't delete it etc!
723                                 } else if(t->opType == OUTBOUND) {
724                                         depList.push_back(t);
725                                         rwyList.pop_front();
726                                         departed = true;
727                                         timeSinceLastDeparture = 0.0;
728                                 } else if(t->opType == CIRCUIT) {
729                                         circuitList.push_back(t);
730                                         AddToTrafficList(t);
731                                         rwyList.pop_front();
732                                         departed = true;
733                                         timeSinceLastDeparture = 0.0;
734                                 } else if(t->opType == TTT_UNKNOWN) {
735                                         depList.push_back(t);
736                                         circuitList.push_back(t);
737                                         AddToTrafficList(t);
738                                         rwyList.pop_front();
739                                         departed = true;
740                                         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.
741                                 } else {
742                                         // HELP - we shouldn't ever get here!!!
743                                 }
744                         }
745                 }
746         }
747 }
748
749 // Do one plane from the approach list
750 void FGTower::CheckApproachList(double dt) {
751         if(appList.size()) {
752                 if(appListItr == appList.end()) {
753                         appListItr = appList.begin();
754                 }
755                 TowerPlaneRec* t = *appListItr;
756                 //cout << "t = " << t << endl;
757                 if(t->isUser) {
758                         t->pos.setlon(user_lon_node->getDoubleValue());
759                         t->pos.setlat(user_lat_node->getDoubleValue());
760                         t->pos.setelev(user_elev_node->getDoubleValue());
761                 } else {
762                         // TODO - set/update the position if it's an AI plane
763                 }                               
764                 if(t->nextOnRwy && !(t->clearedToLand)) {
765                         // check distance away and whether runway occupied
766                         // and schedule transmission if necessary
767                 }                               
768                 ++appListItr;
769         }
770 }
771
772 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
773 // plus the constraint position as a rwy orientated orthopos (meters)
774 bool FGTower::GetCrosswindConstraint(double& cpos) {
775         if(crosswind_leg_pos != 0.0) {
776                 cpos = crosswind_leg_pos;
777                 return(true);
778         } else {
779                 cpos = 0.0;
780                 return(false);
781         }
782 }
783 bool FGTower::GetDownwindConstraint(double& dpos) {
784         if(downwind_leg_pos != 0.0) {
785                 dpos = downwind_leg_pos;
786                 return(true);
787         } else {
788                 dpos = 0.0;
789                 return(false);
790         }
791 }
792 bool FGTower::GetBaseConstraint(double& bpos) {
793         if(base_leg_pos != 0.0) {
794                 bpos = base_leg_pos;
795                 return(true);
796         } else {
797                 bpos = 0.0;
798                 return(false);
799         }
800 }
801
802
803 // Figure out which runways are active.
804 // For now we'll just be simple and do one active runway - eventually this will get much more complex
805 // This is a private function - public interface to the results of this is through GetActiveRunway
806 void FGTower::DoRwyDetails() {
807         //cout << "GetRwyDetails called" << endl;
808         
809         // Based on the airport-id and wind get the active runway
810         
811         //wind
812         double hdg = wind_from_hdg->getDoubleValue();
813         double speed = wind_speed_knots->getDoubleValue();
814         hdg = (speed == 0.0 ? 270.0 : hdg);
815         //cout << "Heading = " << hdg << '\n';
816         
817         FGRunway runway;
818         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
819         if(rwyGood) {
820                 activeRwy = runway.rwy_no;
821                 rwy.rwyID = runway.rwy_no;
822                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
823                 
824                 // Get the threshold position
825                 double other_way = runway.heading - 180.0;
826                 while(other_way <= 0.0) {
827                         other_way += 360.0;
828                 }
829         // move to the +l end/center of the runway
830                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
831         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
832                 Point3D ref = origin;
833         double tshlon, tshlat, tshr;
834                 double tolon, tolat, tor;
835                 rwy.length = runway.length * SG_FEET_TO_METER;
836                 rwy.width = runway.width * SG_FEET_TO_METER;
837         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
838                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
839         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
840                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
841                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
842                 // now copy what we need out of runway into rwy
843         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
844                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
845                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
846                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
847                 rwy.hdg = runway.heading;
848                 // Set the projection for the local area based on this active runway
849                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
850                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
851                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
852         } else {
853                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
854                 activeRwy = "NN";
855         }
856 }
857
858
859 // Figure out if a given position lies on the active runway
860 // Might have to change when we consider more than one active rwy.
861 bool FGTower::OnActiveRunway(Point3D pt) {
862         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
863         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
864         Point3D xyp = ortho.ConvertToLocal(pt);
865         
866         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
867         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
868
869         double rlen = rwy.length/2.0 + 5.0;
870         double rwidth = rwy.width/2.0;
871         double ldiff = fabs(xyp.y() - xyc.y());
872         double wdiff = fabs(xyp.x() - xyc.x());
873
874         return((ldiff < rlen) && (wdiff < rwidth));
875 }       
876
877
878 // Figure out if a given position lies on any runway or not
879 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
880 bool FGTower::OnAnyRunway(Point3D pt) {
881         ATCData ad;
882         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
883         if(dist < 0.0) {
884                 return(false);
885         }
886         // Based on the airport-id, go through all the runways and check for a point in them
887         
888         // TODO - do we actually need to search for the airport - surely we already know our ident and
889         // can just search runways of our airport???
890         //cout << "Airport ident is " << ad.ident << '\n';
891         FGRunway runway;
892         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
893         if(!rwyGood) {
894                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
895         }
896         bool on = false;
897         while(runway.id == ad.ident) {          
898                 on = OnRunway(pt, runway);
899                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
900                 if(on) return(true);
901                 globals->get_runways()->next(&runway);          
902         }
903         return(on);
904 }
905
906
907 // Returns true if successful
908 bool FGTower::RemoveFromTrafficList(string id) {
909         tower_plane_rec_list_iterator twrItr;
910         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
911                 TowerPlaneRec* tpr = *twrItr;
912                 if(tpr->plane.callsign == id) {
913                         trafficList.erase(twrItr);
914                         return(true);
915                 }
916         }       
917         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
918         return(false);
919 }
920
921
922 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
923 // and set nextOnRwy if so.
924 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
925 // For planes holding they are put in the first position with time to go, and the return value is
926 // true if in the first position (nextOnRwy) and false otherwise.
927 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
928 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
929         //cout << "ADD: " << trafficList.size();
930         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << '\n';
931         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.
932         double departure_sep_time = 60.0;       // Separation time behind departing airplanes.  Comments above also apply.
933         bool conflict = false;
934         double lastETA = 0.0;
935         bool firstTime = true;
936         // FIXME - make this more robust for different plane types eg. light following heavy.
937         tower_plane_rec_list_iterator twrItr;
938         //twrItr = trafficList.begin();
939         //while(1) {
940         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
941                 //if(twrItr == trafficList.end()) {
942                 //      cout << "  END  ";
943                 //      trafficList.push_back(t);
944                 //      return(holding ? firstTime : conflict);
945                 //} else {
946                         TowerPlaneRec* tpr = *twrItr;
947                         if(holding) {
948                                 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
949                                 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
950                                 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0); 
951                                 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
952                                 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
953                                 // and if not needs time to clear the rwy anyway.
954                                 if(tpr->eta  - lastETA > slot_time) {
955                                         t->nextOnRwy = firstTime;
956                                         trafficList.insert(twrItr, t);
957                                         //cout << "\tH\t" << trafficList.size() << '\n';
958                                         return(firstTime);
959                                 }
960                                 firstTime = false;
961                         } else {
962                                 if(t->eta < tpr->eta) {
963                                         // Ugg - this one's tricky.
964                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
965                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
966                                                 if(tpr->nextOnRwy) {
967                                                         tpr->nextOnRwy = false;
968                                                         t->nextOnRwy = true;
969                                                 }
970                                                 trafficList.insert(twrItr, t);
971                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
972                                                 conflict = true;
973                                                 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
974                                                 if(tpr->nextOnRwy) {
975                                                         tpr->nextOnRwy = false;
976                                                         t->nextOnRwy = true;
977                                                 }
978                                                 trafficList.insert(twrItr, t);
979                                         }
980                                         //cout << "\tC\t" << trafficList.size() << '\n';
981                                         return(conflict);
982                                 }
983                         }
984                 //}
985                 //++twrItr;
986         }
987         // If we get here we must be at the end of the list, or maybe the list is empty.
988         if(!trafficList.size()) {
989                 t->nextOnRwy = true;
990                 // conflict and firstTime should be false and true respectively in this case anyway.
991         }
992         trafficList.push_back(t);
993         //cout << "\tE\t" << trafficList.size() << '\n';
994         return(holding ? firstTime : conflict);
995 }
996
997
998 // Calculate the eta of a plane to the threshold.
999 // For ground traffic this is the fastest they can get there.
1000 // For air traffic this is the middle approximation.
1001 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1002         // For now we'll be very crude and hardwire expected speeds to C172-like values
1003         // The speeds below are specified in knots IAS and then converted to m/s
1004         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
1005         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
1006         double final_ias = 70.0 * 0.514444;             // Speed during final approach
1007         
1008         //if(printout) {
1009         //      cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1010         //      cout << (tpr->isUser ? "USER\n" : "AI\n");
1011         //}
1012         
1013         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1014         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1015         
1016         Point3D op = ortho.ConvertToLocal(tpr->pos);
1017         //if(printout) {
1018         //      cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1019         //      cout << "opType is " << tpr->opType << '\n';
1020         //}
1021         double dist_out_m = op.y();
1022         double dist_across_m = fabs(op.x());    // FIXME = the fabs is a hack to cope with the fact that we don't know the circuit direction yet
1023         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1024         
1025         if(tpr->opType == STRAIGHT_IN) {
1026                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1027                 if(dist_to_go_m < 1000) {
1028                         tpr->eta = dist_to_go_m / final_ias;
1029                 } else {
1030                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1031                 }
1032         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1033                 // It's complicated - depends on if base leg is delayed or not
1034                 //if(printout) {
1035                 //      cout << "Leg = " << tpr->leg << '\n';
1036                 //}
1037                 if(tpr->leg == LANDING_ROLL) {
1038                         tpr->eta = 0;
1039                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1040                         tpr->eta = fabs(dist_out_m) / final_ias;
1041                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1042                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1043                 } else {
1044                         // Need to calculate where base leg is likely to be
1045                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1046                         // 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
1047                         double nominal_base_dist_out_m = -1000;
1048                         double current_base_dist_out_m;
1049                         if(!GetBaseConstraint(current_base_dist_out_m)) {
1050                                 current_base_dist_out_m = nominal_base_dist_out_m;
1051                         }
1052                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
1053                         double current_dist_across_m;
1054                         if(!GetDownwindConstraint(current_dist_across_m)) {
1055                                 current_dist_across_m = nominal_dist_across_m;
1056                         }
1057                         double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1058                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
1059                         //if(printout) cout << "a = " << tpr->eta << '\n';
1060                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1061                                 tpr->eta += dist_across_m / circuit_ias;
1062                                 //if(printout) cout << "b = " << tpr->eta << '\n';
1063                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1064                                 //if(printout) cout << "c = " << tpr->eta << '\n';
1065                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1066                                 if(dist_across_m > nominal_dist_across_m) {
1067                                         tpr->eta += dist_across_m / circuit_ias;
1068                                 } else {
1069                                         tpr->eta += nominal_dist_across_m / circuit_ias;
1070                                 }
1071                                 // should we use the dist across of the previous plane if there is previous still on downwind?
1072                                 //if(printout) cout << "bb = " << tpr->eta << '\n';
1073                                 if(dist_out_m > nominal_cross_dist_out_m) {
1074                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1075                                 } else {
1076                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1077                                 }
1078                                 //if(printout) cout << "cc = " << tpr->eta << '\n';
1079                                 if(nominal_dist_across_m > dist_across_m) {
1080                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1081                                 } else {
1082                                         // Nothing to add
1083                                 }
1084                                 //if(printout) cout << "dd = " << tpr->eta << '\n';
1085                         } else {
1086                                 // We've only just started - why not use a generic estimate?
1087                                 tpr->eta = 240.0;
1088                         }
1089                 }
1090                 //if(printout) {
1091                 //      cout << "ETA = " << tpr->eta << '\n';
1092                 //}
1093         } else {
1094                 tpr->eta = 99999;
1095         }       
1096 }
1097
1098
1099 // Calculate the distance of a plane to the threshold in meters
1100 // TODO - Modify to calculate flying distance of a plane in the circuit
1101 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1102         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1103 }
1104
1105
1106 // Calculate the distance of a plane to the threshold in miles
1107 // TODO - Modify to calculate flying distance of a plane in the circuit
1108 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1109         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
1110 }
1111
1112
1113 // Iterate through all the lists and call CalcETA for all the planes.
1114 void FGTower::doThresholdETACalc() {
1115         tower_plane_rec_list_iterator twrItr;
1116         // Do the approach list first
1117         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1118                 TowerPlaneRec* tpr = *twrItr;
1119                 CalcETA(tpr);
1120         }       
1121         // Then the circuit list
1122         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1123                 TowerPlaneRec* tpr = *twrItr;
1124                 CalcETA(tpr);
1125         }
1126 }
1127                 
1128
1129 // Check that the planes in traffic list are correctly ordered,
1130 // that the nearest (timewise) is flagged next on rwy, and return
1131 // true if any threshold use conflicts are detected, false otherwise.
1132 bool FGTower::doThresholdUseOrder() {
1133         bool conflict = false;
1134         
1135         // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1136         // Here's the rather simplistic assumptions we're using:
1137         // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1138         // In order of priority for runway use:
1139         // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1140         // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1141         // and holding planes until a space.
1142         // When calculating if a holding plane can use the runway, time clearance from last departure
1143         // as well as time clearance to next arrival must be considered.
1144         
1145         trafficList.clear();
1146         
1147         tower_plane_rec_list_iterator twrItr;
1148         // Do the approach list first
1149         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1150                 TowerPlaneRec* tpr = *twrItr;
1151                 conflict = AddToTrafficList(tpr);
1152         }       
1153         // Then the circuit list
1154         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1155                 TowerPlaneRec* tpr = *twrItr;
1156                 conflict = AddToTrafficList(tpr);
1157         }
1158         // And finally the hold list
1159         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1160                 TowerPlaneRec* tpr = *twrItr;
1161                 AddToTrafficList(tpr, true);
1162         }
1163         
1164         if(0) {
1165         //if(ident == "KEMT") {
1166                 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1167                         TowerPlaneRec* tpr = *twrItr;
1168                         cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1169                 }
1170                 cout << '\n';
1171         }
1172         
1173         return(conflict);
1174 }
1175
1176 /*
1177 void FGTower::doCommunication() {
1178 }
1179 */
1180
1181 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1182 // i.e. list_pos = 1 implies next to use runway.
1183 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1184         if(trafficList.size() < list_pos) {
1185                 return(99999);
1186         }
1187
1188         tower_plane_rec_list_iterator twrItr;
1189         twrItr = trafficList.begin();
1190         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1191         TowerPlaneRec* tpr = *twrItr;
1192         CalcETA(tpr, printout);
1193         //cout << "ETA returned = " << tpr->eta << '\n';
1194         return(tpr->eta);
1195 }
1196         
1197
1198 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1199         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1200         TowerPlaneRec* t = new TowerPlaneRec;
1201         t->plane = plane;
1202         t->planePtr = requestee;
1203         t->holdShortReported = true;
1204         t->clearanceCounter = 0;
1205         t->clearedToLineUp = false;
1206         t->clearedToTakeOff = false;
1207         t->opType = operation;
1208         
1209         //cout << "Hold Short reported by " << plane.callsign << '\n';
1210         
1211         bool next = AddToTrafficList(t, true);
1212         
1213         if(next) {
1214                 //cout << "Next to take off - respond with clearance\n";
1215                 double teta = GetTrafficETA(2);
1216                 if(teta < 150.0) {
1217                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1218                         //cout << "Reducing response time to request due imminent traffic\n";
1219                 }
1220         } else {
1221                 //cout << "Not next to take off - respond with hold\n";
1222         }
1223         
1224         //cout << "t = " << t << '\n';
1225         
1226         holdList.push_back(t);
1227 }
1228
1229 void FGTower::RequestLandingClearance(string ID) {
1230         //cout << "Request Landing Clearance called...\n";
1231         
1232         // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1233         // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1234         
1235         TowerPlaneRec* t = new TowerPlaneRec;
1236         t->isUser = true;
1237         t->clearedToLand = false;
1238         t->pos.setlon(user_lon_node->getDoubleValue());
1239         t->pos.setlat(user_lat_node->getDoubleValue());
1240         t->pos.setelev(user_elev_node->getDoubleValue());
1241         
1242         // TODO
1243         // Calculate where the user is in relation to the active runway and it's circuit
1244         // and set the op-type as appropriate.
1245         
1246         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1247         t->opType = STRAIGHT_IN;
1248         
1249         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
1250         t->plane.callsign = ID;
1251         
1252         appList.push_back(t);   // Not necessarily permanent
1253         AddToTrafficList(t);
1254 }
1255
1256 void FGTower::RequestDepartureClearance(string ID) {
1257         //cout << "Request Departure Clearance called...\n";
1258 }       
1259 //void FGTower::ReportFinal(string ID);
1260 //void FGTower::ReportLongFinal(string ID);
1261 //void FGTower::ReportOuterMarker(string ID);
1262 //void FGTower::ReportMiddleMarker(string ID);
1263 //void FGTower::ReportInnerMarker(string ID);
1264 //void FGTower::ReportGoingAround(string ID);
1265 void FGTower::ReportRunwayVacated(string ID) {
1266         //cout << "Report Runway Vacated Called...\n";
1267 }
1268
1269 void FGTower::ReportDownwind(string ID) {
1270         // Tell the plane reporting what number she is in the circuit
1271 }
1272
1273 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1274         switch(ttt) {
1275         case(CIRCUIT):      return(os << "CIRCUIT");
1276         case(INBOUND):      return(os << "INBOUND");
1277         case(OUTBOUND):     return(os << "OUTBOUND");
1278         case(TTT_UNKNOWN):  return(os << "UNKNOWN");
1279         case(STRAIGHT_IN):  return(os << "STRAIGHT_IN");
1280         }
1281         return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");
1282 }
1283