]> git.mxchange.org Git - flightgear.git/blobdiff - src/ATC/trafficcontrol.cxx
Different fix for traffic shutdown crash.
[flightgear.git] / src / ATC / trafficcontrol.cxx
index 685df21da7773ebe825f4f9d4b951e8fceedbca7..6b77890a0acc5d461ea85eb97c2c7fce92e53010 100644 (file)
@@ -25,6 +25,7 @@
 #endif
 
 #include <algorithm>
+#include <cstdio>
 
 #include <osg/Geode>
 #include <osg/Geometry>
@@ -34,6 +35,9 @@
 #include <simgear/scene/material/EffectGeode.hxx>
 #include <simgear/scene/material/matlib.hxx>
 #include <simgear/scene/material/mat.hxx>
+#include <simgear/scene/util/OsgMath.hxx>
+#include <simgear/timing/sg_time.hxx>
+
 #include <Scenery/scenery.hxx>
 
 #include "trafficcontrol.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>
+#include <Airports/airport.hxx>
+#include <Radio/radio.hxx>
+#include <signal.h>
 
 using std::sort;
+using std::string;
+using std::cout;
+using std::endl;
+
+namespace {
+
+TrafficVectorIterator findTraffic(TrafficVector& vec, int id)
+{
+    TrafficVectorIterator it = vec.begin();
+    for (; it != vec.end(); ++it) {
+        if (it->getId() == id) {
+            return it;
+        }
+    }
+
+    return it; // vec.end, effectively
+}
+
+void clearTrafficControllers(TrafficVector& vec)
+{
+    TrafficVectorIterator it = vec.begin();
+    for (; it != vec.end(); ++it) {
+        it->getAircraft()->clearATCController();
+    }
+}
+
+} // of anonymous namespace
 
 /***************************************************************************
  * ActiveRunway
@@ -58,7 +90,7 @@ time_t ActiveRunway::requestTimeSlot(time_t eta)
     time_t newEta;
     time_t separation = 90;
     bool found = false;
-    if (estimatedArrivalTimes.size() == 0) {
+    if (estimatedArrivalTimes.empty()) {
         estimatedArrivalTimes.push_back(eta);
         return eta;
     } else {
@@ -126,7 +158,9 @@ time_t ActiveRunway::requestTimeSlot(time_t eta)
     estimatedArrivalTimes.push_back(newEta);
     sort(estimatedArrivalTimes.begin(), estimatedArrivalTimes.end());
     // do some housekeeping : remove any timestamps that are past
-    time_t now = time(NULL) + fgGetLong("/sim/time/warp");
+
+    time_t now = globals->get_time_params()->get_cur_time();
+
     TimeVectorIterator i = estimatedArrivalTimes.begin();
     while (i != estimatedArrivalTimes.end()) {
         if ((*i) < now) {
@@ -140,6 +174,27 @@ time_t ActiveRunway::requestTimeSlot(time_t eta)
     return newEta;
 }
 
+void ActiveRunway::printDepartureCue()
+{
+    cout << "Departure cue for " << rwy << ": " << endl;
+    for (AircraftVecIterator atc = departureCue.begin(); atc != departureCue.end(); atc++) {
+        cout << "     " << (*atc)->getCallSign() << " "  << (*atc)->getTakeOffStatus();
+        cout << " " << (*atc)->_getLatitude() << " " << (*atc)->_getLongitude() << (*atc)-> getSpeed() << " " << (*atc)->getAltitude() << endl;
+    }
+    
+}
+
+FGAIAircraft* ActiveRunway::getFirstOfStatus(int stat)
+{
+    for (AircraftVecIterator atc =departureCue.begin(); atc != departureCue.end(); atc++) {
+        if ((*atc)->getTakeOffStatus() == stat)
+            return (*atc);
+    }
+    return 0;
+}
+
+
+
 /***************************************************************************
  * FGTrafficRecord
  **************************************************************************/
@@ -152,26 +207,25 @@ FGTrafficRecord::FGTrafficRecord():
         allowTransmission(true),
         allowPushback(true),
         priority(0),
+        timer(0),
         latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
 {
 }
 
+FGTrafficRecord::~FGTrafficRecord()
+{
+}
+
 void FGTrafficRecord::setPositionAndIntentions(int pos,
         FGAIFlightPlan * route)
 {
 
     currentPos = pos;
-    if (intentions.size()) {
+    if (! intentions.empty()) {
         intVecIterator i = intentions.begin();
         if ((*i) != pos) {
-            SG_LOG(SG_GENERAL, SG_ALERT,
-                   "Error in FGTrafficRecord::setPositionAndIntentions");
-            //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
-            for (intVecIterator i = intentions.begin();
-                    i != intentions.end(); i++) {
-                //cerr << (*i) << " ";
-            }
-            //cerr << endl;
+            SG_LOG(SG_ATC, SG_ALERT,
+                   "Error in FGTrafficRecord::setPositionAndIntentions at " << SG_ORIGIN);
         }
         intentions.erase(i);
     } else {
@@ -179,22 +233,23 @@ void FGTrafficRecord::setPositionAndIntentions(int pos,
         int size = route->getNrOfWayPoints();
         //cerr << "Setting pos" << pos << " ";
         //cerr << "setting intentions ";
-        for (int i = 0; i < size; i++) {
+        for (int i = 2; i < size; i++) {
             int val = route->getRouteIndex(i);
-            //cerr << val<< " ";
-            if ((val) && (val != pos)) {
-                intentions.push_back(val);
-                //cerr << "[set] ";
-            }
+            intentions.push_back(val);
         }
-        //cerr << endl;
-        //while (route->next(&legNr, &routeNr)) {
-        //intentions.push_back(routeNr);
-        //}
-        //route->rewind(currentPos);
     }
-    //exit(1);
 }
+
+void FGTrafficRecord::setAircraft(FGAIAircraft *ref)
+{
+    aircraft = ref;
+}
+
+FGAIAircraft* FGTrafficRecord::getAircraft() const
+{
+    return aircraft.ptr();
+}
+
 /**
  * Check if another aircraft is ahead of the current one, and on the same
  * return true / false is the is/isn't the case.
@@ -209,7 +264,7 @@ bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
         result = true;
     }
-    //  else if (other.intentions.size())
+    //  else if (! other.intentions.empty())
     //     {
     //       cerr << "Start check 2" << endl;
     //       intVecIterator i = other.intentions.begin();
@@ -219,7 +274,7 @@ bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
     //     result = true;
     //       }
-    else if (intentions.size()) {
+    else if (! intentions.empty()) {
         //cerr << "Start check 3" << endl;
         intVecIterator i = intentions.begin();
         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
@@ -263,18 +318,18 @@ int FGTrafficRecord::crosses(FGGroundNetwork * net,
         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
         return currentTargetNode;
-    if (intentions.size()) {
+    if (! intentions.empty()) {
         for (i = intentions.begin(); i != intentions.end(); i++) {
             if ((*i) > 0) {
-                if ((currentTargetNode ==
-                        net->findSegment(*i)->getEnd()->getIndex())) {
+                if (currentTargetNode ==
+                        net->findSegment(*i)->getEnd()->getIndex()) {
                     //cerr << "Current crosses at " << currentTargetNode <<endl;
                     return currentTargetNode;
                 }
             }
         }
     }
-    if (other.intentions.size()) {
+    if (! other.intentions.empty()) {
         for (i = other.intentions.begin(); i != other.intentions.end();
                 i++) {
             if ((*i) > 0) {
@@ -286,7 +341,7 @@ int FGTrafficRecord::crosses(FGGroundNetwork * net,
             }
         }
     }
-    if (intentions.size() && other.intentions.size()) {
+    if (! intentions.empty() && ! other.intentions.empty()) {
         for (i = intentions.begin(); i != intentions.end(); i++) {
             for (j = other.intentions.begin(); j != other.intentions.end();
                     j++) {
@@ -318,7 +373,7 @@ bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
             net->findSegment(other.currentPos)->getEnd()->getIndex();
     if ((node == othernode) && (node != -1))
         return true;
-    if (other.intentions.size()) {
+    if (! other.intentions.empty()) {
         for (intVecIterator i = other.intentions.begin();
                 i != other.intentions.end(); i++) {
             if (*i > 0) {
@@ -330,7 +385,7 @@ bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
     }
     //if (other.currentPos > 0)
     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
-    //if (intentions.size())
+    //if (! intentions.empty())
     //  {
     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
     //    {
@@ -374,7 +429,7 @@ bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
                         }
                     }
             }
-            if (other.intentions.size()) {
+            if (! other.intentions.empty()) {
                 for (intVecIterator j = other.intentions.begin();
                         j != other.intentions.end(); j++) {
                     // cerr << "Current segment 1 " << (*i) << endl;
@@ -402,9 +457,9 @@ bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
     return false;
 }
 
-bool FGTrafficRecord::isActive(int margin)
+bool FGTrafficRecord::isActive(int margin) const
 {
-    time_t now = time(NULL) + fgGetLong("/sim/time/warp");
+    time_t now = globals->get_time_params()->get_cur_time();
     time_t deptime = aircraft->getTrafficRef()->getDepartureTime();
     return ((now + margin) > deptime);
 }
@@ -422,7 +477,7 @@ void FGTrafficRecord::setHeadingAdjustment(double heading)
     instruction.setHeading(heading);
 }
 
-bool FGTrafficRecord::pushBackAllowed()
+bool FGTrafficRecord::pushBackAllowed() const
 {
     return allowPushback;
 }
@@ -449,7 +504,7 @@ FGATCInstruction::FGATCInstruction()
 }
 
 
-bool FGATCInstruction::hasInstruction()
+bool FGATCInstruction::hasInstruction() const
 {
     return (holdPattern || holdPosition || changeSpeed || changeHeading
             || changeAltitude || resolveCircularWait);
@@ -470,11 +525,14 @@ FGATCController::FGATCController()
     available = true;
     lastTransmission = 0;
     initialized = false;
+    lastTransmissionDirection = ATC_AIR_TO_GROUND;
+    group = NULL;
 }
 
 FGATCController::~FGATCController()
 {
-    //cerr << "running FGATController destructor" << endl;
+    FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
+    mgr->removeController(this);
 }
 
 string FGATCController::getGateName(FGAIAircraft * ref)
@@ -487,7 +545,7 @@ bool FGATCController::isUserAircraft(FGAIAircraft* ac)
     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false;
 };
 
-void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
+void FGATCController::transmit(FGTrafficRecord * rec, FGAirportDynamics *parent, AtcMsgId msgId,
                                AtcMsgDir msgDir, bool audible)
 {
     string sender, receiver;
@@ -508,6 +566,7 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
     FGAIFlightPlan *fp;
     string fltRules;
     string instructionText;
+    int ground_to_air=0;
 
     //double commFreqD;
     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
@@ -548,6 +607,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:
@@ -579,8 +639,7 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
         getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
                                        heading);
         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
-        fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
-             getDynamics()->getSID(activeRunway, heading);
+        fp = NULL;
         rec->getAircraft()->GetFlightPlan()->setSID(fp);
         if (fp) {
             SID = fp->getName() + " departure";
@@ -715,10 +774,33 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
         // 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 ((stationFreq > 0)&&
+            ((onBoardRadioFreqI0 == stationFreq)||
+             (onBoardRadioFreqI1 == stationFreq))) {
             if (rec->allowTransmissions()) {
-                fgSetString("/sim/messages/atc", text.c_str());
+               
+               if( fgGetBool( "/sim/radio/use-itm-attenuation", false ) ) {
+                       //cerr << "Using ITM radio propagation" << endl;
+                       FGRadioTransmission* radio = new FGRadioTransmission();
+                       SGGeod sender_pos;
+                       double sender_alt_ft, sender_alt;
+                       if(ground_to_air) {
+                  sender_pos = parent->parent()->geod();
+                                }
+                               else {
+                                     sender_alt_ft = rec->getAltitude();
+                                     sender_alt = sender_alt_ft * SG_FEET_TO_METER;
+                                     sender_pos= SGGeod::fromDegM( rec->getLongitude(),
+                                            rec->getLatitude(), sender_alt );
+                               }
+                               double frequency = ((double)stationFreq) / 100;
+                       radio->receiveATC(sender_pos, frequency, text, ground_to_air);
+                       delete radio;
+               }
+               else {
+                       fgSetString("/sim/messages/atc", text.c_str());
+               }
             }
         }
     } else {
@@ -726,6 +808,7 @@ void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
     }
 }
 
+
 string FGATCController::formatATCFrequency3_2(int freq)
 {
     char buffer[7];
@@ -735,7 +818,7 @@ string FGATCController::formatATCFrequency3_2(int freq)
 
 // TODO: Set transponder codes according to real-world routes.
 // The current version just returns a random string of four octal numbers.
-string FGATCController::genTransponderCode(string fltRules)
+string FGATCController::genTransponderCode(const string& fltRules)
 {
     if (fltRules == "VFR") {
         return string("1200");
@@ -766,6 +849,15 @@ FGTowerController::FGTowerController(FGAirportDynamics *par) :
     parent = par;
 }
 
+FGTowerController::~FGTowerController()
+{
+    // to avoid the exception described in:
+    // https://sourceforge.net/p/flightgear/codetickets/1864/
+    // we want to ensure AI aircraft signing-off is a no-op now
+
+    clearTrafficControllers(activeTraffic);
+}
+
 //
 void FGTowerController::announcePosition(int id,
         FGAIFlightPlan * intendedRoute,
@@ -779,7 +871,7 @@ void FGTowerController::announcePosition(int id,
     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
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -789,7 +881,7 @@ void FGTowerController::announcePosition(int id,
         }
     }
     // Add a new TrafficRecord if no one exsists for this aircraft.
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
+    if (i == activeTraffic.end() || (activeTraffic.empty())) {
         FGTrafficRecord rec;
         rec.setId(id);
 
@@ -802,7 +894,7 @@ void FGTowerController::announcePosition(int id,
         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()) {
+        if (! activeRunways.empty()) {
             while (rwy != activeRunways.end()) {
                 if (rwy->getRunwayName() == intendedRoute->getRunway()) {
                     break;
@@ -833,7 +925,7 @@ void FGTowerController::updateAircraftInformation(int id, double lat, double lon
     // Search whether the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
     TrafficVectorIterator current, closest;
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -843,9 +935,9 @@ void FGTowerController::updateAircraftInformation(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");
+    if (i == activeTraffic.end() || (activeTraffic.empty())) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: updating aircraft without traffic record at " << SG_ORIGIN);
     } else {
         i->setPositionAndHeading(lat, lon, heading, speed, alt);
         current = i;
@@ -855,7 +947,15 @@ void FGTowerController::updateAircraftInformation(int id, double lat, double lon
     // 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();
+    //if (parent->getId() == fgGetString("/sim/presets/airport-id")) {
+    //    for (rwy = activeRunways.begin(); rwy != activeRunways.end(); rwy++) {
+    //        rwy->printDepartureCue();
+    //    }
+    //}
+    
+    rwy = activeRunways.begin();
     while (rwy != activeRunways.end()) {
         if (rwy->getRunwayName() == current->getRunway()) {
             break;
@@ -878,22 +978,29 @@ void FGTowerController::updateAircraftInformation(int id, double lat, double lon
         }
     } */
     // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
+    FGAIAircraft* ac= rwy->getFirstAircraftInDepartureCue();
+    if (ac->getTakeOffStatus() == 1) {
+        ac->setTakeOffStatus(2);
+    }
     if (current->getAircraft()->getTakeOffStatus() == 2) {
+        current -> setHoldPosition(false);
+    } else {
         current->setHoldPosition(true);
-        int clearanceId = rwy->getCleared();
-        if (clearanceId) {
-            if (id == clearanceId) {
-                current->setHoldPosition(false);
-            }
-        } else {
-            if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
-                rwy->setCleared(id);
-            }
+    }
+    int clearanceId = rwy->getCleared();
+    if (clearanceId) {
+        if (id == clearanceId) {
+            current->setHoldPosition(false);
         }
     } else {
-        
+        if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
+            rwy->setCleared(id);
+            FGAIAircraft *ac = rwy->getFirstOfStatus(1);
+            if (ac)
+                ac->setTakeOffStatus(2);
+        }
     }
-}
+} 
 
 
 void FGTowerController::signOff(int id)
@@ -901,7 +1008,7 @@ void FGTowerController::signOff(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if 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
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -912,7 +1019,7 @@ void FGTowerController::signOff(int id)
     }
     // If this aircraft has left the runway, we can clear the departure record for this runway
     ActiveRunwayVecIterator rwy = activeRunways.begin();
-    if (activeRunways.size()) {
+    if (! activeRunways.empty()) {
         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
         while (rwy != activeRunways.end()) {
             if (rwy->getRunwayName() == i->getRunway()) {
@@ -924,13 +1031,13 @@ void FGTowerController::signOff(int id)
             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");
+            SG_LOG(SG_ATC, SG_ALERT,
+                   "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff at " << SG_ORIGIN);
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: Aircraft without traffic record is signing off from tower");
+    if (i == activeTraffic.end() || (activeTraffic.empty())) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: Aircraft without traffic record is signing off from tower at " << SG_ORIGIN);
     } else {
         i->getAircraft()->resetTakeOffStatus();
         i = activeTraffic.erase(i);
@@ -949,7 +1056,7 @@ bool FGTowerController::hasInstruction(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -958,9 +1065,9 @@ bool FGTowerController::hasInstruction(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: checking ATC instruction for aircraft without traffic record");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: checking ATC instruction for aircraft without traffic record at " << SG_ORIGIN);
     } else {
         return i->hasInstruction();
     }
@@ -973,7 +1080,7 @@ FGATCInstruction FGTowerController::getInstruction(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -982,9 +1089,9 @@ FGATCInstruction FGTowerController::getInstruction(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: requesting ATC instruction for aircraft without traffic record");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: requesting ATC instruction for aircraft without traffic record at " << SG_ORIGIN);
     } else {
         return i->getInstruction();
     }
@@ -992,7 +1099,7 @@ FGATCInstruction FGTowerController::getInstruction(int id)
 }
 
 void FGTowerController::render(bool visible) {
-    //cerr << "FGTowerController::render function not yet implemented" << endl;
+    //std::cerr << "FGTowerController::render function not yet implemented" << std::endl;
 }
 
 string FGTowerController::getName() {
@@ -1016,6 +1123,11 @@ FGStartupController::FGStartupController(FGAirportDynamics *par):
     parent = par;
 }
 
+FGStartupController::~FGStartupController()
+{
+    clearTrafficControllers(activeTraffic);
+}
+
 void FGStartupController::announcePosition(int id,
         FGAIFlightPlan * intendedRoute,
         int currentPosition, double lat,
@@ -1028,7 +1140,7 @@ void FGStartupController::announcePosition(int id,
     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
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1038,7 +1150,7 @@ void FGStartupController::announcePosition(int id,
         }
     }
     // Add a new TrafficRecord if no one exsists for this aircraft.
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
         FGTrafficRecord rec;
         rec.setId(id);
 
@@ -1068,7 +1180,7 @@ bool FGStartupController::hasInstruction(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1077,9 +1189,9 @@ bool FGStartupController::hasInstruction(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: checking ATC instruction for aircraft without traffic record");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: checking ATC instruction for aircraft without traffic record at " << SG_ORIGIN);
     } else {
         return i->hasInstruction();
     }
@@ -1092,7 +1204,7 @@ FGATCInstruction FGStartupController::getInstruction(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1101,9 +1213,9 @@ FGATCInstruction FGStartupController::getInstruction(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: requesting ATC instruction for aircraft without traffic record");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: requesting ATC instruction for aircraft without traffic record at " << SG_ORIGIN);
     } else {
         return i->getInstruction();
     }
@@ -1115,7 +1227,7 @@ void FGStartupController::signOff(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if 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
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1124,9 +1236,9 @@ void FGStartupController::signOff(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: Aircraft without traffic record is signing off from tower");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: Aircraft without traffic record is signing off from tower at " << SG_ORIGIN);
     } else {
         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
         i = activeTraffic.erase(i);
@@ -1141,7 +1253,7 @@ bool FGStartupController::checkTransmissionState(int st, time_t now, time_t star
         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);
+            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);
@@ -1150,13 +1262,13 @@ bool FGStartupController::checkTransmissionState(int st, time_t now, time_t star
                 FGATCDialogNew::instance()->removeEntry(1);
             } else {
                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
-                transmit(&(*i), msgId, msgDir, false);
+                transmit(&(*i), &(*parent), msgId, msgDir, false);
                 return false;
             }
         }
         if (now > startTime) {
             //cerr << "Transmitting startup msg" << endl;
-            transmit(&(*i), msgId, msgDir, true);
+            transmit(&(*i), &(*parent), msgId, msgDir, true);
             i->updateState();
             lastTransmission = now;
             available = false;
@@ -1174,7 +1286,7 @@ void FGStartupController::updateAircraftInformation(int id, double lat, double l
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
     TrafficVectorIterator current, closest;
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1186,8 +1298,8 @@ void FGStartupController::updateAircraftInformation(int id, double lat, double l
 //    // 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");
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: updating aircraft without traffic record at " << SG_ORIGIN);
     } else {
         i->setPositionAndHeading(lat, lon, heading, speed, alt);
         current = i;
@@ -1199,7 +1311,8 @@ void FGStartupController::updateAircraftInformation(int id, double lat, double l
     // 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");
+    time_t now = globals->get_time_params()->get_cur_time();
+
     //cerr << i->getAircraft()->getTrafficRef()->getCallSign()
     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
     //     << " at parking " << getGateName(i->getAircraft()) << endl;
@@ -1225,11 +1338,11 @@ void FGStartupController::updateAircraftInformation(int id, double lat, double l
         if (now > startTime + 200) {
             if (i->pushBackAllowed()) {
                 i->allowRepeatedTransmissions();
-                transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
+                transmit(&(*i), &(*parent), MSG_PERMIT_PUSHBACK_CLEARANCE,
                          ATC_GROUND_TO_AIR, true);
                 i->updateState();
             } else {
-                transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
+                transmit(&(*i), &(*parent), MSG_HOLD_PUSHBACK_CLEARANCE,
                          ATC_GROUND_TO_AIR, true);
                 i->suppressRepeatedTransmissions();
             }
@@ -1247,7 +1360,7 @@ 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();
+    obj_pos = makeZUpFrame(geod);
     // 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,
@@ -1259,7 +1372,7 @@ static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
 
 void FGStartupController::render(bool visible)
 {
-
+    //std::cerr << "Rendering startup controller" << std::endl;
     SGMaterialLib *matlib = globals->get_matlib();
     if (group) {
         //int nr = ;
@@ -1276,12 +1389,14 @@ void FGStartupController::render(bool visible)
     if (visible) {
         group = new osg::Group;
         FGScenery * local_scenery = globals->get_scenery();
-        double elevation_meters = 0.0;
-        double elevation_feet = 0.0;
+        //double elevation_meters = 0.0;
+        //double elevation_feet = 0.0;
 
 
         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
         double dx = 0;
+        time_t now = globals->get_time_params()->get_cur_time();
+
         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
             if (i->isActive(300)) {
                 // Handle start point
@@ -1290,10 +1405,10 @@ void FGStartupController::render(bool visible)
                 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()));
+                    SGGeod end  (segment->getEnd()->geod());
 
                     double length = SGGeodesy::distanceM(start, end);
-                    //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
+                    //heading = SGGeodesy::headingDeg(start->geod(), end->geod());
 
                     double az2, heading; //, distanceM;
                     SGGeodesy::inverse(start, end, heading, az2, length);
@@ -1313,12 +1428,12 @@ void FGStartupController::render(bool visible)
                     } else {
                         elevationStart = ((i)->getAircraft()->_getAltitude() * SG_FEET_TO_METER);
                     }
-                    double elevationEnd   = segment->getEnd()->getElevation();
+                    double elevationEnd   = segment->getEnd()->getElevationM();
                     if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
                         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_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
                             //elevation_meters += 0.5;
                         }
                         else {
@@ -1351,10 +1466,10 @@ void FGStartupController::render(bool visible)
                     geode->addDrawable(geometry);
                     //osg::Node *custom_obj;
                     SGMaterial *mat;
-                    if (segment->hasBlock()) {
-                        mat = matlib->find("UnidirectionalTaperRed");
+                    if (segment->hasBlock(now)) {
+                        mat = matlib->find("UnidirectionalTaperRed", center);
                     } else {
-                        mat = matlib->find("UnidirectionalTaperGreen");
+                        mat = matlib->find("UnidirectionalTaperGreen", center);
                     }
                     if (mat)
                         geode->setEffect(mat->get_effect());
@@ -1375,13 +1490,13 @@ void FGStartupController::render(bool visible)
                         obj_trans->setDataVariance(osg::Object::STATIC);
                         FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
 
-                        double elevationStart = segment->getStart()->getElevation();
-                        double elevationEnd   = segment->getEnd  ()->getElevation();
+                        double elevationStart = segment->getStart()->getElevationM();
+                        double elevationEnd   = segment->getEnd  ()->getElevationM();
                         if ((elevationStart == 0) || (elevationStart == parent->getElevation())) {
-                            SGGeod center2 = segment->getStart()->getGeod();
+                            SGGeod center2 = segment->getStart()->geod();
                             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_feet = elevationStart * SG_METER_TO_FEET + 0.5;
                                 //elevation_meters += 0.5;
                             }
                             else {
@@ -1390,10 +1505,10 @@ void FGStartupController::render(bool visible)
                             segment->getStart()->setElevation(elevationStart);
                         }
                         if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
-                            SGGeod center2 = segment->getEnd()->getGeod();
+                            SGGeod center2 = segment->getEnd()->geod();
                             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_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
                                 //elevation_meters += 0.5;
                             }
                             else {
@@ -1409,8 +1524,9 @@ void FGStartupController::render(bool visible)
 
                         //cerr << "2. Using mean elevation : " << elevationMean << " and " << slope << endl;
 
-
-                        WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), elevationMean + 0.5 + dx, -(segment->getHeading()), slope );
+                        SGGeod segCenter(segment->getCenter());
+                        WorldCoordinate( obj_pos, segCenter.getLatitudeDeg(),
+                                        segCenter.getLongitudeDeg(), elevationMean + 0.5 + dx, -(segment->getHeading()), slope );
 
                         //WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
 
@@ -1428,10 +1544,10 @@ void FGStartupController::render(bool visible)
                         geode->addDrawable(geometry);
                         //osg::Node *custom_obj;
                         SGMaterial *mat;
-                        if (segment->hasBlock()) {
-                            mat = matlib->find("UnidirectionalTaperRed");
+                        if (segment->hasBlock(now)) {
+                            mat = matlib->find("UnidirectionalTaperRed", segCenter);
                         } else {
-                            mat = matlib->find("UnidirectionalTaperGreen");
+                            mat = matlib->find("UnidirectionalTaperGreen", segCenter);
                         }
                         if (mat)
                             geode->setEffect(mat->get_effect());
@@ -1471,6 +1587,11 @@ FGApproachController::FGApproachController(FGAirportDynamics *par):
     parent = par;
 }
 
+FGApproachController::~FGApproachController()
+{
+    clearTrafficControllers(activeTraffic);
+}
+
 //
 void FGApproachController::announcePosition(int id,
         FGAIFlightPlan * intendedRoute,
@@ -1484,7 +1605,7 @@ void FGApproachController::announcePosition(int id,
     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
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1494,7 +1615,7 @@ void FGApproachController::announcePosition(int id,
         }
     }
     // Add a new TrafficRecord if no one exsists for this aircraft.
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
         FGTrafficRecord rec;
         rec.setId(id);
 
@@ -1517,7 +1638,7 @@ void FGApproachController::updateAircraftInformation(int id, double lat, double
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
     TrafficVectorIterator current, closest;
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1527,9 +1648,9 @@ void FGApproachController::updateAircraftInformation(int id, double lat, double
         }
     }
 //    // 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");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: updating aircraft without traffic record at " << SG_ORIGIN);
     } else {
         i->setPositionAndHeading(lat, lon, heading, speed, alt);
         current = i;
@@ -1566,7 +1687,7 @@ void FGApproachController::signOff(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if 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
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1575,9 +1696,9 @@ void FGApproachController::signOff(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: Aircraft without traffic record is signing off from approach");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: Aircraft without traffic record is signing off from approach at " << SG_ORIGIN);
     } else {
         i = activeTraffic.erase(i);
     }
@@ -1595,7 +1716,7 @@ bool FGApproachController::hasInstruction(int id)
     TrafficVectorIterator i = activeTraffic.begin();
     // Search search if the current id has an entry
     // This might be faster using a map instead of a vector, but let's start by taking a safe route
-    if (activeTraffic.size()) {
+    if (! activeTraffic.empty()) {
         //while ((i->getId() != id) && i != activeTraffic.end()) {
         while (i != activeTraffic.end()) {
             if (i->getId() == id) {
@@ -1604,9 +1725,9 @@ bool FGApproachController::hasInstruction(int id)
             i++;
         }
     }
-    if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: checking ATC instruction for aircraft without traffic record");
+    if (i == activeTraffic.end() || activeTraffic.empty()) {
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: checking ATC instruction for aircraft without traffic record at " << SG_ORIGIN);
     } else {
         return i->hasInstruction();
     }
@@ -1629,8 +1750,8 @@ FGATCInstruction FGApproachController::getInstruction(int id)
         }
     }
     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
-        SG_LOG(SG_GENERAL, SG_ALERT,
-               "AI error: requesting ATC instruction for aircraft without traffic record");
+        SG_LOG(SG_ATC, SG_ALERT,
+               "AI error: requesting ATC instruction for aircraft without traffic record at " << SG_ORIGIN);
     } else {
         return i->getInstruction();
     }
@@ -1638,7 +1759,7 @@ FGATCInstruction FGApproachController::getInstruction(int id)
 }
 
 
-ActiveRunway *FGApproachController::getRunway(string name)
+ActiveRunway *FGApproachController::getRunway(const string& name)
 {
     ActiveRunwayVecIterator rwy = activeRunways.begin();
     if (activeRunways.size()) {
@@ -1658,7 +1779,7 @@ ActiveRunway *FGApproachController::getRunway(string name)
 }
 
 void FGApproachController::render(bool visible) {
-    //cerr << "FGApproachController::render function not yet implemented" << endl;
+    //std::cerr << "FGApproachController::render function not yet implemented" << std::endl;
 }