]> git.mxchange.org Git - flightgear.git/blobdiff - src/ATC/tower.cxx
Return position
[flightgear.git] / src / ATC / tower.cxx
index 72eedfbed6c0674699cfabc3a125d8e8474d55d0..b84ba6ba6ccf3b6a331da065dc6c65625565938e 100644 (file)
@@ -28,6 +28,7 @@
 #include "ATCmgr.hxx"
 #include "ATCutils.hxx"
 #include "commlist.hxx"
+#include "AILocalTraffic.hxx"
 
 SG_USING_STD(cout);
 
@@ -42,7 +43,10 @@ longFinalReported(false),
 longFinalAcknowledged(false),
 finalReported(false),
 finalAcknowledged(false),
-leg(TWR_UNKNOWN),
+onRwy(false),
+nextOnRwy(false),
+opType(TTT_UNKNOWN),
+leg(LEG_UNKNOWN),
 isUser(false)
 {
        plane.callsign = "UNKNOWN";
@@ -57,7 +61,10 @@ longFinalReported(false),
 longFinalAcknowledged(false),
 finalReported(false),
 finalAcknowledged(false),
-leg(TWR_UNKNOWN),
+onRwy(false),
+nextOnRwy(false),
+opType(TTT_UNKNOWN),
+leg(LEG_UNKNOWN),
 isUser(false)
 {
        plane = p;
@@ -72,7 +79,10 @@ longFinalReported(false),
 longFinalAcknowledged(false),
 finalReported(false),
 finalAcknowledged(false),
-leg(TWR_UNKNOWN),
+onRwy(false),
+nextOnRwy(false),
+opType(TTT_UNKNOWN),
+leg(LEG_UNKNOWN),
 isUser(false)
 {
        plane.callsign = "UNKNOWN";
@@ -88,7 +98,10 @@ longFinalReported(false),
 longFinalAcknowledged(false),
 finalReported(false),
 finalAcknowledged(false),
-leg(TWR_UNKNOWN),
+onRwy(false),
+nextOnRwy(false),
+opType(TTT_UNKNOWN),
+leg(LEG_UNKNOWN),
 isUser(false)
 {
        plane = p;
@@ -103,7 +116,7 @@ FGTower::FGTower() {
        
        // Init the property nodes - TODO - need to make sure we're getting surface winds.
        wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
-       wind_speed_knots = fgGetNode("/environment/wind-speed-kts", true);
+       wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
        
        holdListItr = holdList.begin();
        appListItr = appList.begin();
@@ -111,6 +124,8 @@ FGTower::FGTower() {
        rwyListItr = rwyList.begin();
        circuitListItr = circuitList.begin();
        trafficListItr = trafficList.begin();
+       
+       freqClear = true;
 }
 
 FGTower::~FGTower() {
@@ -126,6 +141,7 @@ void FGTower::Init() {
        user_lon_node = fgGetNode("/position/longitude-deg", true);
        user_lat_node = fgGetNode("/position/latitude-deg", true);
        user_elev_node = fgGetNode("/position/altitude-ft", true);
+       user_hdg_node = fgGetNode("/orientation/heading-deg", true);
        
        // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
        // I'll punt the startup issue for now though!!!
@@ -186,7 +202,9 @@ void FGTower::Init() {
                // Assume the user is started at the threshold ready to take-off
                TowerPlaneRec* t = new TowerPlaneRec;
                t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
-               t->opType = OUTBOUND;   // How do we determine if the user actually wants to do circuits?
+               t->plane.type = GA_SINGLE;
+               t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
+               t->leg = TAKEOFF_ROLL;
                t->isUser = true;
                t->planePtr = NULL;
                t->clearedToTakeOff = true;
@@ -195,105 +213,412 @@ void FGTower::Init() {
 }
 
 void FGTower::Update(double dt) {
+       static int ii = 0;      // Counter for spreading the load
+       int ii_max = 15;
        //cout << "T" << flush;
-    // Each time step, what do we need to do?
-    // We need to go through the list of outstanding requests and acknowedgements
-    // and process at least one of them.
-    // We need to go through the list of planes under our control and check if
-    // any need to be addressed.
-    // We need to check for planes not under our control coming within our 
-    // control area and address if necessary.
-
+       // Each time step, what do we need to do?
+       // We need to go through the list of outstanding requests and acknowedgements
+       // and process at least one of them.
+       // We need to go through the list of planes under our control and check if
+       // any need to be addressed.
+       // We need to check for planes not under our control coming within our 
+       // control area and address if necessary.
+       
        // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
        
        // Sort the arriving planes
-
+       
        // Calculate the eta of each plane to the threshold.
        // For ground traffic this is the fastest they can get there.
        // For air traffic this is the middle approximation.
-       doThresholdETACalc();
+       if(ii == 1) {
+               doThresholdETACalc();
+       }
        
        // Order the list of traffic as per expected threshold use and flag any conflicts
-       bool conflicts = doThresholdUseOrder();
+       if(ii == 2) {
+               bool conflicts = doThresholdUseOrder();
+       }
        
        // sortConficts() !!!
        
        // Do one plane from the hold list
-       if(holdList.size()) {
-               //cout << "A" << endl;
-               //cout << "*holdListItr = " << *holdListItr << endl;
-               if(holdListItr == holdList.end()) {
-                       holdListItr = holdList.begin();
-               }
-               //cout << "*holdListItr = " << *holdListItr << endl;
-               //Process(*holdListItr);
-               TowerPlaneRec* t = *holdListItr;
-               //cout << "t = " << t << endl;
-               if(t->holdShortReported) {
-                       //cout << "B" << endl;
-                       double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
-                       if(t->clearanceCounter > responseTime) {
-                               //cout << "C" << endl;
+       if(ii == 4) {
+               if(holdList.size()) {
+                       //cout << "*holdListItr = " << *holdListItr << endl;
+                       if(holdListItr == holdList.end()) {
+                               holdListItr = holdList.begin();
+                       }
+                       //cout << "*holdListItr = " << *holdListItr << endl;
+                       //Process(*holdListItr);
+                       TowerPlaneRec* t = *holdListItr;
+                       //cout << "t = " << t << endl;
+                       if(t->holdShortReported) {
+                               double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
+                               if(t->clearanceCounter > responseTime) {
+                                       if(t->nextOnRwy) {
+                                               if(rwyOccupied) {
+                                                       // Do nothing for now - consider acknowloging hold short eventually
+                                               } else {
+                                                       // Lets Roll !!!!
+                                                       string trns = t->plane.callsign;
+                                                       //if(departed plane < some threshold in time away) {
+                                                               if(0) {         // FIXME
+                                                                       trns += " line up";
+                                                                       t->clearedToLineUp = true;
+                                                                       t->planePtr->RegisterTransmission(3);   // cleared to line-up
+                                                                       t->leg = TAKEOFF_ROLL;
+                                                       //} else if(arriving plane < some threshold away) {
+                                                               } else if(GetTrafficETA(2) < 150.0) {
+                                                                       trns += " cleared immediate take-off";
+                                                                       if(trafficList.size()) {
+                                                                               tower_plane_rec_list_iterator trfcItr = trafficList.begin();
+                                                                               trfcItr++;      // At the moment the holding plane should be first in trafficList.
+                                                                                                       // Note though that this will break if holding planes aren't put in trafficList in the future.
+                                                                               TowerPlaneRec* trfc = *trfcItr;
+                                                                               trns += "... traffic is";
+                                                                               switch(trfc->plane.type) {
+                                                                               case UNKNOWN:
+                                                                                       break;
+                                                                               case GA_SINGLE:
+                                                                                       trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
+                                                                                       break;
+                                                                               case GA_HP_SINGLE:
+                                                                                       trns += " a Piper";
+                                                                                       break;
+                                                                               case GA_TWIN:
+                                                                                       trns += " a King-air";
+                                                                                       break;
+                                                                               case GA_JET:
+                                                                                       trns += " a Learjet";
+                                                                                       break;
+                                                                               case MEDIUM:
+                                                                                       trns += " a Regional";
+                                                                                       break;
+                                                                               case HEAVY:
+                                                                                       trns += " a Heavy";
+                                                                                       break;
+                                                                               case MIL_JET:
+                                                                                       trns += " Military";
+                                                                                       break;
+                                                                               }
+                                                                               if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
+                                                                                       double miles_out = CalcDistOutMiles(trfc);
+                                                                                       if(miles_out < 2) {
+                                                                                               trns += " on final";
+                                                                                       } else {
+                                                                                               trns += " on ";
+                                                                                               trns += ConvertNumToSpokenDigits((int)miles_out);
+                                                                                               trns += " mile final";
+                                                                                       }
+                                                                               } else if(trfc->opType == CIRCUIT) {
+                                                                                       switch(trfc->leg) {
+                                                                                       case FINAL:
+                                                                                               trns += " on final";
+                                                                                               break;
+                                                                                       case TURN4:
+                                                                                               trns += " turning final";
+                                                                                               break;
+                                                                                       case BASE:
+                                                                                               trns += " on base";
+                                                                                               break;
+                                                                                       case TURN3:
+                                                                                               trns += " turning base";
+                                                                                               break;
+                                                                                       case DOWNWIND:
+                                                                                               trns += " in circuit";
+                                                                                               break;
+                                                                                       // And to eliminate compiler warnings...
+                                                                                       case TAKEOFF_ROLL: break;
+                                                                                       case CLIMBOUT:     break;
+                                                                                       case TURN1:        break;
+                                                                                       case CROSSWIND:    break;
+                                                                                       case TURN2:        break;
+                                                                                       case LANDING_ROLL: break;
+                                                                                       case LEG_UNKNOWN:  break;
+                                                                                       }
+                                                                               }
+                                                                       } else {
+                                                                               // By definition there should be some arriving traffic if we're cleared for immediate takeoff
+                                                                               SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
+                                                                       }
+                                                                       t->clearedToTakeOff = true;
+                                                                       t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
+                                                                       t->leg = TAKEOFF_ROLL;
+                                                               } else {
+                                                                       trns += " cleared for take-off";
+                                                                       // TODO - add traffic is... ?
+                                                                       t->clearedToTakeOff = true;
+                                                                       t->planePtr->RegisterTransmission(4);   // cleared to take-off
+                                                                       t->leg = TAKEOFF_ROLL;
+                                                               }
+                                                               if(display) {
+                                                                       globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                                                               }
+                                                               t->holdShortReported = false;
+                                                               t->clearanceCounter = 0;
+                                                               rwyList.push_back(t);
+                                                               rwyOccupied = true;
+                                                               holdList.erase(holdListItr);
+                                                               holdListItr = holdList.begin();
+                                               }
+                                       } else {
+                                               // Tell him to hold and what position he is.
+                                               // Not currently sure under which circumstances we do or don't bother transmitting this.
+                                               string trns = t->plane.callsign;
+                                               trns += " hold position";
+                                               if(display) {
+                                                       globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                                               }
+                                               t->holdShortReported = false;
+                                               t->clearanceCounter = 0;
+                                               // TODO - add some idea of what traffic is blocking him.
+                                       }
+                               } else {
+                                       t->clearanceCounter += (dt * holdList.size() * ii_max);
+                               }
+                       } else {        // not responding to report, but still need to clear if clear
                                if(t->nextOnRwy) {
-                                       //cout << "D" << endl;
                                        if(rwyOccupied) {
-                                               //cout << "E" << endl;
                                                // Do nothing for now - consider acknowloging hold short eventually
                                        } else {
                                                // Lets Roll !!!!
                                                string trns = t->plane.callsign;
                                                //if(departed plane < some threshold in time away) {
-                                               if(0) {         // FIXME
-                                                       trns += " line up";
-                                                       t->clearedToLineUp = true;
-                                                       t->planePtr->RegisterTransmission(3);   // cleared to line-up
+                                                       if(0) {         // FIXME
+                                                               trns += " line up";
+                                                               t->clearedToLineUp = true;
+                                                               t->planePtr->RegisterTransmission(3);   // cleared to line-up
+                                                               t->leg = TAKEOFF_ROLL;
                                                //} else if(arriving plane < some threshold away) {
-                                               } else if(0) {  // FIXME
-                                                       trns += " cleared immediate take-off";
-                                                       // TODO - add traffic is... ?
-                                                       t->clearedToTakeOff = true;
-                                                       t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
+                                                       } else if(GetTrafficETA(2) < 150.0) {
+                                                               trns += " cleared immediate take-off";
+                                                               // TODO - add traffic is... ?
+                                                               t->clearedToTakeOff = true;
+                                                               t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
+                                                               t->leg = TAKEOFF_ROLL;
+                                                       } else {
+                                                               trns += " cleared for take-off";
+                                                               // TODO - add traffic is... ?
+                                                               t->clearedToTakeOff = true;
+                                                               t->planePtr->RegisterTransmission(4);   // cleared to take-off
+                                                               t->leg = TAKEOFF_ROLL;
+                                                       }
+                                                       if(display) {
+                                                               globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                                                       }
+                                                       rwyList.push_back(t);
+                                                       rwyOccupied = true;
+                                                       holdList.erase(holdListItr);
+                                                       holdListItr = holdList.begin();
+                                       }
+                               }
+                               // TODO - remove the considerable code duplication above!
+                       }
+                       ++holdListItr;
+               }
+       }
+       
+       // 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!!
+       // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
+       if(ii == 5) {
+               if(rwyOccupied) {
+                       if(!rwyList.size()) {
+                               rwyOccupied = false;
+                       } else {
+                               rwyListItr = rwyList.begin();
+                               TowerPlaneRec* t = *rwyListItr;
+                               if(t->isUser) {
+                                       bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
+                                       // TODO - how do we find the position when it's not the user?
+                                       if(!on_rwy) {
+                                               if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
+                                                       rwyList.pop_front();
+                                                       delete t;
+                                                       // TODO - tell it to taxi / contact ground / don't delete it etc!
+                                               } else if(t->opType == OUTBOUND) {
+                                                       depList.push_back(t);
+                                                       rwyList.pop_front();
+                                               } else if(t->opType == CIRCUIT) {
+                                                       circuitList.push_back(t);
+                                                       //cout << "Oggy oggy oggy\n";
+                                                       AddToTrafficList(t);
+                                                       rwyList.pop_front();
+                                               } else if(t->opType == TTT_UNKNOWN) {
+                                                       depList.push_back(t);
+                                                       circuitList.push_back(t);
+                                                       //cout << "Aggy aggy aggy\n";
+                                                       AddToTrafficList(t);
+                                                       rwyList.pop_front();
                                                } else {
-                                                       trns += " cleared for take-off";
-                                                       // TODO - add traffic is... ?
-                                                       t->clearedToTakeOff = true;
-                                                       t->planePtr->RegisterTransmission(4);   // cleared to take-off
+                                                       // HELP - we shouldn't ever get here!!!
                                                }
-                                               if(display) {
-                                                       globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
+                                       }
+                               } // else TODO figure out what to do when it's not the user
+                       }
+               }
+       }
+       
+       // do the ciruit list
+       if(ii == 6) {
+               // Clear the constraints - we recalculate here.
+               base_leg_pos = 0.0;
+               downwind_leg_pos = 0.0;
+               crosswind_leg_pos = 0.0;
+               if(circuitList.size()) {
+                       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!!
+                       TowerPlaneRec* t = *circuitListItr;
+                       if(t->isUser) {
+                               t->pos.setlon(user_lon_node->getDoubleValue());
+                               t->pos.setlat(user_lat_node->getDoubleValue());
+                               t->pos.setelev(user_elev_node->getDoubleValue());
+                       } else {
+                               // TODO - set/update the position if it's an AI plane
+                       }
+                       Point3D tortho = ortho.ConvertToLocal(t->pos);
+                       if(t->isUser) {
+                               // Need to figure out which leg he's on
+                               //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
+                               double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
+                               //cout << " ho = " << ho << '\n';
+                               // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
+                               // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
+                               if(abs(ho) < 30) {
+                                       // could be either takeoff, climbout or landing - check orthopos.y
+                                       //cout << "tortho.y = " << tortho.y() << '\n';
+                                       if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
+                                               t->leg = FINAL;
+                                               //cout << "Final\n";
+                                       } else {
+                                               t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
+                                               //cout << "Climbout\n";
+                                               // If it's the user we may be unsure of his/her intentions.
+                                               // (Hopefully the AI planes won't try confusing the sim!!!)
+                                               if(t->opType == TTT_UNKNOWN) {
+                                                       if(tortho.y() > 5000) {
+                                                               // 5 km out from threshold - assume it's a departure
+                                                               t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
+                                                               // Since we are unknown operation we should be in depList already.
+                                                               circuitList.erase(circuitListItr);
+                                                               RemoveFromTrafficList(t->plane.callsign);
+                                                               circuitListItr = circuitList.begin();
+                                                       }
+                                               } else if(t->opType == CIRCUIT) {
+                                                       if(tortho.y() > 10000) {
+                                                               // 10 km out - assume the user has abandoned the circuit!!
+                                                               t->opType = OUTBOUND;
+                                                               depList.push_back(t);
+                                                               circuitList.erase(circuitListItr);
+                                                               circuitListItr = circuitList.begin();
+                                                       }
                                                }
-                                               t->holdShortReported = false;
-                                               t->clearanceCounter = 0;
-                                               rwyList.push_back(t);
-                                               rwyOccupied = true;
-                                               holdList.erase(holdListItr);
-                                               holdListItr = holdList.begin();
+                                       }
+                               } else if(abs(ho) < 60) {
+                                       // turn1 or turn 4
+                                       // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
+                                       if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
+                                               t->leg = TURN1;
+                                               //cout << "Turn1\n";
+                                       } else {
+                                               t->leg = TURN4;
+                                               //cout << "Turn4\n";
+                                       }
+                               } else if(abs(ho) < 120) {
+                                       // crosswind or base
+                                       // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
+                                       if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
+                                               t->leg = CROSSWIND;
+                                               //cout << "Crosswind\n";
+                                       } else {
+                                               t->leg = BASE;
+                                               //cout << "Base\n";
+                                       }
+                               } else if(abs(ho) < 150) {
+                                       // turn2 or turn 3
+                                       // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
+                                       if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
+                                               t->leg = TURN2;
+                                               //cout << "Turn2\n";
+                                       } else {
+                                               t->leg = TURN3;
+                                               // Probably safe now to assume the user is flying a circuit
+                                               t->opType = CIRCUIT;
+                                               //cout << "Turn3\n";
                                        }
                                } else {
-                                       // possibly tell him to hold and what position he is?
+                                       // downwind
+                                       t->leg = DOWNWIND;
+                                       //cout << "Downwind\n";
                                }
                        } else {
-                               t->clearanceCounter += (dt * holdList.size());
+                               t->leg = t->planePtr->GetLeg();
                        }
-               }                               
-               ++holdListItr;
+                       switch(t->leg) {
+                       case FINAL:
+                               // 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.
+                               base_leg_pos = tortho.y();
+                               //cout << "base_leg_pos = " << base_leg_pos << '\n';
+                               break;
+                       case TURN4:
+                               // Fall through to base
+                       case BASE:
+                               base_leg_pos = tortho.y();
+                               //cout << "base_leg_pos = " << base_leg_pos << '\n';
+                               break;
+                       case TURN3:
+                               // Fall through to downwind
+                       case DOWNWIND:
+                               // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
+                               base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
+                               //cout << "base_leg_pos = " << base_leg_pos;
+                               downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
+                               //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
+                               break;
+                       case TURN2:
+                               // Fall through to crosswind
+                       case CROSSWIND:
+                               crosswind_leg_pos = tortho.y();
+                               //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
+                               break;
+                       case TURN1:
+                               // Fall through to climbout
+                       case CLIMBOUT:
+                               // Only use current by constraint as largest
+                               crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
+                               //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
+                               break;
+                       case TAKEOFF_ROLL:
+                               break;
+                       case LEG_UNKNOWN:
+                               break;
+                       case LANDING_ROLL:
+                               break;
+                       default:
+                               break;
+                       }
+               }
        }
        
-       // 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!!
-       if(rwyOccupied) {
-               if(!rwyList.size()) {
-                       rwyOccupied = false;
-               } else {
-                       rwyListItr = rwyList.begin();
-                       TowerPlaneRec* t = *rwyListItr;
+       // Do one plane from the approach list
+       if(ii == 7) {
+               if(appList.size()) {
+                       if(appListItr == appList.end()) {
+                               appListItr = appList.begin();
+                       }
+                       TowerPlaneRec* t = *appListItr;
+                       //cout << "t = " << t << endl;
                        if(t->isUser) {
-                               bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
-                               // TODO - how do we find the position when it's not the user?
-                               if(!on_rwy) {
-                                       rwyList.pop_front();
-                                       delete t;
-                               }
-                       } // else TODO figure out what to do when it's not the user
+                               t->pos.setlon(user_lon_node->getDoubleValue());
+                               t->pos.setlat(user_lat_node->getDoubleValue());
+                               t->pos.setelev(user_elev_node->getDoubleValue());
+                       } else {
+                               // TODO - set/update the position if it's an AI plane
+                       }                               
+                       if(t->nextOnRwy && !(t->clearedToLand)) {
+                               // check distance away and whether runway occupied
+                               // and schedule transmission if necessary
+                       }                               
+                       ++appListItr;
                }
        }
        
@@ -310,7 +635,55 @@ void FGTower::Update(double dt) {
                }
                ground->Update(dt);
        }
-       //cout << "R " << flush;
+       
+       ++ii;
+       // How big should ii get - ie how long should the update cycle interval stretch?
+       if(ii >= ii_max) {
+               ii = 0;
+       }
+
+       if(ident == "KEMT") {   
+               // For AI debugging convienience - may be removed
+               Point3D user_pos;
+               user_pos.setlon(user_lon_node->getDoubleValue());
+               user_pos.setlat(user_lat_node->getDoubleValue());
+               user_pos.setelev(user_elev_node->getDoubleValue());
+               Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
+               fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
+               fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
+               fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
+       }
+}
+
+
+// Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
+// plus the constraint position as a rwy orientated orthopos (meters)
+bool FGTower::GetCrosswindConstraint(double& cpos) {
+       if(crosswind_leg_pos != 0.0) {
+               cpos = crosswind_leg_pos;
+               return(true);
+       } else {
+               cpos = 0.0;
+               return(false);
+       }
+}
+bool FGTower::GetDownwindConstraint(double& dpos) {
+       if(downwind_leg_pos != 0.0) {
+               dpos = downwind_leg_pos;
+               return(true);
+       } else {
+               dpos = 0.0;
+               return(false);
+       }
+}
+bool FGTower::GetBaseConstraint(double& bpos) {
+       if(base_leg_pos != 0.0) {
+               bpos = base_leg_pos;
+               return(true);
+       } else {
+               bpos = 0.0;
+               return(false);
+       }
 }
 
 
@@ -321,10 +694,6 @@ void FGTower::DoRwyDetails() {
        //cout << "GetRwyDetails called" << endl;
        
        // Based on the airport-id and wind get the active runway
-       SGPath path( globals->get_fg_root() );
-       path.append( "Airports" );
-       path.append( "runways.mk4" );
-       FGRunways runways( path.c_str() );
        
        //wind
        double hdg = wind_from_hdg->getDoubleValue();
@@ -333,7 +702,7 @@ void FGTower::DoRwyDetails() {
        //cout << "Heading = " << hdg << '\n';
        
        FGRunway runway;
-       bool rwyGood = runways.search(ident, int(hdg), &runway);
+       bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
        if(rwyGood) {
                activeRwy = runway.rwy_no;
                rwy.rwyID = runway.rwy_no;
@@ -351,6 +720,7 @@ void FGTower::DoRwyDetails() {
        double tshlon, tshlat, tshr;
                double tolon, tolat, tor;
                rwy.length = runway.length * SG_FEET_TO_METER;
+               rwy.width = runway.width * SG_FEET_TO_METER;
        geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
                                rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
        geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
@@ -376,22 +746,24 @@ void FGTower::DoRwyDetails() {
 // Figure out if a given position lies on the active runway
 // Might have to change when we consider more than one active rwy.
 bool FGTower::OnActiveRunway(Point3D pt) {
-       SGPath path( globals->get_fg_root() );
-       path.append( "Airports" );
-       path.append( "runways.mk4" );
-       FGRunways runways( path.c_str() );
+       // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
+       Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
+       Point3D xyp = ortho.ConvertToLocal(pt);
        
-       FGRunway runway;
-       bool rwyGood = runways.search(ident, activeRwy, &runway);
-       if(!rwyGood) {
-               SG_LOG(SG_ATC, SG_WARN, "Unable to find runway " << activeRwy << " for airport ID " << ident << " in FGTower");
-       }
-       return false;   // TODO - this is an emergency patch to correct a framerate problem - FIXME properly!!!
-       //return(OnRunway(pt, &runway) ? true : false);
+       //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
+       //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
+
+       double rlen = rwy.length/2.0 + 5.0;
+       double rwidth = rwy.width/2.0;
+       double ldiff = fabs(xyp.y() - xyc.y());
+       double wdiff = fabs(xyp.x() - xyc.x());
+
+       return((ldiff < rlen) && (wdiff < rwidth));
 }      
 
 
 // Figure out if a given position lies on any runway or not
+// Only call this at startup - reading the runways database is expensive and needs to be fixed!
 bool FGTower::OnAnyRunway(Point3D pt) {
        ATCData ad;
        double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
@@ -399,96 +771,219 @@ bool FGTower::OnAnyRunway(Point3D pt) {
                return(false);
        }
        // Based on the airport-id, go through all the runways and check for a point in them
-       SGPath spath( globals->get_fg_root() );
-       spath.append( "Airports" );
-       spath.append( "runways.mk4" );
-       FGRunways runways( spath.c_str() );
        
        // TODO - do we actually need to search for the airport - surely we already know our ident and
        // can just search runways of our airport???
        //cout << "Airport ident is " << ad.ident << '\n';
        FGRunway runway;
-       bool rwyGood = runways.search(ad.ident, &runway);
+       bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
        if(!rwyGood) {
                SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
        }
        bool on = false;
        while(runway.id == ad.ident) {          
-               on = OnRunway(pt, &runway);
+               on = OnRunway(pt, runway);
                //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
                if(on) return(true);
-               runways.next(&runway);          
+               globals->get_runways()->next(&runway);          
        }
        return(on);
 }
 
 
-// Calculate the eta of each plane to the threshold.
+// Returns true if successful
+bool FGTower::RemoveFromTrafficList(string id) {
+       tower_plane_rec_list_iterator twrItr;
+       for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               if(tpr->plane.callsign == id) {
+                       trafficList.erase(twrItr);
+                       return(true);
+               }
+       }       
+       SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
+       return(false);
+}
+
+
+// Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
+// and set nextOnRwy if so.
+// Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
+// For planes holding they are put in the first position with time to go, and the return value is
+// true if in the first position (nextOnRwy) and false otherwise.
+bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
+       //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << '\n';
+       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.
+       bool conflict = false;
+       double lastETA = 0.0;
+       bool firstTime = true;
+       // FIXME - make this more robust for different plane types eg. light following heavy.
+       tower_plane_rec_list_iterator twrItr;
+       for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               if(holding) {
+                       //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
+                       //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
+                       if(tpr->eta  - lastETA > separation_time) {
+                               t->nextOnRwy = firstTime;
+                               trafficList.insert(twrItr, t);
+                               return(firstTime);
+                       }
+                       firstTime = false;
+               } else {
+                       if(t->eta < tpr->eta) {
+                               // Ugg - this one's tricky.
+                               // It depends on what the two planes are doing and whether there's a conflict what we do.
+                               if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
+                                       if(tpr->nextOnRwy) {
+                                               tpr->nextOnRwy = false;
+                                               t->nextOnRwy = true;
+                                       }
+                                       trafficList.insert(twrItr, t);
+                               } else {        // Ooops - this ones tricky - we have a potential conflict!
+                                       conflict = true;
+                               }
+                               return(conflict);
+                       }
+               }
+       }
+       // If we get here we must be at the end of the list, or maybe the list is empty.
+       if(!trafficList.size()) {
+               t->nextOnRwy = true;
+               // conflict and firstTime should be false and true respectively in this case anyway.
+       }
+       trafficList.push_back(t);
+       return(holding ? firstTime : conflict);
+}
+
+
+// Calculate the eta of a plane to the threshold.
 // For ground traffic this is the fastest they can get there.
 // For air traffic this is the middle approximation.
-void FGTower::doThresholdETACalc() {
+void FGTower::CalcETA(TowerPlaneRec* tpr) {
        // For now we'll be very crude and hardwire expected speeds to C172-like values
        // The speeds below are specified in knots IAS and then converted to m/s
        double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
        double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
        double final_ias = 70.0 * 0.514444;             // Speed during final approach
-
-       tower_plane_rec_list_iterator twrItr;
-
+       
        // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
        // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
-       for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
-               TowerPlaneRec* tpr = *twrItr;
-               Point3D op = ortho.ConvertToLocal(tpr->pos);
-               double dist_out_m = op.y();
-               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
-               //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
-               if(tpr->opType == CIRCUIT) {
-                       // It's complicated - depends on if base leg is delayed or not
-                       if(tpr->leg == TWR_LANDING_ROLL) {
-                               tpr->eta = 0;
-                       } else if(tpr->leg == TWR_FINAL) {
-                               tpr->eta = fabs(dist_out_m) / final_ias;
-                       } else if(tpr->leg == TWR_BASE) {
-                               tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
+       
+       Point3D op = ortho.ConvertToLocal(tpr->pos);
+       double dist_out_m = op.y();
+       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
+       //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
+       
+       if(tpr->opType == STRAIGHT_IN) {
+               double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
+               if(dist_to_go_m < 1000) {
+                       tpr->eta = dist_to_go_m / final_ias;
+               } else {
+                       tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
+               }
+       } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
+               // It's complicated - depends on if base leg is delayed or not
+               if(tpr->leg == LANDING_ROLL) {
+                       tpr->eta = 0;
+               } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
+                       tpr->eta = fabs(dist_out_m) / final_ias;
+               } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
+                       tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
+               } else {
+                       // Need to calculate where base leg is likely to be
+                       // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
+                       // 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
+                       double nominal_base_dist_out_m = -1000;
+                       double current_base_dist_out_m;
+                       if(!GetBaseConstraint(current_base_dist_out_m)) {
+                               current_base_dist_out_m = nominal_base_dist_out_m;
+                       }
+                       double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
+                       double current_dist_across_m;
+                       if(!GetDownwindConstraint(current_dist_across_m)) {
+                               current_dist_across_m = nominal_dist_across_m;
+                       }
+                       double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
+                       tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
+                       if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
+                               tpr->eta += dist_across_m / circuit_ias;
+                               tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
+                       } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
+                               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?
+                               tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
+                               tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
                        } else {
-                               // Need to calculate where base leg is likely to be
-                               // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
-                               // 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
-                               double nominal_base_dist_out_m = -1000;
-                               double current_base_dist_out_m = nominal_base_dist_out_m;
-                               double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
-                               double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
-                               tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
-                               if(tpr->leg == TWR_DOWNWIND) {
-                                       tpr->eta += dist_across_m / circuit_ias;
-                                       tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
-                               } else if(tpr->leg == TWR_CROSSWIND) {
-                                       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?
-                                       tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
-                                       tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
-                               } else {
-                                       // We've only just started - why not use a generic estimate?
-                               }
+                               // We've only just started - why not use a generic estimate?
                        }
-               } else if((tpr->opType == INBOUND) || (tpr->opType == STRAIGHT_IN)) {
-                       // It's simpler!
-               } else {
-                       // Must be outbound - ignore it!
                }
                //cout << "ETA = " << tpr->eta << '\n';
+       } else {
+               tpr->eta = 99999;
+       }       
+}
+
+
+// Calculate the distance of a plane to the threshold in meters
+// TODO - Modify to calculate flying distance of a plane in the circuit
+double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
+       return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
+}
+
+
+// Calculate the distance of a plane to the threshold in miles
+// TODO - Modify to calculate flying distance of a plane in the circuit
+double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
+       return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
+}
+
+
+// Iterate through all the lists and call CalcETA for all the planes.
+void FGTower::doThresholdETACalc() {
+       tower_plane_rec_list_iterator twrItr;
+       // Do the approach list first
+       for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               CalcETA(tpr);
+       }       
+       // Then the circuit list
+       for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
+               TowerPlaneRec* tpr = *twrItr;
+               CalcETA(tpr);
        }
 }
                
 
+// Check that the planes in traffic list are correctly ordered,
+// that the nearest (timewise) is flagged next on rwy, and return
+// true if any threshold use conflicts are detected, false otherwise.
 bool FGTower::doThresholdUseOrder() {
-       return(true);
+       bool conflict = false;
+       
+       // TODO - write some code here!
+       
+       return(conflict);
 }
 
 void FGTower::doCommunication() {
 }
 
-void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIEntity* requestee, tower_traffic_type operation) {
+// Return the ETA of plane no. list_pos (1-based) in the traffic list.
+// i.e. list_pos = 1 implies next to use runway.
+double FGTower::GetTrafficETA(unsigned int list_pos) {
+       if(trafficList.size() < list_pos) {
+               return(99999);
+       }
+
+       tower_plane_rec_list_iterator twrItr;
+       twrItr = trafficList.begin();
+       for(unsigned int i = 1; i < list_pos; i++, twrItr++);
+       //cout << "ETA returned = " << (*twrItr)->eta << '\n';
+       return((*twrItr)->eta);
+}
+       
+
+void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
        // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
        TowerPlaneRec* t = new TowerPlaneRec;
        t->plane = plane;
@@ -499,8 +994,20 @@ void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIEntity* requestee, tower_tr
        t->clearedToTakeOff = false;
        t->opType = operation;
        
-       // HACK ALERT - THIS IS HARDWIRED FOR TESTING - FIXME TODO ETC
-       t->nextOnRwy = true;
+       //cout << "Hold Short reported by " << plane.callsign << '\n';
+       
+       bool next = AddToTrafficList(t, true);
+       
+       if(next) {
+               //cout << "Next to take off - respond with clearance\n";
+               double teta = GetTrafficETA(2);
+               if(teta < 150.0) {
+                       t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
+                       //cout << "Reducing response time to request due imminent traffic\n";
+               }
+       } else {
+               //cout << "Not next to take off - respond with hold\n";
+       }
        
        //cout << "t = " << t << '\n';
        
@@ -509,7 +1016,31 @@ void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIEntity* requestee, tower_tr
 
 void FGTower::RequestLandingClearance(string ID) {
        //cout << "Request Landing Clearance called...\n";
+       
+       // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
+       // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
+       
+       TowerPlaneRec* t = new TowerPlaneRec;
+       t->isUser = true;
+       t->clearedToLand = false;
+       t->pos.setlon(user_lon_node->getDoubleValue());
+       t->pos.setlat(user_lat_node->getDoubleValue());
+       t->pos.setelev(user_elev_node->getDoubleValue());
+       
+       // TODO
+       // Calculate where the user is in relation to the active runway and it's circuit
+       // and set the op-type as appropriate.
+       
+       // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
+       t->opType = STRAIGHT_IN;
+       
+       t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
+       t->plane.callsign = ID;
+       
+       appList.push_back(t);   // Not necessarily permanent
+       AddToTrafficList(t);
 }
+
 void FGTower::RequestDepartureClearance(string ID) {
        //cout << "Request Departure Clearance called...\n";
 }