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),
49 plane.callsign = "UNKNOWN";
52 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
54 clearedToLineUp(false),
55 clearedToTakeOff(false),
56 holdShortReported(false),
57 longFinalReported(false),
58 longFinalAcknowledged(false),
60 finalAcknowledged(false),
67 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
69 clearedToLineUp(false),
70 clearedToTakeOff(false),
71 holdShortReported(false),
72 longFinalReported(false),
73 longFinalAcknowledged(false),
75 finalAcknowledged(false),
79 plane.callsign = "UNKNOWN";
83 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
85 clearedToLineUp(false),
86 clearedToTakeOff(false),
87 holdShortReported(false),
88 longFinalReported(false),
89 longFinalAcknowledged(false),
91 finalAcknowledged(false),
103 ATCmgr = globals->get_ATC_mgr();
105 // Init the property nodes - TODO - need to make sure we're getting surface winds.
106 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
107 wind_speed_knots = fgGetNode("/environment/wind-speed-kts", true);
109 holdListItr = holdList.begin();
110 appListItr = appList.begin();
111 depListItr = depList.begin();
112 rwyListItr = rwyList.begin();
113 circuitListItr = circuitList.begin();
114 trafficListItr = trafficList.begin();
117 FGTower::~FGTower() {
118 if(!separateGround) {
123 void FGTower::Init() {
126 // Pointers to user's position
127 user_lon_node = fgGetNode("/position/longitude-deg", true);
128 user_lat_node = fgGetNode("/position/latitude-deg", true);
129 user_elev_node = fgGetNode("/position/altitude-ft", true);
130 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
132 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
133 // I'll punt the startup issue for now though!!!
136 // Setup the ground control at this airport
138 //cout << "Tower ident = " << ident << '\n';
139 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
140 if(a.ground_freq) { // Ground control
141 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
142 separateGround = true;
144 // Something has gone wrong :-(
145 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
146 ground = new FGGround(ident);
147 separateGround = false;
150 ground->SetDisplay();
152 ground->SetNoDisplay();
156 // Initialise ground anyway to do the shortest path stuff!
157 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
158 ground = new FGGround(ident);
159 separateGround = false;
162 ground->SetDisplay();
164 ground->SetNoDisplay();
168 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
169 // Initialise ground anyway to avoid segfault later
170 ground = new FGGround(ident);
171 separateGround = false;
174 ground->SetDisplay();
176 ground->SetNoDisplay();
180 // Get the airport elevation
181 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
185 // FIXME - this currently assumes use of the active rwy by the user.
186 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
188 // Assume the user is started at the threshold ready to take-off
189 TowerPlaneRec* t = new TowerPlaneRec;
190 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
191 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
192 t->leg = TAKEOFF_ROLL;
195 t->clearedToTakeOff = true;
196 rwyList.push_back(t);
200 void FGTower::Update(double dt) {
201 static int ii = 0; // Counter for spreading the load
203 //cout << "T" << flush;
204 // Each time step, what do we need to do?
205 // We need to go through the list of outstanding requests and acknowedgements
206 // and process at least one of them.
207 // We need to go through the list of planes under our control and check if
208 // any need to be addressed.
209 // We need to check for planes not under our control coming within our
210 // control area and address if necessary.
212 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
214 // Sort the arriving planes
216 // Calculate the eta of each plane to the threshold.
217 // For ground traffic this is the fastest they can get there.
218 // For air traffic this is the middle approximation.
220 doThresholdETACalc();
223 // Order the list of traffic as per expected threshold use and flag any conflicts
225 bool conflicts = doThresholdUseOrder();
228 // sortConficts() !!!
230 // Do one plane from the hold list
232 if(holdList.size()) {
233 //cout << "A" << endl;
234 //cout << "*holdListItr = " << *holdListItr << endl;
235 if(holdListItr == holdList.end()) {
236 holdListItr = holdList.begin();
238 //cout << "*holdListItr = " << *holdListItr << endl;
239 //Process(*holdListItr);
240 TowerPlaneRec* t = *holdListItr;
241 //cout << "t = " << t << endl;
242 if(t->holdShortReported) {
243 //cout << "B" << endl;
244 double responseTime = 10.0; // seconds - this should get more sophisticated at some point
245 if(t->clearanceCounter > responseTime) {
246 //cout << "C" << endl;
248 //cout << "D" << endl;
250 //cout << "E" << endl;
251 // Do nothing for now - consider acknowloging hold short eventually
254 string trns = t->plane.callsign;
255 //if(departed plane < some threshold in time away) {
258 t->clearedToLineUp = true;
259 t->planePtr->RegisterTransmission(3); // cleared to line-up
260 t->leg = TAKEOFF_ROLL;
261 //} else if(arriving plane < some threshold away) {
262 } else if(0) { // FIXME
263 trns += " cleared immediate take-off";
264 // TODO - add traffic is... ?
265 t->clearedToTakeOff = true;
266 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
267 t->leg = TAKEOFF_ROLL;
269 trns += " cleared for take-off";
270 // TODO - add traffic is... ?
271 t->clearedToTakeOff = true;
272 t->planePtr->RegisterTransmission(4); // cleared to take-off
273 t->leg = TAKEOFF_ROLL;
276 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
278 t->holdShortReported = false;
279 t->clearanceCounter = 0;
280 rwyList.push_back(t);
282 holdList.erase(holdListItr);
283 holdListItr = holdList.begin();
286 // possibly tell him to hold and what position he is?
289 t->clearanceCounter += (dt * holdList.size() * ii_max);
296 // 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!!
299 if(!rwyList.size()) {
302 rwyListItr = rwyList.begin();
303 TowerPlaneRec* t = *rwyListItr;
305 bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
306 // TODO - how do we find the position when it's not the user?
308 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
311 // TODO - tell it to taxi / contact ground / don't delete it etc!
312 } else if(t->opType == OUTBOUND) {
313 depList.push_back(t);
315 } else if(t->opType == CIRCUIT) {
316 circuitList.push_back(t);
318 } else if(t->opType == TTT_UNKNOWN) {
319 depList.push_back(t);
320 circuitList.push_back(t);
323 // HELP - we shouldn't ever get here!!!
326 } // else TODO figure out what to do when it's not the user
331 // do the ciruit list
333 // Clear the constraints - we recalculate here.
335 downwind_leg_pos = 0.0;
336 crosswind_leg_pos = 0.0;
337 if(circuitList.size()) {
338 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!!
339 TowerPlaneRec* t = *circuitListItr;
340 Point3D tortho = ortho.ConvertToLocal(t->pos);
342 // Need to figure out which leg he's on
343 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
344 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
345 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
347 // could be either takeoff, climbout or landing - check orthopos.y
348 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == LANDING_ROLL)) {
349 t->leg = LANDING_ROLL;
350 //cout << "Landing_roll\n";
352 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
353 //cout << "Climbout\n";
355 } else if(abs(ho) < 60) {
357 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
358 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
365 } else if(abs(ho) < 120) {
367 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
368 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
370 //cout << "Crosswind\n";
375 } else if(abs(ho) < 150) {
377 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
378 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
388 //cout << "Downwind\n";
391 t->leg = t->planePtr->GetLeg();
395 // 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.
396 base_leg_pos = tortho.y();
399 // Fall through to base
401 base_leg_pos = tortho.y();
404 // Fall through to downwind
406 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
407 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
408 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
411 // Fall through to crosswind
413 crosswind_leg_pos = tortho.y();
416 // Fall through to climbout
418 // Only use current by constraint as largest
419 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.x() : crosswind_leg_pos);
435 if(!separateGround) {
436 // The display stuff might have to get more clever than this when not separate
437 // since the tower and ground might try communicating simultaneously even though
438 // they're mean't to be the same contoller/frequency!!
440 ground->SetDisplay();
442 ground->SetNoDisplay();
448 // How big should ii get - ie how long should the update cycle interval stretch?
455 // Figure out which runways are active.
456 // For now we'll just be simple and do one active runway - eventually this will get much more complex
457 // This is a private function - public interface to the results of this is through GetActiveRunway
458 void FGTower::DoRwyDetails() {
459 //cout << "GetRwyDetails called" << endl;
461 // Based on the airport-id and wind get the active runway
462 SGPath path( globals->get_fg_root() );
463 path.append( "Airports" );
464 path.append( "runways.mk4" );
465 FGRunways runways( path.c_str() );
468 double hdg = wind_from_hdg->getDoubleValue();
469 double speed = wind_speed_knots->getDoubleValue();
470 hdg = (speed == 0.0 ? 270.0 : hdg);
471 //cout << "Heading = " << hdg << '\n';
474 bool rwyGood = runways.search(ident, int(hdg), &runway);
476 activeRwy = runway.rwy_no;
477 rwy.rwyID = runway.rwy_no;
478 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
480 // Get the threshold position
481 double other_way = runway.heading - 180.0;
482 while(other_way <= 0.0) {
485 // move to the +l end/center of the runway
486 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
487 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
488 Point3D ref = origin;
489 double tshlon, tshlat, tshr;
490 double tolon, tolat, tor;
491 rwy.length = runway.length * SG_FEET_TO_METER;
492 rwy.width = runway.width * SG_FEET_TO_METER;
493 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
494 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
495 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
496 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
497 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
498 // now copy what we need out of runway into rwy
499 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
500 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
501 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
502 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
503 rwy.hdg = runway.heading;
504 // Set the projection for the local area based on this active runway
505 ortho.Init(rwy.threshold_pos, rwy.hdg);
506 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
507 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
509 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
515 // Figure out if a given position lies on the active runway
516 // Might have to change when we consider more than one active rwy.
517 bool FGTower::OnActiveRunway(Point3D pt) {
518 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
519 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
520 Point3D xyp = ortho.ConvertToLocal(pt);
522 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
523 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
525 double rlen = rwy.length/2.0 + 5.0;
526 double rwidth = rwy.width/2.0;
527 double ldiff = fabs(xyp.y() - xyc.y());
528 double wdiff = fabs(xyp.x() - xyc.x());
530 return((ldiff < rlen) && (wdiff < rwidth));
534 // Figure out if a given position lies on any runway or not
535 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
536 bool FGTower::OnAnyRunway(Point3D pt) {
538 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
542 // Based on the airport-id, go through all the runways and check for a point in them
543 SGPath spath( globals->get_fg_root() );
544 spath.append( "Airports" );
545 spath.append( "runways.mk4" );
546 FGRunways runways( spath.c_str() );
548 // TODO - do we actually need to search for the airport - surely we already know our ident and
549 // can just search runways of our airport???
550 //cout << "Airport ident is " << ad.ident << '\n';
552 bool rwyGood = runways.search(ad.ident, &runway);
554 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
557 while(runway.id == ad.ident) {
558 on = OnRunway(pt, runway);
559 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
561 runways.next(&runway);
567 // Calculate the eta of each plane to the threshold.
568 // For ground traffic this is the fastest they can get there.
569 // For air traffic this is the middle approximation.
570 void FGTower::doThresholdETACalc() {
571 // For now we'll be very crude and hardwire expected speeds to C172-like values
572 // The speeds below are specified in knots IAS and then converted to m/s
573 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
574 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
575 double final_ias = 70.0 * 0.514444; // Speed during final approach
577 tower_plane_rec_list_iterator twrItr;
579 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
580 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
581 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
582 TowerPlaneRec* tpr = *twrItr;
583 Point3D op = ortho.ConvertToLocal(tpr->pos);
584 double dist_out_m = op.y();
585 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
586 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
587 if(tpr->opType == CIRCUIT) {
588 // It's complicated - depends on if base leg is delayed or not
589 if(tpr->leg == LANDING_ROLL) {
591 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
592 tpr->eta = fabs(dist_out_m) / final_ias;
593 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
594 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
596 // Need to calculate where base leg is likely to be
597 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
598 // 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
599 double nominal_base_dist_out_m = -1000;
600 double current_base_dist_out_m = nominal_base_dist_out_m;
601 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
602 double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
603 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
604 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
605 tpr->eta += dist_across_m / circuit_ias;
606 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
607 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
608 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?
609 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
610 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
612 // We've only just started - why not use a generic estimate?
615 } else if((tpr->opType == INBOUND) || (tpr->opType == STRAIGHT_IN)) {
618 // Must be outbound - ignore it!
620 //cout << "ETA = " << tpr->eta << '\n';
625 bool FGTower::doThresholdUseOrder() {
629 void FGTower::doCommunication() {
632 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
633 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
634 TowerPlaneRec* t = new TowerPlaneRec;
636 t->planePtr = requestee;
637 t->holdShortReported = true;
638 t->clearanceCounter = 0;
639 t->clearedToLineUp = false;
640 t->clearedToTakeOff = false;
641 t->opType = operation;
643 // HACK ALERT - THIS IS HARDWIRED FOR TESTING - FIXME TODO ETC
646 //cout << "t = " << t << '\n';
648 holdList.push_back(t);
651 void FGTower::RequestLandingClearance(string ID) {
652 //cout << "Request Landing Clearance called...\n";
654 void FGTower::RequestDepartureClearance(string ID) {
655 //cout << "Request Departure Clearance called...\n";
657 //void FGTower::ReportFinal(string ID);
658 //void FGTower::ReportLongFinal(string ID);
659 //void FGTower::ReportOuterMarker(string ID);
660 //void FGTower::ReportMiddleMarker(string ID);
661 //void FGTower::ReportInnerMarker(string ID);
662 //void FGTower::ReportGoingAround(string ID);
663 void FGTower::ReportRunwayVacated(string ID) {
664 //cout << "Report Runway Vacated Called...\n";