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 longFinalReported(false),
43 longFinalAcknowledged(false),
45 finalAcknowledged(false),
50 landingType(AIP_LT_UNKNOWN),
53 plane.callsign = "UNKNOWN";
56 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
58 clearedToLineUp(false),
59 clearedToTakeOff(false),
60 holdShortReported(false),
61 longFinalReported(false),
62 longFinalAcknowledged(false),
64 finalAcknowledged(false),
69 landingType(AIP_LT_UNKNOWN),
75 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
77 clearedToLineUp(false),
78 clearedToTakeOff(false),
79 holdShortReported(false),
80 longFinalReported(false),
81 longFinalAcknowledged(false),
83 finalAcknowledged(false),
88 landingType(AIP_LT_UNKNOWN),
91 plane.callsign = "UNKNOWN";
95 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
97 clearedToLineUp(false),
98 clearedToTakeOff(false),
99 holdShortReported(false),
100 longFinalReported(false),
101 longFinalAcknowledged(false),
102 finalReported(false),
103 finalAcknowledged(false),
108 landingType(AIP_LT_UNKNOWN),
119 ATCmgr = globals->get_ATC_mgr();
121 // Init the property nodes - TODO - need to make sure we're getting surface winds.
122 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
123 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
126 update_count_max = 15;
128 holdListItr = holdList.begin();
129 appListItr = appList.begin();
130 depListItr = depList.begin();
131 rwyListItr = rwyList.begin();
132 circuitListItr = circuitList.begin();
133 trafficListItr = trafficList.begin();
137 timeSinceLastDeparture = 9999;
141 FGTower::~FGTower() {
142 if(!separateGround) {
147 void FGTower::Init() {
150 // Pointers to user's position
151 user_lon_node = fgGetNode("/position/longitude-deg", true);
152 user_lat_node = fgGetNode("/position/latitude-deg", true);
153 user_elev_node = fgGetNode("/position/altitude-ft", true);
154 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
156 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
157 // I'll punt the startup issue for now though!!!
160 // Setup the ground control at this airport
162 //cout << "Tower ident = " << ident << '\n';
163 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
164 if(a.ground_freq) { // Ground control
165 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
166 separateGround = true;
168 // Something has gone wrong :-(
169 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
170 ground = new FGGround(ident);
171 separateGround = false;
174 ground->SetDisplay();
176 ground->SetNoDisplay();
180 // Initialise ground anyway to do the shortest path stuff!
181 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
182 ground = new FGGround(ident);
183 separateGround = false;
186 ground->SetDisplay();
188 ground->SetNoDisplay();
192 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
193 // Initialise ground anyway to avoid segfault later
194 ground = new FGGround(ident);
195 separateGround = false;
198 ground->SetDisplay();
200 ground->SetNoDisplay();
204 // Get the airport elevation
205 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
209 // FIXME - this currently assumes use of the active rwy by the user.
210 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
212 // Assume the user is started at the threshold ready to take-off
213 TowerPlaneRec* t = new TowerPlaneRec;
214 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
215 t->plane.type = GA_SINGLE;
216 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
217 t->landingType = AIP_LT_UNKNOWN;
218 t->leg = TAKEOFF_ROLL;
221 t->clearedToTakeOff = true;
222 rwyList.push_back(t);
227 void FGTower::Update(double dt) {
228 //cout << "T" << flush;
229 // Each time step, what do we need to do?
230 // We need to go through the list of outstanding requests and acknowedgements
231 // and process at least one of them.
232 // We need to go through the list of planes under our control and check if
233 // any need to be addressed.
234 // We need to check for planes not under our control coming within our
235 // control area and address if necessary.
237 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
239 // Sort the arriving planes
242 if(ident == "KEMT") {
243 cout << update_count << "\ttL: " << trafficList.size() << " cL: " << circuitList.size() << " hL: " << holdList.size() << " aL: " << appList.size() << '\n';
247 if(departed != false) {
248 timeSinceLastDeparture += dt;
249 //if(ident == "KEMT")
250 // cout << " dt = " << dt << " timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
253 // Calculate the eta of each plane to the threshold.
254 // For ground traffic this is the fastest they can get there.
255 // For air traffic this is the middle approximation.
256 if(update_count == 1) {
257 doThresholdETACalc();
260 // Order the list of traffic as per expected threshold use and flag any conflicts
261 if(update_count == 2) {
262 //bool conflicts = doThresholdUseOrder();
263 doThresholdUseOrder();
266 // sortConficts() !!!
268 // Do one plane from the hold list
269 if(update_count == 4) {
271 if(holdList.size()) {
272 //cout << "*holdListItr = " << *holdListItr << endl;
273 if(holdListItr == holdList.end()) {
274 holdListItr = holdList.begin();
276 //cout << "*holdListItr = " << *holdListItr << endl;
277 //Process(*holdListItr);
278 TowerPlaneRec* t = *holdListItr;
279 //cout << "t = " << t << endl;
280 if(t->holdShortReported) {
282 double responseTime = 10.0; // seconds - this should get more sophisticated at some point
283 if(t->clearanceCounter > responseTime) {
285 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!!)
286 // Do nothing for now - consider acknowloging hold short eventually
289 string trns = t->plane.callsign;
290 //if(departed plane < some threshold in time away) {
293 t->clearedToLineUp = true;
294 t->planePtr->RegisterTransmission(3); // cleared to line-up
295 t->leg = TAKEOFF_ROLL;
296 //} else if(arriving plane < some threshold away) {
297 } else if(GetTrafficETA(2) < 150.0) {
298 trns += " cleared immediate take-off";
299 if(trafficList.size()) {
300 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
301 trfcItr++; // At the moment the holding plane should be first in trafficList.
302 // Note though that this will break if holding planes aren't put in trafficList in the future.
303 TowerPlaneRec* trfc = *trfcItr;
304 trns += "... traffic is";
305 switch(trfc->plane.type) {
309 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
315 trns += " a King-air";
318 trns += " a Learjet";
321 trns += " a Regional";
330 if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
331 double miles_out = CalcDistOutMiles(trfc);
336 trns += ConvertNumToSpokenDigits((int)miles_out);
337 trns += " mile final";
339 } else if(trfc->opType == CIRCUIT) {
345 trns += " turning final";
351 trns += " turning base";
354 trns += " in circuit";
356 // And to eliminate compiler warnings...
357 case TAKEOFF_ROLL: break;
358 case CLIMBOUT: break;
360 case CROSSWIND: break;
362 case LANDING_ROLL: break;
363 case LEG_UNKNOWN: break;
367 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
368 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
370 t->clearedToTakeOff = true;
371 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
372 t->leg = TAKEOFF_ROLL;
374 timeSinceLastDeparture = 0.0;
376 trns += " cleared for take-off";
377 // TODO - add traffic is... ?
378 t->clearedToTakeOff = true;
379 t->planePtr->RegisterTransmission(4); // cleared to take-off
380 t->leg = TAKEOFF_ROLL;
382 timeSinceLastDeparture = 0.0;
385 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
387 t->holdShortReported = false;
388 t->clearanceCounter = 0;
389 rwyList.push_back(t);
391 holdList.erase(holdListItr);
392 holdListItr = holdList.begin();
395 // Tell him to hold and what position he is.
396 // Not currently sure under which circumstances we do or don't bother transmitting this.
397 string trns = t->plane.callsign;
398 trns += " hold position";
400 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
402 t->holdShortReported = false;
403 t->clearanceCounter = 0;
404 // TODO - add some idea of what traffic is blocking him.
407 t->clearanceCounter += (dt * holdList.size() * update_count_max);
409 } else { // not responding to report, but still need to clear if clear
412 //cout << "departed = " << departed << '\n';
413 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
415 // Do nothing for now - consider acknowloging hold short eventually
416 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
417 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
420 string trns = t->plane.callsign;
421 //cout << "******************* squaggle\n";
422 //cout << "departed = " << departed << '\n';
423 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
424 //if(departed plane < some threshold in time away) {
428 t->clearedToLineUp = true;
429 t->planePtr->RegisterTransmission(3); // cleared to line-up
430 t->leg = TAKEOFF_ROLL;
431 //} else if(arriving plane < some threshold away) {
432 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
434 trns += " cleared immediate take-off";
435 // TODO - add traffic is... ?
436 t->clearedToTakeOff = true;
437 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
438 t->leg = TAKEOFF_ROLL;
440 timeSinceLastDeparture = 0.0;
441 } else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
443 trns += " cleared for take-off";
444 // TODO - add traffic is... ?
445 t->clearedToTakeOff = true;
446 t->planePtr->RegisterTransmission(4); // cleared to take-off
447 t->leg = TAKEOFF_ROLL;
449 timeSinceLastDeparture = 0.0;
454 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
456 rwyList.push_back(t);
458 holdList.erase(holdListItr);
459 holdListItr = holdList.begin();
462 // TODO - rationalise the considerable code duplication above!
468 // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
475 // 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!!
476 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
477 // (However, at the moment there should only be one airplane on the rwy at once, until we
478 // start allowing planes to line up whilst previous arrival clears the rwy.)
479 if(update_count == 5) {
481 if(!rwyList.size()) {
484 rwyListItr = rwyList.begin();
485 TowerPlaneRec* t = *rwyListItr;
487 t->pos.setlon(user_lon_node->getDoubleValue());
488 t->pos.setlat(user_lat_node->getDoubleValue());
489 t->pos.setelev(user_elev_node->getDoubleValue());
491 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.
493 bool on_rwy = OnActiveRunway(t->pos);
495 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
498 // TODO - tell it to taxi / contact ground / don't delete it etc!
499 } else if(t->opType == OUTBOUND) {
500 depList.push_back(t);
503 timeSinceLastDeparture = 0.0;
504 } else if(t->opType == CIRCUIT) {
505 circuitList.push_back(t);
509 timeSinceLastDeparture = 0.0;
510 } else if(t->opType == TTT_UNKNOWN) {
511 depList.push_back(t);
512 circuitList.push_back(t);
516 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.
518 // HELP - we shouldn't ever get here!!!
525 // do the ciruit list
526 if(update_count == 6) {
527 // Clear the constraints - we recalculate here.
529 downwind_leg_pos = 0.0;
530 crosswind_leg_pos = 0.0;
532 if(circuitList.size()) { // Do one plane from the circuit
533 if(circuitListItr == circuitList.end()) {
534 circuitListItr = circuitList.begin();
536 TowerPlaneRec* t = *circuitListItr;
538 t->pos.setlon(user_lon_node->getDoubleValue());
539 t->pos.setlat(user_lat_node->getDoubleValue());
540 t->pos.setelev(user_elev_node->getDoubleValue());
542 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.
543 t->landingType = t->planePtr->GetLandingOption();
544 //cout << "AI plane landing option is " << t->landingType << '\n';
546 Point3D tortho = ortho.ConvertToLocal(t->pos);
548 // Need to figure out which leg he's on
549 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
550 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
551 //cout << " ho = " << ho << '\n';
552 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
553 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
555 // could be either takeoff, climbout or landing - check orthopos.y
556 //cout << "tortho.y = " << tortho.y() << '\n';
557 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
561 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
562 //cout << "Climbout\n";
563 // If it's the user we may be unsure of his/her intentions.
564 // (Hopefully the AI planes won't try confusing the sim!!!)
565 if(t->opType == TTT_UNKNOWN) {
566 if(tortho.y() > 5000) {
567 // 5 km out from threshold - assume it's a departure
568 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
569 // Since we are unknown operation we should be in depList already.
570 circuitList.erase(circuitListItr);
571 RemoveFromTrafficList(t->plane.callsign);
572 circuitListItr = circuitList.begin();
574 } else if(t->opType == CIRCUIT) {
575 if(tortho.y() > 10000) {
576 // 10 km out - assume the user has abandoned the circuit!!
577 t->opType = OUTBOUND;
578 depList.push_back(t);
579 circuitList.erase(circuitListItr);
580 circuitListItr = circuitList.begin();
584 } else if(abs(ho) < 60) {
586 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
587 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
594 } else if(abs(ho) < 120) {
596 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
597 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
599 //cout << "Crosswind\n";
604 } else if(abs(ho) < 150) {
606 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
607 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
612 // Probably safe now to assume the user is flying a circuit
619 //cout << "Downwind\n";
621 if(t->leg == FINAL) {
622 if(OnActiveRunway(t->pos)) {
623 t->leg = LANDING_ROLL;
627 t->leg = t->planePtr->GetLeg();
630 // Set the constraints IF this is the first plane in the circuit
631 // 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!!
632 if(circuitListItr == circuitList.begin()) {
635 // 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.
636 base_leg_pos = tortho.y();
637 //cout << "base_leg_pos = " << base_leg_pos << '\n';
640 // Fall through to base
642 base_leg_pos = tortho.y();
643 //cout << "base_leg_pos = " << base_leg_pos << '\n';
646 // Fall through to downwind
648 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
649 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
650 //cout << "base_leg_pos = " << base_leg_pos;
651 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
652 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
655 // Fall through to crosswind
657 crosswind_leg_pos = tortho.y();
658 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
661 // Fall through to climbout
663 // Only use current by constraint as largest
664 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
665 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
678 if(t->leg == FINAL) {
679 if(t->landingType == FULL_STOP) t->opType = INBOUND;
680 } else if(t->leg == LANDING_ROLL) {
681 rwyList.push_front(t);
682 RemoveFromTrafficList(t->plane.callsign);
684 t->opType = TTT_UNKNOWN;
685 } // TODO - allow the user to specify opType via ATC menu
686 circuitListItr = circuitList.erase(circuitListItr);
687 if(circuitListItr == circuitList.end() ) {
688 circuitListItr = circuitList.begin();
695 // Do one plane from the approach list
696 if(update_count == 7) {
698 if(appListItr == appList.end()) {
699 appListItr = appList.begin();
701 TowerPlaneRec* t = *appListItr;
702 //cout << "t = " << t << endl;
704 t->pos.setlon(user_lon_node->getDoubleValue());
705 t->pos.setlat(user_lat_node->getDoubleValue());
706 t->pos.setelev(user_elev_node->getDoubleValue());
708 // TODO - set/update the position if it's an AI plane
710 if(t->nextOnRwy && !(t->clearedToLand)) {
711 // check distance away and whether runway occupied
712 // and schedule transmission if necessary
718 // TODO - do one plane from the departure list and set departed = false when out of consideration
722 if(!separateGround) {
723 // The display stuff might have to get more clever than this when not separate
724 // since the tower and ground might try communicating simultaneously even though
725 // they're mean't to be the same contoller/frequency!!
727 ground->SetDisplay();
729 ground->SetNoDisplay();
735 // How big should ii get - ie how long should the update cycle interval stretch?
736 if(update_count >= update_count_max) {
740 // Call the base class update for the response time handling.
743 if(ident == "KEMT") {
744 // For AI debugging convienience - may be removed
746 user_pos.setlon(user_lon_node->getDoubleValue());
747 user_pos.setlat(user_lat_node->getDoubleValue());
748 user_pos.setelev(user_elev_node->getDoubleValue());
749 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
750 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
751 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
752 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
757 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
758 // plus the constraint position as a rwy orientated orthopos (meters)
759 bool FGTower::GetCrosswindConstraint(double& cpos) {
760 if(crosswind_leg_pos != 0.0) {
761 cpos = crosswind_leg_pos;
768 bool FGTower::GetDownwindConstraint(double& dpos) {
769 if(downwind_leg_pos != 0.0) {
770 dpos = downwind_leg_pos;
777 bool FGTower::GetBaseConstraint(double& bpos) {
778 if(base_leg_pos != 0.0) {
788 // Figure out which runways are active.
789 // For now we'll just be simple and do one active runway - eventually this will get much more complex
790 // This is a private function - public interface to the results of this is through GetActiveRunway
791 void FGTower::DoRwyDetails() {
792 //cout << "GetRwyDetails called" << endl;
794 // Based on the airport-id and wind get the active runway
797 double hdg = wind_from_hdg->getDoubleValue();
798 double speed = wind_speed_knots->getDoubleValue();
799 hdg = (speed == 0.0 ? 270.0 : hdg);
800 //cout << "Heading = " << hdg << '\n';
803 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
805 activeRwy = runway.rwy_no;
806 rwy.rwyID = runway.rwy_no;
807 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
809 // Get the threshold position
810 double other_way = runway.heading - 180.0;
811 while(other_way <= 0.0) {
814 // move to the +l end/center of the runway
815 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
816 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
817 Point3D ref = origin;
818 double tshlon, tshlat, tshr;
819 double tolon, tolat, tor;
820 rwy.length = runway.length * SG_FEET_TO_METER;
821 rwy.width = runway.width * SG_FEET_TO_METER;
822 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
823 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
824 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
825 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
826 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
827 // now copy what we need out of runway into rwy
828 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
829 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
830 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
831 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
832 rwy.hdg = runway.heading;
833 // Set the projection for the local area based on this active runway
834 ortho.Init(rwy.threshold_pos, rwy.hdg);
835 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
836 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
838 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
844 // Figure out if a given position lies on the active runway
845 // Might have to change when we consider more than one active rwy.
846 bool FGTower::OnActiveRunway(Point3D pt) {
847 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
848 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
849 Point3D xyp = ortho.ConvertToLocal(pt);
851 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
852 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
854 double rlen = rwy.length/2.0 + 5.0;
855 double rwidth = rwy.width/2.0;
856 double ldiff = fabs(xyp.y() - xyc.y());
857 double wdiff = fabs(xyp.x() - xyc.x());
859 return((ldiff < rlen) && (wdiff < rwidth));
863 // Figure out if a given position lies on any runway or not
864 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
865 bool FGTower::OnAnyRunway(Point3D pt) {
867 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
871 // Based on the airport-id, go through all the runways and check for a point in them
873 // TODO - do we actually need to search for the airport - surely we already know our ident and
874 // can just search runways of our airport???
875 //cout << "Airport ident is " << ad.ident << '\n';
877 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
879 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
882 while(runway.id == ad.ident) {
883 on = OnRunway(pt, runway);
884 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
886 globals->get_runways()->next(&runway);
892 // Returns true if successful
893 bool FGTower::RemoveFromTrafficList(string id) {
894 tower_plane_rec_list_iterator twrItr;
895 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
896 TowerPlaneRec* tpr = *twrItr;
897 if(tpr->plane.callsign == id) {
898 trafficList.erase(twrItr);
902 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
907 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
908 // and set nextOnRwy if so.
909 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
910 // For planes holding they are put in the first position with time to go, and the return value is
911 // true if in the first position (nextOnRwy) and false otherwise.
912 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
913 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
914 //cout << "ADD: " << trafficList.size();
915 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << '\n';
916 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.
917 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
918 bool conflict = false;
919 double lastETA = 0.0;
920 bool firstTime = true;
921 // FIXME - make this more robust for different plane types eg. light following heavy.
922 tower_plane_rec_list_iterator twrItr;
923 //twrItr = trafficList.begin();
925 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
926 //if(twrItr == trafficList.end()) {
928 // trafficList.push_back(t);
929 // return(holding ? firstTime : conflict);
931 TowerPlaneRec* tpr = *twrItr;
933 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
934 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
935 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
936 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
937 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
938 // and if not needs time to clear the rwy anyway.
939 if(tpr->eta - lastETA > slot_time) {
940 t->nextOnRwy = firstTime;
941 trafficList.insert(twrItr, t);
942 //cout << "\tH\t" << trafficList.size() << '\n';
947 if(t->eta < tpr->eta) {
948 // Ugg - this one's tricky.
949 // It depends on what the two planes are doing and whether there's a conflict what we do.
950 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
952 tpr->nextOnRwy = false;
955 trafficList.insert(twrItr, t);
956 } else { // Ooops - this ones tricky - we have a potential conflict!
958 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
960 tpr->nextOnRwy = false;
963 trafficList.insert(twrItr, t);
965 //cout << "\tC\t" << trafficList.size() << '\n';
972 // If we get here we must be at the end of the list, or maybe the list is empty.
973 if(!trafficList.size()) {
975 // conflict and firstTime should be false and true respectively in this case anyway.
977 trafficList.push_back(t);
978 //cout << "\tE\t" << trafficList.size() << '\n';
979 return(holding ? firstTime : conflict);
983 // Calculate the eta of a plane to the threshold.
984 // For ground traffic this is the fastest they can get there.
985 // For air traffic this is the middle approximation.
986 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
987 // For now we'll be very crude and hardwire expected speeds to C172-like values
988 // The speeds below are specified in knots IAS and then converted to m/s
989 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
990 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
991 double final_ias = 70.0 * 0.514444; // Speed during final approach
994 // cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
995 // cout << (tpr->isUser ? "USER\n" : "AI\n");
998 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
999 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1001 Point3D op = ortho.ConvertToLocal(tpr->pos);
1003 // cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1004 // cout << "opType is " << tpr->opType << '\n';
1006 double dist_out_m = op.y();
1007 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
1008 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1010 if(tpr->opType == STRAIGHT_IN) {
1011 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1012 if(dist_to_go_m < 1000) {
1013 tpr->eta = dist_to_go_m / final_ias;
1015 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1017 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1018 // It's complicated - depends on if base leg is delayed or not
1020 // cout << "Leg = " << tpr->leg << '\n';
1022 if(tpr->leg == LANDING_ROLL) {
1024 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1025 tpr->eta = fabs(dist_out_m) / final_ias;
1026 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1027 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1029 // Need to calculate where base leg is likely to be
1030 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1031 // 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
1032 double nominal_base_dist_out_m = -1000;
1033 double current_base_dist_out_m;
1034 if(!GetBaseConstraint(current_base_dist_out_m)) {
1035 current_base_dist_out_m = nominal_base_dist_out_m;
1037 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1038 double current_dist_across_m;
1039 if(!GetDownwindConstraint(current_dist_across_m)) {
1040 current_dist_across_m = nominal_dist_across_m;
1042 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1043 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1044 //if(printout) cout << "a = " << tpr->eta << '\n';
1045 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1046 tpr->eta += dist_across_m / circuit_ias;
1047 //if(printout) cout << "b = " << tpr->eta << '\n';
1048 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1049 //if(printout) cout << "c = " << tpr->eta << '\n';
1050 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1051 if(dist_across_m > nominal_dist_across_m) {
1052 tpr->eta += dist_across_m / circuit_ias;
1054 tpr->eta += nominal_dist_across_m / circuit_ias;
1056 // should we use the dist across of the previous plane if there is previous still on downwind?
1057 //if(printout) cout << "bb = " << tpr->eta << '\n';
1058 if(dist_out_m > nominal_cross_dist_out_m) {
1059 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1061 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1063 //if(printout) cout << "cc = " << tpr->eta << '\n';
1064 if(nominal_dist_across_m > dist_across_m) {
1065 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1069 //if(printout) cout << "dd = " << tpr->eta << '\n';
1071 // We've only just started - why not use a generic estimate?
1076 // cout << "ETA = " << tpr->eta << '\n';
1084 // Calculate the distance of a plane to the threshold in meters
1085 // TODO - Modify to calculate flying distance of a plane in the circuit
1086 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1087 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1091 // Calculate the distance of a plane to the threshold in miles
1092 // TODO - Modify to calculate flying distance of a plane in the circuit
1093 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1094 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1098 // Iterate through all the lists and call CalcETA for all the planes.
1099 void FGTower::doThresholdETACalc() {
1100 tower_plane_rec_list_iterator twrItr;
1101 // Do the approach list first
1102 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1103 TowerPlaneRec* tpr = *twrItr;
1106 // Then the circuit list
1107 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1108 TowerPlaneRec* tpr = *twrItr;
1114 // Check that the planes in traffic list are correctly ordered,
1115 // that the nearest (timewise) is flagged next on rwy, and return
1116 // true if any threshold use conflicts are detected, false otherwise.
1117 bool FGTower::doThresholdUseOrder() {
1118 bool conflict = false;
1120 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1121 // Here's the rather simplistic assumptions we're using:
1122 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1123 // In order of priority for runway use:
1124 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1125 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1126 // and holding planes until a space.
1127 // When calculating if a holding plane can use the runway, time clearance from last departure
1128 // as well as time clearance to next arrival must be considered.
1130 trafficList.clear();
1132 tower_plane_rec_list_iterator twrItr;
1133 // Do the approach list first
1134 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1135 TowerPlaneRec* tpr = *twrItr;
1136 conflict = AddToTrafficList(tpr);
1138 // Then the circuit list
1139 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1140 TowerPlaneRec* tpr = *twrItr;
1141 conflict = AddToTrafficList(tpr);
1143 // And finally the hold list
1144 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1145 TowerPlaneRec* tpr = *twrItr;
1146 AddToTrafficList(tpr, true);
1150 //if(ident == "KEMT") {
1151 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1152 TowerPlaneRec* tpr = *twrItr;
1153 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1162 void FGTower::doCommunication() {
1166 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1167 // i.e. list_pos = 1 implies next to use runway.
1168 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1169 if(trafficList.size() < list_pos) {
1173 tower_plane_rec_list_iterator twrItr;
1174 twrItr = trafficList.begin();
1175 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1176 TowerPlaneRec* tpr = *twrItr;
1177 CalcETA(tpr, printout);
1178 //cout << "ETA returned = " << tpr->eta << '\n';
1183 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1184 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1185 TowerPlaneRec* t = new TowerPlaneRec;
1187 t->planePtr = requestee;
1188 t->holdShortReported = true;
1189 t->clearanceCounter = 0;
1190 t->clearedToLineUp = false;
1191 t->clearedToTakeOff = false;
1192 t->opType = operation;
1194 //cout << "Hold Short reported by " << plane.callsign << '\n';
1196 bool next = AddToTrafficList(t, true);
1199 //cout << "Next to take off - respond with clearance\n";
1200 double teta = GetTrafficETA(2);
1202 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1203 //cout << "Reducing response time to request due imminent traffic\n";
1206 //cout << "Not next to take off - respond with hold\n";
1209 //cout << "t = " << t << '\n';
1211 holdList.push_back(t);
1214 void FGTower::RequestLandingClearance(string ID) {
1215 //cout << "Request Landing Clearance called...\n";
1217 // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1218 // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1220 TowerPlaneRec* t = new TowerPlaneRec;
1222 t->clearedToLand = false;
1223 t->pos.setlon(user_lon_node->getDoubleValue());
1224 t->pos.setlat(user_lat_node->getDoubleValue());
1225 t->pos.setelev(user_elev_node->getDoubleValue());
1228 // Calculate where the user is in relation to the active runway and it's circuit
1229 // and set the op-type as appropriate.
1231 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1232 t->opType = STRAIGHT_IN;
1234 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1235 t->plane.callsign = ID;
1237 appList.push_back(t); // Not necessarily permanent
1238 AddToTrafficList(t);
1241 void FGTower::RequestDepartureClearance(string ID) {
1242 //cout << "Request Departure Clearance called...\n";
1244 //void FGTower::ReportFinal(string ID);
1245 //void FGTower::ReportLongFinal(string ID);
1246 //void FGTower::ReportOuterMarker(string ID);
1247 //void FGTower::ReportMiddleMarker(string ID);
1248 //void FGTower::ReportInnerMarker(string ID);
1249 //void FGTower::ReportGoingAround(string ID);
1250 void FGTower::ReportRunwayVacated(string ID) {
1251 //cout << "Report Runway Vacated Called...\n";
1254 void FGTower::ReportDownwind(string ID) {
1255 // Tell the plane reporting what number she is in the circuit
1258 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1260 case(CIRCUIT): return(os << "CIRCUIT");
1261 case(INBOUND): return(os << "INBOUND");
1262 case(OUTBOUND): return(os << "OUTBOUND");
1263 case(TTT_UNKNOWN): return(os << "UNKNOWN");
1264 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
1266 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");