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"
36 TowerPlaneRec::TowerPlaneRec() :
38 clearedToLineUp(false),
39 clearedToTakeOff(false),
40 holdShortReported(false),
41 longFinalReported(false),
42 longFinalAcknowledged(false),
44 finalAcknowledged(false),
48 plane.callsign = "UNKNOWN";
51 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
53 clearedToLineUp(false),
54 clearedToTakeOff(false),
55 holdShortReported(false),
56 longFinalReported(false),
57 longFinalAcknowledged(false),
59 finalAcknowledged(false),
66 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
68 clearedToLineUp(false),
69 clearedToTakeOff(false),
70 holdShortReported(false),
71 longFinalReported(false),
72 longFinalAcknowledged(false),
74 finalAcknowledged(false),
78 plane.callsign = "UNKNOWN";
82 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
84 clearedToLineUp(false),
85 clearedToTakeOff(false),
86 holdShortReported(false),
87 longFinalReported(false),
88 longFinalAcknowledged(false),
90 finalAcknowledged(false),
102 ATCmgr = globals->get_ATC_mgr();
104 // Init the property nodes - TODO - need to make sure we're getting surface winds.
105 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
106 wind_speed_knots = fgGetNode("/environment/wind-speed-kts", true);
108 holdListItr = holdList.begin();
109 appListItr = appList.begin();
110 depListItr = depList.begin();
111 rwyListItr = rwyList.begin();
112 circuitListItr = circuitList.begin();
113 trafficListItr = trafficList.begin();
116 FGTower::~FGTower() {
117 if(!separateGround) {
122 void FGTower::Init() {
125 // Pointers to user's position
126 user_lon_node = fgGetNode("/position/longitude-deg", true);
127 user_lat_node = fgGetNode("/position/latitude-deg", true);
128 user_elev_node = fgGetNode("/position/altitude-ft", true);
130 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
131 // I'll punt the startup issue for now though!!!
134 // Setup the ground control at this airport
136 //cout << "Tower ident = " << ident << '\n';
137 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
138 if(a.ground_freq) { // Ground control
139 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
140 separateGround = true;
142 // Something has gone wrong :-(
143 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
144 ground = new FGGround(ident);
145 separateGround = false;
148 ground->SetDisplay();
150 ground->SetNoDisplay();
154 // Initialise ground anyway to do the shortest path stuff!
155 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
156 ground = new FGGround(ident);
157 separateGround = false;
160 ground->SetDisplay();
162 ground->SetNoDisplay();
166 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
167 // Initialise ground anyway to avoid segfault later
168 ground = new FGGround(ident);
169 separateGround = false;
172 ground->SetDisplay();
174 ground->SetNoDisplay();
178 // Get the airport elevation
179 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
183 // FIXME - this currently assumes use of the active rwy by the user.
184 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
186 // Assume the user is started at the threshold ready to take-off
187 TowerPlaneRec* t = new TowerPlaneRec;
188 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
189 t->opType = OUTBOUND; // How do we determine if the user actually wants to do circuits?
192 t->clearedToTakeOff = true;
193 rwyList.push_back(t);
197 void FGTower::Update(double dt) {
198 //cout << "T" << flush;
199 // Each time step, what do we need to do?
200 // We need to go through the list of outstanding requests and acknowedgements
201 // and process at least one of them.
202 // We need to go through the list of planes under our control and check if
203 // any need to be addressed.
204 // We need to check for planes not under our control coming within our
205 // control area and address if necessary.
207 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
209 // Sort the arriving planes
211 // Calculate the eta of each plane to the threshold.
212 // For ground traffic this is the fastest they can get there.
213 // For air traffic this is the middle approximation.
214 doThresholdETACalc();
216 // Order the list of traffic as per expected threshold use and flag any conflicts
217 bool conflicts = doThresholdUseOrder();
219 // sortConficts() !!!
221 // Do one plane from the hold list
222 if(holdList.size()) {
223 //cout << "A" << endl;
224 //cout << "*holdListItr = " << *holdListItr << endl;
225 if(holdListItr == holdList.end()) {
226 holdListItr = holdList.begin();
228 //cout << "*holdListItr = " << *holdListItr << endl;
229 //Process(*holdListItr);
230 TowerPlaneRec* t = *holdListItr;
231 //cout << "t = " << t << endl;
232 if(t->holdShortReported) {
233 //cout << "B" << endl;
234 double responseTime = 10.0; // seconds - this should get more sophisticated at some point
235 if(t->clearanceCounter > responseTime) {
236 //cout << "C" << endl;
238 //cout << "D" << endl;
240 //cout << "E" << endl;
241 // Do nothing for now - consider acknowloging hold short eventually
244 string trns = t->plane.callsign;
245 //if(departed plane < some threshold in time away) {
248 t->clearedToLineUp = true;
249 t->planePtr->RegisterTransmission(3); // cleared to line-up
250 //} else if(arriving plane < some threshold away) {
251 } else if(0) { // FIXME
252 trns += " cleared immediate take-off";
253 // TODO - add traffic is... ?
254 t->clearedToTakeOff = true;
255 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
257 trns += " cleared for take-off";
258 // TODO - add traffic is... ?
259 t->clearedToTakeOff = true;
260 t->planePtr->RegisterTransmission(4); // cleared to take-off
263 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
265 t->holdShortReported = false;
266 t->clearanceCounter = 0;
267 rwyList.push_back(t);
269 holdList.erase(holdListItr);
270 holdListItr = holdList.begin();
273 // possibly tell him to hold and what position he is?
276 t->clearanceCounter += (dt * holdList.size());
282 // 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!!
284 if(!rwyList.size()) {
287 rwyListItr = rwyList.begin();
288 TowerPlaneRec* t = *rwyListItr;
290 bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
291 // TODO - how do we find the position when it's not the user?
296 } // else TODO figure out what to do when it's not the user
302 if(!separateGround) {
303 // The display stuff might have to get more clever than this when not separate
304 // since the tower and ground might try communicating simultaneously even though
305 // they're mean't to be the same contoller/frequency!!
307 ground->SetDisplay();
309 ground->SetNoDisplay();
313 //cout << "R " << flush;
317 // Figure out which runways are active.
318 // For now we'll just be simple and do one active runway - eventually this will get much more complex
319 // This is a private function - public interface to the results of this is through GetActiveRunway
320 void FGTower::DoRwyDetails() {
321 //cout << "GetRwyDetails called" << endl;
323 // Based on the airport-id and wind get the active runway
324 SGPath path( globals->get_fg_root() );
325 path.append( "Airports" );
326 path.append( "runways.mk4" );
327 FGRunways runways( path.c_str() );
330 double hdg = wind_from_hdg->getDoubleValue();
331 double speed = wind_speed_knots->getDoubleValue();
332 hdg = (speed == 0.0 ? 270.0 : hdg);
333 //cout << "Heading = " << hdg << '\n';
336 bool rwyGood = runways.search(ident, int(hdg), &runway);
338 activeRwy = runway.rwy_no;
339 rwy.rwyID = runway.rwy_no;
340 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
342 // Get the threshold position
343 double other_way = runway.heading - 180.0;
344 while(other_way <= 0.0) {
347 // move to the +l end/center of the runway
348 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
349 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
350 Point3D ref = origin;
351 double tshlon, tshlat, tshr;
352 double tolon, tolat, tor;
353 rwy.length = runway.length * SG_FEET_TO_METER;
354 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
355 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
356 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
357 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
358 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
359 // now copy what we need out of runway into rwy
360 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
361 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
362 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
363 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
364 rwy.hdg = runway.heading;
365 // Set the projection for the local area based on this active runway
366 ortho.Init(rwy.threshold_pos, rwy.hdg);
367 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
368 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
370 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
376 // Figure out if a given position lies on the active runway
377 // Might have to change when we consider more than one active rwy.
378 bool FGTower::OnActiveRunway(Point3D pt) {
379 SGPath path( globals->get_fg_root() );
380 path.append( "Airports" );
381 path.append( "runways.mk4" );
382 FGRunways runways( path.c_str() );
385 bool rwyGood = runways.search(ident, activeRwy, &runway);
387 SG_LOG(SG_ATC, SG_WARN, "Unable to find runway " << activeRwy << " for airport ID " << ident << " in FGTower");
389 return false; // TODO - this is an emergency patch to correct a framerate problem - FIXME properly!!!
390 //return(OnRunway(pt, &runway) ? true : false);
394 // Figure out if a given position lies on any runway or not
395 bool FGTower::OnAnyRunway(Point3D pt) {
397 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
401 // Based on the airport-id, go through all the runways and check for a point in them
402 SGPath spath( globals->get_fg_root() );
403 spath.append( "Airports" );
404 spath.append( "runways.mk4" );
405 FGRunways runways( spath.c_str() );
407 // TODO - do we actually need to search for the airport - surely we already know our ident and
408 // can just search runways of our airport???
409 //cout << "Airport ident is " << ad.ident << '\n';
411 bool rwyGood = runways.search(ad.ident, &runway);
413 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
416 while(runway.id == ad.ident) {
417 on = OnRunway(pt, &runway);
418 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
420 runways.next(&runway);
426 // Calculate the eta of each plane to the threshold.
427 // For ground traffic this is the fastest they can get there.
428 // For air traffic this is the middle approximation.
429 void FGTower::doThresholdETACalc() {
430 // For now we'll be very crude and hardwire expected speeds to C172-like values
431 // The speeds below are specified in knots IAS and then converted to m/s
432 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
433 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
434 double final_ias = 70.0 * 0.514444; // Speed during final approach
436 tower_plane_rec_list_iterator twrItr;
438 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
439 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
440 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
441 TowerPlaneRec* tpr = *twrItr;
442 Point3D op = ortho.ConvertToLocal(tpr->pos);
443 double dist_out_m = op.y();
444 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
445 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
446 if(tpr->opType == CIRCUIT) {
447 // It's complicated - depends on if base leg is delayed or not
448 if(tpr->leg == TWR_LANDING_ROLL) {
450 } else if(tpr->leg == TWR_FINAL) {
451 tpr->eta = fabs(dist_out_m) / final_ias;
452 } else if(tpr->leg == TWR_BASE) {
453 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
455 // Need to calculate where base leg is likely to be
456 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
457 // 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
458 double nominal_base_dist_out_m = -1000;
459 double current_base_dist_out_m = nominal_base_dist_out_m;
460 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
461 double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
462 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
463 if(tpr->leg == TWR_DOWNWIND) {
464 tpr->eta += dist_across_m / circuit_ias;
465 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
466 } else if(tpr->leg == TWR_CROSSWIND) {
467 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?
468 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
469 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
471 // We've only just started - why not use a generic estimate?
474 } else if((tpr->opType == INBOUND) || (tpr->opType == STRAIGHT_IN)) {
477 // Must be outbound - ignore it!
479 //cout << "ETA = " << tpr->eta << '\n';
484 bool FGTower::doThresholdUseOrder() {
488 void FGTower::doCommunication() {
491 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIEntity* requestee, tower_traffic_type operation) {
492 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
493 TowerPlaneRec* t = new TowerPlaneRec;
495 t->planePtr = requestee;
496 t->holdShortReported = true;
497 t->clearanceCounter = 0;
498 t->clearedToLineUp = false;
499 t->clearedToTakeOff = false;
500 t->opType = operation;
502 // HACK ALERT - THIS IS HARDWIRED FOR TESTING - FIXME TODO ETC
505 //cout << "t = " << t << '\n';
507 holdList.push_back(t);
510 void FGTower::RequestLandingClearance(string ID) {
511 //cout << "Request Landing Clearance called...\n";
513 void FGTower::RequestDepartureClearance(string ID) {
514 //cout << "Request Departure Clearance called...\n";
516 //void FGTower::ReportFinal(string ID);
517 //void FGTower::ReportLongFinal(string ID);
518 //void FGTower::ReportOuterMarker(string ID);
519 //void FGTower::ReportMiddleMarker(string ID);
520 //void FGTower::ReportInnerMarker(string ID);
521 //void FGTower::ReportGoingAround(string ID);
522 void FGTower::ReportRunwayVacated(string ID) {
523 //cout << "Report Runway Vacated Called...\n";