1 // FGTower - a class to provide tower control at towered airports.
3 // Written by David Luff, started March 2002.
5 // Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk
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.
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.
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.
21 #include <Main/globals.hxx>
22 #include <Airports/runways.hxx>
23 #include <simgear/math/sg_geodesy.hxx>
24 #include <simgear/debug/logstream.hxx>
27 #include "ATCdisplay.hxx"
29 #include "ATCutils.hxx"
30 #include "commlist.hxx"
31 #include "AILocalTraffic.hxx"
37 TowerPlaneRec::TowerPlaneRec() :
39 clearedToLineUp(false),
40 clearedToTakeOff(false),
41 holdShortReported(false),
42 downwindReported(false),
43 longFinalReported(false),
44 longFinalAcknowledged(false),
46 finalAcknowledged(false),
51 landingType(AIP_LT_UNKNOWN),
54 plane.callsign = "UNKNOWN";
57 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
59 clearedToLineUp(false),
60 clearedToTakeOff(false),
61 holdShortReported(false),
62 downwindReported(false),
63 longFinalReported(false),
64 longFinalAcknowledged(false),
66 finalAcknowledged(false),
71 landingType(AIP_LT_UNKNOWN),
77 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
79 clearedToLineUp(false),
80 clearedToTakeOff(false),
81 holdShortReported(false),
82 downwindReported(false),
83 longFinalReported(false),
84 longFinalAcknowledged(false),
86 finalAcknowledged(false),
91 landingType(AIP_LT_UNKNOWN),
94 plane.callsign = "UNKNOWN";
98 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
100 clearedToLineUp(false),
101 clearedToTakeOff(false),
102 holdShortReported(false),
103 downwindReported(false),
104 longFinalReported(false),
105 longFinalAcknowledged(false),
106 finalReported(false),
107 finalAcknowledged(false),
112 landingType(AIP_LT_UNKNOWN),
122 /*******************************************
125 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in.
127 AI plane lands even when user on rwy - make it go-around instead.
129 Tell AI plane to contact ground when taxiing in.
131 Use track instead of heading to determine what leg of the circuit the user is flying.
133 Use altitude as well as position to try to determine if the user has left the circuit.
135 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and
136 will break when planes start queueing.
138 Implement ReportRunwayVacated
139 *******************************************/
142 ATCmgr = globals->get_ATC_mgr();
144 // Init the property nodes - TODO - need to make sure we're getting surface winds.
145 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
146 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
149 update_count_max = 15;
151 holdListItr = holdList.begin();
152 appListItr = appList.begin();
153 depListItr = depList.begin();
154 rwyListItr = rwyList.begin();
155 circuitListItr = circuitList.begin();
156 trafficListItr = trafficList.begin();
160 timeSinceLastDeparture = 9999;
164 FGTower::~FGTower() {
165 if(!separateGround) {
170 void FGTower::Init() {
173 // Pointers to user's position
174 user_lon_node = fgGetNode("/position/longitude-deg", true);
175 user_lat_node = fgGetNode("/position/latitude-deg", true);
176 user_elev_node = fgGetNode("/position/altitude-ft", true);
177 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
179 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
180 // I'll punt the startup issue for now though!!!
183 // Setup the ground control at this airport
185 //cout << "Tower ident = " << ident << '\n';
186 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
187 if(a.ground_freq) { // Ground control
188 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
189 separateGround = true;
191 // Something has gone wrong :-(
192 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
193 ground = new FGGround(ident);
194 separateGround = false;
197 ground->SetDisplay();
199 ground->SetNoDisplay();
203 // Initialise ground anyway to do the shortest path stuff!
204 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
205 ground = new FGGround(ident);
206 separateGround = false;
209 ground->SetDisplay();
211 ground->SetNoDisplay();
215 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
216 // Initialise ground anyway to avoid segfault later
217 ground = new FGGround(ident);
218 separateGround = false;
221 ground->SetDisplay();
223 ground->SetNoDisplay();
227 // Get the airport elevation
228 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
232 // FIXME - this currently assumes use of the active rwy by the user.
233 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
235 // Assume the user is started at the threshold ready to take-off
236 TowerPlaneRec* t = new TowerPlaneRec;
237 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
238 t->plane.type = GA_SINGLE;
239 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
240 t->landingType = AIP_LT_UNKNOWN;
241 t->leg = TAKEOFF_ROLL;
244 t->clearedToTakeOff = true;
245 rwyList.push_back(t);
250 void FGTower::Update(double dt) {
251 //cout << "T" << endl;
252 // Each time step, what do we need to do?
253 // We need to go through the list of outstanding requests and acknowedgements
254 // and process at least one of them.
255 // We need to go through the list of planes under our control and check if
256 // any need to be addressed.
257 // We need to check for planes not under our control coming within our
258 // control area and address if necessary.
260 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
262 // Sort the arriving planes
265 if(ident == "KEMT") {
266 cout << update_count << "\ttL: " << trafficList.size() << " cL: " << circuitList.size() << " hL: " << holdList.size() << " aL: " << appList.size() << '\n';
270 if(departed != false) {
271 timeSinceLastDeparture += dt;
272 //if(ident == "KEMT")
273 // cout << " dt = " << dt << " timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
277 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
280 responseReqd = false;
283 // Calculate the eta of each plane to the threshold.
284 // For ground traffic this is the fastest they can get there.
285 // For air traffic this is the middle approximation.
286 if(update_count == 1) {
287 doThresholdETACalc();
290 // Order the list of traffic as per expected threshold use and flag any conflicts
291 if(update_count == 2) {
292 //bool conflicts = doThresholdUseOrder();
293 doThresholdUseOrder();
296 // sortConficts() !!!
298 if(update_count == 4) {
302 // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
309 if(update_count == 5 && rwyOccupied) {
313 if(update_count == 6) {
314 CheckCircuitList(dt);
317 if(update_count == 7) {
318 CheckApproachList(dt);
321 // TODO - do one plane from the departure list and set departed = false when out of consideration
325 if(!separateGround) {
326 // The display stuff might have to get more clever than this when not separate
327 // since the tower and ground might try communicating simultaneously even though
328 // they're mean't to be the same contoller/frequency!!
330 ground->SetDisplay();
332 ground->SetNoDisplay();
338 // How big should ii get - ie how long should the update cycle interval stretch?
339 if(update_count >= update_count_max) {
343 // Call the base class update for the response time handling.
346 if(ident == "KEMT") {
347 // For AI debugging convienience - may be removed
349 user_pos.setlon(user_lon_node->getDoubleValue());
350 user_pos.setlat(user_lat_node->getDoubleValue());
351 user_pos.setelev(user_elev_node->getDoubleValue());
352 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
353 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
354 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
355 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
358 //cout << "Done T" << endl;
361 void FGTower::Respond() {
362 //cout << "Entering Respond..." << endl;
363 TowerPlaneRec* t = FindPlane(responseID);
366 if(t->downwindReported) {
367 t->downwindReported = false;
369 for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
370 if((*twrItr)->plane.callsign == responseID) break;
373 string trns = "Number ";
374 trns += ConvertNumToSpokenDigits(i);
376 trns += t->plane.callsign;
378 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
380 if(t->isUser && t->opType == TTT_UNKNOWN) {
383 } else if(t->holdShortReported) {
385 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!!)
386 // Do nothing for now - consider acknowloging hold short eventually
388 ClearHoldingPlane(t);
389 t->leg = TAKEOFF_ROLL;
390 rwyList.push_back(t);
392 // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
393 // FIXME TODO - FIX THIS!!!
394 if(holdList.size()) {
395 if(holdListItr == holdList.end()) {
396 holdListItr = holdList.begin();
398 holdList.erase(holdListItr);
399 holdListItr = holdList.begin();
403 // Tell him to hold and what position he is.
404 // Not currently sure under which circumstances we do or don't bother transmitting this.
405 string trns = t->plane.callsign;
406 trns += " hold position";
408 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
410 // TODO - add some idea of what traffic is blocking him.
412 t->holdShortReported = false;
415 freqClear = true; // FIXME - set this to come true after enough time to render the message
416 //cout << "Done Respond" << endl;
419 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land -
420 // this should be done prior to calling this function.
421 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
422 //cout << "Entering ClearHoldingPlane..." << endl;
424 string trns = t->plane.callsign;
425 //if(departed plane < some threshold in time away) {
427 //if(timeSinceLastDeparture <= 60.0 && departed == true) {
429 t->clearedToLineUp = true;
430 t->planePtr->RegisterTransmission(3); // cleared to line-up
431 //} else if(arriving plane < some threshold away) {
432 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
433 trns += " cleared immediate take-off";
434 if(trafficList.size()) {
435 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
436 trfcItr++; // At the moment the holding plane should be first in trafficList.
437 // Note though that this will break if holding planes aren't put in trafficList in the future.
438 TowerPlaneRec* trfc = *trfcItr;
439 trns += "... traffic is";
440 switch(trfc->plane.type) {
444 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
450 trns += " a King-air";
453 trns += " a Learjet";
456 trns += " a Regional";
465 //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
466 if(trfc->opType == STRAIGHT_IN) {
467 double miles_out = CalcDistOutMiles(trfc);
472 trns += ConvertNumToSpokenDigits((int)miles_out);
473 trns += " mile final";
475 } else if(trfc->opType == CIRCUIT) {
476 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
482 trns += " turning final";
488 trns += " turning base";
491 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.
493 // And to eliminate compiler warnings...
494 case TAKEOFF_ROLL: break;
495 case CLIMBOUT: break;
497 case CROSSWIND: break;
499 case LANDING_ROLL: break;
500 case LEG_UNKNOWN: break;
504 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
505 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
507 t->clearedToTakeOff = true;
508 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
510 timeSinceLastDeparture = 0.0;
512 //} else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
513 trns += " cleared for take-off";
514 // TODO - add traffic is... ?
515 t->clearedToTakeOff = true;
516 t->planePtr->RegisterTransmission(4); // cleared to take-off
518 timeSinceLastDeparture = 0.0;
521 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
523 //cout << "Done ClearHoldingPlane " << endl;
526 // Do one plane from the hold list
527 void FGTower::CheckHoldList(double dt) {
528 //cout << "Entering CheckHoldList..." << endl;
529 if(holdList.size()) {
530 //cout << "*holdListItr = " << *holdListItr << endl;
531 if(holdListItr == holdList.end()) {
532 holdListItr = holdList.begin();
534 //cout << "*holdListItr = " << *holdListItr << endl;
535 //Process(*holdListItr);
536 TowerPlaneRec* t = *holdListItr;
537 //cout << "t = " << t << endl;
538 if(t->holdShortReported) {
539 // NO-OP - leave it to the response handler.
540 } else { // not responding to report, but still need to clear if clear
542 //cout << "departed = " << departed << '\n';
543 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
546 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
547 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
549 ClearHoldingPlane(t);
550 t->leg = TAKEOFF_ROLL;
551 rwyList.push_back(t);
553 holdList.erase(holdListItr);
554 holdListItr = holdList.begin();
557 // TODO - rationalise the considerable code duplication above!
561 //cout << "Done CheckHoldList" << endl;
564 // do the ciruit list
565 void FGTower::CheckCircuitList(double dt) {
566 //cout << "Entering CheckCircuitList..." << endl;
567 // Clear the constraints - we recalculate here.
569 downwind_leg_pos = 0.0;
570 crosswind_leg_pos = 0.0;
572 if(circuitList.size()) { // Do one plane from the circuit
573 if(circuitListItr == circuitList.end()) {
574 circuitListItr = circuitList.begin();
576 TowerPlaneRec* t = *circuitListItr;
578 t->pos.setlon(user_lon_node->getDoubleValue());
579 t->pos.setlat(user_lat_node->getDoubleValue());
580 t->pos.setelev(user_elev_node->getDoubleValue());
582 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.
583 t->landingType = t->planePtr->GetLandingOption();
584 //cout << "AI plane landing option is " << t->landingType << '\n';
586 Point3D tortho = ortho.ConvertToLocal(t->pos);
588 // Need to figure out which leg he's on
589 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
590 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
591 //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
592 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
593 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
595 // could be either takeoff, climbout or landing - check orthopos.y
596 //cout << "tortho.y = " << tortho.y() << '\n';
597 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
601 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
602 //cout << "Climbout\n";
603 // If it's the user we may be unsure of his/her intentions.
604 // (Hopefully the AI planes won't try confusing the sim!!!)
605 if(t->opType == TTT_UNKNOWN) {
606 if(tortho.y() > 5000) {
607 // 5 km out from threshold - assume it's a departure
608 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
609 // Since we are unknown operation we should be in depList already.
610 circuitList.erase(circuitListItr);
611 RemoveFromTrafficList(t->plane.callsign);
612 circuitListItr = circuitList.begin();
614 } else if(t->opType == CIRCUIT) {
615 if(tortho.y() > 10000) {
616 // 10 km out - assume the user has abandoned the circuit!!
617 t->opType = OUTBOUND;
618 depList.push_back(t);
619 circuitList.erase(circuitListItr);
620 circuitListItr = circuitList.begin();
624 } else if(abs(ho) < 60) {
626 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
627 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
634 } else if(abs(ho) < 120) {
636 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
637 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
639 //cout << "Crosswind\n";
644 } else if(abs(ho) < 150) {
646 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
647 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
652 // Probably safe now to assume the user is flying a circuit
659 //cout << "Downwind\n";
661 if(t->leg == FINAL) {
662 if(OnActiveRunway(t->pos)) {
663 t->leg = LANDING_ROLL;
667 t->leg = t->planePtr->GetLeg();
670 // Set the constraints IF this is the first plane in the circuit
671 // 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!!
672 if(circuitListItr == circuitList.begin()) {
675 // 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.
676 base_leg_pos = tortho.y();
677 //cout << "base_leg_pos = " << base_leg_pos << '\n';
680 // Fall through to base
682 base_leg_pos = tortho.y();
683 //cout << "base_leg_pos = " << base_leg_pos << '\n';
686 // Fall through to downwind
688 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
689 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
690 //cout << "base_leg_pos = " << base_leg_pos;
691 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
692 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
695 // Fall through to crosswind
697 crosswind_leg_pos = tortho.y();
698 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
701 // Fall through to climbout
703 // Only use current by constraint as largest
704 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
705 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
718 if(t->leg == FINAL) {
719 if(t->landingType == FULL_STOP) t->opType = INBOUND;
720 } else if(t->leg == LANDING_ROLL) {
721 rwyList.push_front(t);
722 RemoveFromTrafficList(t->plane.callsign);
724 t->opType = TTT_UNKNOWN;
725 } // TODO - allow the user to specify opType via ATC menu
726 circuitListItr = circuitList.erase(circuitListItr);
727 if(circuitListItr == circuitList.end() ) {
728 circuitListItr = circuitList.begin();
733 //cout << "Done CheckCircuitList" << endl;
736 // 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!!
737 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
738 // (However, at the moment there should only be one airplane on the rwy at once, until we
739 // start allowing planes to line up whilst previous arrival clears the rwy.)
740 void FGTower::CheckRunwayList(double dt) {
741 //cout << "Entering CheckRunwayList..." << endl;
743 if(!rwyList.size()) {
746 rwyListItr = rwyList.begin();
747 TowerPlaneRec* t = *rwyListItr;
749 t->pos.setlon(user_lon_node->getDoubleValue());
750 t->pos.setlat(user_lat_node->getDoubleValue());
751 t->pos.setelev(user_elev_node->getDoubleValue());
753 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.
755 bool on_rwy = OnActiveRunway(t->pos);
757 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
760 // TODO - tell it to taxi / contact ground / don't delete it etc!
761 } else if(t->opType == OUTBOUND) {
762 depList.push_back(t);
765 timeSinceLastDeparture = 0.0;
766 } else if(t->opType == CIRCUIT) {
767 circuitList.push_back(t);
771 timeSinceLastDeparture = 0.0;
772 } else if(t->opType == TTT_UNKNOWN) {
773 depList.push_back(t);
774 circuitList.push_back(t);
778 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.
780 // HELP - we shouldn't ever get here!!!
785 //cout << "Done CheckRunwayList" << endl;
788 // Do one plane from the approach list
789 void FGTower::CheckApproachList(double dt) {
791 if(appListItr == appList.end()) {
792 appListItr = appList.begin();
794 TowerPlaneRec* t = *appListItr;
795 //cout << "t = " << t << endl;
797 t->pos.setlon(user_lon_node->getDoubleValue());
798 t->pos.setlat(user_lat_node->getDoubleValue());
799 t->pos.setelev(user_elev_node->getDoubleValue());
801 // TODO - set/update the position if it's an AI plane
803 if(t->nextOnRwy && !(t->clearedToLand)) {
804 // check distance away and whether runway occupied
805 // and schedule transmission if necessary
811 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
812 // plus the constraint position as a rwy orientated orthopos (meters)
813 bool FGTower::GetCrosswindConstraint(double& cpos) {
814 if(crosswind_leg_pos != 0.0) {
815 cpos = crosswind_leg_pos;
822 bool FGTower::GetDownwindConstraint(double& dpos) {
823 if(downwind_leg_pos != 0.0) {
824 dpos = downwind_leg_pos;
831 bool FGTower::GetBaseConstraint(double& bpos) {
832 if(base_leg_pos != 0.0) {
842 // Figure out which runways are active.
843 // For now we'll just be simple and do one active runway - eventually this will get much more complex
844 // This is a private function - public interface to the results of this is through GetActiveRunway
845 void FGTower::DoRwyDetails() {
846 //cout << "GetRwyDetails called" << endl;
848 // Based on the airport-id and wind get the active runway
851 double hdg = wind_from_hdg->getDoubleValue();
852 double speed = wind_speed_knots->getDoubleValue();
853 hdg = (speed == 0.0 ? 270.0 : hdg);
854 //cout << "Heading = " << hdg << '\n';
857 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
859 activeRwy = runway.rwy_no;
860 rwy.rwyID = runway.rwy_no;
861 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
863 // Get the threshold position
864 double other_way = runway.heading - 180.0;
865 while(other_way <= 0.0) {
868 // move to the +l end/center of the runway
869 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
870 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
871 Point3D ref = origin;
872 double tshlon, tshlat, tshr;
873 double tolon, tolat, tor;
874 rwy.length = runway.length * SG_FEET_TO_METER;
875 rwy.width = runway.width * SG_FEET_TO_METER;
876 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
877 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
878 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
879 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
880 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
881 // now copy what we need out of runway into rwy
882 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
883 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
884 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
885 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
886 rwy.hdg = runway.heading;
887 // Set the projection for the local area based on this active runway
888 ortho.Init(rwy.threshold_pos, rwy.hdg);
889 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
890 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
892 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
898 // Figure out if a given position lies on the active runway
899 // Might have to change when we consider more than one active rwy.
900 bool FGTower::OnActiveRunway(Point3D pt) {
901 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
902 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
903 Point3D xyp = ortho.ConvertToLocal(pt);
905 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
906 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
908 double rlen = rwy.length/2.0 + 5.0;
909 double rwidth = rwy.width/2.0;
910 double ldiff = fabs(xyp.y() - xyc.y());
911 double wdiff = fabs(xyp.x() - xyc.x());
913 return((ldiff < rlen) && (wdiff < rwidth));
917 // Figure out if a given position lies on any runway or not
918 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
919 bool FGTower::OnAnyRunway(Point3D pt) {
921 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
925 // Based on the airport-id, go through all the runways and check for a point in them
927 // TODO - do we actually need to search for the airport - surely we already know our ident and
928 // can just search runways of our airport???
929 //cout << "Airport ident is " << ad.ident << '\n';
931 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
933 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
936 while(runway.id == ad.ident) {
937 on = OnRunway(pt, runway);
938 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
940 globals->get_runways()->next(&runway);
946 // Returns true if successful
947 bool FGTower::RemoveFromTrafficList(string id) {
948 tower_plane_rec_list_iterator twrItr;
949 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
950 TowerPlaneRec* tpr = *twrItr;
951 if(tpr->plane.callsign == id) {
952 trafficList.erase(twrItr);
956 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
961 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
962 // and set nextOnRwy if so.
963 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
964 // For planes holding they are put in the first position with time to go, and the return value is
965 // true if in the first position (nextOnRwy) and false otherwise.
966 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
967 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
968 //cout << "ADD: " << trafficList.size();
969 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
970 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.
971 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
972 bool conflict = false;
973 double lastETA = 0.0;
974 bool firstTime = true;
975 // FIXME - make this more robust for different plane types eg. light following heavy.
976 tower_plane_rec_list_iterator twrItr;
977 //twrItr = trafficList.begin();
979 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
980 //if(twrItr == trafficList.end()) {
982 // trafficList.push_back(t);
983 // return(holding ? firstTime : conflict);
985 TowerPlaneRec* tpr = *twrItr;
987 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
988 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
989 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
990 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
991 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
992 // and if not needs time to clear the rwy anyway.
993 if(tpr->eta - lastETA > slot_time) {
994 t->nextOnRwy = firstTime;
995 trafficList.insert(twrItr, t);
996 //cout << "\tH\t" << trafficList.size() << '\n';
1001 if(t->eta < tpr->eta) {
1002 // Ugg - this one's tricky.
1003 // It depends on what the two planes are doing and whether there's a conflict what we do.
1004 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1005 if(tpr->nextOnRwy) {
1006 tpr->nextOnRwy = false;
1007 t->nextOnRwy = true;
1009 trafficList.insert(twrItr, t);
1010 } else { // Ooops - this ones tricky - we have a potential conflict!
1012 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1013 if(tpr->nextOnRwy) {
1014 tpr->nextOnRwy = false;
1015 t->nextOnRwy = true;
1017 trafficList.insert(twrItr, t);
1019 //cout << "\tC\t" << trafficList.size() << '\n';
1026 // If we get here we must be at the end of the list, or maybe the list is empty.
1027 if(!trafficList.size()) {
1028 t->nextOnRwy = true;
1029 // conflict and firstTime should be false and true respectively in this case anyway.
1031 trafficList.push_back(t);
1032 //cout << "\tE\t" << trafficList.size() << endl;
1033 return(holding ? firstTime : conflict);
1037 // Calculate the eta of a plane to the threshold.
1038 // For ground traffic this is the fastest they can get there.
1039 // For air traffic this is the middle approximation.
1040 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1041 // For now we'll be very crude and hardwire expected speeds to C172-like values
1042 // The speeds below are specified in knots IAS and then converted to m/s
1043 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
1044 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
1045 double final_ias = 70.0 * 0.514444; // Speed during final approach
1048 //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1049 //cout << (tpr->isUser ? "USER\n" : "AI\n");
1053 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1054 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1056 Point3D op = ortho.ConvertToLocal(tpr->pos);
1058 // cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1059 // cout << "opType is " << tpr->opType << '\n';
1061 double dist_out_m = op.y();
1062 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
1063 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1065 if(tpr->opType == STRAIGHT_IN) {
1066 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1067 if(dist_to_go_m < 1000) {
1068 tpr->eta = dist_to_go_m / final_ias;
1070 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1072 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1073 // It's complicated - depends on if base leg is delayed or not
1075 // cout << "Leg = " << tpr->leg << '\n';
1077 if(tpr->leg == LANDING_ROLL) {
1079 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1080 tpr->eta = fabs(dist_out_m) / final_ias;
1081 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1082 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1084 // Need to calculate where base leg is likely to be
1085 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1086 // 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
1087 double nominal_base_dist_out_m = -1000;
1088 double current_base_dist_out_m;
1089 if(!GetBaseConstraint(current_base_dist_out_m)) {
1090 current_base_dist_out_m = nominal_base_dist_out_m;
1092 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1093 double current_dist_across_m;
1094 if(!GetDownwindConstraint(current_dist_across_m)) {
1095 current_dist_across_m = nominal_dist_across_m;
1097 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1098 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1099 //if(printout) cout << "a = " << tpr->eta << '\n';
1100 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1101 tpr->eta += dist_across_m / circuit_ias;
1102 //if(printout) cout << "b = " << tpr->eta << '\n';
1103 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1104 //if(printout) cout << "c = " << tpr->eta << '\n';
1105 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1106 if(dist_across_m > nominal_dist_across_m) {
1107 tpr->eta += dist_across_m / circuit_ias;
1109 tpr->eta += nominal_dist_across_m / circuit_ias;
1111 // should we use the dist across of the previous plane if there is previous still on downwind?
1112 //if(printout) cout << "bb = " << tpr->eta << '\n';
1113 if(dist_out_m > nominal_cross_dist_out_m) {
1114 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1116 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1118 //if(printout) cout << "cc = " << tpr->eta << '\n';
1119 if(nominal_dist_across_m > dist_across_m) {
1120 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1124 //if(printout) cout << "dd = " << tpr->eta << '\n';
1126 // We've only just started - why not use a generic estimate?
1131 // cout << "ETA = " << tpr->eta << '\n';
1139 // Calculate the distance of a plane to the threshold in meters
1140 // TODO - Modify to calculate flying distance of a plane in the circuit
1141 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1142 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1146 // Calculate the distance of a plane to the threshold in miles
1147 // TODO - Modify to calculate flying distance of a plane in the circuit
1148 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1149 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1153 // Iterate through all the lists and call CalcETA for all the planes.
1154 void FGTower::doThresholdETACalc() {
1155 //cout << "Entering doThresholdETACalc..." << endl;
1156 tower_plane_rec_list_iterator twrItr;
1157 // Do the approach list first
1158 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1159 TowerPlaneRec* tpr = *twrItr;
1162 // Then the circuit list
1163 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1164 TowerPlaneRec* tpr = *twrItr;
1167 //cout << "Done doThresholdETCCalc" << endl;
1171 // Check that the planes in traffic list are correctly ordered,
1172 // that the nearest (timewise) is flagged next on rwy, and return
1173 // true if any threshold use conflicts are detected, false otherwise.
1174 bool FGTower::doThresholdUseOrder() {
1175 //cout << "Entering doThresholdUseOrder..." << endl;
1176 bool conflict = false;
1178 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1179 // Here's the rather simplistic assumptions we're using:
1180 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1181 // In order of priority for runway use:
1182 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1183 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1184 // and holding planes until a space.
1185 // When calculating if a holding plane can use the runway, time clearance from last departure
1186 // as well as time clearance to next arrival must be considered.
1188 trafficList.clear();
1190 tower_plane_rec_list_iterator twrItr;
1191 // Do the approach list first
1192 //cout << "A" << flush;
1193 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1194 TowerPlaneRec* tpr = *twrItr;
1195 conflict = AddToTrafficList(tpr);
1197 // Then the circuit list
1198 //cout << "C" << flush;
1199 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1200 TowerPlaneRec* tpr = *twrItr;
1201 conflict = AddToTrafficList(tpr);
1203 // And finally the hold list
1204 //cout << "H" << endl;
1205 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1206 TowerPlaneRec* tpr = *twrItr;
1207 AddToTrafficList(tpr, true);
1211 //if(ident == "KEMT") {
1212 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1213 TowerPlaneRec* tpr = *twrItr;
1214 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1219 //cout << "Done doThresholdUseOrder" << endl;
1224 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1225 // i.e. list_pos = 1 implies next to use runway.
1226 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1227 if(trafficList.size() < list_pos) {
1231 tower_plane_rec_list_iterator twrItr;
1232 twrItr = trafficList.begin();
1233 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1234 TowerPlaneRec* tpr = *twrItr;
1235 CalcETA(tpr, printout);
1236 //cout << "ETA returned = " << tpr->eta << '\n';
1241 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1242 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1243 TowerPlaneRec* t = new TowerPlaneRec;
1245 t->planePtr = requestee;
1246 t->holdShortReported = true;
1247 t->clearedToLineUp = false;
1248 t->clearedToTakeOff = false;
1249 t->opType = operation;
1251 //cout << "Hold Short reported by " << plane.callsign << '\n';
1254 bool next = AddToTrafficList(t, true);
1256 double teta = GetTrafficETA(2);
1258 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1259 //cout << "Reducing response time to request due imminent traffic\n";
1264 // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1266 holdList.push_back(t);
1268 responseReqd = true;
1271 void FGTower::RequestLandingClearance(string ID) {
1272 //cout << "Request Landing Clearance called...\n";
1274 // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1275 // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1277 TowerPlaneRec* t = new TowerPlaneRec;
1279 t->clearedToLand = false;
1280 t->pos.setlon(user_lon_node->getDoubleValue());
1281 t->pos.setlat(user_lat_node->getDoubleValue());
1282 t->pos.setelev(user_elev_node->getDoubleValue());
1285 // Calculate where the user is in relation to the active runway and it's circuit
1286 // and set the op-type as appropriate.
1288 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1289 t->opType = STRAIGHT_IN;
1291 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1292 t->plane.callsign = ID;
1294 appList.push_back(t); // Not necessarily permanent
1295 AddToTrafficList(t);
1298 void FGTower::RequestDepartureClearance(string ID) {
1299 //cout << "Request Departure Clearance called...\n";
1301 //void FGTower::ReportFinal(string ID);
1302 //void FGTower::ReportLongFinal(string ID);
1303 //void FGTower::ReportOuterMarker(string ID);
1304 //void FGTower::ReportMiddleMarker(string ID);
1305 //void FGTower::ReportInnerMarker(string ID);
1306 //void FGTower::ReportGoingAround(string ID);
1307 void FGTower::ReportRunwayVacated(string ID) {
1308 //cout << "Report Runway Vacated Called...\n";
1311 TowerPlaneRec* FGTower::FindPlane(string ID) {
1312 tower_plane_rec_list_iterator twrItr;
1313 // Do the approach list first
1314 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1315 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1317 // Then the circuit list
1318 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1319 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1321 // And finally the hold list
1322 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1323 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1325 SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
1329 void FGTower::ReportDownwind(string ID) {
1330 //cout << "ReportDownwind(...) called\n";
1331 // Tell the plane reporting what number she is in the circuit
1332 TowerPlaneRec* t = FindPlane(ID);
1334 t->downwindReported = true;
1335 responseReqd = true;
1337 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
1341 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1343 case(CIRCUIT): return(os << "CIRCUIT");
1344 case(INBOUND): return(os << "INBOUND");
1345 case(OUTBOUND): return(os << "OUTBOUND");
1346 case(TTT_UNKNOWN): return(os << "UNKNOWN");
1347 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
1349 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");