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),
52 plane.callsign = "UNKNOWN";
55 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
57 clearedToLineUp(false),
58 clearedToTakeOff(false),
59 holdShortReported(false),
60 longFinalReported(false),
61 longFinalAcknowledged(false),
63 finalAcknowledged(false),
73 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
75 clearedToLineUp(false),
76 clearedToTakeOff(false),
77 holdShortReported(false),
78 longFinalReported(false),
79 longFinalAcknowledged(false),
81 finalAcknowledged(false),
88 plane.callsign = "UNKNOWN";
92 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
94 clearedToLineUp(false),
95 clearedToTakeOff(false),
96 holdShortReported(false),
97 longFinalReported(false),
98 longFinalAcknowledged(false),
100 finalAcknowledged(false),
115 ATCmgr = globals->get_ATC_mgr();
117 // Init the property nodes - TODO - need to make sure we're getting surface winds.
118 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
119 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
121 holdListItr = holdList.begin();
122 appListItr = appList.begin();
123 depListItr = depList.begin();
124 rwyListItr = rwyList.begin();
125 circuitListItr = circuitList.begin();
126 trafficListItr = trafficList.begin();
131 FGTower::~FGTower() {
132 if(!separateGround) {
137 void FGTower::Init() {
140 // Pointers to user's position
141 user_lon_node = fgGetNode("/position/longitude-deg", true);
142 user_lat_node = fgGetNode("/position/latitude-deg", true);
143 user_elev_node = fgGetNode("/position/altitude-ft", true);
144 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
146 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
147 // I'll punt the startup issue for now though!!!
150 // Setup the ground control at this airport
152 //cout << "Tower ident = " << ident << '\n';
153 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
154 if(a.ground_freq) { // Ground control
155 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
156 separateGround = true;
158 // Something has gone wrong :-(
159 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
160 ground = new FGGround(ident);
161 separateGround = false;
164 ground->SetDisplay();
166 ground->SetNoDisplay();
170 // Initialise ground anyway to do the shortest path stuff!
171 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
172 ground = new FGGround(ident);
173 separateGround = false;
176 ground->SetDisplay();
178 ground->SetNoDisplay();
182 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
183 // Initialise ground anyway to avoid segfault later
184 ground = new FGGround(ident);
185 separateGround = false;
188 ground->SetDisplay();
190 ground->SetNoDisplay();
194 // Get the airport elevation
195 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
199 // FIXME - this currently assumes use of the active rwy by the user.
200 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
202 // Assume the user is started at the threshold ready to take-off
203 TowerPlaneRec* t = new TowerPlaneRec;
204 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
205 t->plane.type = GA_SINGLE;
206 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
207 t->leg = TAKEOFF_ROLL;
210 t->clearedToTakeOff = true;
211 rwyList.push_back(t);
215 void FGTower::Update(double dt) {
216 static int ii = 0; // Counter for spreading the load
218 //cout << "T" << flush;
219 // Each time step, what do we need to do?
220 // We need to go through the list of outstanding requests and acknowedgements
221 // and process at least one of them.
222 // We need to go through the list of planes under our control and check if
223 // any need to be addressed.
224 // We need to check for planes not under our control coming within our
225 // control area and address if necessary.
227 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
229 // Sort the arriving planes
231 // Calculate the eta of each plane to the threshold.
232 // For ground traffic this is the fastest they can get there.
233 // For air traffic this is the middle approximation.
235 doThresholdETACalc();
238 // Order the list of traffic as per expected threshold use and flag any conflicts
240 bool conflicts = doThresholdUseOrder();
243 // sortConficts() !!!
245 // Do one plane from the hold list
247 if(holdList.size()) {
248 //cout << "*holdListItr = " << *holdListItr << endl;
249 if(holdListItr == holdList.end()) {
250 holdListItr = holdList.begin();
252 //cout << "*holdListItr = " << *holdListItr << endl;
253 //Process(*holdListItr);
254 TowerPlaneRec* t = *holdListItr;
255 //cout << "t = " << t << endl;
256 if(t->holdShortReported) {
257 double responseTime = 10.0; // seconds - this should get more sophisticated at some point
258 if(t->clearanceCounter > responseTime) {
261 // Do nothing for now - consider acknowloging hold short eventually
264 string trns = t->plane.callsign;
265 //if(departed plane < some threshold in time away) {
268 t->clearedToLineUp = true;
269 t->planePtr->RegisterTransmission(3); // cleared to line-up
270 t->leg = TAKEOFF_ROLL;
271 //} else if(arriving plane < some threshold away) {
272 } else if(GetTrafficETA(2) < 150.0) {
273 trns += " cleared immediate take-off";
274 if(trafficList.size()) {
275 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
276 trfcItr++; // At the moment the holding plane should be first in trafficList.
277 // Note though that this will break if holding planes aren't put in trafficList in the future.
278 TowerPlaneRec* trfc = *trfcItr;
279 trns += "... traffic is";
280 switch(trfc->plane.type) {
284 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
290 trns += " a King-air";
293 trns += " a Learjet";
296 trns += " a Regional";
305 if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
306 double miles_out = CalcDistOutMiles(trfc);
311 trns += ConvertNumToSpokenDigits((int)miles_out);
312 trns += " mile final";
314 } else if(trfc->opType == CIRCUIT) {
320 trns += " turning final";
326 trns += " turning base";
329 trns += " in circuit";
331 // And to eliminate compiler warnings...
332 case TAKEOFF_ROLL: break;
333 case CLIMBOUT: break;
335 case CROSSWIND: break;
337 case LANDING_ROLL: break;
338 case LEG_UNKNOWN: break;
342 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
343 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
345 t->clearedToTakeOff = true;
346 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
347 t->leg = TAKEOFF_ROLL;
349 trns += " cleared for take-off";
350 // TODO - add traffic is... ?
351 t->clearedToTakeOff = true;
352 t->planePtr->RegisterTransmission(4); // cleared to take-off
353 t->leg = TAKEOFF_ROLL;
356 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
358 t->holdShortReported = false;
359 t->clearanceCounter = 0;
360 rwyList.push_back(t);
362 holdList.erase(holdListItr);
363 holdListItr = holdList.begin();
366 // Tell him to hold and what position he is.
367 // Not currently sure under which circumstances we do or don't bother transmitting this.
368 string trns = t->plane.callsign;
369 trns += " hold position";
371 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
373 t->holdShortReported = false;
374 t->clearanceCounter = 0;
375 // TODO - add some idea of what traffic is blocking him.
378 t->clearanceCounter += (dt * holdList.size() * ii_max);
380 } else { // not responding to report, but still need to clear if clear
383 // Do nothing for now - consider acknowloging hold short eventually
386 string trns = t->plane.callsign;
387 //if(departed plane < some threshold in time away) {
390 t->clearedToLineUp = true;
391 t->planePtr->RegisterTransmission(3); // cleared to line-up
392 t->leg = TAKEOFF_ROLL;
393 //} else if(arriving plane < some threshold away) {
394 } else if(GetTrafficETA(2) < 150.0) {
395 trns += " cleared immediate take-off";
396 // TODO - add traffic is... ?
397 t->clearedToTakeOff = true;
398 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
399 t->leg = TAKEOFF_ROLL;
401 trns += " cleared for take-off";
402 // TODO - add traffic is... ?
403 t->clearedToTakeOff = true;
404 t->planePtr->RegisterTransmission(4); // cleared to take-off
405 t->leg = TAKEOFF_ROLL;
408 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
410 rwyList.push_back(t);
412 holdList.erase(holdListItr);
413 holdListItr = holdList.begin();
416 // TODO - remove the considerable code duplication above!
422 // 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!!
423 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
426 if(!rwyList.size()) {
429 rwyListItr = rwyList.begin();
430 TowerPlaneRec* t = *rwyListItr;
432 bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
433 // TODO - how do we find the position when it's not the user?
435 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
438 // TODO - tell it to taxi / contact ground / don't delete it etc!
439 } else if(t->opType == OUTBOUND) {
440 depList.push_back(t);
442 } else if(t->opType == CIRCUIT) {
443 circuitList.push_back(t);
444 //cout << "Oggy oggy oggy\n";
447 } else if(t->opType == TTT_UNKNOWN) {
448 depList.push_back(t);
449 circuitList.push_back(t);
450 //cout << "Aggy aggy aggy\n";
454 // HELP - we shouldn't ever get here!!!
457 } // else TODO figure out what to do when it's not the user
462 // do the ciruit list
464 // Clear the constraints - we recalculate here.
466 downwind_leg_pos = 0.0;
467 crosswind_leg_pos = 0.0;
468 if(circuitList.size()) {
469 circuitListItr = circuitList.begin(); // TODO - at the moment we're constraining plane 2 based on plane 1 - this won't work for 3 planes in the circuit!!
470 TowerPlaneRec* t = *circuitListItr;
472 t->pos.setlon(user_lon_node->getDoubleValue());
473 t->pos.setlat(user_lat_node->getDoubleValue());
474 t->pos.setelev(user_elev_node->getDoubleValue());
476 // TODO - set/update the position if it's an AI plane
478 Point3D tortho = ortho.ConvertToLocal(t->pos);
480 // Need to figure out which leg he's on
481 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
482 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
483 //cout << " ho = " << ho << '\n';
484 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
485 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
487 // could be either takeoff, climbout or landing - check orthopos.y
488 //cout << "tortho.y = " << tortho.y() << '\n';
489 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
493 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
494 //cout << "Climbout\n";
495 // If it's the user we may be unsure of his/her intentions.
496 // (Hopefully the AI planes won't try confusing the sim!!!)
497 if(t->opType == TTT_UNKNOWN) {
498 if(tortho.y() > 5000) {
499 // 5 km out from threshold - assume it's a departure
500 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
501 // Since we are unknown operation we should be in depList already.
502 circuitList.erase(circuitListItr);
503 RemoveFromTrafficList(t->plane.callsign);
504 circuitListItr = circuitList.begin();
506 } else if(t->opType == CIRCUIT) {
507 if(tortho.y() > 10000) {
508 // 10 km out - assume the user has abandoned the circuit!!
509 t->opType = OUTBOUND;
510 depList.push_back(t);
511 circuitList.erase(circuitListItr);
512 circuitListItr = circuitList.begin();
516 } else if(abs(ho) < 60) {
518 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
519 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
526 } else if(abs(ho) < 120) {
528 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
529 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
531 //cout << "Crosswind\n";
536 } else if(abs(ho) < 150) {
538 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
539 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
544 // Probably safe now to assume the user is flying a circuit
551 //cout << "Downwind\n";
554 t->leg = t->planePtr->GetLeg();
558 // 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.
559 base_leg_pos = tortho.y();
560 //cout << "base_leg_pos = " << base_leg_pos << '\n';
563 // Fall through to base
565 base_leg_pos = tortho.y();
566 //cout << "base_leg_pos = " << base_leg_pos << '\n';
569 // Fall through to downwind
571 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
572 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
573 //cout << "base_leg_pos = " << base_leg_pos;
574 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
575 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
578 // Fall through to crosswind
580 crosswind_leg_pos = tortho.y();
581 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
584 // Fall through to climbout
586 // Only use current by constraint as largest
587 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
588 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
602 // Do one plane from the approach list
605 if(appListItr == appList.end()) {
606 appListItr = appList.begin();
608 TowerPlaneRec* t = *appListItr;
609 //cout << "t = " << t << endl;
611 t->pos.setlon(user_lon_node->getDoubleValue());
612 t->pos.setlat(user_lat_node->getDoubleValue());
613 t->pos.setelev(user_elev_node->getDoubleValue());
615 // TODO - set/update the position if it's an AI plane
617 if(t->nextOnRwy && !(t->clearedToLand)) {
618 // check distance away and whether runway occupied
619 // and schedule transmission if necessary
627 if(!separateGround) {
628 // The display stuff might have to get more clever than this when not separate
629 // since the tower and ground might try communicating simultaneously even though
630 // they're mean't to be the same contoller/frequency!!
632 ground->SetDisplay();
634 ground->SetNoDisplay();
640 // How big should ii get - ie how long should the update cycle interval stretch?
645 if(ident == "KEMT") {
646 // For AI debugging convienience - may be removed
648 user_pos.setlon(user_lon_node->getDoubleValue());
649 user_pos.setlat(user_lat_node->getDoubleValue());
650 user_pos.setelev(user_elev_node->getDoubleValue());
651 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
652 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
653 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
654 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
659 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
660 // plus the constraint position as a rwy orientated orthopos (meters)
661 bool FGTower::GetCrosswindConstraint(double& cpos) {
662 if(crosswind_leg_pos != 0.0) {
663 cpos = crosswind_leg_pos;
670 bool FGTower::GetDownwindConstraint(double& dpos) {
671 if(downwind_leg_pos != 0.0) {
672 dpos = downwind_leg_pos;
679 bool FGTower::GetBaseConstraint(double& bpos) {
680 if(base_leg_pos != 0.0) {
690 // Figure out which runways are active.
691 // For now we'll just be simple and do one active runway - eventually this will get much more complex
692 // This is a private function - public interface to the results of this is through GetActiveRunway
693 void FGTower::DoRwyDetails() {
694 //cout << "GetRwyDetails called" << endl;
696 // Based on the airport-id and wind get the active runway
699 double hdg = wind_from_hdg->getDoubleValue();
700 double speed = wind_speed_knots->getDoubleValue();
701 hdg = (speed == 0.0 ? 270.0 : hdg);
702 //cout << "Heading = " << hdg << '\n';
705 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
707 activeRwy = runway.rwy_no;
708 rwy.rwyID = runway.rwy_no;
709 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
711 // Get the threshold position
712 double other_way = runway.heading - 180.0;
713 while(other_way <= 0.0) {
716 // move to the +l end/center of the runway
717 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
718 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
719 Point3D ref = origin;
720 double tshlon, tshlat, tshr;
721 double tolon, tolat, tor;
722 rwy.length = runway.length * SG_FEET_TO_METER;
723 rwy.width = runway.width * SG_FEET_TO_METER;
724 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
725 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
726 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
727 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
728 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
729 // now copy what we need out of runway into rwy
730 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
731 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
732 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
733 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
734 rwy.hdg = runway.heading;
735 // Set the projection for the local area based on this active runway
736 ortho.Init(rwy.threshold_pos, rwy.hdg);
737 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
738 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
740 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
746 // Figure out if a given position lies on the active runway
747 // Might have to change when we consider more than one active rwy.
748 bool FGTower::OnActiveRunway(Point3D pt) {
749 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
750 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
751 Point3D xyp = ortho.ConvertToLocal(pt);
753 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
754 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
756 double rlen = rwy.length/2.0 + 5.0;
757 double rwidth = rwy.width/2.0;
758 double ldiff = fabs(xyp.y() - xyc.y());
759 double wdiff = fabs(xyp.x() - xyc.x());
761 return((ldiff < rlen) && (wdiff < rwidth));
765 // Figure out if a given position lies on any runway or not
766 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
767 bool FGTower::OnAnyRunway(Point3D pt) {
769 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
773 // Based on the airport-id, go through all the runways and check for a point in them
775 // TODO - do we actually need to search for the airport - surely we already know our ident and
776 // can just search runways of our airport???
777 //cout << "Airport ident is " << ad.ident << '\n';
779 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
781 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
784 while(runway.id == ad.ident) {
785 on = OnRunway(pt, runway);
786 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
788 globals->get_runways()->next(&runway);
794 // Returns true if successful
795 bool FGTower::RemoveFromTrafficList(string id) {
796 tower_plane_rec_list_iterator twrItr;
797 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
798 TowerPlaneRec* tpr = *twrItr;
799 if(tpr->plane.callsign == id) {
800 trafficList.erase(twrItr);
804 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
809 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
810 // and set nextOnRwy if so.
811 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
812 // For planes holding they are put in the first position with time to go, and the return value is
813 // true if in the first position (nextOnRwy) and false otherwise.
814 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
815 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << '\n';
816 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.
817 bool conflict = false;
818 double lastETA = 0.0;
819 bool firstTime = true;
820 // FIXME - make this more robust for different plane types eg. light following heavy.
821 tower_plane_rec_list_iterator twrItr;
822 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
823 TowerPlaneRec* tpr = *twrItr;
825 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
826 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
827 if(tpr->eta - lastETA > separation_time) {
828 t->nextOnRwy = firstTime;
829 trafficList.insert(twrItr, t);
834 if(t->eta < tpr->eta) {
835 // Ugg - this one's tricky.
836 // It depends on what the two planes are doing and whether there's a conflict what we do.
837 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
839 tpr->nextOnRwy = false;
842 trafficList.insert(twrItr, t);
843 } else { // Ooops - this ones tricky - we have a potential conflict!
850 // If we get here we must be at the end of the list, or maybe the list is empty.
851 if(!trafficList.size()) {
853 // conflict and firstTime should be false and true respectively in this case anyway.
855 trafficList.push_back(t);
856 return(holding ? firstTime : conflict);
860 // Calculate the eta of a plane to the threshold.
861 // For ground traffic this is the fastest they can get there.
862 // For air traffic this is the middle approximation.
863 void FGTower::CalcETA(TowerPlaneRec* tpr) {
864 // For now we'll be very crude and hardwire expected speeds to C172-like values
865 // The speeds below are specified in knots IAS and then converted to m/s
866 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
867 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
868 double final_ias = 70.0 * 0.514444; // Speed during final approach
870 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
871 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
873 Point3D op = ortho.ConvertToLocal(tpr->pos);
874 double dist_out_m = op.y();
875 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
876 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
878 if(tpr->opType == STRAIGHT_IN) {
879 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
880 if(dist_to_go_m < 1000) {
881 tpr->eta = dist_to_go_m / final_ias;
883 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
885 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
886 // It's complicated - depends on if base leg is delayed or not
887 if(tpr->leg == LANDING_ROLL) {
889 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
890 tpr->eta = fabs(dist_out_m) / final_ias;
891 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
892 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
894 // Need to calculate where base leg is likely to be
895 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
896 // 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
897 double nominal_base_dist_out_m = -1000;
898 double current_base_dist_out_m;
899 if(!GetBaseConstraint(current_base_dist_out_m)) {
900 current_base_dist_out_m = nominal_base_dist_out_m;
902 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
903 double current_dist_across_m;
904 if(!GetDownwindConstraint(current_dist_across_m)) {
905 current_dist_across_m = nominal_dist_across_m;
907 double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
908 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
909 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
910 tpr->eta += dist_across_m / circuit_ias;
911 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
912 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
913 tpr->eta += nominal_dist_across_m / circuit_ias; // should we use the dist across of the previous plane if there is previous still on downwind?
914 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
915 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
917 // We've only just started - why not use a generic estimate?
920 //cout << "ETA = " << tpr->eta << '\n';
927 // Calculate the distance of a plane to the threshold in meters
928 // TODO - Modify to calculate flying distance of a plane in the circuit
929 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
930 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
934 // Calculate the distance of a plane to the threshold in miles
935 // TODO - Modify to calculate flying distance of a plane in the circuit
936 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
937 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
941 // Iterate through all the lists and call CalcETA for all the planes.
942 void FGTower::doThresholdETACalc() {
943 tower_plane_rec_list_iterator twrItr;
944 // Do the approach list first
945 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
946 TowerPlaneRec* tpr = *twrItr;
949 // Then the circuit list
950 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
951 TowerPlaneRec* tpr = *twrItr;
957 // Check that the planes in traffic list are correctly ordered,
958 // that the nearest (timewise) is flagged next on rwy, and return
959 // true if any threshold use conflicts are detected, false otherwise.
960 bool FGTower::doThresholdUseOrder() {
961 bool conflict = false;
963 // TODO - write some code here!
968 void FGTower::doCommunication() {
971 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
972 // i.e. list_pos = 1 implies next to use runway.
973 double FGTower::GetTrafficETA(unsigned int list_pos) {
974 if(trafficList.size() < list_pos) {
978 tower_plane_rec_list_iterator twrItr;
979 twrItr = trafficList.begin();
980 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
981 //cout << "ETA returned = " << (*twrItr)->eta << '\n';
982 return((*twrItr)->eta);
986 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
987 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
988 TowerPlaneRec* t = new TowerPlaneRec;
990 t->planePtr = requestee;
991 t->holdShortReported = true;
992 t->clearanceCounter = 0;
993 t->clearedToLineUp = false;
994 t->clearedToTakeOff = false;
995 t->opType = operation;
997 //cout << "Hold Short reported by " << plane.callsign << '\n';
999 bool next = AddToTrafficList(t, true);
1002 //cout << "Next to take off - respond with clearance\n";
1003 double teta = GetTrafficETA(2);
1005 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1006 //cout << "Reducing response time to request due imminent traffic\n";
1009 //cout << "Not next to take off - respond with hold\n";
1012 //cout << "t = " << t << '\n';
1014 holdList.push_back(t);
1017 void FGTower::RequestLandingClearance(string ID) {
1018 //cout << "Request Landing Clearance called...\n";
1020 // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1021 // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1023 TowerPlaneRec* t = new TowerPlaneRec;
1025 t->clearedToLand = false;
1026 t->pos.setlon(user_lon_node->getDoubleValue());
1027 t->pos.setlat(user_lat_node->getDoubleValue());
1028 t->pos.setelev(user_elev_node->getDoubleValue());
1031 // Calculate where the user is in relation to the active runway and it's circuit
1032 // and set the op-type as appropriate.
1034 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1035 t->opType = STRAIGHT_IN;
1037 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1038 t->plane.callsign = ID;
1040 appList.push_back(t); // Not necessarily permanent
1041 AddToTrafficList(t);
1044 void FGTower::RequestDepartureClearance(string ID) {
1045 //cout << "Request Departure Clearance called...\n";
1047 //void FGTower::ReportFinal(string ID);
1048 //void FGTower::ReportLongFinal(string ID);
1049 //void FGTower::ReportOuterMarker(string ID);
1050 //void FGTower::ReportMiddleMarker(string ID);
1051 //void FGTower::ReportInnerMarker(string ID);
1052 //void FGTower::ReportGoingAround(string ID);
1053 void FGTower::ReportRunwayVacated(string ID) {
1054 //cout << "Report Runway Vacated Called...\n";