]> git.mxchange.org Git - flightgear.git/blobdiff - src/ATC/trafficcontrol.cxx
functional radio signal attenuation
[flightgear.git] / src / ATC / trafficcontrol.cxx
index 53ddf28b5ec394dfdfd65cb83fbe513eccef230e..15520295a5ec24296b6b9fd84acfa95c08c80406 100644 (file)
 #endif
 
 #include <algorithm>
+#include <math.h>
+#include <stdlib.h>
+#include <deque>
+
+#include <osg/Geode>
+#include <osg/Geometry>
+#include <osg/MatrixTransform>
+#include <osg/Shape>
+
+#include <simgear/scene/material/EffectGeode.hxx>
+#include <simgear/scene/material/matlib.hxx>
+#include <simgear/scene/material/mat.hxx>
+#include <Scenery/scenery.hxx>
 
 #include "trafficcontrol.hxx"
+#include "atc_mgr.hxx"
 #include <AIModel/AIAircraft.hxx>
 #include <AIModel/AIFlightPlan.hxx>
 #include <AIModel/performancedata.hxx>
 #include <AIModel/performancedb.hxx>
+#include <ATC/atc_mgr.hxx>
 #include <Traffic/TrafficMgr.hxx>
 #include <Airports/groundnetwork.hxx>
 #include <Airports/dynamics.hxx>
-
+#include <Airports/simple.hxx>
+#define WITH_POINT_TO_POINT
+#include "itm.cpp"
 
 using std::sort;
 
@@ -74,7 +91,7 @@ time_t ActiveRunway::requestTimeSlot(time_t eta)
                 }
             } else {
                 if ((((*j) - (*i)) > (separation * 2))) {       // found a potential slot
-                    // now check whether this slow is usable:
+                    // now check whether this slot is usable:
                     // 1) eta should fall between the two points
                     //    i.e. eta > i AND eta < j
                     //
@@ -181,6 +198,11 @@ void FGTrafficRecord::setPositionAndIntentions(int pos,
     }
     //exit(1);
 }
+/**
+ * Check if another aircraft is ahead of the current one, and on the same 
+ * return true / false is the is/isn't the case.
+ *
+ ****************************************************************************/
 
 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
 {
@@ -397,6 +419,10 @@ void FGTrafficRecord::setHeadingAdjustment(double heading)
 
 bool FGTrafficRecord::pushBackAllowed()
 {
+    // With the user ATC / AI integration, checking whether the user's aircraft is near no longer works, because
+    // this will effectively block the user's aircraft itself from receiving pushback clearance. 
+    // So, what can we do?
+    /*
     double course, az2, dist;
     SGGeod curr(SGGeod::fromDegM(getLongitude(),
                                  getLatitude(), getAltitude()));
@@ -407,7 +433,13 @@ bool FGTrafficRecord::pushBackAllowed()
     SGGeodesy::inverse(curr, user, course, az2, dist);
     //cerr << "Distance to user : " << dist << endl;
     return (dist > 250);
+    */
+
 
+    // In essence, we should check whether the pusbback route itself, as well as the associcated
+    // taxiways near the pushback point are free of traffic. 
+    // To do so, we need to 
+    return true;
 }
 
 
@@ -447,9 +479,16 @@ bool FGATCInstruction::hasInstruction()
 
 FGATCController::FGATCController()
 {
+    //cerr << "running FGATController constructor" << endl;
     dt_count = 0;
     available = true;
     lastTransmission = 0;
+    initialized = false;
+}
+
+FGATCController::~FGATCController()
+{
+     //cerr << "running FGATController destructor" << endl;
 }
 
 string FGATCController::getGateName(FGAIAircraft * ref)
@@ -457,16 +496,23 @@ string FGATCController::getGateName(FGAIAircraft * ref)
     return ref->atGate();
 }
 
-void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
-                               AtcMsgDir msgDir)
+bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
+{ 
+    return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
+};
+
+void FGATCController::transmit(FGTrafficRecord * rec, FGAirportDynamics *parent, AtcMsgId msgId,
+                               AtcMsgDir msgDir, bool audible)
 {
     string sender, receiver;
     int stationFreq = 0;
     int taxiFreq = 0;
+    int towerFreq = 0;
     int freqId = 0;
     string atisInformation;
     string text;
     string taxiFreqStr;
+    string towerFreqStr;
     double heading = 0;
     string activeRunway;
     string fltType;
@@ -475,28 +521,38 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
     string transponderCode;
     FGAIFlightPlan *fp;
     string fltRules;
+    string instructionText;
+    int ground_to_air=0;
 
     //double commFreqD;
     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
+    if (rec->getAircraft()->getTaxiClearanceRequest()) {
+        instructionText = "push-back and taxi";
+    } else {
+        instructionText = "taxi";
+    }
     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
     switch (rec->getLeg()) {
+    case 1:
     case 2:
-    case 3:
         freqId = rec->getNextFrequency();
         stationFreq =
             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
         taxiFreq =
             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
-            getDynamics()->getGroundFrequency(3);
+            getDynamics()->getGroundFrequency(2);
+        towerFreq = 
+            rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
+            getDynamics()->getTowerFrequency(2);
         receiver =
             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
             getName() + "-Ground";
         atisInformation =
             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
-            getDynamics()->getAtisInformation();
+            getDynamics()->getAtisSequence();
         break;
-    case 4:
+    case 3:
         receiver =
             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
             getName() + "-Tower";
@@ -507,6 +563,7 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
         string tmp = sender;
         sender = receiver;
         receiver = tmp;
+        ground_to_air=1;
     }
     switch (msgId) {
     case MSG_ANNOUNCE_ENGINE_START:
@@ -554,7 +611,7 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
             receiver + ". Start-up approved. " + atisInformation +
             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
             transponderCode + ". " +
-            "For push-back and taxi clearance call " + taxiFreqStr + ". " +
+            "For "+ instructionText + " clearance call " + taxiFreqStr + ". " +
             sender + " control.";
         break;
     case MSG_DENY_ENGINE_START:
@@ -572,11 +629,12 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
         transponderCode = rec->getAircraft()->GetTransponderCode();
+
         text =
             receiver + ". Start-up approved. " + atisInformation +
             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
             transponderCode + ". " +
-            "For push-back and taxi clearance call " + taxiFreqStr + ". " +
+            "For " + instructionText + " clearance call " + taxiFreqStr + ". " +
             sender;
         break;
     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
@@ -590,10 +648,18 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
         text = receiver + ". Roger. " + sender;
         break;
     case MSG_REQUEST_PUSHBACK_CLEARANCE:
-        text = receiver + ". Request push-back. " + sender;
+        if (rec->getAircraft()->getTaxiClearanceRequest()) {
+            text = receiver + ". Request push-back. " + sender;
+        } else {
+            text = receiver + ". Request Taxi clearance. " + sender;
+        }
         break;
     case MSG_PERMIT_PUSHBACK_CLEARANCE:
-        text = receiver + ". Push-back approved. " + sender;
+        if (rec->getAircraft()->getTaxiClearanceRequest()) {
+            text = receiver + ". Push-back approved. " + sender;
+        } else {
+            text = receiver + ". Cleared to Taxi." + sender;
+        }
         break;
     case MSG_HOLD_PUSHBACK_CLEARANCE:
         text = receiver + ". Standby. " + sender;
@@ -619,29 +685,241 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
     case MSG_ACKNOWLEDGE_RESUME_TAXI:
         text = receiver + ". Continuing Taxi. " + sender;
         break;
+    case MSG_REPORT_RUNWAY_HOLD_SHORT:
+        activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
+        //activeRunway = "test";
+        text = receiver + ". Holding short runway " 
+                        + activeRunway 
+                        + ". " + sender;
+        //text = "test1";
+        //cerr << "1 Currently at leg " << rec->getLeg() << endl;
+        break;
+    case MSG_ACKNOWLEDGE_REPORT_RUNWAY_HOLD_SHORT:
+        activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
+        text = receiver + "Roger. Holding short runway " 
+        //                + activeRunway 
+                        + ". " + sender;
+        //text = "test2";
+        //cerr << "2 Currently at leg " << rec->getLeg() << endl;
+        break;
+    case MSG_SWITCH_TOWER_FREQUENCY:
+        towerFreqStr = formatATCFrequency3_2(towerFreq);
+        text = receiver + "Contact Tower at " + towerFreqStr + ". " + sender;
+        //text = "test3";
+        //cerr << "3 Currently at leg " << rec->getLeg() << endl;
+        break;
+    case MSG_ACKNOWLEDGE_SWITCH_TOWER_FREQUENCY:
+        towerFreqStr = formatATCFrequency3_2(towerFreq);
+        text = receiver + "Roger, switching to tower at " + towerFreqStr + ". " + sender;
+        //text = "test4";
+        //cerr << "4 Currently at leg " << rec->getLeg() << endl;
+        break;
     default:
+        //text = "test3";
         text = text + sender + ". Transmitting unknown Message";
         break;
     }
-    double onBoardRadioFreq0 =
-        fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
-    double onBoardRadioFreq1 =
-        fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
-    int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
-    int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
-    //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
-
-    // Display ATC message only when one of the radios is tuned
-    // the relevant frequency.
-    // Note that distance attenuation is currently not yet implemented
-    if ((onBoardRadioFreqI0 == stationFreq)
-        || (onBoardRadioFreqI1 == stationFreq)) {
-        if (rec->allowTransmissions()) {
-            fgSetString("/sim/messages/atc", text.c_str());
+    if (audible) {
+        double onBoardRadioFreq0 =
+            fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
+        double onBoardRadioFreq1 =
+            fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
+        int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
+        int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
+        //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
+
+        // Display ATC message only when one of the radios is tuned
+        // the relevant frequency.
+        // Note that distance attenuation is currently not yet implemented
+                
+        if ((onBoardRadioFreqI0 == stationFreq)
+            || (onBoardRadioFreqI1 == stationFreq)) {
+               double snr = calculate_attenuation(rec, parent, ground_to_air);
+               if (snr <= 0)
+                       return;
+               if (snr > 0 && snr < 12) {
+                       //for low SNR values implement a way to make the conversation
+                       //hard to understand but audible
+                       string hash_noise = " ";
+                       int reps = fabs((int)snr - 11);
+                       int t_size = text.size();
+                       for (int n=1;n<=reps * 2;n++) {
+                               int pos = rand() % t_size -1;
+                               text.replace(pos,1, hash_noise);
+                       }
+                       
+               }
+               
+            if (rec->allowTransmissions()) {
+                fgSetString("/sim/messages/atc", text.c_str());
+            }
         }
+    } else {
+        FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
+        atc->getATCDialog()->addEntry(1, text);
+        
     }
 }
 
+double FGATCController::calculate_attenuation(FGTrafficRecord * rec, FGAirportDynamics *parent,
+                               int ground_to_air) {
+       //////////////////////////////////////////////////
+        ///  Implement radio attenuation               //
+        ///  based on the Longley-Rice propagation model//
+        //////////////////////////////////////////////////
+        
+        FGScenery * scenery = globals->get_scenery();
+        // player aircraft position
+        double own_lat = fgGetDouble("/position/latitude-deg");
+        double own_lon = fgGetDouble("/position/longitude-deg");
+        double own_alt_ft = fgGetDouble("/position/altitude-ft");
+        double own_alt= own_alt_ft * SG_FEET_TO_METER;
+        
+        cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
+        
+        SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
+        SGGeod max_own_pos = SGGeod::fromDegM( own_lon, own_lat, SG_MAX_ELEVATION_M );
+        SGGeoc center = SGGeoc::fromGeod( max_own_pos );
+        SGGeoc own_pos_c = SGGeoc::fromGeod( own_pos );
+        
+        // position of sender radio antenna (HAAT)
+        // sender can be aircraft or ground station
+        double ATC_HAAT = 30.0;
+        double Aircraft_HAAT = 7.0;
+        double sender_alt_ft,sender_alt;
+        double transceiver_height=0.0;
+        double receiver_height=0.0;
+        SGGeod sender_pos;
+        if(ground_to_air) {
+               sender_alt_ft = parent->getElevation();
+               sender_alt = sender_alt_ft * SG_FEET_TO_METER + ATC_HAAT;
+               sender_pos= SGGeod::fromDegM( parent->getLongitude(),
+                       parent->getLatitude(), sender_alt );
+       }
+       else {
+               sender_alt_ft = rec->getAltitude();
+               sender_alt = sender_alt_ft * SG_FEET_TO_METER + Aircraft_HAAT;
+               sender_pos= SGGeod::fromDegM( rec->getLongitude(),
+                       rec->getLatitude(), sender_alt );
+       }
+       SGGeoc sender_pos_c = SGGeoc::fromGeod( sender_pos );
+       cerr << "ITM:: sender Lat: " << parent->getLatitude() << ", Lon: " << parent->getLongitude() << ", Alt: " << sender_alt << endl;
+       
+        double point_distance= 90.0; // regular SRTM is 90 meters
+        double course = SGGeodesy::courseRad(own_pos_c, sender_pos_c);
+        double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
+        double probe_distance = 0.0;
+        
+        cerr << "ITM:: Distance: " << distance_m << endl;
+        
+        double max_points = distance_m / point_distance;
+        deque<double> _elevations;
+        
+        SGGeod probe_pilot = SGGeod::fromGeoc(center.advanceRadM( course, 0 ));
+        double elevation_under_pilot = 0.0;
+       if (scenery->get_elevation_m( probe_pilot, elevation_under_pilot, NULL )) {
+               receiver_height = own_alt - elevation_under_pilot;
+       }
+       _elevations.push_front(receiver_height);
+       
+       SGGeod probe_sender = SGGeod::fromGeoc(center.advanceRadM( course, distance_m ));
+        double elevation_under_sender = 0.0;
+       if (scenery->get_elevation_m( probe_sender, elevation_under_sender, NULL )) {
+               transceiver_height = sender_alt - elevation_under_sender;
+       }
+        
+        // If distance larger than this value (400 km), assume reception imposssible
+        // technically 400 km is no problem if LOS conditions exist,
+        // but we do this to spare resources
+        if (distance_m > 400000)
+               return -1.0;
+        
+        int e_size = (deque<unsigned>::size_type)max_points;
+        
+        while (_elevations.size() < e_size) {
+               probe_distance += point_distance;
+               SGGeod probe = SGGeod::fromGeoc(center.advanceRadM( course, probe_distance ));
+               
+               double elevation_m = 0.0;
+       
+               if (scenery->get_elevation_m( probe, elevation_m, NULL )) {
+                        _elevations.push_front(elevation_m);
+                        //cerr << "ITM:: Probe elev: " << elevation_m << endl;
+               }
+       }
+       
+       _elevations.push_front(transceiver_height);
+       double max_alt_between=0.0;
+       for( deque<double>::size_type i = 0; i < _elevations.size(); i++ ) {
+               if (_elevations[i] > max_alt_between) {
+                       max_alt_between = _elevations[i];
+               }
+       }
+       
+       double num_points= (double)_elevations.size();
+       cerr << "ITM:: Max alt between: " << max_alt_between << ", num points:" << num_points << endl;
+       _elevations.push_front(point_distance);
+       _elevations.push_front(num_points -1);
+       int size = _elevations.size();
+       double itm_elev[size];
+       for(int i=0;i<size;i++) {
+               itm_elev[i]=_elevations[i];
+               //cerr << "ITM:: itm_elev: " << _elevations[i] << endl;
+       }
+       
+       ////////////// ITM default parameters //////////////
+       // later perhaps take them from tile materials?
+       double eps_dielect=15.0;
+       double sgm_conductivity = 0.005;
+       double eno = 301.0;
+       double frq_mhz = 125.0;         // middle of bandplan
+       int radio_climate = 5;          // continental temperate
+       int pol=1;      // assuming vertical polarization
+       double conf = 0.90;     // my own tests in Radiomobile have worked best with these values
+       double rel = 0.80;      // ^^
+       double dbloss;
+       char strmode[150];
+       int errnum;
+       
+       /////////// radio parameters ///////////
+       double receiver_sensitivity = -112.0;   // typical AM receiver sensitivity in dBm
+       // AM transmitter power in dBm.
+       // Note this value is calculated from the typical final transistor stage output
+       // !!! small aircraft have portable transmitters which operate at 36 dBm output (4 Watts)
+       // later store this value in aircraft description
+       // ATC comms usually operate high power equipment, thus making the link asymetrical; this is ignored for now
+       if(ground_to_air)
+               double transmitter_power = 49.0;
+       else
+               double transmitter_power = 43.0;
+       if(ground_to_air)
+               double antenna_gain = 5.0; //pilot plane's antenna gain + Controller antenna gain
+       else
+               double antenna_gain = 2.0; //pilot plane's antenna gain + AI aircraft antenna gain
+       double link_budget = transmitter_power - receiver_sensitivity + antenna_gain;   
+       
+       
+       // first Fresnel zone radius
+       // frequency in the middle of the bandplan, more accuracy is not necessary
+       double fz_clr= 8.657 * sqrt(distance_m / 0.125);
+       
+       // TODO: If we clear the first Fresnel zone, we are into line of sight teritory
+
+       // else we need to calculate point to point link loss
+
+       point_to_point(itm_elev, sender_alt, own_alt,
+               eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
+               pol, conf, rel, dbloss, strmode, errnum);
+
+       cerr << "ITM:: Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum << endl;
+       
+       //if (errnum !=0 && errnum !=1)
+       //      return -1;
+       double snr = link_budget - dbloss;
+       return snr;
+
+}
+
 string FGATCController::formatATCFrequency3_2(int freq)
 {
     char buffer[7];
@@ -663,13 +941,23 @@ string FGATCController::genTransponderCode(string fltRules)
     }
 }
 
+void FGATCController::init() 
+{
+   if (!initialized) {
+       FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
+       mgr->addController(this);
+       initialized = true;
+    }
+}
+
 /***************************************************************************
  * class FGTowerController
  *
  **************************************************************************/
-FGTowerController::FGTowerController():
+FGTowerController::FGTowerController(FGAirportDynamics *par) :
 FGATCController()
 {
+    parent = par;
 }
 
 // 
@@ -681,6 +969,7 @@ void FGTowerController::announcePosition(int id,
                                          double radius, int leg,
                                          FGAIAircraft * ref)
 {
+    init();
     TrafficVectorIterator i = activeTraffic.begin();
     // Search whether the current id alread has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
@@ -702,16 +991,37 @@ void FGTowerController::announcePosition(int id,
         rec.setRunway(intendedRoute->getRunway());
         rec.setLeg(leg);
         //rec.setCallSign(callsign);
+        rec.setRadius(radius);
         rec.setAircraft(ref);
         activeTraffic.push_back(rec);
+        // Don't just schedule the aircraft for the tower controller, also assign if to the correct active runway. 
+        ActiveRunwayVecIterator rwy = activeRunways.begin();
+        if (activeRunways.size()) {
+            while (rwy != activeRunways.end()) {
+                if (rwy->getRunwayName() == intendedRoute->getRunway()) {
+                    break;
+                }
+                rwy++;
+            }
+        }
+        if (rwy == activeRunways.end()) {
+            ActiveRunway aRwy(intendedRoute->getRunway(), id);
+            aRwy.addToDepartureCue(ref);
+            activeRunways.push_back(aRwy);
+            rwy = (activeRunways.end()-1);
+        } else {
+            rwy->addToDepartureCue(ref);
+        }
+
+        //cerr << ref->getTrafficRef()->getCallSign() << " You are number " << rwy->getDepartureCueSize() <<  " for takeoff " << endl;
     } else {
         i->setPositionAndHeading(lat, lon, heading, speed, alt);
     }
 }
 
-void FGTowerController::update(int id, double lat, double lon,
-                               double heading, double speed, double alt,
-                               double dt)
+void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
+                                                  double heading, double speed, double alt,
+                                                  double dt)
 {
     TrafficVectorIterator i = activeTraffic.begin();
     // Search whether the current id has an entry
@@ -736,29 +1046,43 @@ void FGTowerController::update(int id, double lat, double lon,
     }
     setDt(getDt() + dt);
 
-//    // see if we already have a clearance record for the currently active runway
+    // see if we already have a clearance record for the currently active runway
+    // NOTE: dd. 2011-08-07: Because the active runway has been constructed in the announcePosition function, we may safely assume that is
+    // already exists here. So, we can simplify the current code. 
     ActiveRunwayVecIterator rwy = activeRunways.begin();
-    // again, a map might be more efficient here
-    if (activeRunways.size()) {
-        //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
-        while (rwy != activeRunways.end()) {
-            if (rwy->getRunwayName() == current->getRunway()) {
-                break;
-            }
-            rwy++;
+    while (rwy != activeRunways.end()) {
+        if (rwy->getRunwayName() == current->getRunway()) {
+            break;
         }
+        rwy++;
     }
-    if (rwy == activeRunways.end()) {
-        ActiveRunway aRwy(current->getRunway(), id);
-        activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
-        current->setHoldPosition(false);        // Clear the current aircraft to continue
-    } else {
-        // Okay, we have a clearance record for this runway, so check
-        // whether the clearence ID matches that of the current aircraft
-        if (id == rwy->getCleared()) {
-            current->setHoldPosition(false);
+
+    // only bother running the following code if the current aircraft is the
+    // first in line for depature
+    /* if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
+        if (rwy->getCleared()) {
+            if (id == rwy->getCleared()) {
+                current->setHoldPosition(false);
+            } else {
+                current->setHoldPosition(true);
+            }
         } else {
-            current->setHoldPosition(true);
+            // For now. At later stages, this will probably be the place to check for inbound traffc.
+            rwy->setCleared(id);
+        }
+    } */
+    // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
+    if (current->getAircraft()->getTakeOffStatus() == 2) {
+        current->setHoldPosition(true);
+        int clearanceId = rwy->getCleared();
+        if (clearanceId) {
+            if (id == clearanceId) {
+                current->setHoldPosition(false);
+            }
+        } else {
+            if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
+                rwy->setCleared(id);
+            }
         }
     }
 }
@@ -789,7 +1113,8 @@ void FGTowerController::signOff(int id)
             rwy++;
         }
         if (rwy != activeRunways.end()) {
-            rwy = activeRunways.erase(rwy);
+            rwy->setCleared(0);
+            rwy->updateDepartureCue();
         } else {
             SG_LOG(SG_GENERAL, SG_ALERT,
                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
@@ -799,7 +1124,9 @@ void FGTowerController::signOff(int id)
         SG_LOG(SG_GENERAL, SG_ALERT,
                "AI error: Aircraft without traffic record is signing off from tower");
     } else {
+        i->getAircraft()->resetTakeOffStatus();
         i = activeTraffic.erase(i);
+        //cerr << "Signing off from tower controller" << endl;
     }
 }
 
@@ -856,13 +1183,24 @@ FGATCInstruction FGTowerController::getInstruction(int id)
     return FGATCInstruction();
 }
 
+void FGTowerController::render(bool visible) {
+    //cerr << "FGTowerController::render function not yet implemented" << endl;
+}
+
+string FGTowerController::getName() {
+    return string(parent->getId() + "-tower");
+}
+
+
+
 /***************************************************************************
  * class FGStartupController
  *
  **************************************************************************/
-FGStartupController::FGStartupController():
-FGATCController()
+FGStartupController::FGStartupController(FGAirportDynamics *par):
+    FGATCController()
 {
+    parent = par;
 }
 
 void FGStartupController::announcePosition(int id,
@@ -873,6 +1211,7 @@ void FGStartupController::announcePosition(int id,
                                            double radius, int leg,
                                            FGAIAircraft * ref)
 {
+    init();
     TrafficVectorIterator i = activeTraffic.begin();
     // Search whether the current id alread has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
@@ -893,11 +1232,13 @@ void FGStartupController::announcePosition(int id,
         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
         rec.setRunway(intendedRoute->getRunway());
         rec.setLeg(leg);
+        rec.setPositionAndIntentions(currentPosition, intendedRoute);
         //rec.setCallSign(callsign);
         rec.setAircraft(ref);
         rec.setHoldPosition(true);
         activeTraffic.push_back(rec);
     } else {
+        i->setPositionAndIntentions(currentPosition, intendedRoute);
         i->setPositionAndHeading(lat, lon, heading, speed, alt);
 
     }
@@ -974,13 +1315,48 @@ void FGStartupController::signOff(int id)
         SG_LOG(SG_GENERAL, SG_ALERT,
                "AI error: Aircraft without traffic record is signing off from tower");
     } else {
+        //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
         i = activeTraffic.erase(i);
     }
 }
 
-void FGStartupController::update(int id, double lat, double lon,
-                                 double heading, double speed, double alt,
-                                 double dt)
+bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
+                               AtcMsgDir msgDir)
+{
+    int state = i->getState();
+    if ((state == st) && available) {
+        if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
+            
+            //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
+            static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
+            int n = trans_num->getIntValue();
+            if (n == 0) {
+                trans_num->setIntValue(-1);
+                 // PopupCallback(n);
+                 //cerr << "Selected transmission message " << n << endl;
+                 FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
+                 atc->getATCDialog()->removeEntry(1);
+            } else {
+                //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
+                transmit(&(*i), &(*parent), msgId, msgDir, false);
+                return false;
+            }
+        }
+        if (now > startTime) {
+            //cerr << "Transmitting startup msg" << endl;
+            transmit(&(*i), &(*parent), msgId, msgDir, true);
+            i->updateState();
+            lastTransmission = now;
+            available = false;
+            return true;
+        }
+    }
+    return false;
+}
+
+void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
+                                                    double heading, double speed, double alt,
+                                                    double dt)
 {
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
@@ -996,6 +1372,7 @@ void FGStartupController::update(int id, double lat, double lon,
         }
     }
 //    // update position of the current aircraft
+
     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
         SG_LOG(SG_GENERAL, SG_ALERT,
                "AI error: updating aircraft without traffic record");
@@ -1006,8 +1383,10 @@ void FGStartupController::update(int id, double lat, double lon,
     setDt(getDt() + dt);
 
     int state = i->getState();
-    time_t startTime =
-        i->getAircraft()->getTrafficRef()->getDepartureTime();
+
+    // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
+    // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
+    time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
@@ -1017,91 +1396,29 @@ void FGStartupController::update(int id, double lat, double lon,
         available = true;
     }
 
-    if ((state == 0) && available) {
-        if (now > startTime) {
-            //cerr << "Transmitting startup msg" << endl;
-            transmit(&(*i), MSG_ANNOUNCE_ENGINE_START, ATC_AIR_TO_GROUND);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
-    }
-    if ((state == 1) && available) {
-        if (now > startTime + 60) {
-            transmit(&(*i), MSG_REQUEST_ENGINE_START, ATC_AIR_TO_GROUND);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
-    }
-    if ((state == 2) && available) {
-        if (now > startTime + 80) {
-            transmit(&(*i), MSG_PERMIT_ENGINE_START, ATC_GROUND_TO_AIR);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
-    }
-    if ((state == 3) && available) {
-        if (now > startTime + 100) {
-            transmit(&(*i), MSG_ACKNOWLEDGE_ENGINE_START,
-                     ATC_AIR_TO_GROUND);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
-    }
-    // Note: The next four stages are only necessesary when Startup control is
-    //  on a different frequency, compared to ground control
-    if ((state == 4) && available) {
-        if (now > startTime + 130) {
-            transmit(&(*i), MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,
-                     ATC_AIR_TO_GROUND);
-            i->updateState();
-            i->nextFrequency();
-            lastTransmission = now;
-            available = false;
-        }
-    }
-    if ((state == 5) && available) {
-        if (now > startTime + 140) {
-            transmit(&(*i), MSG_INITIATE_CONTACT, ATC_AIR_TO_GROUND);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
-    }
-    if ((state == 6) && available) {
-        if (now > startTime + 150) {
-            transmit(&(*i), MSG_ACKNOWLEDGE_INITIATE_CONTACT,
-                     ATC_GROUND_TO_AIR);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
+    checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
+    checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
+    checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
+    checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
+    if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
+        i->nextFrequency();
     }
+    checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
+    checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
+    checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
 
-    // TODO: Switch to APRON control and request pushback Clearance.
-    // Get Push back clearance
-    if ((state == 7) && available) {
-        if (now > startTime + 180) {
-            transmit(&(*i), MSG_REQUEST_PUSHBACK_CLEARANCE,
-                     ATC_AIR_TO_GROUND);
-            i->updateState();
-            lastTransmission = now;
-            available = false;
-        }
-    }
+
+   
     if ((state == 8) && available) {
         if (now > startTime + 200) {
             if (i->pushBackAllowed()) {
                 i->allowRepeatedTransmissions();
-                transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
-                         ATC_GROUND_TO_AIR);
+                transmit(&(*i), &(*parent), MSG_PERMIT_PUSHBACK_CLEARANCE,
+                         ATC_GROUND_TO_AIR, true);
                 i->updateState();
             } else {
-                transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
-                         ATC_GROUND_TO_AIR);
+                transmit(&(*i), &(*parent), MSG_HOLD_PUSHBACK_CLEARANCE,
+                         ATC_GROUND_TO_AIR, true);
                 i->suppressRepeatedTransmissions();
             }
             lastTransmission = now;
@@ -1113,14 +1430,215 @@ void FGStartupController::update(int id, double lat, double lon,
     }
 }
 
+// Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
+static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
+                            double lon, double elev, double hdg, double slope)
+{
+    SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
+    obj_pos = geod.makeZUpFrame();
+    // hdg is not a compass heading, but a counter-clockwise rotation
+    // around the Z axis
+    obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
+                                        0.0, 0.0, 1.0));
+    obj_pos.preMult(osg::Matrix::rotate(slope * SGD_DEGREES_TO_RADIANS,
+                                        0.0, 1.0, 0.0));
+}
+
+
+void FGStartupController::render(bool visible)
+{
+
+    SGMaterialLib *matlib = globals->get_matlib();
+    if (group) {
+        //int nr = ;
+        globals->get_scenery()->get_scene_graph()->removeChild(group);
+        //while (group->getNumChildren()) {
+        //  cerr << "Number of children: " << group->getNumChildren() << endl;
+        //simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
+          //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
+           //geode->releaseGLObjects();
+           //group->removeChild(geode);
+           //delete geode;
+        group = 0;
+    }
+    if (visible) {
+        group = new osg::Group;
+        FGScenery * local_scenery = globals->get_scenery();
+        double elevation_meters = 0.0;
+        double elevation_feet = 0.0;
+
+
+        //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
+        double dx = 0;
+        for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
+            // Handle start point
+            int pos = i->getCurrentPosition();
+            //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
+            if (pos > 0) {
+                FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
+                SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
+                SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
+
+                double length = SGGeodesy::distanceM(start, end);
+                //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
+
+                double az2, heading; //, distanceM;
+                SGGeodesy::inverse(start, end, heading, az2, length);
+                double coveredDistance = length * 0.5;
+                SGGeod center;
+                SGGeodesy::direct(start, heading, coveredDistance, center, az2);
+                //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
+                ///////////////////////////////////////////////////////////////////////////////
+                // Make a helper function out of this
+                osg::Matrix obj_pos;
+                osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
+                obj_trans->setDataVariance(osg::Object::STATIC);
+                // Experimental: Calculate slope here, based on length, and the individual elevations
+                double elevationStart;
+                if (isUserAircraft((i)->getAircraft())) {
+                    elevationStart = fgGetDouble("/position/ground-elev-m");
+                } else {
+                    elevationStart = ((i)->getAircraft()->_getAltitude()); 
+                }
+                double elevationEnd   = segment->getEnd()->getElevation();
+                if (elevationEnd == 0) {
+                    SGGeod center2 = end;
+                    center2.setElevationM(SG_MAX_ELEVATION_M);
+                    if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
+                        elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
+                            //elevation_meters += 0.5;
+                    }
+                    else { 
+                        elevationEnd = parent->getElevation()+8+dx;
+                    }
+                    segment->getEnd()->setElevation(elevationEnd);
+                }
+
+                double elevationMean  = (elevationStart + elevationEnd) / 2.0;
+                double elevDiff       = elevationEnd - elevationStart;
+               
+               double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
+                
+               //cerr << "1. Using mean elevation : " << elevationMean << " and " << slope << endl;
+
+                WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), elevationMean + 0.5, -(heading), slope );
+;
+
+                obj_trans->setMatrix( obj_pos );
+                //osg::Vec3 center(0, 0, 0)
+
+                float width = length /2.0;
+                osg::Vec3 corner(-width, 0, 0.25f);
+                osg::Vec3 widthVec(2*width + 1, 0, 0);
+                osg::Vec3 heightVec(0, 1, 0);
+                osg::Geometry* geometry;
+                geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
+                simgear::EffectGeode* geode = new simgear::EffectGeode;
+                geode->setName("test");
+                geode->addDrawable(geometry);
+                //osg::Node *custom_obj;
+                SGMaterial *mat = matlib->find("UnidirectionalTaper");
+                if (mat)
+                    geode->setEffect(mat->get_effect());
+                obj_trans->addChild(geode);
+                // wire as much of the scene graph together as we can
+                //->addChild( obj_trans );
+                group->addChild( obj_trans );
+                /////////////////////////////////////////////////////////////////////
+            } else {
+                //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
+            }
+            for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
+                osg::Matrix obj_pos;
+                int k = (*j);
+                if (k > 0) {
+                    //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
+                    osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
+                    obj_trans->setDataVariance(osg::Object::STATIC);
+                    FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
+
+                    double elevationStart = segment->getStart()->getElevation();
+                    double elevationEnd   = segment->getEnd  ()->getElevation();
+                    if (elevationStart == 0) {
+                        SGGeod center2 = segment->getStart()->getGeod();
+                        center2.setElevationM(SG_MAX_ELEVATION_M);
+                        if (local_scenery->get_elevation_m( center2, elevationStart, NULL )) {
+                            elevation_feet = elevationStart * SG_METER_TO_FEET + 0.5;
+                            //elevation_meters += 0.5;
+                        }
+                        else { 
+                            elevationStart = parent->getElevation()+8+dx;
+                        }
+                        segment->getStart()->setElevation(elevationStart);
+                    }
+                    if (elevationEnd == 0) {
+                        SGGeod center2 = segment->getEnd()->getGeod();
+                        center2.setElevationM(SG_MAX_ELEVATION_M);
+                        if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
+                            elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
+                            //elevation_meters += 0.5;
+                        }
+                        else { 
+                            elevationEnd = parent->getElevation()+8+dx;
+                        }
+                        segment->getEnd()->setElevation(elevationEnd);
+                    }
+                    double elevationMean  = (elevationStart + elevationEnd) / 2.0;
+                    double elevDiff       = elevationEnd - elevationStart;
+                    double length         = segment->getLength();
+                    double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
+                
+                    //cerr << "2. Using mean elevation : " << elevationMean << " and " << slope << endl;
+
+
+                    WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), elevationMean + 0.5, -(segment->getHeading()), slope );
+
+                    //WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
+
+                    obj_trans->setMatrix( obj_pos );
+                    //osg::Vec3 center(0, 0, 0)
+
+                    float width = segment->getLength() /2.0;
+                    osg::Vec3 corner(-width, 0, 0.25f);
+                    osg::Vec3 widthVec(2*width + 1, 0, 0);
+                    osg::Vec3 heightVec(0, 1, 0);
+                    osg::Geometry* geometry;
+                    geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
+                    simgear::EffectGeode* geode = new simgear::EffectGeode;
+                    geode->setName("test");
+                    geode->addDrawable(geometry);
+                    //osg::Node *custom_obj;
+                    SGMaterial *mat = matlib->find("UnidirectionalTaper");
+                    if (mat)
+                        geode->setEffect(mat->get_effect());
+                    obj_trans->addChild(geode);
+                    // wire as much of the scene graph together as we can
+                    //->addChild( obj_trans );
+                    group->addChild( obj_trans );
+                } else {
+                    //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
+                }
+            }
+            //dx += 0.1;
+        }
+        globals->get_scenery()->get_scene_graph()->addChild(group);
+    }
+}
+
+string FGStartupController::getName() {
+    return string(parent->getId() + "-startup");
+}
+
 
 /***************************************************************************
  * class FGApproachController
  *
  **************************************************************************/
-FGApproachController::FGApproachController():
+FGApproachController::FGApproachController(FGAirportDynamics *par):
 FGATCController()
 {
+    parent = par;
 }
 
 // 
@@ -1132,6 +1650,7 @@ void FGApproachController::announcePosition(int id,
                                             double alt, double radius,
                                             int leg, FGAIAircraft * ref)
 {
+    init();
     TrafficVectorIterator i = activeTraffic.begin();
     // Search whether the current id alread has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
@@ -1160,9 +1679,9 @@ void FGApproachController::announcePosition(int id,
     }
 }
 
-void FGApproachController::update(int id, double lat, double lon,
-                                  double heading, double speed, double alt,
-                                  double dt)
+void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
+                                                     double heading, double speed, double alt,
+                                                     double dt)
 {
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
@@ -1303,3 +1822,13 @@ ActiveRunway *FGApproachController::getRunway(string name)
     }
     return &(*rwy);
 }
+
+void FGApproachController::render(bool visible) {
+    //cerr << "FGApproachController::render function not yet implemented" << endl;
+}
+
+
+
+string FGApproachController::getName() {
+    return string(parent->getId() + "-approach");
+}