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),
123 ATCmgr = globals->get_ATC_mgr();
125 // Init the property nodes - TODO - need to make sure we're getting surface winds.
126 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
127 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
130 update_count_max = 15;
132 holdListItr = holdList.begin();
133 appListItr = appList.begin();
134 depListItr = depList.begin();
135 rwyListItr = rwyList.begin();
136 circuitListItr = circuitList.begin();
137 trafficListItr = trafficList.begin();
141 timeSinceLastDeparture = 9999;
145 FGTower::~FGTower() {
146 if(!separateGround) {
151 void FGTower::Init() {
154 // Pointers to user's position
155 user_lon_node = fgGetNode("/position/longitude-deg", true);
156 user_lat_node = fgGetNode("/position/latitude-deg", true);
157 user_elev_node = fgGetNode("/position/altitude-ft", true);
158 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
160 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
161 // I'll punt the startup issue for now though!!!
164 // Setup the ground control at this airport
166 //cout << "Tower ident = " << ident << '\n';
167 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
168 if(a.ground_freq) { // Ground control
169 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
170 separateGround = true;
172 // Something has gone wrong :-(
173 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
174 ground = new FGGround(ident);
175 separateGround = false;
178 ground->SetDisplay();
180 ground->SetNoDisplay();
184 // Initialise ground anyway to do the shortest path stuff!
185 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
186 ground = new FGGround(ident);
187 separateGround = false;
190 ground->SetDisplay();
192 ground->SetNoDisplay();
196 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
197 // Initialise ground anyway to avoid segfault later
198 ground = new FGGround(ident);
199 separateGround = false;
202 ground->SetDisplay();
204 ground->SetNoDisplay();
208 // Get the airport elevation
209 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
213 // FIXME - this currently assumes use of the active rwy by the user.
214 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
216 // Assume the user is started at the threshold ready to take-off
217 TowerPlaneRec* t = new TowerPlaneRec;
218 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
219 t->plane.type = GA_SINGLE;
220 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
221 t->landingType = AIP_LT_UNKNOWN;
222 t->leg = TAKEOFF_ROLL;
225 t->clearedToTakeOff = true;
226 rwyList.push_back(t);
231 void FGTower::Update(double dt) {
232 //cout << "T" << endl;
233 // Each time step, what do we need to do?
234 // We need to go through the list of outstanding requests and acknowedgements
235 // and process at least one of them.
236 // We need to go through the list of planes under our control and check if
237 // any need to be addressed.
238 // We need to check for planes not under our control coming within our
239 // control area and address if necessary.
241 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
243 // Sort the arriving planes
246 if(ident == "KEMT") {
247 cout << update_count << "\ttL: " << trafficList.size() << " cL: " << circuitList.size() << " hL: " << holdList.size() << " aL: " << appList.size() << '\n';
251 if(departed != false) {
252 timeSinceLastDeparture += dt;
253 //if(ident == "KEMT")
254 // cout << " dt = " << dt << " timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
258 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
261 responseReqd = false;
264 // Calculate the eta of each plane to the threshold.
265 // For ground traffic this is the fastest they can get there.
266 // For air traffic this is the middle approximation.
267 if(update_count == 1) {
268 doThresholdETACalc();
271 // Order the list of traffic as per expected threshold use and flag any conflicts
272 if(update_count == 2) {
273 //bool conflicts = doThresholdUseOrder();
274 doThresholdUseOrder();
277 // sortConficts() !!!
279 if(update_count == 4) {
283 // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
290 if(update_count == 5 && rwyOccupied) {
294 if(update_count == 6) {
295 CheckCircuitList(dt);
298 if(update_count == 7) {
299 CheckApproachList(dt);
302 // TODO - do one plane from the departure list and set departed = false when out of consideration
306 if(!separateGround) {
307 // The display stuff might have to get more clever than this when not separate
308 // since the tower and ground might try communicating simultaneously even though
309 // they're mean't to be the same contoller/frequency!!
311 ground->SetDisplay();
313 ground->SetNoDisplay();
319 // How big should ii get - ie how long should the update cycle interval stretch?
320 if(update_count >= update_count_max) {
324 // Call the base class update for the response time handling.
327 if(ident == "KEMT") {
328 // For AI debugging convienience - may be removed
330 user_pos.setlon(user_lon_node->getDoubleValue());
331 user_pos.setlat(user_lat_node->getDoubleValue());
332 user_pos.setelev(user_elev_node->getDoubleValue());
333 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
334 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
335 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
336 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
339 //cout << "Done T" << endl;
342 void FGTower::Respond() {
343 //cout << "Entering Respond..." << endl;
344 TowerPlaneRec* t = FindPlane(responseID);
347 if(t->downwindReported) {
348 t->downwindReported = false;
350 for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
351 if((*twrItr)->plane.callsign == responseID) break;
354 string trns = "Number ";
355 trns += ConvertNumToSpokenDigits(i);
357 trns += t->plane.callsign;
359 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
361 if(t->isUser && t->opType == TTT_UNKNOWN) {
364 } else if(t->holdShortReported) {
366 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!!)
367 // Do nothing for now - consider acknowloging hold short eventually
369 ClearHoldingPlane(t);
370 t->leg = TAKEOFF_ROLL;
371 rwyList.push_back(t);
373 // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
374 // FIXME TODO - FIX THIS!!!
375 if(holdList.size()) {
376 if(holdListItr == holdList.end()) {
377 holdListItr = holdList.begin();
379 holdList.erase(holdListItr);
380 holdListItr = holdList.begin();
384 // Tell him to hold and what position he is.
385 // Not currently sure under which circumstances we do or don't bother transmitting this.
386 string trns = t->plane.callsign;
387 trns += " hold position";
389 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
391 // TODO - add some idea of what traffic is blocking him.
393 t->holdShortReported = false;
396 freqClear = true; // FIXME - set this to come true after enough time to render the message
397 //cout << "Done Respond" << endl;
400 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land -
401 // this should be done prior to calling this function.
402 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
403 //cout << "Entering ClearHoldingPlane..." << endl;
405 string trns = t->plane.callsign;
406 //if(departed plane < some threshold in time away) {
408 //if(timeSinceLastDeparture <= 60.0 && departed == true) {
410 t->clearedToLineUp = true;
411 t->planePtr->RegisterTransmission(3); // cleared to line-up
412 //} else if(arriving plane < some threshold away) {
413 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
414 trns += " cleared immediate take-off";
415 if(trafficList.size()) {
416 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
417 trfcItr++; // At the moment the holding plane should be first in trafficList.
418 // Note though that this will break if holding planes aren't put in trafficList in the future.
419 TowerPlaneRec* trfc = *trfcItr;
420 trns += "... traffic is";
421 switch(trfc->plane.type) {
425 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
431 trns += " a King-air";
434 trns += " a Learjet";
437 trns += " a Regional";
446 //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
447 if(trfc->opType == STRAIGHT_IN) {
448 double miles_out = CalcDistOutMiles(trfc);
453 trns += ConvertNumToSpokenDigits((int)miles_out);
454 trns += " mile final";
456 } else if(trfc->opType == CIRCUIT) {
457 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
463 trns += " turning final";
469 trns += " turning base";
472 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.
474 // And to eliminate compiler warnings...
475 case TAKEOFF_ROLL: break;
476 case CLIMBOUT: break;
478 case CROSSWIND: break;
480 case LANDING_ROLL: break;
481 case LEG_UNKNOWN: break;
485 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
486 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
488 t->clearedToTakeOff = true;
489 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
491 timeSinceLastDeparture = 0.0;
493 //} else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
494 trns += " cleared for take-off";
495 // TODO - add traffic is... ?
496 t->clearedToTakeOff = true;
497 t->planePtr->RegisterTransmission(4); // cleared to take-off
499 timeSinceLastDeparture = 0.0;
502 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
504 //cout << "Done ClearHoldingPlane " << endl;
507 // Do one plane from the hold list
508 void FGTower::CheckHoldList(double dt) {
509 //cout << "Entering CheckHoldList..." << endl;
510 if(holdList.size()) {
511 //cout << "*holdListItr = " << *holdListItr << endl;
512 if(holdListItr == holdList.end()) {
513 holdListItr = holdList.begin();
515 //cout << "*holdListItr = " << *holdListItr << endl;
516 //Process(*holdListItr);
517 TowerPlaneRec* t = *holdListItr;
518 //cout << "t = " << t << endl;
519 if(t->holdShortReported) {
520 // NO-OP - leave it to the response handler.
521 } else { // not responding to report, but still need to clear if clear
523 //cout << "departed = " << departed << '\n';
524 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
527 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
528 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
530 ClearHoldingPlane(t);
531 t->leg = TAKEOFF_ROLL;
532 rwyList.push_back(t);
534 holdList.erase(holdListItr);
535 holdListItr = holdList.begin();
538 // TODO - rationalise the considerable code duplication above!
542 //cout << "Done CheckHoldList" << endl;
545 // do the ciruit list
546 void FGTower::CheckCircuitList(double dt) {
547 //cout << "Entering CheckCircuitList..." << endl;
548 // Clear the constraints - we recalculate here.
550 downwind_leg_pos = 0.0;
551 crosswind_leg_pos = 0.0;
553 if(circuitList.size()) { // Do one plane from the circuit
554 if(circuitListItr == circuitList.end()) {
555 circuitListItr = circuitList.begin();
557 TowerPlaneRec* t = *circuitListItr;
559 t->pos.setlon(user_lon_node->getDoubleValue());
560 t->pos.setlat(user_lat_node->getDoubleValue());
561 t->pos.setelev(user_elev_node->getDoubleValue());
563 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.
564 t->landingType = t->planePtr->GetLandingOption();
565 //cout << "AI plane landing option is " << t->landingType << '\n';
567 Point3D tortho = ortho.ConvertToLocal(t->pos);
569 // Need to figure out which leg he's on
570 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
571 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
572 //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
573 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
574 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
576 // could be either takeoff, climbout or landing - check orthopos.y
577 //cout << "tortho.y = " << tortho.y() << '\n';
578 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
582 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
583 //cout << "Climbout\n";
584 // If it's the user we may be unsure of his/her intentions.
585 // (Hopefully the AI planes won't try confusing the sim!!!)
586 if(t->opType == TTT_UNKNOWN) {
587 if(tortho.y() > 5000) {
588 // 5 km out from threshold - assume it's a departure
589 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
590 // Since we are unknown operation we should be in depList already.
591 circuitList.erase(circuitListItr);
592 RemoveFromTrafficList(t->plane.callsign);
593 circuitListItr = circuitList.begin();
595 } else if(t->opType == CIRCUIT) {
596 if(tortho.y() > 10000) {
597 // 10 km out - assume the user has abandoned the circuit!!
598 t->opType = OUTBOUND;
599 depList.push_back(t);
600 circuitList.erase(circuitListItr);
601 circuitListItr = circuitList.begin();
605 } else if(abs(ho) < 60) {
607 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
608 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
615 } else if(abs(ho) < 120) {
617 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
618 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
620 //cout << "Crosswind\n";
625 } else if(abs(ho) < 150) {
627 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
628 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
633 // Probably safe now to assume the user is flying a circuit
640 //cout << "Downwind\n";
642 if(t->leg == FINAL) {
643 if(OnActiveRunway(t->pos)) {
644 t->leg = LANDING_ROLL;
648 t->leg = t->planePtr->GetLeg();
651 // Set the constraints IF this is the first plane in the circuit
652 // 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!!
653 if(circuitListItr == circuitList.begin()) {
656 // 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.
657 base_leg_pos = tortho.y();
658 //cout << "base_leg_pos = " << base_leg_pos << '\n';
661 // Fall through to base
663 base_leg_pos = tortho.y();
664 //cout << "base_leg_pos = " << base_leg_pos << '\n';
667 // Fall through to downwind
669 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
670 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
671 //cout << "base_leg_pos = " << base_leg_pos;
672 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
673 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
676 // Fall through to crosswind
678 crosswind_leg_pos = tortho.y();
679 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
682 // Fall through to climbout
684 // Only use current by constraint as largest
685 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
686 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
699 if(t->leg == FINAL) {
700 if(t->landingType == FULL_STOP) t->opType = INBOUND;
701 } else if(t->leg == LANDING_ROLL) {
702 rwyList.push_front(t);
703 RemoveFromTrafficList(t->plane.callsign);
705 t->opType = TTT_UNKNOWN;
706 } // TODO - allow the user to specify opType via ATC menu
707 circuitListItr = circuitList.erase(circuitListItr);
708 if(circuitListItr == circuitList.end() ) {
709 circuitListItr = circuitList.begin();
714 //cout << "Done CheckCircuitList" << endl;
717 // 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!!
718 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
719 // (However, at the moment there should only be one airplane on the rwy at once, until we
720 // start allowing planes to line up whilst previous arrival clears the rwy.)
721 void FGTower::CheckRunwayList(double dt) {
722 //cout << "Entering CheckRunwayList..." << endl;
724 if(!rwyList.size()) {
727 rwyListItr = rwyList.begin();
728 TowerPlaneRec* t = *rwyListItr;
730 t->pos.setlon(user_lon_node->getDoubleValue());
731 t->pos.setlat(user_lat_node->getDoubleValue());
732 t->pos.setelev(user_elev_node->getDoubleValue());
734 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.
736 bool on_rwy = OnActiveRunway(t->pos);
738 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
741 // TODO - tell it to taxi / contact ground / don't delete it etc!
742 } else if(t->opType == OUTBOUND) {
743 depList.push_back(t);
746 timeSinceLastDeparture = 0.0;
747 } else if(t->opType == CIRCUIT) {
748 circuitList.push_back(t);
752 timeSinceLastDeparture = 0.0;
753 } else if(t->opType == TTT_UNKNOWN) {
754 depList.push_back(t);
755 circuitList.push_back(t);
759 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.
761 // HELP - we shouldn't ever get here!!!
766 //cout << "Done CheckRunwayList" << endl;
769 // Do one plane from the approach list
770 void FGTower::CheckApproachList(double dt) {
772 if(appListItr == appList.end()) {
773 appListItr = appList.begin();
775 TowerPlaneRec* t = *appListItr;
776 //cout << "t = " << t << endl;
778 t->pos.setlon(user_lon_node->getDoubleValue());
779 t->pos.setlat(user_lat_node->getDoubleValue());
780 t->pos.setelev(user_elev_node->getDoubleValue());
782 // TODO - set/update the position if it's an AI plane
784 if(t->nextOnRwy && !(t->clearedToLand)) {
785 // check distance away and whether runway occupied
786 // and schedule transmission if necessary
792 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
793 // plus the constraint position as a rwy orientated orthopos (meters)
794 bool FGTower::GetCrosswindConstraint(double& cpos) {
795 if(crosswind_leg_pos != 0.0) {
796 cpos = crosswind_leg_pos;
803 bool FGTower::GetDownwindConstraint(double& dpos) {
804 if(downwind_leg_pos != 0.0) {
805 dpos = downwind_leg_pos;
812 bool FGTower::GetBaseConstraint(double& bpos) {
813 if(base_leg_pos != 0.0) {
823 // Figure out which runways are active.
824 // For now we'll just be simple and do one active runway - eventually this will get much more complex
825 // This is a private function - public interface to the results of this is through GetActiveRunway
826 void FGTower::DoRwyDetails() {
827 //cout << "GetRwyDetails called" << endl;
829 // Based on the airport-id and wind get the active runway
832 double hdg = wind_from_hdg->getDoubleValue();
833 double speed = wind_speed_knots->getDoubleValue();
834 hdg = (speed == 0.0 ? 270.0 : hdg);
835 //cout << "Heading = " << hdg << '\n';
838 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
840 activeRwy = runway.rwy_no;
841 rwy.rwyID = runway.rwy_no;
842 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
844 // Get the threshold position
845 double other_way = runway.heading - 180.0;
846 while(other_way <= 0.0) {
849 // move to the +l end/center of the runway
850 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
851 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
852 Point3D ref = origin;
853 double tshlon, tshlat, tshr;
854 double tolon, tolat, tor;
855 rwy.length = runway.length * SG_FEET_TO_METER;
856 rwy.width = runway.width * SG_FEET_TO_METER;
857 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
858 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
859 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
860 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
861 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
862 // now copy what we need out of runway into rwy
863 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
864 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
865 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
866 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
867 rwy.hdg = runway.heading;
868 // Set the projection for the local area based on this active runway
869 ortho.Init(rwy.threshold_pos, rwy.hdg);
870 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
871 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
873 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
879 // Figure out if a given position lies on the active runway
880 // Might have to change when we consider more than one active rwy.
881 bool FGTower::OnActiveRunway(Point3D pt) {
882 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
883 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
884 Point3D xyp = ortho.ConvertToLocal(pt);
886 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
887 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
889 double rlen = rwy.length/2.0 + 5.0;
890 double rwidth = rwy.width/2.0;
891 double ldiff = fabs(xyp.y() - xyc.y());
892 double wdiff = fabs(xyp.x() - xyc.x());
894 return((ldiff < rlen) && (wdiff < rwidth));
898 // Figure out if a given position lies on any runway or not
899 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
900 bool FGTower::OnAnyRunway(Point3D pt) {
902 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
906 // Based on the airport-id, go through all the runways and check for a point in them
908 // TODO - do we actually need to search for the airport - surely we already know our ident and
909 // can just search runways of our airport???
910 //cout << "Airport ident is " << ad.ident << '\n';
912 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
914 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
917 while(runway.id == ad.ident) {
918 on = OnRunway(pt, runway);
919 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
921 globals->get_runways()->next(&runway);
927 // Returns true if successful
928 bool FGTower::RemoveFromTrafficList(string id) {
929 tower_plane_rec_list_iterator twrItr;
930 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
931 TowerPlaneRec* tpr = *twrItr;
932 if(tpr->plane.callsign == id) {
933 trafficList.erase(twrItr);
937 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
942 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
943 // and set nextOnRwy if so.
944 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
945 // For planes holding they are put in the first position with time to go, and the return value is
946 // true if in the first position (nextOnRwy) and false otherwise.
947 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
948 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
949 //cout << "ADD: " << trafficList.size();
950 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
951 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.
952 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
953 bool conflict = false;
954 double lastETA = 0.0;
955 bool firstTime = true;
956 // FIXME - make this more robust for different plane types eg. light following heavy.
957 tower_plane_rec_list_iterator twrItr;
958 //twrItr = trafficList.begin();
960 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
961 //if(twrItr == trafficList.end()) {
963 // trafficList.push_back(t);
964 // return(holding ? firstTime : conflict);
966 TowerPlaneRec* tpr = *twrItr;
968 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
969 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
970 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
971 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
972 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
973 // and if not needs time to clear the rwy anyway.
974 if(tpr->eta - lastETA > slot_time) {
975 t->nextOnRwy = firstTime;
976 trafficList.insert(twrItr, t);
977 //cout << "\tH\t" << trafficList.size() << '\n';
982 if(t->eta < tpr->eta) {
983 // Ugg - this one's tricky.
984 // It depends on what the two planes are doing and whether there's a conflict what we do.
985 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
987 tpr->nextOnRwy = false;
990 trafficList.insert(twrItr, t);
991 } else { // Ooops - this ones tricky - we have a potential conflict!
993 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
995 tpr->nextOnRwy = false;
998 trafficList.insert(twrItr, t);
1000 //cout << "\tC\t" << trafficList.size() << '\n';
1007 // If we get here we must be at the end of the list, or maybe the list is empty.
1008 if(!trafficList.size()) {
1009 t->nextOnRwy = true;
1010 // conflict and firstTime should be false and true respectively in this case anyway.
1012 trafficList.push_back(t);
1013 //cout << "\tE\t" << trafficList.size() << endl;
1014 return(holding ? firstTime : conflict);
1018 // Calculate the eta of a plane to the threshold.
1019 // For ground traffic this is the fastest they can get there.
1020 // For air traffic this is the middle approximation.
1021 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1022 // For now we'll be very crude and hardwire expected speeds to C172-like values
1023 // The speeds below are specified in knots IAS and then converted to m/s
1024 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
1025 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
1026 double final_ias = 70.0 * 0.514444; // Speed during final approach
1029 //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1030 //cout << (tpr->isUser ? "USER\n" : "AI\n");
1034 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1035 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1037 Point3D op = ortho.ConvertToLocal(tpr->pos);
1039 // cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1040 // cout << "opType is " << tpr->opType << '\n';
1042 double dist_out_m = op.y();
1043 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
1044 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1046 if(tpr->opType == STRAIGHT_IN) {
1047 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1048 if(dist_to_go_m < 1000) {
1049 tpr->eta = dist_to_go_m / final_ias;
1051 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1053 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1054 // It's complicated - depends on if base leg is delayed or not
1056 // cout << "Leg = " << tpr->leg << '\n';
1058 if(tpr->leg == LANDING_ROLL) {
1060 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1061 tpr->eta = fabs(dist_out_m) / final_ias;
1062 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1063 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1065 // Need to calculate where base leg is likely to be
1066 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1067 // 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
1068 double nominal_base_dist_out_m = -1000;
1069 double current_base_dist_out_m;
1070 if(!GetBaseConstraint(current_base_dist_out_m)) {
1071 current_base_dist_out_m = nominal_base_dist_out_m;
1073 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1074 double current_dist_across_m;
1075 if(!GetDownwindConstraint(current_dist_across_m)) {
1076 current_dist_across_m = nominal_dist_across_m;
1078 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1079 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1080 //if(printout) cout << "a = " << tpr->eta << '\n';
1081 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1082 tpr->eta += dist_across_m / circuit_ias;
1083 //if(printout) cout << "b = " << tpr->eta << '\n';
1084 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1085 //if(printout) cout << "c = " << tpr->eta << '\n';
1086 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1087 if(dist_across_m > nominal_dist_across_m) {
1088 tpr->eta += dist_across_m / circuit_ias;
1090 tpr->eta += nominal_dist_across_m / circuit_ias;
1092 // should we use the dist across of the previous plane if there is previous still on downwind?
1093 //if(printout) cout << "bb = " << tpr->eta << '\n';
1094 if(dist_out_m > nominal_cross_dist_out_m) {
1095 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1097 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1099 //if(printout) cout << "cc = " << tpr->eta << '\n';
1100 if(nominal_dist_across_m > dist_across_m) {
1101 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1105 //if(printout) cout << "dd = " << tpr->eta << '\n';
1107 // We've only just started - why not use a generic estimate?
1112 // cout << "ETA = " << tpr->eta << '\n';
1120 // Calculate the distance of a plane to the threshold in meters
1121 // TODO - Modify to calculate flying distance of a plane in the circuit
1122 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1123 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1127 // Calculate the distance of a plane to the threshold in miles
1128 // TODO - Modify to calculate flying distance of a plane in the circuit
1129 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1130 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1134 // Iterate through all the lists and call CalcETA for all the planes.
1135 void FGTower::doThresholdETACalc() {
1136 //cout << "Entering doThresholdETACalc..." << endl;
1137 tower_plane_rec_list_iterator twrItr;
1138 // Do the approach list first
1139 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1140 TowerPlaneRec* tpr = *twrItr;
1143 // Then the circuit list
1144 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1145 TowerPlaneRec* tpr = *twrItr;
1148 //cout << "Done doThresholdETCCalc" << endl;
1152 // Check that the planes in traffic list are correctly ordered,
1153 // that the nearest (timewise) is flagged next on rwy, and return
1154 // true if any threshold use conflicts are detected, false otherwise.
1155 bool FGTower::doThresholdUseOrder() {
1156 //cout << "Entering doThresholdUseOrder..." << endl;
1157 bool conflict = false;
1159 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1160 // Here's the rather simplistic assumptions we're using:
1161 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1162 // In order of priority for runway use:
1163 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1164 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1165 // and holding planes until a space.
1166 // When calculating if a holding plane can use the runway, time clearance from last departure
1167 // as well as time clearance to next arrival must be considered.
1169 trafficList.clear();
1171 tower_plane_rec_list_iterator twrItr;
1172 // Do the approach list first
1173 //cout << "A" << flush;
1174 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1175 TowerPlaneRec* tpr = *twrItr;
1176 conflict = AddToTrafficList(tpr);
1178 // Then the circuit list
1179 //cout << "C" << flush;
1180 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1181 TowerPlaneRec* tpr = *twrItr;
1182 conflict = AddToTrafficList(tpr);
1184 // And finally the hold list
1185 //cout << "H" << endl;
1186 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1187 TowerPlaneRec* tpr = *twrItr;
1188 AddToTrafficList(tpr, true);
1192 //if(ident == "KEMT") {
1193 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1194 TowerPlaneRec* tpr = *twrItr;
1195 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1200 //cout << "Done doThresholdUseOrder" << endl;
1205 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1206 // i.e. list_pos = 1 implies next to use runway.
1207 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1208 if(trafficList.size() < list_pos) {
1212 tower_plane_rec_list_iterator twrItr;
1213 twrItr = trafficList.begin();
1214 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1215 TowerPlaneRec* tpr = *twrItr;
1216 CalcETA(tpr, printout);
1217 //cout << "ETA returned = " << tpr->eta << '\n';
1222 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1223 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1224 TowerPlaneRec* t = new TowerPlaneRec;
1226 t->planePtr = requestee;
1227 t->holdShortReported = true;
1228 t->clearanceCounter = 0;
1229 t->clearedToLineUp = false;
1230 t->clearedToTakeOff = false;
1231 t->opType = operation;
1233 //cout << "Hold Short reported by " << plane.callsign << '\n';
1236 bool next = AddToTrafficList(t, true);
1238 double teta = GetTrafficETA(2);
1240 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1241 //cout << "Reducing response time to request due imminent traffic\n";
1246 // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1248 holdList.push_back(t);
1250 responseReqd = true;
1253 void FGTower::RequestLandingClearance(string ID) {
1254 //cout << "Request Landing Clearance called...\n";
1256 // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1257 // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1259 TowerPlaneRec* t = new TowerPlaneRec;
1261 t->clearedToLand = false;
1262 t->pos.setlon(user_lon_node->getDoubleValue());
1263 t->pos.setlat(user_lat_node->getDoubleValue());
1264 t->pos.setelev(user_elev_node->getDoubleValue());
1267 // Calculate where the user is in relation to the active runway and it's circuit
1268 // and set the op-type as appropriate.
1270 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1271 t->opType = STRAIGHT_IN;
1273 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1274 t->plane.callsign = ID;
1276 appList.push_back(t); // Not necessarily permanent
1277 AddToTrafficList(t);
1280 void FGTower::RequestDepartureClearance(string ID) {
1281 //cout << "Request Departure Clearance called...\n";
1283 //void FGTower::ReportFinal(string ID);
1284 //void FGTower::ReportLongFinal(string ID);
1285 //void FGTower::ReportOuterMarker(string ID);
1286 //void FGTower::ReportMiddleMarker(string ID);
1287 //void FGTower::ReportInnerMarker(string ID);
1288 //void FGTower::ReportGoingAround(string ID);
1289 void FGTower::ReportRunwayVacated(string ID) {
1290 //cout << "Report Runway Vacated Called...\n";
1293 TowerPlaneRec* FGTower::FindPlane(string ID) {
1294 tower_plane_rec_list_iterator twrItr;
1295 // Do the approach list first
1296 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1297 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1299 // Then the circuit list
1300 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1301 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1303 // And finally the hold list
1304 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1305 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1307 SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
1311 void FGTower::ReportDownwind(string ID) {
1312 //cout << "ReportDownwind(...) called\n";
1313 // Tell the plane reporting what number she is in the circuit
1314 TowerPlaneRec* t = FindPlane(ID);
1316 t->downwindReported = true;
1317 responseReqd = true;
1319 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
1323 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1325 case(CIRCUIT): return(os << "CIRCUIT");
1326 case(INBOUND): return(os << "INBOUND");
1327 case(OUTBOUND): return(os << "OUTBOUND");
1328 case(TTT_UNKNOWN): return(os << "UNKNOWN");
1329 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
1331 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");