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 <strings.h> // bcopy()
23 #include <Main/globals.hxx>
24 #include <Airports/runways.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/debug/logstream.hxx>
29 #include "ATCdisplay.hxx"
31 #include "ATCutils.hxx"
32 #include "ATCDialog.hxx"
33 #include "commlist.hxx"
34 #include "AILocalTraffic.hxx"
40 TowerPlaneRec::TowerPlaneRec() :
42 clearedToLineUp(false),
43 clearedToTakeOff(false),
44 holdShortReported(false),
45 downwindReported(false),
46 longFinalReported(false),
47 longFinalAcknowledged(false),
49 finalAcknowledged(false),
50 rwyVacatedReported(false),
51 rwyVacatedAcknowledged(false),
52 instructedToGoAround(false),
55 vfrArrivalReported(false),
56 vfrArrivalAcknowledged(false),
59 landingType(AIP_LT_UNKNOWN),
62 plane.callsign = "UNKNOWN";
65 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
67 clearedToLineUp(false),
68 clearedToTakeOff(false),
69 holdShortReported(false),
70 downwindReported(false),
71 longFinalReported(false),
72 longFinalAcknowledged(false),
74 finalAcknowledged(false),
75 rwyVacatedReported(false),
76 rwyVacatedAcknowledged(false),
77 instructedToGoAround(false),
80 vfrArrivalReported(false),
81 vfrArrivalAcknowledged(false),
84 landingType(AIP_LT_UNKNOWN),
90 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
92 clearedToLineUp(false),
93 clearedToTakeOff(false),
94 holdShortReported(false),
95 downwindReported(false),
96 longFinalReported(false),
97 longFinalAcknowledged(false),
99 finalAcknowledged(false),
100 rwyVacatedReported(false),
101 rwyVacatedAcknowledged(false),
102 instructedToGoAround(false),
105 vfrArrivalReported(false),
106 vfrArrivalAcknowledged(false),
109 landingType(AIP_LT_UNKNOWN),
112 plane.callsign = "UNKNOWN";
116 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
117 clearedToLand(false),
118 clearedToLineUp(false),
119 clearedToTakeOff(false),
120 holdShortReported(false),
121 downwindReported(false),
122 longFinalReported(false),
123 longFinalAcknowledged(false),
124 finalReported(false),
125 finalAcknowledged(false),
126 rwyVacatedReported(false),
127 rwyVacatedAcknowledged(false),
128 instructedToGoAround(false),
131 vfrArrivalReported(false),
132 vfrArrivalAcknowledged(false),
135 landingType(AIP_LT_UNKNOWN),
145 /*******************************************
148 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in.
150 Tell AI plane to contact ground when taxiing in.
152 Use track instead of heading to determine what leg of the circuit the user is flying.
154 Use altitude as well as position to try to determine if the user has left the circuit.
156 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and
157 will break when planes start queueing.
159 Implement ReportRunwayVacated
160 *******************************************/
163 ATCmgr = globals->get_ATC_mgr();
165 // Init the property nodes - TODO - need to make sure we're getting surface winds.
166 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
167 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
170 update_count_max = 15;
172 holdListItr = holdList.begin();
173 appListItr = appList.begin();
174 depListItr = depList.begin();
175 rwyListItr = rwyList.begin();
176 circuitListItr = circuitList.begin();
177 trafficListItr = trafficList.begin();
181 timeSinceLastDeparture = 9999;
184 nominal_downwind_leg_pos = 1000.0;
185 nominal_base_leg_pos = -1000.0;
186 // TODO - set nominal crosswind leg pos based on minimum distance from takeoff end of rwy.
189 FGTower::~FGTower() {
190 if(!separateGround) {
195 void FGTower::Init() {
198 // Pointers to user's position
199 user_lon_node = fgGetNode("/position/longitude-deg", true);
200 user_lat_node = fgGetNode("/position/latitude-deg", true);
201 user_elev_node = fgGetNode("/position/altitude-ft", true);
202 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
204 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
205 // I'll punt the startup issue for now though!!!
208 // Setup the ground control at this airport
210 //cout << "Tower ident = " << ident << '\n';
211 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
212 if(a.ground_freq) { // Ground control
213 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
214 separateGround = true;
216 // Something has gone wrong :-(
217 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
218 ground = new FGGround(ident);
219 separateGround = false;
222 ground->SetDisplay();
224 ground->SetNoDisplay();
228 // Initialise ground anyway to do the shortest path stuff!
229 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
230 ground = new FGGround(ident);
231 separateGround = false;
234 ground->SetDisplay();
236 ground->SetNoDisplay();
240 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
241 // Initialise ground anyway to avoid segfault later
242 ground = new FGGround(ident);
243 separateGround = false;
246 ground->SetDisplay();
248 ground->SetNoDisplay();
252 // Get the airport elevation
253 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
257 // FIXME - this currently assumes use of the active rwy by the user.
258 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
260 // Assume the user is started at the threshold ready to take-off
261 TowerPlaneRec* t = new TowerPlaneRec;
262 t->plane.callsign = fgGetString("/sim/user/callsign");
263 t->plane.type = GA_SINGLE; // FIXME - hardwired!!
264 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
265 t->landingType = AIP_LT_UNKNOWN;
266 t->leg = TAKEOFF_ROLL;
269 t->clearedToTakeOff = true;
270 rwyList.push_back(t);
273 // For now assume that this means the user is not at the airport and is in the air.
274 // TODO FIXME - this will break when user starts on apron, at hold short, etc.
275 current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with the ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
279 void FGTower::Update(double dt) {
280 //cout << "T" << endl;
281 // Each time step, what do we need to do?
282 // We need to go through the list of outstanding requests and acknowedgements
283 // and process at least one of them.
284 // We need to go through the list of planes under our control and check if
285 // any need to be addressed.
286 // We need to check for planes not under our control coming within our
287 // control area and address if necessary.
289 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
291 // Sort the arriving planes
294 if(ident == "KEMT") {
295 cout << update_count << "\ttL: " << trafficList.size() << " cL: " << circuitList.size() << " hL: " << holdList.size() << " aL: " << appList.size() << '\n';
298 //if(ident == "EGNX") cout << display << '\n';
300 if(departed != false) {
301 timeSinceLastDeparture += dt;
302 //if(ident == "KEMT")
303 // cout << " dt = " << dt << " timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
306 //cout << ident << " respond = " << respond << " responseReqd = " << responseReqd << '\n';
308 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
311 responseReqd = false;
314 // Calculate the eta of each plane to the threshold.
315 // For ground traffic this is the fastest they can get there.
316 // For air traffic this is the middle approximation.
317 if(update_count == 1) {
318 doThresholdETACalc();
321 // Order the list of traffic as per expected threshold use and flag any conflicts
322 if(update_count == 2) {
323 //bool conflicts = doThresholdUseOrder();
324 doThresholdUseOrder();
327 // sortConficts() !!!
329 if(update_count == 4) {
333 // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
340 if(update_count == 5 && rwyOccupied) {
344 if(update_count == 6) {
345 CheckCircuitList(dt);
348 if(update_count == 7) {
349 CheckApproachList(dt);
352 // TODO - do one plane from the departure list and set departed = false when out of consideration
356 if(!separateGround) {
357 // The display stuff might have to get more clever than this when not separate
358 // since the tower and ground might try communicating simultaneously even though
359 // they're mean't to be the same contoller/frequency!!
361 ground->SetDisplay();
363 ground->SetNoDisplay();
369 // How big should ii get - ie how long should the update cycle interval stretch?
370 if(update_count >= update_count_max) {
374 // Call the base class update for the response time handling.
377 if(ident == "KEMT") {
378 // For AI debugging convienience - may be removed
380 user_pos.setlon(user_lon_node->getDoubleValue());
381 user_pos.setlat(user_lat_node->getDoubleValue());
382 user_pos.setelev(user_elev_node->getDoubleValue());
383 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
384 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
385 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
386 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
389 //cout << "Done T" << endl;
392 void FGTower::ReceiveUserCallback(int code) {
393 if(code == (int)USER_REQUEST_VFR_DEPARTURE) {
394 cout << "User requested departure\n";
395 } else if(code == (int)USER_REQUEST_VFR_ARRIVAL) {
396 VFRArrivalContact("USER");
397 } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP) {
398 VFRArrivalContact("USER", FULL_STOP);
399 } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO) {
400 VFRArrivalContact("USER", TOUCH_AND_GO);
401 } else if(code == (int)USER_REPORT_DOWNWIND) {
402 ReportDownwind("USER");
403 } else if(code == (int)USER_REPORT_3_MILE_FINAL) {
404 // For now we'll just call report final instead of report long final to avoid having to alter the response code
406 } else if(code == (int)USER_REPORT_RWY_VACATED) {
407 ReportRunwayVacated("USER");
411 void FGTower::Respond() {
412 cout << "Entering Respond, responseID = " << responseID << endl;
413 TowerPlaneRec* t = FindPlane(responseID);
416 if(t->vfrArrivalReported && !t->vfrArrivalAcknowledged) {
417 // Testing - hardwire straight in for now
418 string trns = t->plane.callsign;
422 // Should we clear staight in or for downwind entry?
423 // For now we'll clear straight in if greater than 1km from a line drawn through the threshold perpendicular to the rwy.
424 // Later on we might check the actual heading and direct some of those to enter on downwind or base.
425 Point3D op = ortho.ConvertToLocal(t->pos);
427 trns += " Report three mile straight-in runway ";
428 current_atcdialog->add_entry(ident, "@AP Tower @CS @MI mile final Runway @RW", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL);
430 // For now we'll just request reporting downwind.
431 // TODO - In real life something like 'report 2 miles southwest right downwind rwy 19R' might be used
432 // but I'm not sure how to handle all permutations of which direction to tell to report from yet.
434 trns += (rwy.patternDirection ? "right " : "left ");
435 trns += "downwind runway ";
436 current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
438 trns += ConvertRwyNumToSpokenString(activeRwy);
440 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
442 cout << "Not displaying, trns was " << trns << '\n';
444 t->vfrArrivalAcknowledged = true;
445 } else if(t->downwindReported) {
446 t->downwindReported = false;
448 for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
449 if((*twrItr)->plane.callsign == responseID) break;
452 string trns = t->plane.callsign;
454 trns += ConvertNumToSpokenDigits(i);
457 trns += "Cleared to land";
458 t->clearedToLand = true;
461 globals->get_ATC_display()->RegisterSingleMessage(trns);
464 if(t->opType == TTT_UNKNOWN) t->opType = CIRCUIT;
465 current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
467 } else if(t->holdShortReported) {
469 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!!)
470 // Do nothing for now - consider acknowloging hold short eventually
472 ClearHoldingPlane(t);
473 t->leg = TAKEOFF_ROLL;
474 rwyList.push_back(t);
476 // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
477 // FIXME TODO - FIX THIS!!!
478 if(holdList.size()) {
479 if(holdListItr == holdList.end()) {
480 holdListItr = holdList.begin();
482 holdList.erase(holdListItr);
483 holdListItr = holdList.begin();
487 // Tell him to hold and what position he is.
488 // Not currently sure under which circumstances we do or don't bother transmitting this.
489 string trns = t->plane.callsign;
490 trns += " hold position";
492 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
494 // TODO - add some idea of what traffic is blocking him.
496 t->holdShortReported = false;
497 } else if(t->finalReported && !(t->finalAcknowledged)) {
499 string trns = t->plane.callsign;
500 cout << (t->nextOnRwy ? "Next on rwy " : "Not next!! ");
501 cout << (rwyOccupied ? "RWY OCCUPIED!!\n" : "Rwy not occupied\n");
502 if(t->nextOnRwy && !rwyOccupied) {
503 if(t->landingType == FULL_STOP) {
504 trns += " cleared to land ";
506 trns += " cleared for the option ";
509 t->clearedToLand = true;
510 if(t->isUser) current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
511 } else if(t->eta < 20) {
512 // Do nothing - we'll be telling it to go around in less than 10 seconds if the
513 // runway doesn't clear so no point in calling "continue approach".
516 trns += " continue approach";
517 t->clearedToLand = false;
519 if(display && disp) {
520 globals->get_ATC_display()->RegisterSingleMessage(trns);
522 t->finalAcknowledged = true;
523 } else if(t->rwyVacatedReported && !(t->rwyVacatedAcknowledged)) {
524 string trns = t->plane.callsign;
526 trns += " Contact ground on ";
527 double f = globals->get_ATC_mgr()->GetFrequency(ident, GROUND) / 100.0;
529 sprintf(buf, "%.2f", f);
534 trns += " cleared for taxi to the GA parking";
537 globals->get_ATC_display()->RegisterSingleMessage(trns);
539 t->rwyVacatedAcknowledged = true;
540 // Maybe we should check that the plane really *has* vacated the runway!
543 freqClear = true; // FIXME - set this to come true after enough time to render the message
544 //cout << "Done Respond" << endl;
547 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land -
548 // this should be done prior to calling this function.
549 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
550 //cout << "Entering ClearHoldingPlane..." << endl;
552 string trns = t->plane.callsign;
553 //if(departed plane < some threshold in time away) {
555 //if(timeSinceLastDeparture <= 60.0 && departed == true) {
557 t->clearedToLineUp = true;
558 t->planePtr->RegisterTransmission(3); // cleared to line-up
559 //} else if(arriving plane < some threshold away) {
560 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
561 trns += " cleared immediate take-off";
562 if(trafficList.size()) {
563 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
564 trfcItr++; // At the moment the holding plane should be first in trafficList.
565 // Note though that this will break if holding planes aren't put in trafficList in the future.
566 TowerPlaneRec* trfc = *trfcItr;
567 trns += "... traffic is";
568 switch(trfc->plane.type) {
572 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
578 trns += " a King-air";
581 trns += " a Learjet";
584 trns += " a Regional";
593 //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
594 if(trfc->opType == STRAIGHT_IN) {
595 double miles_out = CalcDistOutMiles(trfc);
600 trns += ConvertNumToSpokenDigits((int)miles_out);
601 trns += " mile final";
603 } else if(trfc->opType == CIRCUIT) {
604 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
610 trns += " turning final";
616 trns += " turning base";
619 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.
621 // And to eliminate compiler warnings...
622 case TAKEOFF_ROLL: break;
623 case CLIMBOUT: break;
625 case CROSSWIND: break;
627 case LANDING_ROLL: break;
628 case LEG_UNKNOWN: break;
632 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
633 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
635 t->clearedToTakeOff = true;
636 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
638 timeSinceLastDeparture = 0.0;
640 //} else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
641 trns += " cleared for take-off";
642 // TODO - add traffic is... ?
643 t->clearedToTakeOff = true;
644 t->planePtr->RegisterTransmission(4); // cleared to take-off
646 timeSinceLastDeparture = 0.0;
649 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
651 //cout << "Done ClearHoldingPlane " << endl;
654 // Do one plane from the hold list
655 void FGTower::CheckHoldList(double dt) {
656 //cout << "Entering CheckHoldList..." << endl;
657 if(holdList.size()) {
658 //cout << "*holdListItr = " << *holdListItr << endl;
659 if(holdListItr == holdList.end()) {
660 holdListItr = holdList.begin();
662 //cout << "*holdListItr = " << *holdListItr << endl;
663 //Process(*holdListItr);
664 TowerPlaneRec* t = *holdListItr;
665 //cout << "t = " << t << endl;
666 if(t->holdShortReported) {
667 // NO-OP - leave it to the response handler.
668 } else { // not responding to report, but still need to clear if clear
670 //cout << "departed = " << departed << '\n';
671 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
674 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
675 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
677 ClearHoldingPlane(t);
678 t->leg = TAKEOFF_ROLL;
679 rwyList.push_back(t);
681 holdList.erase(holdListItr);
682 holdListItr = holdList.begin();
685 // TODO - rationalise the considerable code duplication above!
689 //cout << "Done CheckHoldList" << endl;
692 // do the ciruit list
693 void FGTower::CheckCircuitList(double dt) {
694 //cout << "Entering CheckCircuitList..." << endl;
695 // Clear the constraints - we recalculate here.
697 downwind_leg_pos = 0.0;
698 crosswind_leg_pos = 0.0;
700 if(circuitList.size()) { // Do one plane from the circuit
701 if(circuitListItr == circuitList.end()) {
702 circuitListItr = circuitList.begin();
704 TowerPlaneRec* t = *circuitListItr;
706 t->pos.setlon(user_lon_node->getDoubleValue());
707 t->pos.setlat(user_lat_node->getDoubleValue());
708 t->pos.setelev(user_elev_node->getDoubleValue());
710 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.
711 t->landingType = t->planePtr->GetLandingOption();
712 //cout << "AI plane landing option is " << t->landingType << '\n';
714 Point3D tortho = ortho.ConvertToLocal(t->pos);
716 // Need to figure out which leg he's on
717 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
718 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
719 //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
720 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
721 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
723 // could be either takeoff, climbout or landing - check orthopos.y
724 //cout << "tortho.y = " << tortho.y() << '\n';
725 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
729 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
730 //cout << "Climbout\n";
731 // If it's the user we may be unsure of his/her intentions.
732 // (Hopefully the AI planes won't try confusing the sim!!!)
733 if(t->opType == TTT_UNKNOWN) {
734 if(tortho.y() > 5000) {
735 // 5 km out from threshold - assume it's a departure
736 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
737 // Since we are unknown operation we should be in depList already.
738 circuitList.erase(circuitListItr);
739 RemoveFromTrafficList(t->plane.callsign);
740 circuitListItr = circuitList.begin();
742 } else if(t->opType == CIRCUIT) {
743 if(tortho.y() > 10000) {
744 // 10 km out - assume the user has abandoned the circuit!!
745 t->opType = OUTBOUND;
746 depList.push_back(t);
747 circuitList.erase(circuitListItr);
748 circuitListItr = circuitList.begin();
752 } else if(abs(ho) < 60) {
754 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
755 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
762 } else if(abs(ho) < 120) {
764 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
765 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
767 //cout << "Crosswind\n";
772 } else if(abs(ho) < 150) {
774 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
775 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
780 // Probably safe now to assume the user is flying a circuit
787 //cout << "Downwind\n";
789 if(t->leg == FINAL) {
790 if(OnActiveRunway(t->pos)) {
791 t->leg = LANDING_ROLL;
795 t->leg = t->planePtr->GetLeg();
798 // Set the constraints IF this is the first plane in the circuit
799 // 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!!
800 if(circuitListItr == circuitList.begin()) {
803 // 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.
804 base_leg_pos = tortho.y();
805 //cout << "base_leg_pos = " << base_leg_pos << '\n';
808 // Fall through to base
810 base_leg_pos = tortho.y();
811 //cout << "base_leg_pos = " << base_leg_pos << '\n';
814 // Fall through to downwind
816 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
817 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
818 //cout << "base_leg_pos = " << base_leg_pos;
819 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
820 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
823 // Fall through to crosswind
825 crosswind_leg_pos = tortho.y();
826 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
827 t->instructedToGoAround = false;
830 // Fall through to climbout
832 // Only use current by constraint as largest
833 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
834 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
847 if(t->leg == FINAL) {
848 if(t->landingType == FULL_STOP) t->opType = INBOUND;
849 if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
850 // TODO - need to make this more sophisticated
851 // eg. is the plane accelerating down the runway taking off [OK],
852 // or stationary near the start [V. BAD!!].
853 // For now this should stop the AI plane landing on top of the user.
854 string trns = t->plane.callsign;
855 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
857 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
859 t->instructedToGoAround = true;
861 cout << "Registering Go-around transmission with AI plane\n";
862 t->planePtr->RegisterTransmission(13);
865 } else if(t->leg == LANDING_ROLL) {
866 rwyList.push_front(t);
867 // TODO - if(!clearedToLand) shout something!!
868 t->clearedToLand = false;
869 RemoveFromTrafficList(t->plane.callsign);
871 t->opType = TTT_UNKNOWN;
872 } // TODO - allow the user to specify opType via ATC menu
873 circuitListItr = circuitList.erase(circuitListItr);
874 if(circuitListItr == circuitList.end() ) {
875 circuitListItr = circuitList.begin();
880 //cout << "Done CheckCircuitList" << endl;
883 // 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!!
884 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
885 // (However, at the moment there should only be one airplane on the rwy at once, until we
886 // start allowing planes to line up whilst previous arrival clears the rwy.)
887 void FGTower::CheckRunwayList(double dt) {
888 //cout << "Entering CheckRunwayList..." << endl;
890 if(!rwyList.size()) {
893 rwyListItr = rwyList.begin();
894 TowerPlaneRec* t = *rwyListItr;
896 t->pos.setlon(user_lon_node->getDoubleValue());
897 t->pos.setlat(user_lat_node->getDoubleValue());
898 t->pos.setelev(user_elev_node->getDoubleValue());
900 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.
902 bool on_rwy = OnActiveRunway(t->pos);
904 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
907 // TODO - tell it to taxi / contact ground / don't delete it etc!
908 } else if(t->opType == OUTBOUND) {
909 depList.push_back(t);
912 timeSinceLastDeparture = 0.0;
913 } else if(t->opType == CIRCUIT) {
914 circuitList.push_back(t);
918 timeSinceLastDeparture = 0.0;
919 } else if(t->opType == TTT_UNKNOWN) {
920 depList.push_back(t);
921 circuitList.push_back(t);
925 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.
927 // HELP - we shouldn't ever get here!!!
932 //cout << "Done CheckRunwayList" << endl;
935 // Do one plane from the approach list
936 void FGTower::CheckApproachList(double dt) {
938 if(appListItr == appList.end()) {
939 appListItr = appList.begin();
941 TowerPlaneRec* t = *appListItr;
942 //cout << "t = " << t << endl;
944 t->pos.setlon(user_lon_node->getDoubleValue());
945 t->pos.setlat(user_lat_node->getDoubleValue());
946 t->pos.setelev(user_elev_node->getDoubleValue());
948 // TODO - set/update the position if it's an AI plane
950 if(t->nextOnRwy && !(t->clearedToLand)) {
951 // check distance away and whether runway occupied
952 // and schedule transmission if necessary
958 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
959 // plus the constraint position as a rwy orientated orthopos (meters)
960 bool FGTower::GetCrosswindConstraint(double& cpos) {
961 if(crosswind_leg_pos != 0.0) {
962 cpos = crosswind_leg_pos;
969 bool FGTower::GetDownwindConstraint(double& dpos) {
970 if(fabs(downwind_leg_pos) > nominal_downwind_leg_pos) {
971 dpos = downwind_leg_pos;
978 bool FGTower::GetBaseConstraint(double& bpos) {
979 if(base_leg_pos < nominal_base_leg_pos) {
983 bpos = nominal_base_leg_pos;
989 // Figure out which runways are active.
990 // For now we'll just be simple and do one active runway - eventually this will get much more complex
991 // This is a private function - public interface to the results of this is through GetActiveRunway
992 void FGTower::DoRwyDetails() {
993 //cout << "GetRwyDetails called" << endl;
995 // Based on the airport-id and wind get the active runway
998 double hdg = wind_from_hdg->getDoubleValue();
999 double speed = wind_speed_knots->getDoubleValue();
1000 hdg = (speed == 0.0 ? 270.0 : hdg);
1001 //cout << "Heading = " << hdg << '\n';
1004 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
1006 activeRwy = runway.rwy_no;
1007 rwy.rwyID = runway.rwy_no;
1008 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
1010 // Get the threshold position
1011 double other_way = runway.heading - 180.0;
1012 while(other_way <= 0.0) {
1015 // move to the +l end/center of the runway
1016 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
1017 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
1018 Point3D ref = origin;
1019 double tshlon, tshlat, tshr;
1020 double tolon, tolat, tor;
1021 rwy.length = runway.length * SG_FEET_TO_METER;
1022 rwy.width = runway.width * SG_FEET_TO_METER;
1023 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
1024 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
1025 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
1026 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
1027 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
1028 // now copy what we need out of runway into rwy
1029 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
1030 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
1031 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
1032 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
1033 rwy.hdg = runway.heading;
1034 // Set the projection for the local area based on this active runway
1035 ortho.Init(rwy.threshold_pos, rwy.hdg);
1036 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
1037 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
1039 // Set the pattern direction
1040 // TODO - we'll check for a facilities file with this in eventually - for now assume left traffic except
1041 // for certain circumstances (RH parallel rwy).
1042 rwy.patternDirection = -1; // Left
1043 if(rwy.rwyID.size() == 3) {
1044 rwy.patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1);
1047 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
1053 // Figure out if a given position lies on the active runway
1054 // Might have to change when we consider more than one active rwy.
1055 bool FGTower::OnActiveRunway(Point3D pt) {
1056 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
1057 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
1058 Point3D xyp = ortho.ConvertToLocal(pt);
1060 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
1061 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
1063 double rlen = rwy.length/2.0 + 5.0;
1064 double rwidth = rwy.width/2.0;
1065 double ldiff = fabs(xyp.y() - xyc.y());
1066 double wdiff = fabs(xyp.x() - xyc.x());
1068 return((ldiff < rlen) && (wdiff < rwidth));
1072 // Figure out if a given position lies on any runway or not
1073 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
1074 bool FGTower::OnAnyRunway(Point3D pt) {
1076 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
1080 // Based on the airport-id, go through all the runways and check for a point in them
1082 // TODO - do we actually need to search for the airport - surely we already know our ident and
1083 // can just search runways of our airport???
1084 //cout << "Airport ident is " << ad.ident << '\n';
1086 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
1088 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
1091 while(runway.id == ad.ident) {
1092 on = OnRunway(pt, runway);
1093 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
1094 if(on) return(true);
1095 globals->get_runways()->next(&runway);
1101 // Returns true if successful
1102 bool FGTower::RemoveFromTrafficList(string id) {
1103 tower_plane_rec_list_iterator twrItr;
1104 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1105 TowerPlaneRec* tpr = *twrItr;
1106 if(tpr->plane.callsign == id) {
1107 trafficList.erase(twrItr);
1111 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
1116 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
1117 // and set nextOnRwy if so.
1118 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
1119 // For planes holding they are put in the first position with time to go, and the return value is
1120 // true if in the first position (nextOnRwy) and false otherwise.
1121 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
1122 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
1123 //cout << "ADD: " << trafficList.size();
1124 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
1125 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.
1126 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
1127 bool conflict = false;
1128 double lastETA = 0.0;
1129 bool firstTime = true;
1130 // FIXME - make this more robust for different plane types eg. light following heavy.
1131 tower_plane_rec_list_iterator twrItr;
1132 //twrItr = trafficList.begin();
1134 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1135 //if(twrItr == trafficList.end()) {
1137 // trafficList.push_back(t);
1138 // return(holding ? firstTime : conflict);
1140 TowerPlaneRec* tpr = *twrItr;
1142 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1143 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1144 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
1145 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1146 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1147 // and if not needs time to clear the rwy anyway.
1148 if(tpr->eta - lastETA > slot_time) {
1149 t->nextOnRwy = firstTime;
1150 trafficList.insert(twrItr, t);
1151 //cout << "\tH\t" << trafficList.size() << '\n';
1156 if(t->eta < tpr->eta) {
1157 // Ugg - this one's tricky.
1158 // It depends on what the two planes are doing and whether there's a conflict what we do.
1159 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1160 if(tpr->nextOnRwy) {
1161 tpr->nextOnRwy = false;
1162 t->nextOnRwy = true;
1164 trafficList.insert(twrItr, t);
1165 } else { // Ooops - this ones tricky - we have a potential conflict!
1167 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1168 if(tpr->nextOnRwy) {
1169 tpr->nextOnRwy = false;
1170 t->nextOnRwy = true;
1172 trafficList.insert(twrItr, t);
1174 //cout << "\tC\t" << trafficList.size() << '\n';
1181 // If we get here we must be at the end of the list, or maybe the list is empty.
1182 if(!trafficList.size()) {
1183 t->nextOnRwy = true;
1184 // conflict and firstTime should be false and true respectively in this case anyway.
1186 trafficList.push_back(t);
1187 //cout << "\tE\t" << trafficList.size() << endl;
1188 return(holding ? firstTime : conflict);
1191 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
1192 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
1193 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
1194 //cout << "ADD: " << circuitList.size();
1195 //cout << "AddToCircuitList called, currently size = " << circuitList.size() << endl;
1196 double separation_time = 60.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.
1197 bool conflict = false;
1198 tower_plane_rec_list_iterator twrItr;
1199 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1200 TowerPlaneRec* tpr = *twrItr;
1202 if(t->eta < tpr->eta) {
1203 // Ugg - this one's tricky.
1204 // It depends on what the two planes are doing and whether there's a conflict what we do.
1205 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1206 circuitList.insert(twrItr, t);
1207 } else { // Ooops - this ones tricky - we have a potential conflict!
1209 // HACK - just add anyway for now and flag conflict.
1210 circuitList.insert(twrItr, t);
1212 //cout << "\tC\t" << circuitList.size() << '\n';
1216 // If we get here we must be at the end of the list, or maybe the list is empty.
1217 circuitList.push_back(t); // TODO - check the separation with the preceding plane for the conflict flag.
1218 //cout << "\tE\t" << circuitList.size() << endl;
1223 // Calculate the eta of a plane to the threshold.
1224 // For ground traffic this is the fastest they can get there.
1225 // For air traffic this is the middle approximation.
1226 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1227 // For now we'll be very crude and hardwire expected speeds to C172-like values
1228 // The speeds below are specified in knots IAS and then converted to m/s
1229 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
1230 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
1231 double final_ias = 70.0 * 0.514444; // Speed during final approach
1234 //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1235 //cout << (tpr->isUser ? "USER\n" : "AI\n");
1239 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1240 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1242 Point3D op = ortho.ConvertToLocal(tpr->pos);
1244 //if(!tpr->isUser) cout << "Orthopos is " << op.x() << ", " << op.y() << ' ';
1245 // cout << "opType is " << tpr->opType << '\n';
1247 double dist_out_m = op.y();
1248 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
1249 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1251 if(tpr->opType == STRAIGHT_IN) {
1252 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1253 if(dist_to_go_m < 1000) {
1254 tpr->eta = dist_to_go_m / final_ias;
1256 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1258 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1259 // It's complicated - depends on if base leg is delayed or not
1261 // cout << "Leg = " << tpr->leg << '\n';
1263 if(tpr->leg == LANDING_ROLL) {
1265 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1266 tpr->eta = fabs(dist_out_m) / final_ias;
1267 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1268 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1270 // Need to calculate where base leg is likely to be
1271 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1272 // 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
1273 double nominal_base_dist_out_m = -1000;
1274 double current_base_dist_out_m;
1275 if(!GetBaseConstraint(current_base_dist_out_m)) {
1276 current_base_dist_out_m = nominal_base_dist_out_m;
1278 //cout << "current_base_dist_out_m = " << current_base_dist_out_m << '\n';
1279 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1280 double current_dist_across_m;
1281 if(!GetDownwindConstraint(current_dist_across_m)) {
1282 current_dist_across_m = nominal_dist_across_m;
1284 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1285 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1286 //cout << "a = " << tpr->eta << '\n';
1287 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1288 tpr->eta += dist_across_m / circuit_ias;
1289 //cout << "b = " << tpr->eta << '\n';
1290 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1291 //cout << "c = " << tpr->eta << '\n';
1292 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1293 if(dist_across_m > nominal_dist_across_m) {
1294 tpr->eta += dist_across_m / circuit_ias;
1296 tpr->eta += nominal_dist_across_m / circuit_ias;
1298 // should we use the dist across of the previous plane if there is previous still on downwind?
1299 //if(printout) cout << "bb = " << tpr->eta << '\n';
1300 if(dist_out_m > nominal_cross_dist_out_m) {
1301 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1303 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1305 //if(printout) cout << "cc = " << tpr->eta << '\n';
1306 if(nominal_dist_across_m > dist_across_m) {
1307 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1311 //if(printout) cout << "dd = " << tpr->eta << '\n';
1313 // We've only just started - why not use a generic estimate?
1318 // cout << "ETA = " << tpr->eta << '\n';
1320 //if(!tpr->isUser) cout << tpr->plane.callsign << '\t' << tpr->eta << '\n';
1327 // Calculate the distance of a plane to the threshold in meters
1328 // TODO - Modify to calculate flying distance of a plane in the circuit
1329 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1330 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1334 // Calculate the distance of a plane to the threshold in miles
1335 // TODO - Modify to calculate flying distance of a plane in the circuit
1336 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1337 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1341 // Iterate through all the lists and call CalcETA for all the planes.
1342 void FGTower::doThresholdETACalc() {
1343 //cout << "Entering doThresholdETACalc..." << endl;
1344 tower_plane_rec_list_iterator twrItr;
1345 // Do the approach list first
1346 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1347 TowerPlaneRec* tpr = *twrItr;
1350 // Then the circuit list
1351 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1352 TowerPlaneRec* tpr = *twrItr;
1355 //cout << "Done doThresholdETCCalc" << endl;
1359 // Check that the planes in traffic list are correctly ordered,
1360 // that the nearest (timewise) is flagged next on rwy, and return
1361 // true if any threshold use conflicts are detected, false otherwise.
1362 bool FGTower::doThresholdUseOrder() {
1363 //cout << "Entering doThresholdUseOrder..." << endl;
1364 bool conflict = false;
1366 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1367 // Here's the rather simplistic assumptions we're using:
1368 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1369 // In order of priority for runway use:
1370 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1371 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1372 // and holding planes until a space.
1373 // When calculating if a holding plane can use the runway, time clearance from last departure
1374 // as well as time clearance to next arrival must be considered.
1376 trafficList.clear();
1378 tower_plane_rec_list_iterator twrItr;
1379 // Do the approach list first
1380 //cout << "A" << flush;
1381 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1382 TowerPlaneRec* tpr = *twrItr;
1383 conflict = AddToTrafficList(tpr);
1385 // Then the circuit list
1386 //cout << "C" << flush;
1387 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1388 TowerPlaneRec* tpr = *twrItr;
1389 conflict = AddToTrafficList(tpr);
1391 // And finally the hold list
1392 //cout << "H" << endl;
1393 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1394 TowerPlaneRec* tpr = *twrItr;
1395 AddToTrafficList(tpr, true);
1399 //if(ident == "KEMT") {
1400 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1401 TowerPlaneRec* tpr = *twrItr;
1402 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1407 //cout << "Done doThresholdUseOrder" << endl;
1412 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1413 // i.e. list_pos = 1 implies next to use runway.
1414 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1415 if(trafficList.size() < list_pos) {
1419 tower_plane_rec_list_iterator twrItr;
1420 twrItr = trafficList.begin();
1421 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1422 TowerPlaneRec* tpr = *twrItr;
1423 CalcETA(tpr, printout);
1424 //cout << "ETA returned = " << tpr->eta << '\n';
1429 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1430 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1431 TowerPlaneRec* t = new TowerPlaneRec;
1433 t->planePtr = requestee;
1434 t->holdShortReported = true;
1435 t->clearedToLineUp = false;
1436 t->clearedToTakeOff = false;
1437 t->opType = operation;
1438 t->pos = requestee->GetPos();
1440 //cout << "Hold Short reported by " << plane.callsign << '\n';
1441 SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign);
1444 bool next = AddToTrafficList(t, true);
1446 double teta = GetTrafficETA(2);
1448 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1449 //cout << "Reducing response time to request due imminent traffic\n";
1454 // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1456 holdList.push_back(t);
1458 responseReqd = true;
1461 // Register the presence of an AI plane at a point where contact would already have been made in real life
1462 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
1463 void FGTower::RegisterAIPlane(PlaneRec plane, FGAIPlane* ai, tower_traffic_type op, PatternLeg lg) {
1464 // At the moment this is only going to be tested with inserting an AI plane on downwind
1465 TowerPlaneRec* t = new TowerPlaneRec;
1470 t->pos = ai->GetPos();
1474 if(op == CIRCUIT && lg != LEG_UNKNOWN) {
1475 AddToCircuitList(t);
1480 doThresholdUseOrder();
1483 // Contact tower for VFR approach
1484 // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo"
1485 // This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec.
1486 // opt defaults to AIP_LT_UNKNOWN
1487 void FGTower::VFRArrivalContact(string ID, LandingType opt) {
1488 //cout << "Request Landing Clearance called...\n";
1490 // For now we'll assume that the user is a light plane and can get him/her to join the circuit if necessary.
1493 string usercall = fgGetString("/sim/user/callsign");
1494 if(ID == "USER" || ID == usercall) {
1495 t = FindPlane(usercall);
1497 //cout << "NOT t\n";
1498 t = new TowerPlaneRec;
1500 t->pos.setlon(user_lon_node->getDoubleValue());
1501 t->pos.setlat(user_lat_node->getDoubleValue());
1502 t->pos.setelev(user_elev_node->getDoubleValue());
1505 // Oops - the plane is already registered with this tower - maybe we took off and flew a giant circuit without
1506 // quite getting out of tower airspace - just ignore for now and treat as new arrival.
1507 // TODO - Maybe should remove from departure and circuit list if in there though!!
1510 // Oops - something has gone wrong - put out a warning
1511 cout << "WARNING - FGTower::VFRContact(string ID, LandingType lt) called with ID " << ID << " which does not appear to be the user.\n";
1517 // Calculate where the plane is in relation to the active runway and it's circuit
1518 // and set the op-type as appropriate.
1520 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1521 t->opType = STRAIGHT_IN;
1523 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1524 t->plane.callsign = usercall;
1526 t->vfrArrivalReported = true;
1527 responseReqd = true;
1529 appList.push_back(t); // Not necessarily permanent
1530 AddToTrafficList(t);
1532 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1533 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1534 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1537 void FGTower::RequestDepartureClearance(string ID) {
1538 //cout << "Request Departure Clearance called...\n";
1541 void FGTower::ReportFinal(string ID) {
1543 ID = fgGetString("/sim/user/callsign");
1544 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1546 TowerPlaneRec* t = FindPlane(ID);
1548 t->finalReported = true;
1549 t->finalAcknowledged = false;
1550 if(!(t->clearedToLand)) {
1551 responseReqd = true;
1552 } // possibly respond with wind even if already cleared to land?
1554 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
1558 void FGTower::ReportLongFinal(string ID) {
1560 ID = fgGetString("/sim/user/callsign");
1561 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1563 TowerPlaneRec* t = FindPlane(ID);
1565 t->longFinalReported = true;
1566 t->longFinalAcknowledged = false;
1567 if(!(t->clearedToLand)) {
1568 responseReqd = true;
1569 } // possibly respond with wind even if already cleared to land?
1571 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportLongFinal(...)");
1575 //void FGTower::ReportOuterMarker(string ID);
1576 //void FGTower::ReportMiddleMarker(string ID);
1577 //void FGTower::ReportInnerMarker(string ID);
1578 //void FGTower::ReportGoingAround(string ID);
1580 void FGTower::ReportRunwayVacated(string ID) {
1581 //cout << "Report Runway Vacated Called...\n";
1583 ID = fgGetString("/sim/user/callsign");
1584 current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
1586 TowerPlaneRec* t = FindPlane(ID);
1588 t->rwyVacatedReported = true;
1589 responseReqd = true;
1591 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
1595 TowerPlaneRec* FGTower::FindPlane(string ID) {
1596 tower_plane_rec_list_iterator twrItr;
1597 // Do the approach list first
1598 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1599 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1601 // Then the circuit list
1602 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1603 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1605 // And finally the hold list
1606 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1607 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1609 SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
1613 void FGTower::ReportDownwind(string ID) {
1614 //cout << "ReportDownwind(...) called\n";
1616 ID = fgGetString("/sim/user/callsign");
1617 current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
1619 TowerPlaneRec* t = FindPlane(ID);
1621 t->downwindReported = true;
1622 responseReqd = true;
1624 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
1628 string FGTower::GenText(const string& m, int c) {
1629 const int cmax = 300;
1639 string usercall = fgGetString("/sim/user/callsign");
1641 //transmission_list_type tmissions = transmissionlist_station[station];
1642 //transmission_list_iterator current = tmissions.begin();
1643 //transmission_list_iterator last = tmissions.end();
1645 //for ( ; current != last ; ++current ) {
1646 // if ( current->get_code().c1 == code.c1 &&
1647 // current->get_code().c2 == code.c2 &&
1648 // current->get_code().c3 == code.c3 ) {
1650 //if ( ttext ) message = current->get_transtext();
1651 //else message = current->get_menutext();
1652 strcpy( &mes[0], m.c_str() );
1654 // Replace all the '@' parameters with the actual text.
1655 int check = 0; // If mes gets overflowed the while loop can go infinite
1656 while ( strchr(&mes[0], crej) != NULL ) { // ie. loop until no more occurances of crej ('@') found
1657 pos = strchr( &mes[0], crej );
1658 bcopy(pos, &tag[0], 3);
1662 for ( i=0; i<cmax; i++ ) {
1663 if ( mes[i] == crej ) {
1668 strncpy( &dum[0], &mes[0], len );
1671 if ( strcmp ( tag, "@ST" ) == 0 )
1672 //strcat( &dum[0], tpars.station.c_str() );
1673 strcat(&dum[0], ident.c_str());
1674 else if ( strcmp ( tag, "@AP" ) == 0 )
1675 //strcat( &dum[0], tpars.airport.c_str() );
1676 strcat(&dum[0], name.c_str());
1677 else if ( strcmp ( tag, "@CS" ) == 0 )
1678 //strcat( &dum[0], tpars.callsign.c_str() );
1679 strcat(&dum[0], usercall.c_str());
1680 else if ( strcmp ( tag, "@TD" ) == 0 ) {
1682 if ( tpars.tdir == 1 ) {
1683 char buf[] = "left";
1684 strcat( &dum[0], &buf[0] );
1687 char buf[] = "right";
1688 strcat( &dum[0], &buf[0] );
1692 else if ( strcmp ( tag, "@HE" ) == 0 ) {
1695 sprintf( buf, "%i", (int)(tpars.heading) );
1696 strcat( &dum[0], &buf[0] );
1699 else if ( strcmp ( tag, "@VD" ) == 0 ) {
1701 if ( tpars.VDir == 1 ) {
1702 char buf[] = "Descend and maintain";
1703 strcat( &dum[0], &buf[0] );
1705 else if ( tpars.VDir == 2 ) {
1706 char buf[] = "Maintain";
1707 strcat( &dum[0], &buf[0] );
1709 else if ( tpars.VDir == 3 ) {
1710 char buf[] = "Climb and maintain";
1711 strcat( &dum[0], &buf[0] );
1715 else if ( strcmp ( tag, "@AL" ) == 0 ) {
1718 sprintf( buf, "%i", (int)(tpars.alt) );
1719 strcat( &dum[0], &buf[0] );
1722 else if ( strcmp ( tag, "@MI" ) == 0 ) {
1724 //sprintf( buf, "%3.1f", tpars.miles );
1725 int dist_miles = dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())) / 1600;
1726 sprintf(buf, "%i", dist_miles);
1727 strcat( &dum[0], &buf[0] );
1729 else if ( strcmp ( tag, "@FR" ) == 0 ) {
1732 sprintf( buf, "%6.2f", tpars.freq );
1733 strcat( &dum[0], &buf[0] );
1736 else if ( strcmp ( tag, "@RW" ) == 0 ) {
1737 strcat(&dum[0], ConvertRwyNumToSpokenString(activeRwy).c_str());
1738 } else if(strcmp(tag, "@CD") == 0) { // @CD = compass direction
1739 double h = GetHeadingFromTo(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
1740 while(h < 0.0) h += 360.0;
1741 while(h > 360.0) h -= 360.0;
1742 if(h < 22.5 || h > 337.5) {
1743 strcat(&dum[0], "North");
1744 } else if(h < 67.5) {
1745 strcat(&dum[0], "North-East");
1746 } else if(h < 112.5) {
1747 strcat(&dum[0], "East");
1748 } else if(h < 157.5) {
1749 strcat(&dum[0], "South-East");
1750 } else if(h < 202.5) {
1751 strcat(&dum[0], "South");
1752 } else if(h < 247.5) {
1753 strcat(&dum[0], "South-West");
1754 } else if(h < 292.5) {
1755 strcat(&dum[0], "West");
1757 strcat(&dum[0], "North-West");
1760 cout << "Tag " << tag << " not found" << endl;
1763 strcat( &dum[0], &mes[len+3] );
1764 strcpy( &mes[0], &dum[0] );
1768 SG_LOG(SG_ATC, SG_WARN, "WARNING: Possibly endless loop terminated in FGTransmissionlist::gen_text(...)");
1773 //cout << mes << endl;
1777 if ( mes != "" ) return mes;
1778 else return "No transmission found";
1781 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1783 case(CIRCUIT): return(os << "CIRCUIT");
1784 case(INBOUND): return(os << "INBOUND");
1785 case(OUTBOUND): return(os << "OUTBOUND");
1786 case(TTT_UNKNOWN): return(os << "UNKNOWN");
1787 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
1789 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");