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;
413 } else if(t->finalReported && !(t->finalAcknowledged)) {
414 string trns = t->plane.callsign;
415 if(t->nextOnRwy && !rwyOccupied) {
416 if(t->landingType == FULL_STOP) {
417 trns += " cleared to land ";
419 trns += " cleared for the option ";
422 t->clearedToLand = true;
424 trns += " continue approach";
425 t->clearedToLand = false;
428 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
430 t->finalAcknowledged = true;
433 freqClear = true; // FIXME - set this to come true after enough time to render the message
434 //cout << "Done Respond" << endl;
437 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land -
438 // this should be done prior to calling this function.
439 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
440 //cout << "Entering ClearHoldingPlane..." << endl;
442 string trns = t->plane.callsign;
443 //if(departed plane < some threshold in time away) {
445 //if(timeSinceLastDeparture <= 60.0 && departed == true) {
447 t->clearedToLineUp = true;
448 t->planePtr->RegisterTransmission(3); // cleared to line-up
449 //} else if(arriving plane < some threshold away) {
450 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
451 trns += " cleared immediate take-off";
452 if(trafficList.size()) {
453 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
454 trfcItr++; // At the moment the holding plane should be first in trafficList.
455 // Note though that this will break if holding planes aren't put in trafficList in the future.
456 TowerPlaneRec* trfc = *trfcItr;
457 trns += "... traffic is";
458 switch(trfc->plane.type) {
462 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
468 trns += " a King-air";
471 trns += " a Learjet";
474 trns += " a Regional";
483 //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
484 if(trfc->opType == STRAIGHT_IN) {
485 double miles_out = CalcDistOutMiles(trfc);
490 trns += ConvertNumToSpokenDigits((int)miles_out);
491 trns += " mile final";
493 } else if(trfc->opType == CIRCUIT) {
494 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
500 trns += " turning final";
506 trns += " turning base";
509 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.
511 // And to eliminate compiler warnings...
512 case TAKEOFF_ROLL: break;
513 case CLIMBOUT: break;
515 case CROSSWIND: break;
517 case LANDING_ROLL: break;
518 case LEG_UNKNOWN: break;
522 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
523 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
525 t->clearedToTakeOff = true;
526 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
528 timeSinceLastDeparture = 0.0;
530 //} else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
531 trns += " cleared for take-off";
532 // TODO - add traffic is... ?
533 t->clearedToTakeOff = true;
534 t->planePtr->RegisterTransmission(4); // cleared to take-off
536 timeSinceLastDeparture = 0.0;
539 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
541 //cout << "Done ClearHoldingPlane " << endl;
544 // Do one plane from the hold list
545 void FGTower::CheckHoldList(double dt) {
546 //cout << "Entering CheckHoldList..." << endl;
547 if(holdList.size()) {
548 //cout << "*holdListItr = " << *holdListItr << endl;
549 if(holdListItr == holdList.end()) {
550 holdListItr = holdList.begin();
552 //cout << "*holdListItr = " << *holdListItr << endl;
553 //Process(*holdListItr);
554 TowerPlaneRec* t = *holdListItr;
555 //cout << "t = " << t << endl;
556 if(t->holdShortReported) {
557 // NO-OP - leave it to the response handler.
558 } else { // not responding to report, but still need to clear if clear
560 //cout << "departed = " << departed << '\n';
561 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
564 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
565 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
567 ClearHoldingPlane(t);
568 t->leg = TAKEOFF_ROLL;
569 rwyList.push_back(t);
571 holdList.erase(holdListItr);
572 holdListItr = holdList.begin();
575 // TODO - rationalise the considerable code duplication above!
579 //cout << "Done CheckHoldList" << endl;
582 // do the ciruit list
583 void FGTower::CheckCircuitList(double dt) {
584 //cout << "Entering CheckCircuitList..." << endl;
585 // Clear the constraints - we recalculate here.
587 downwind_leg_pos = 0.0;
588 crosswind_leg_pos = 0.0;
590 if(circuitList.size()) { // Do one plane from the circuit
591 if(circuitListItr == circuitList.end()) {
592 circuitListItr = circuitList.begin();
594 TowerPlaneRec* t = *circuitListItr;
596 t->pos.setlon(user_lon_node->getDoubleValue());
597 t->pos.setlat(user_lat_node->getDoubleValue());
598 t->pos.setelev(user_elev_node->getDoubleValue());
600 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.
601 t->landingType = t->planePtr->GetLandingOption();
602 //cout << "AI plane landing option is " << t->landingType << '\n';
604 Point3D tortho = ortho.ConvertToLocal(t->pos);
606 // Need to figure out which leg he's on
607 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
608 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
609 //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
610 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
611 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
613 // could be either takeoff, climbout or landing - check orthopos.y
614 //cout << "tortho.y = " << tortho.y() << '\n';
615 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
619 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
620 //cout << "Climbout\n";
621 // If it's the user we may be unsure of his/her intentions.
622 // (Hopefully the AI planes won't try confusing the sim!!!)
623 if(t->opType == TTT_UNKNOWN) {
624 if(tortho.y() > 5000) {
625 // 5 km out from threshold - assume it's a departure
626 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
627 // Since we are unknown operation we should be in depList already.
628 circuitList.erase(circuitListItr);
629 RemoveFromTrafficList(t->plane.callsign);
630 circuitListItr = circuitList.begin();
632 } else if(t->opType == CIRCUIT) {
633 if(tortho.y() > 10000) {
634 // 10 km out - assume the user has abandoned the circuit!!
635 t->opType = OUTBOUND;
636 depList.push_back(t);
637 circuitList.erase(circuitListItr);
638 circuitListItr = circuitList.begin();
642 } else if(abs(ho) < 60) {
644 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
645 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
652 } else if(abs(ho) < 120) {
654 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
655 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
657 //cout << "Crosswind\n";
662 } else if(abs(ho) < 150) {
664 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
665 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
670 // Probably safe now to assume the user is flying a circuit
677 //cout << "Downwind\n";
679 if(t->leg == FINAL) {
680 if(OnActiveRunway(t->pos)) {
681 t->leg = LANDING_ROLL;
685 t->leg = t->planePtr->GetLeg();
688 // Set the constraints IF this is the first plane in the circuit
689 // 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!!
690 if(circuitListItr == circuitList.begin()) {
693 // 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.
694 base_leg_pos = tortho.y();
695 //cout << "base_leg_pos = " << base_leg_pos << '\n';
698 // Fall through to base
700 base_leg_pos = tortho.y();
701 //cout << "base_leg_pos = " << base_leg_pos << '\n';
704 // Fall through to downwind
706 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
707 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
708 //cout << "base_leg_pos = " << base_leg_pos;
709 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
710 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
713 // Fall through to crosswind
715 crosswind_leg_pos = tortho.y();
716 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
719 // Fall through to climbout
721 // Only use current by constraint as largest
722 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
723 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
736 if(t->leg == FINAL) {
737 if(t->landingType == FULL_STOP) t->opType = INBOUND;
738 } else if(t->leg == LANDING_ROLL) {
739 rwyList.push_front(t);
740 // TODO - if(!clearedToLand) shout something!!
741 t->clearedToLand = false;
742 RemoveFromTrafficList(t->plane.callsign);
744 t->opType = TTT_UNKNOWN;
745 } // TODO - allow the user to specify opType via ATC menu
746 circuitListItr = circuitList.erase(circuitListItr);
747 if(circuitListItr == circuitList.end() ) {
748 circuitListItr = circuitList.begin();
753 //cout << "Done CheckCircuitList" << endl;
756 // 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!!
757 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
758 // (However, at the moment there should only be one airplane on the rwy at once, until we
759 // start allowing planes to line up whilst previous arrival clears the rwy.)
760 void FGTower::CheckRunwayList(double dt) {
761 //cout << "Entering CheckRunwayList..." << endl;
763 if(!rwyList.size()) {
766 rwyListItr = rwyList.begin();
767 TowerPlaneRec* t = *rwyListItr;
769 t->pos.setlon(user_lon_node->getDoubleValue());
770 t->pos.setlat(user_lat_node->getDoubleValue());
771 t->pos.setelev(user_elev_node->getDoubleValue());
773 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.
775 bool on_rwy = OnActiveRunway(t->pos);
777 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
780 // TODO - tell it to taxi / contact ground / don't delete it etc!
781 } else if(t->opType == OUTBOUND) {
782 depList.push_back(t);
785 timeSinceLastDeparture = 0.0;
786 } else if(t->opType == CIRCUIT) {
787 circuitList.push_back(t);
791 timeSinceLastDeparture = 0.0;
792 } else if(t->opType == TTT_UNKNOWN) {
793 depList.push_back(t);
794 circuitList.push_back(t);
798 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.
800 // HELP - we shouldn't ever get here!!!
805 //cout << "Done CheckRunwayList" << endl;
808 // Do one plane from the approach list
809 void FGTower::CheckApproachList(double dt) {
811 if(appListItr == appList.end()) {
812 appListItr = appList.begin();
814 TowerPlaneRec* t = *appListItr;
815 //cout << "t = " << t << endl;
817 t->pos.setlon(user_lon_node->getDoubleValue());
818 t->pos.setlat(user_lat_node->getDoubleValue());
819 t->pos.setelev(user_elev_node->getDoubleValue());
821 // TODO - set/update the position if it's an AI plane
823 if(t->nextOnRwy && !(t->clearedToLand)) {
824 // check distance away and whether runway occupied
825 // and schedule transmission if necessary
831 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
832 // plus the constraint position as a rwy orientated orthopos (meters)
833 bool FGTower::GetCrosswindConstraint(double& cpos) {
834 if(crosswind_leg_pos != 0.0) {
835 cpos = crosswind_leg_pos;
842 bool FGTower::GetDownwindConstraint(double& dpos) {
843 if(downwind_leg_pos != 0.0) {
844 dpos = downwind_leg_pos;
851 bool FGTower::GetBaseConstraint(double& bpos) {
852 if(base_leg_pos != 0.0) {
862 // Figure out which runways are active.
863 // For now we'll just be simple and do one active runway - eventually this will get much more complex
864 // This is a private function - public interface to the results of this is through GetActiveRunway
865 void FGTower::DoRwyDetails() {
866 //cout << "GetRwyDetails called" << endl;
868 // Based on the airport-id and wind get the active runway
871 double hdg = wind_from_hdg->getDoubleValue();
872 double speed = wind_speed_knots->getDoubleValue();
873 hdg = (speed == 0.0 ? 270.0 : hdg);
874 //cout << "Heading = " << hdg << '\n';
877 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
879 activeRwy = runway.rwy_no;
880 rwy.rwyID = runway.rwy_no;
881 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
883 // Get the threshold position
884 double other_way = runway.heading - 180.0;
885 while(other_way <= 0.0) {
888 // move to the +l end/center of the runway
889 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
890 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
891 Point3D ref = origin;
892 double tshlon, tshlat, tshr;
893 double tolon, tolat, tor;
894 rwy.length = runway.length * SG_FEET_TO_METER;
895 rwy.width = runway.width * SG_FEET_TO_METER;
896 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
897 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
898 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
899 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
900 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
901 // now copy what we need out of runway into rwy
902 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
903 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
904 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
905 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
906 rwy.hdg = runway.heading;
907 // Set the projection for the local area based on this active runway
908 ortho.Init(rwy.threshold_pos, rwy.hdg);
909 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
910 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
912 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
918 // Figure out if a given position lies on the active runway
919 // Might have to change when we consider more than one active rwy.
920 bool FGTower::OnActiveRunway(Point3D pt) {
921 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
922 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
923 Point3D xyp = ortho.ConvertToLocal(pt);
925 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
926 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
928 double rlen = rwy.length/2.0 + 5.0;
929 double rwidth = rwy.width/2.0;
930 double ldiff = fabs(xyp.y() - xyc.y());
931 double wdiff = fabs(xyp.x() - xyc.x());
933 return((ldiff < rlen) && (wdiff < rwidth));
937 // Figure out if a given position lies on any runway or not
938 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
939 bool FGTower::OnAnyRunway(Point3D pt) {
941 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
945 // Based on the airport-id, go through all the runways and check for a point in them
947 // TODO - do we actually need to search for the airport - surely we already know our ident and
948 // can just search runways of our airport???
949 //cout << "Airport ident is " << ad.ident << '\n';
951 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
953 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
956 while(runway.id == ad.ident) {
957 on = OnRunway(pt, runway);
958 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
960 globals->get_runways()->next(&runway);
966 // Returns true if successful
967 bool FGTower::RemoveFromTrafficList(string id) {
968 tower_plane_rec_list_iterator twrItr;
969 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
970 TowerPlaneRec* tpr = *twrItr;
971 if(tpr->plane.callsign == id) {
972 trafficList.erase(twrItr);
976 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
981 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
982 // and set nextOnRwy if so.
983 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
984 // For planes holding they are put in the first position with time to go, and the return value is
985 // true if in the first position (nextOnRwy) and false otherwise.
986 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
987 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
988 //cout << "ADD: " << trafficList.size();
989 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
990 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.
991 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
992 bool conflict = false;
993 double lastETA = 0.0;
994 bool firstTime = true;
995 // FIXME - make this more robust for different plane types eg. light following heavy.
996 tower_plane_rec_list_iterator twrItr;
997 //twrItr = trafficList.begin();
999 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1000 //if(twrItr == trafficList.end()) {
1002 // trafficList.push_back(t);
1003 // return(holding ? firstTime : conflict);
1005 TowerPlaneRec* tpr = *twrItr;
1007 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1008 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1009 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
1010 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1011 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1012 // and if not needs time to clear the rwy anyway.
1013 if(tpr->eta - lastETA > slot_time) {
1014 t->nextOnRwy = firstTime;
1015 trafficList.insert(twrItr, t);
1016 //cout << "\tH\t" << trafficList.size() << '\n';
1021 if(t->eta < tpr->eta) {
1022 // Ugg - this one's tricky.
1023 // It depends on what the two planes are doing and whether there's a conflict what we do.
1024 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1025 if(tpr->nextOnRwy) {
1026 tpr->nextOnRwy = false;
1027 t->nextOnRwy = true;
1029 trafficList.insert(twrItr, t);
1030 } else { // Ooops - this ones tricky - we have a potential conflict!
1032 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1033 if(tpr->nextOnRwy) {
1034 tpr->nextOnRwy = false;
1035 t->nextOnRwy = true;
1037 trafficList.insert(twrItr, t);
1039 //cout << "\tC\t" << trafficList.size() << '\n';
1046 // If we get here we must be at the end of the list, or maybe the list is empty.
1047 if(!trafficList.size()) {
1048 t->nextOnRwy = true;
1049 // conflict and firstTime should be false and true respectively in this case anyway.
1051 trafficList.push_back(t);
1052 //cout << "\tE\t" << trafficList.size() << endl;
1053 return(holding ? firstTime : conflict);
1057 // Calculate the eta of a plane to the threshold.
1058 // For ground traffic this is the fastest they can get there.
1059 // For air traffic this is the middle approximation.
1060 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1061 // For now we'll be very crude and hardwire expected speeds to C172-like values
1062 // The speeds below are specified in knots IAS and then converted to m/s
1063 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
1064 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
1065 double final_ias = 70.0 * 0.514444; // Speed during final approach
1068 //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1069 //cout << (tpr->isUser ? "USER\n" : "AI\n");
1073 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1074 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1076 Point3D op = ortho.ConvertToLocal(tpr->pos);
1078 // cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1079 // cout << "opType is " << tpr->opType << '\n';
1081 double dist_out_m = op.y();
1082 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
1083 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1085 if(tpr->opType == STRAIGHT_IN) {
1086 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1087 if(dist_to_go_m < 1000) {
1088 tpr->eta = dist_to_go_m / final_ias;
1090 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1092 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1093 // It's complicated - depends on if base leg is delayed or not
1095 // cout << "Leg = " << tpr->leg << '\n';
1097 if(tpr->leg == LANDING_ROLL) {
1099 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1100 tpr->eta = fabs(dist_out_m) / final_ias;
1101 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1102 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1104 // Need to calculate where base leg is likely to be
1105 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1106 // 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
1107 double nominal_base_dist_out_m = -1000;
1108 double current_base_dist_out_m;
1109 if(!GetBaseConstraint(current_base_dist_out_m)) {
1110 current_base_dist_out_m = nominal_base_dist_out_m;
1112 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1113 double current_dist_across_m;
1114 if(!GetDownwindConstraint(current_dist_across_m)) {
1115 current_dist_across_m = nominal_dist_across_m;
1117 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1118 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1119 //if(printout) cout << "a = " << tpr->eta << '\n';
1120 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1121 tpr->eta += dist_across_m / circuit_ias;
1122 //if(printout) cout << "b = " << tpr->eta << '\n';
1123 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1124 //if(printout) cout << "c = " << tpr->eta << '\n';
1125 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1126 if(dist_across_m > nominal_dist_across_m) {
1127 tpr->eta += dist_across_m / circuit_ias;
1129 tpr->eta += nominal_dist_across_m / circuit_ias;
1131 // should we use the dist across of the previous plane if there is previous still on downwind?
1132 //if(printout) cout << "bb = " << tpr->eta << '\n';
1133 if(dist_out_m > nominal_cross_dist_out_m) {
1134 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1136 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1138 //if(printout) cout << "cc = " << tpr->eta << '\n';
1139 if(nominal_dist_across_m > dist_across_m) {
1140 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1144 //if(printout) cout << "dd = " << tpr->eta << '\n';
1146 // We've only just started - why not use a generic estimate?
1151 // cout << "ETA = " << tpr->eta << '\n';
1159 // Calculate the distance of a plane to the threshold in meters
1160 // TODO - Modify to calculate flying distance of a plane in the circuit
1161 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1162 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1166 // Calculate the distance of a plane to the threshold in miles
1167 // TODO - Modify to calculate flying distance of a plane in the circuit
1168 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1169 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1173 // Iterate through all the lists and call CalcETA for all the planes.
1174 void FGTower::doThresholdETACalc() {
1175 //cout << "Entering doThresholdETACalc..." << endl;
1176 tower_plane_rec_list_iterator twrItr;
1177 // Do the approach list first
1178 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1179 TowerPlaneRec* tpr = *twrItr;
1182 // Then the circuit list
1183 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1184 TowerPlaneRec* tpr = *twrItr;
1187 //cout << "Done doThresholdETCCalc" << endl;
1191 // Check that the planes in traffic list are correctly ordered,
1192 // that the nearest (timewise) is flagged next on rwy, and return
1193 // true if any threshold use conflicts are detected, false otherwise.
1194 bool FGTower::doThresholdUseOrder() {
1195 //cout << "Entering doThresholdUseOrder..." << endl;
1196 bool conflict = false;
1198 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1199 // Here's the rather simplistic assumptions we're using:
1200 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1201 // In order of priority for runway use:
1202 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1203 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1204 // and holding planes until a space.
1205 // When calculating if a holding plane can use the runway, time clearance from last departure
1206 // as well as time clearance to next arrival must be considered.
1208 trafficList.clear();
1210 tower_plane_rec_list_iterator twrItr;
1211 // Do the approach list first
1212 //cout << "A" << flush;
1213 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1214 TowerPlaneRec* tpr = *twrItr;
1215 conflict = AddToTrafficList(tpr);
1217 // Then the circuit list
1218 //cout << "C" << flush;
1219 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1220 TowerPlaneRec* tpr = *twrItr;
1221 conflict = AddToTrafficList(tpr);
1223 // And finally the hold list
1224 //cout << "H" << endl;
1225 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1226 TowerPlaneRec* tpr = *twrItr;
1227 AddToTrafficList(tpr, true);
1231 //if(ident == "KEMT") {
1232 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1233 TowerPlaneRec* tpr = *twrItr;
1234 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1239 //cout << "Done doThresholdUseOrder" << endl;
1244 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1245 // i.e. list_pos = 1 implies next to use runway.
1246 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1247 if(trafficList.size() < list_pos) {
1251 tower_plane_rec_list_iterator twrItr;
1252 twrItr = trafficList.begin();
1253 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1254 TowerPlaneRec* tpr = *twrItr;
1255 CalcETA(tpr, printout);
1256 //cout << "ETA returned = " << tpr->eta << '\n';
1261 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1262 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1263 TowerPlaneRec* t = new TowerPlaneRec;
1265 t->planePtr = requestee;
1266 t->holdShortReported = true;
1267 t->clearedToLineUp = false;
1268 t->clearedToTakeOff = false;
1269 t->opType = operation;
1271 //cout << "Hold Short reported by " << plane.callsign << '\n';
1274 bool next = AddToTrafficList(t, true);
1276 double teta = GetTrafficETA(2);
1278 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1279 //cout << "Reducing response time to request due imminent traffic\n";
1284 // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1286 holdList.push_back(t);
1288 responseReqd = true;
1291 void FGTower::RequestLandingClearance(string ID) {
1292 //cout << "Request Landing Clearance called...\n";
1294 // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1295 // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1297 TowerPlaneRec* t = new TowerPlaneRec;
1299 t->clearedToLand = false;
1300 t->pos.setlon(user_lon_node->getDoubleValue());
1301 t->pos.setlat(user_lat_node->getDoubleValue());
1302 t->pos.setelev(user_elev_node->getDoubleValue());
1305 // Calculate where the user is in relation to the active runway and it's circuit
1306 // and set the op-type as appropriate.
1308 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1309 t->opType = STRAIGHT_IN;
1311 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1312 t->plane.callsign = ID;
1314 appList.push_back(t); // Not necessarily permanent
1315 AddToTrafficList(t);
1318 void FGTower::RequestDepartureClearance(string ID) {
1319 //cout << "Request Departure Clearance called...\n";
1322 void FGTower::ReportFinal(string ID) {
1323 TowerPlaneRec* t = FindPlane(ID);
1325 t->finalReported = true;
1326 t->finalAcknowledged = false;
1327 if(!(t->clearedToLand)) {
1328 responseReqd = true;
1329 } // possibly respond with wind even if already cleared to land?
1331 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
1335 //void FGTower::ReportLongFinal(string ID);
1336 //void FGTower::ReportOuterMarker(string ID);
1337 //void FGTower::ReportMiddleMarker(string ID);
1338 //void FGTower::ReportInnerMarker(string ID);
1339 //void FGTower::ReportGoingAround(string ID);
1341 void FGTower::ReportRunwayVacated(string ID) {
1342 //cout << "Report Runway Vacated Called...\n";
1345 TowerPlaneRec* FGTower::FindPlane(string ID) {
1346 tower_plane_rec_list_iterator twrItr;
1347 // Do the approach list first
1348 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1349 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1351 // Then the circuit list
1352 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1353 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1355 // And finally the hold list
1356 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1357 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1359 SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
1363 void FGTower::ReportDownwind(string ID) {
1364 //cout << "ReportDownwind(...) called\n";
1365 // Tell the plane reporting what number she is in the circuit
1366 TowerPlaneRec* t = FindPlane(ID);
1368 t->downwindReported = true;
1369 responseReqd = true;
1371 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
1375 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1377 case(CIRCUIT): return(os << "CIRCUIT");
1378 case(INBOUND): return(os << "INBOUND");
1379 case(OUTBOUND): return(os << "OUTBOUND");
1380 case(TTT_UNKNOWN): return(os << "UNKNOWN");
1381 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
1383 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");