]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
begin work on radio subsystem
[flightgear.git] / src / ATC / trafficcontrol.cxx
1 // trafficrecord.cxx - Implementation of AIModels ATC code.
2 //
3 // Written by Durk Talsma, started September 2006.
4 //
5 // Copyright (C) 2006 Durk Talsma.
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <algorithm>
28
29 #include <osg/Geode>
30 #include <osg/Geometry>
31 #include <osg/MatrixTransform>
32 #include <osg/Shape>
33
34 #include <simgear/scene/material/EffectGeode.hxx>
35 #include <simgear/scene/material/matlib.hxx>
36 #include <simgear/scene/material/mat.hxx>
37 #include <Scenery/scenery.hxx>
38
39 #include "trafficcontrol.hxx"
40 #include "atc_mgr.hxx"
41 #include <AIModel/AIAircraft.hxx>
42 #include <AIModel/AIFlightPlan.hxx>
43 #include <AIModel/performancedata.hxx>
44 #include <AIModel/performancedb.hxx>
45 #include <ATC/atc_mgr.hxx>
46 #include <Traffic/TrafficMgr.hxx>
47 #include <Airports/groundnetwork.hxx>
48 #include <Airports/dynamics.hxx>
49 #include <Airports/simple.hxx>
50
51 using std::sort;
52
53 /***************************************************************************
54  * ActiveRunway
55  **************************************************************************/
56 time_t ActiveRunway::requestTimeSlot(time_t eta)
57 {
58     time_t newEta;
59     time_t separation = 90;
60     bool found = false;
61     if (estimatedArrivalTimes.size() == 0) {
62         estimatedArrivalTimes.push_back(eta);
63         return eta;
64     } else {
65         TimeVectorIterator i = estimatedArrivalTimes.begin();
66         //cerr << "Checking eta slots " << eta << ": " << endl;
67         for (i = estimatedArrivalTimes.begin();
68              i != estimatedArrivalTimes.end(); i++) {
69             //cerr << "Stored time : " << (*i) << endl;
70         }
71         i = estimatedArrivalTimes.begin();
72         if ((eta + separation) < (*i)) {
73             newEta = eta;
74             found = true;
75             //cerr << "Storing at beginning" << endl;
76         }
77         while ((i != estimatedArrivalTimes.end()) && (!found)) {
78             TimeVectorIterator j = i + 1;
79             if (j == estimatedArrivalTimes.end()) {
80                 if (((*i) + separation) < eta) {
81                     //cerr << "Storing at end" << endl;
82                     newEta = eta;
83                 } else {
84                     newEta = (*i) + separation;
85                     //cerr << "Storing at end + separation" << endl;
86                 }
87             } else {
88                 if ((((*j) - (*i)) > (separation * 2))) {       // found a potential slot
89                     // now check whether this slot is usable:
90                     // 1) eta should fall between the two points
91                     //    i.e. eta > i AND eta < j
92                     //
93                     //cerr << "Found potential slot after " << (*i) << endl;
94                     if (eta > (*i) && (eta < (*j))) {
95                         found = true;
96                         if (eta < ((*i) + separation)) {
97                             newEta = (*i) + separation;
98                             //cerr << "Using  original" << (*i) << " + separation " << endl;
99                         } else {
100                             newEta = eta;
101                             //cerr << "Using original after " << (*i) << endl;
102                         }
103                     } else if (eta < (*i)) {
104                         found = true;
105                         newEta = (*i) + separation;
106                         //cerr << "Using delayed slot after " << (*i) << endl;
107                     }
108                     /*
109                        if (((*j) - separation) < eta) {
110                        found = true;
111                        if (((*i) + separation) < eta) {
112                        newEta = eta;
113                        cerr << "Using original after " << (*i) << endl;
114                        } else {
115                        newEta = (*i) + separation;
116                        cerr << "Using  " << (*i) << " + separation " << endl;
117                        }
118                        } */
119                 }
120             }
121             i++;
122         }
123     }
124     //cerr << ". done. New ETA : " << newEta << endl;
125
126     estimatedArrivalTimes.push_back(newEta);
127     sort(estimatedArrivalTimes.begin(), estimatedArrivalTimes.end());
128     // do some housekeeping : remove any timestamps that are past
129     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
130     TimeVectorIterator i = estimatedArrivalTimes.begin();
131     while (i != estimatedArrivalTimes.end()) {
132         if ((*i) < now) {
133             //cerr << "Deleting timestamp " << (*i) << " (now = " << now << "). " << endl;
134             estimatedArrivalTimes.erase(i);
135             i = estimatedArrivalTimes.begin();
136         } else {
137             i++;
138         }
139     }
140     return newEta;
141 }
142
143 /***************************************************************************
144  * FGTrafficRecord
145  **************************************************************************/
146 FGTrafficRecord::FGTrafficRecord():
147 id(0), waitsForId(0),
148 currentPos(0),
149 leg(0),
150 frequencyId(0),
151 state(0),
152 allowTransmission(true),
153 latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
154 {
155 }
156
157 void FGTrafficRecord::setPositionAndIntentions(int pos,
158                                                FGAIFlightPlan * route)
159 {
160
161     currentPos = pos;
162     if (intentions.size()) {
163         intVecIterator i = intentions.begin();
164         if ((*i) != pos) {
165             SG_LOG(SG_GENERAL, SG_ALERT,
166                    "Error in FGTrafficRecord::setPositionAndIntentions");
167             //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
168             for (intVecIterator i = intentions.begin();
169                  i != intentions.end(); i++) {
170                 //cerr << (*i) << " ";
171             }
172             //cerr << endl;
173         }
174         intentions.erase(i);
175     } else {
176         //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint();
177         int size = route->getNrOfWayPoints();
178         //cerr << "Setting pos" << pos << " ";
179         //cerr << "setting intentions ";
180         for (int i = 0; i < size; i++) {
181             int val = route->getRouteIndex(i);
182             //cerr << val<< " ";
183             if ((val) && (val != pos)) {
184                 intentions.push_back(val);
185                 //cerr << "[set] ";
186             }
187         }
188         //cerr << endl;
189         //while (route->next(&legNr, &routeNr)) {
190         //intentions.push_back(routeNr);
191         //}
192         //route->rewind(currentPos);
193     }
194     //exit(1);
195 }
196 /**
197  * Check if another aircraft is ahead of the current one, and on the same 
198  * return true / false is the is/isn't the case.
199  *
200  ****************************************************************************/
201
202 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
203 {
204     bool result = false;
205     //cerr << "Start check 1" << endl;
206     if (currentPos == other.currentPos) {
207         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
208         result = true;
209     }
210     //  else if (other.intentions.size()) 
211     //     {
212     //       cerr << "Start check 2" << endl;
213     //       intVecIterator i = other.intentions.begin(); 
214     //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
215     //     i++;
216     //       if (i != other.intentions.end()) {
217     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
218     //     result = true;
219     //       }
220     else if (intentions.size()) {
221         //cerr << "Start check 3" << endl;
222         intVecIterator i = intentions.begin();
223         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
224         while (i != intentions.end()) {
225             if ((*i) == other.currentPos) {
226                 break;
227             }
228             i++;
229         }
230         if (i != intentions.end()) {
231             //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
232             result = true;
233         }
234     }
235     //cerr << "Done !!" << endl;
236     return result;
237 }
238
239 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
240                                             double hdg, double spd,
241                                             double alt)
242 {
243     latitude = lat;
244     longitude = lon;
245     heading = hdg;
246     speed = spd;
247     altitude = alt;
248 }
249
250 int FGTrafficRecord::crosses(FGGroundNetwork * net,
251                              FGTrafficRecord & other)
252 {
253     if (checkPositionAndIntentions(other)
254         || (other.checkPositionAndIntentions(*this)))
255         return -1;
256     intVecIterator i, j;
257     int currentTargetNode = 0, otherTargetNode = 0;
258     if (currentPos > 0)
259         currentTargetNode = net->findSegment(currentPos)->getEnd()->getIndex(); // OKAY,... 
260     if (other.currentPos > 0)
261         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
262     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
263         return currentTargetNode;
264     if (intentions.size()) {
265         for (i = intentions.begin(); i != intentions.end(); i++) {
266             if ((*i) > 0) {
267                 if ((currentTargetNode ==
268                      net->findSegment(*i)->getEnd()->getIndex())) {
269                     //cerr << "Current crosses at " << currentTargetNode <<endl;
270                     return currentTargetNode;
271                 }
272             }
273         }
274     }
275     if (other.intentions.size()) {
276         for (i = other.intentions.begin(); i != other.intentions.end();
277              i++) {
278             if ((*i) > 0) {
279                 if (otherTargetNode ==
280                     net->findSegment(*i)->getEnd()->getIndex()) {
281                     //cerr << "Other crosses at " << currentTargetNode <<endl;
282                     return otherTargetNode;
283                 }
284             }
285         }
286     }
287     if (intentions.size() && other.intentions.size()) {
288         for (i = intentions.begin(); i != intentions.end(); i++) {
289             for (j = other.intentions.begin(); j != other.intentions.end();
290                  j++) {
291                 //cerr << "finding segment " << *i << " and " << *j << endl;
292                 if (((*i) > 0) && ((*j) > 0)) {
293                     currentTargetNode =
294                         net->findSegment(*i)->getEnd()->getIndex();
295                     otherTargetNode =
296                         net->findSegment(*j)->getEnd()->getIndex();
297                     if (currentTargetNode == otherTargetNode) {
298                         //cerr << "Routes will cross at " << currentTargetNode << endl;
299                         return currentTargetNode;
300                     }
301                 }
302             }
303         }
304     }
305     return -1;
306 }
307
308 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
309                               FGTrafficRecord & other)
310 {
311     int node = -1, othernode = -1;
312     if (currentPos > 0)
313         node = net->findSegment(currentPos)->getEnd()->getIndex();
314     if (other.currentPos > 0)
315         othernode =
316             net->findSegment(other.currentPos)->getEnd()->getIndex();
317     if ((node == othernode) && (node != -1))
318         return true;
319     if (other.intentions.size()) {
320         for (intVecIterator i = other.intentions.begin();
321              i != other.intentions.end(); i++) {
322             if (*i > 0) {
323                 othernode = net->findSegment(*i)->getEnd()->getIndex();
324                 if ((node == othernode) && (node > -1))
325                     return true;
326             }
327         }
328     }
329     //if (other.currentPos > 0)
330     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
331     //if (intentions.size())
332     //  {
333     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
334     //    {
335     //      if (*i > 0) 
336     //        {
337     //          node = net->findSegment(*i)->getEnd()->getIndex();
338     //          if ((node == othernode) && (node > -1))
339     //            return true;
340     //        }
341     //    }
342     //  }
343     return false;
344 }
345
346
347 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
348                                  FGTrafficRecord & other, int node)
349 {
350     // Check if current segment is the reverse segment for the other aircraft
351     FGTaxiSegment *opp;
352     //cerr << "Current segment " << currentPos << endl;
353     if ((currentPos > 0) && (other.currentPos > 0)) {
354         opp = net->findSegment(currentPos)->opposite();
355         if (opp) {
356             if (opp->getIndex() == other.currentPos)
357                 return true;
358         }
359
360         for (intVecIterator i = intentions.begin(); i != intentions.end();
361              i++) {
362             if ((opp = net->findSegment(other.currentPos)->opposite())) {
363                 if ((*i) > 0)
364                     if (opp->getIndex() ==
365                         net->findSegment(*i)->getIndex()) {
366                         if (net->findSegment(*i)->getStart()->getIndex() ==
367                             node) {
368                             {
369                                 //cerr << "Found the node " << node << endl;
370                                 return true;
371                             }
372                         }
373                     }
374             }
375             if (other.intentions.size()) {
376                 for (intVecIterator j = other.intentions.begin();
377                      j != other.intentions.end(); j++) {
378                     // cerr << "Current segment 1 " << (*i) << endl;
379                     if ((*i) > 0) {
380                         if ((opp = net->findSegment(*i)->opposite())) {
381                             if (opp->getIndex() ==
382                                 net->findSegment(*j)->getIndex()) {
383                                 //cerr << "Nodes " << net->findSegment(*i)->getIndex()
384                                 //   << " and  " << net->findSegment(*j)->getIndex()
385                                 //   << " are opposites " << endl;
386                                 if (net->findSegment(*i)->getStart()->
387                                     getIndex() == node) {
388                                     {
389                                         //cerr << "Found the node " << node << endl;
390                                         return true;
391                                     }
392                                 }
393                             }
394                         }
395                     }
396                 }
397             }
398         }
399     }
400     return false;
401 }
402
403 void FGTrafficRecord::setSpeedAdjustment(double spd)
404 {
405     instruction.setChangeSpeed(true);
406     instruction.setSpeed(spd);
407 }
408
409 void FGTrafficRecord::setHeadingAdjustment(double heading)
410 {
411     instruction.setChangeHeading(true);
412     instruction.setHeading(heading);
413 }
414
415 bool FGTrafficRecord::pushBackAllowed()
416 {
417     // With the user ATC / AI integration, checking whether the user's aircraft is near no longer works, because
418     // this will effectively block the user's aircraft itself from receiving pushback clearance. 
419     // So, what can we do?
420     /*
421     double course, az2, dist;
422     SGGeod curr(SGGeod::fromDegM(getLongitude(),
423                                  getLatitude(), getAltitude()));
424
425     double userLatitude = fgGetDouble("/position/latitude-deg");
426     double userLongitude = fgGetDouble("/position/longitude-deg");
427     SGGeod user(SGGeod::fromDeg(userLongitude, userLatitude));
428     SGGeodesy::inverse(curr, user, course, az2, dist);
429     //cerr << "Distance to user : " << dist << endl;
430     return (dist > 250);
431     */
432
433
434     // In essence, we should check whether the pusbback route itself, as well as the associcated
435     // taxiways near the pushback point are free of traffic. 
436     // To do so, we need to 
437     return true;
438 }
439
440
441
442 /***************************************************************************
443  * FGATCInstruction
444  *
445  **************************************************************************/
446 FGATCInstruction::FGATCInstruction()
447 {
448     holdPattern = false;
449     holdPosition = false;
450     changeSpeed = false;
451     changeHeading = false;
452     changeAltitude = false;
453     resolveCircularWait = false;
454
455     speed = 0;
456     heading = 0;
457     alt = 0;
458 }
459
460
461 bool FGATCInstruction::hasInstruction()
462 {
463     return (holdPattern || holdPosition || changeSpeed || changeHeading
464             || changeAltitude || resolveCircularWait);
465 }
466
467 /***************************************************************************
468  * FGATCController
469  *
470  **************************************************************************/
471
472
473
474
475 FGATCController::FGATCController()
476 {
477     //cerr << "running FGATController constructor" << endl;
478     dt_count = 0;
479     available = true;
480     lastTransmission = 0;
481     initialized = false;
482 }
483
484 FGATCController::~FGATCController()
485 {
486      //cerr << "running FGATController destructor" << endl;
487 }
488
489 string FGATCController::getGateName(FGAIAircraft * ref)
490 {
491     return ref->atGate();
492 }
493
494 bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
495
496     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
497 };
498
499 void FGATCController::transmit(FGTrafficRecord * rec, FGAirportDynamics *parent, AtcMsgId msgId,
500                                AtcMsgDir msgDir, bool audible)
501 {
502     string sender, receiver;
503     int stationFreq = 0;
504     int taxiFreq = 0;
505     int towerFreq = 0;
506     int freqId = 0;
507     string atisInformation;
508     string text;
509     string taxiFreqStr;
510     string towerFreqStr;
511     double heading = 0;
512     string activeRunway;
513     string fltType;
514     string rwyClass;
515     string SID;
516     string transponderCode;
517     FGAIFlightPlan *fp;
518     string fltRules;
519     string instructionText;
520     int ground_to_air=0;
521
522     //double commFreqD;
523     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
524     if (rec->getAircraft()->getTaxiClearanceRequest()) {
525         instructionText = "push-back and taxi";
526     } else {
527         instructionText = "taxi";
528     }
529     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
530     switch (rec->getLeg()) {
531     case 1:
532     case 2:
533         freqId = rec->getNextFrequency();
534         stationFreq =
535             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
536             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
537         taxiFreq =
538             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
539             getDynamics()->getGroundFrequency(2);
540         towerFreq = 
541             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
542             getDynamics()->getTowerFrequency(2);
543         receiver =
544             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
545             getName() + "-Ground";
546         atisInformation =
547             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
548             getDynamics()->getAtisSequence();
549         break;
550     case 3:
551         receiver =
552             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
553             getName() + "-Tower";
554         break;
555     }
556     // Swap sender and receiver value in case of a ground to air transmission
557     if (msgDir == ATC_GROUND_TO_AIR) {
558         string tmp = sender;
559         sender = receiver;
560         receiver = tmp;
561         ground_to_air=1;
562     }
563     switch (msgId) {
564     case MSG_ANNOUNCE_ENGINE_START:
565         text = sender + ". Ready to Start up";
566         break;
567     case MSG_REQUEST_ENGINE_START:
568         text =
569             receiver + ", This is " + sender + ". Position " +
570             getGateName(rec->getAircraft()) + ". Information " +
571             atisInformation + ". " +
572             rec->getAircraft()->getTrafficRef()->getFlightRules() +
573             " to " +
574             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
575             getName() + ". Request start-up";
576         break;
577         // Acknowledge engine startup permission
578         // Assign departure runway
579         // Assign SID, if necessery (TODO)
580     case MSG_PERMIT_ENGINE_START:
581         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
582
583         heading = rec->getAircraft()->getTrafficRef()->getCourse();
584         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
585         rwyClass =
586             rec->getAircraft()->GetFlightPlan()->
587             getRunwayClassFromTrafficType(fltType);
588
589         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
590             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
591                                            heading);
592         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
593         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
594             getDynamics()->getSID(activeRunway, heading);
595         rec->getAircraft()->GetFlightPlan()->setSID(fp);
596         if (fp) {
597             SID = fp->getName() + " departure";
598         } else {
599             SID = "fly runway heading ";
600         }
601         //snprintf(buffer, 7, "%3.2f", heading);
602         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
603         transponderCode = genTransponderCode(fltRules);
604         rec->getAircraft()->SetTransponderCode(transponderCode);
605         text =
606             receiver + ". Start-up approved. " + atisInformation +
607             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
608             transponderCode + ". " +
609             "For "+ instructionText + " clearance call " + taxiFreqStr + ". " +
610             sender + " control.";
611         break;
612     case MSG_DENY_ENGINE_START:
613         text = receiver + ". Standby";
614         break;
615     case MSG_ACKNOWLEDGE_ENGINE_START:
616         fp = rec->getAircraft()->GetFlightPlan()->getSID();
617         if (fp) {
618             SID =
619                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
620                 " departure";
621         } else {
622             SID = "fly runway heading ";
623         }
624         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
625         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
626         transponderCode = rec->getAircraft()->GetTransponderCode();
627
628         text =
629             receiver + ". Start-up approved. " + atisInformation +
630             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
631             transponderCode + ". " +
632             "For " + instructionText + " clearance call " + taxiFreqStr + ". " +
633             sender;
634         break;
635     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
636         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
637         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
638         break;
639     case MSG_INITIATE_CONTACT:
640         text = receiver + ". With you. " + sender;
641         break;
642     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
643         text = receiver + ". Roger. " + sender;
644         break;
645     case MSG_REQUEST_PUSHBACK_CLEARANCE:
646         if (rec->getAircraft()->getTaxiClearanceRequest()) {
647             text = receiver + ". Request push-back. " + sender;
648         } else {
649             text = receiver + ". Request Taxi clearance. " + sender;
650         }
651         break;
652     case MSG_PERMIT_PUSHBACK_CLEARANCE:
653         if (rec->getAircraft()->getTaxiClearanceRequest()) {
654             text = receiver + ". Push-back approved. " + sender;
655         } else {
656             text = receiver + ". Cleared to Taxi." + sender;
657         }
658         break;
659     case MSG_HOLD_PUSHBACK_CLEARANCE:
660         text = receiver + ". Standby. " + sender;
661         break;
662     case MSG_REQUEST_TAXI_CLEARANCE:
663         text = receiver + ". Ready to Taxi. " + sender;
664         break;
665     case MSG_ISSUE_TAXI_CLEARANCE:
666         text = receiver + ". Cleared to taxi. " + sender;
667         break;
668     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
669         text = receiver + ". Cleared to taxi. " + sender;
670         break;
671     case MSG_HOLD_POSITION:
672         text = receiver + ". Hold Position. " + sender;
673         break;
674     case MSG_ACKNOWLEDGE_HOLD_POSITION:
675         text = receiver + ". Holding Position. " + sender;
676         break;
677     case MSG_RESUME_TAXI:
678         text = receiver + ". Resume Taxiing. " + sender;
679         break;
680     case MSG_ACKNOWLEDGE_RESUME_TAXI:
681         text = receiver + ". Continuing Taxi. " + sender;
682         break;
683     case MSG_REPORT_RUNWAY_HOLD_SHORT:
684         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
685         //activeRunway = "test";
686         text = receiver + ". Holding short runway " 
687                         + activeRunway 
688                         + ". " + sender;
689         //text = "test1";
690         //cerr << "1 Currently at leg " << rec->getLeg() << endl;
691         break;
692     case MSG_ACKNOWLEDGE_REPORT_RUNWAY_HOLD_SHORT:
693         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
694         text = receiver + "Roger. Holding short runway " 
695         //                + activeRunway 
696                         + ". " + sender;
697         //text = "test2";
698         //cerr << "2 Currently at leg " << rec->getLeg() << endl;
699         break;
700     case MSG_SWITCH_TOWER_FREQUENCY:
701         towerFreqStr = formatATCFrequency3_2(towerFreq);
702         text = receiver + "Contact Tower at " + towerFreqStr + ". " + sender;
703         //text = "test3";
704         //cerr << "3 Currently at leg " << rec->getLeg() << endl;
705         break;
706     case MSG_ACKNOWLEDGE_SWITCH_TOWER_FREQUENCY:
707         towerFreqStr = formatATCFrequency3_2(towerFreq);
708         text = receiver + "Roger, switching to tower at " + towerFreqStr + ". " + sender;
709         //text = "test4";
710         //cerr << "4 Currently at leg " << rec->getLeg() << endl;
711         break;
712     default:
713         //text = "test3";
714         text = text + sender + ". Transmitting unknown Message";
715         break;
716     }
717     if (audible) {
718         double onBoardRadioFreq0 =
719             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
720         double onBoardRadioFreq1 =
721             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
722         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
723         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
724         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
725
726         // Display ATC message only when one of the radios is tuned
727         // the relevant frequency.
728         // Note that distance attenuation is currently not yet implemented
729                 
730         if ((onBoardRadioFreqI0 == stationFreq)
731             || (onBoardRadioFreqI1 == stationFreq)) {
732                 
733             if (rec->allowTransmissions()) {
734                 
735                 fgSetString("/sim/messages/atc", text.c_str());
736             }
737         }
738     } else {
739         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
740         atc->getATCDialog()->addEntry(1, text);
741         
742     }
743 }
744
745
746 string FGATCController::formatATCFrequency3_2(int freq)
747 {
748     char buffer[7];
749     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
750     return string(buffer);
751 }
752
753 // TODO: Set transponder codes according to real-world routes.
754 // The current version just returns a random string of four octal numbers. 
755 string FGATCController::genTransponderCode(string fltRules)
756 {
757     if (fltRules == "VFR") {
758         return string("1200");
759     } else {
760         char buffer[5];
761         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
762                  rand() % 8);
763         return string(buffer);
764     }
765 }
766
767 void FGATCController::init() 
768 {
769    if (!initialized) {
770        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
771        mgr->addController(this);
772        initialized = true;
773     }
774 }
775
776 /***************************************************************************
777  * class FGTowerController
778  *
779  **************************************************************************/
780 FGTowerController::FGTowerController(FGAirportDynamics *par) :
781 FGATCController()
782 {
783     parent = par;
784 }
785
786 // 
787 void FGTowerController::announcePosition(int id,
788                                          FGAIFlightPlan * intendedRoute,
789                                          int currentPosition, double lat,
790                                          double lon, double heading,
791                                          double speed, double alt,
792                                          double radius, int leg,
793                                          FGAIAircraft * ref)
794 {
795     init();
796     TrafficVectorIterator i = activeTraffic.begin();
797     // Search whether the current id alread has an entry
798     // This might be faster using a map instead of a vector, but let's start by taking a safe route
799     if (activeTraffic.size()) {
800         //while ((i->getId() != id) && i != activeTraffic.end()) {
801         while (i != activeTraffic.end()) {
802             if (i->getId() == id) {
803                 break;
804             }
805             i++;
806         }
807     }
808     // Add a new TrafficRecord if no one exsists for this aircraft.
809     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
810         FGTrafficRecord rec;
811         rec.setId(id);
812
813         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
814         rec.setRunway(intendedRoute->getRunway());
815         rec.setLeg(leg);
816         //rec.setCallSign(callsign);
817         rec.setRadius(radius);
818         rec.setAircraft(ref);
819         activeTraffic.push_back(rec);
820         // Don't just schedule the aircraft for the tower controller, also assign if to the correct active runway. 
821         ActiveRunwayVecIterator rwy = activeRunways.begin();
822         if (activeRunways.size()) {
823             while (rwy != activeRunways.end()) {
824                 if (rwy->getRunwayName() == intendedRoute->getRunway()) {
825                     break;
826                 }
827                 rwy++;
828             }
829         }
830         if (rwy == activeRunways.end()) {
831             ActiveRunway aRwy(intendedRoute->getRunway(), id);
832             aRwy.addToDepartureCue(ref);
833             activeRunways.push_back(aRwy);
834             rwy = (activeRunways.end()-1);
835         } else {
836             rwy->addToDepartureCue(ref);
837         }
838
839         //cerr << ref->getTrafficRef()->getCallSign() << " You are number " << rwy->getDepartureCueSize() <<  " for takeoff " << endl;
840     } else {
841         i->setPositionAndHeading(lat, lon, heading, speed, alt);
842     }
843 }
844
845 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
846                                                   double heading, double speed, double alt,
847                                                   double dt)
848 {
849     TrafficVectorIterator i = activeTraffic.begin();
850     // Search whether the current id has an entry
851     // This might be faster using a map instead of a vector, but let's start by taking a safe route
852     TrafficVectorIterator current, closest;
853     if (activeTraffic.size()) {
854         //while ((i->getId() != id) && i != activeTraffic.end()) {
855         while (i != activeTraffic.end()) {
856             if (i->getId() == id) {
857                 break;
858             }
859             i++;
860         }
861     }
862 //    // update position of the current aircraft
863     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
864         SG_LOG(SG_GENERAL, SG_ALERT,
865                "AI error: updating aircraft without traffic record");
866     } else {
867         i->setPositionAndHeading(lat, lon, heading, speed, alt);
868         current = i;
869     }
870     setDt(getDt() + dt);
871
872     // see if we already have a clearance record for the currently active runway
873     // NOTE: dd. 2011-08-07: Because the active runway has been constructed in the announcePosition function, we may safely assume that is
874     // already exists here. So, we can simplify the current code. 
875     ActiveRunwayVecIterator rwy = activeRunways.begin();
876     while (rwy != activeRunways.end()) {
877         if (rwy->getRunwayName() == current->getRunway()) {
878             break;
879         }
880         rwy++;
881     }
882
883     // only bother running the following code if the current aircraft is the
884     // first in line for depature
885     /* if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
886         if (rwy->getCleared()) {
887             if (id == rwy->getCleared()) {
888                 current->setHoldPosition(false);
889             } else {
890                 current->setHoldPosition(true);
891             }
892         } else {
893             // For now. At later stages, this will probably be the place to check for inbound traffc.
894             rwy->setCleared(id);
895         }
896     } */
897     // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
898     if (current->getAircraft()->getTakeOffStatus() == 2) {
899         current->setHoldPosition(true);
900         int clearanceId = rwy->getCleared();
901         if (clearanceId) {
902             if (id == clearanceId) {
903                 current->setHoldPosition(false);
904             }
905         } else {
906             if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
907                 rwy->setCleared(id);
908             }
909         }
910     }
911 }
912
913
914 void FGTowerController::signOff(int id)
915 {
916     TrafficVectorIterator i = activeTraffic.begin();
917     // Search search if the current id alread has an entry
918     // This might be faster using a map instead of a vector, but let's start by taking a safe route
919     if (activeTraffic.size()) {
920         //while ((i->getId() != id) && i != activeTraffic.end()) {
921         while (i != activeTraffic.end()) {
922             if (i->getId() == id) {
923                 break;
924             }
925             i++;
926         }
927     }
928     // If this aircraft has left the runway, we can clear the departure record for this runway
929     ActiveRunwayVecIterator rwy = activeRunways.begin();
930     if (activeRunways.size()) {
931         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
932         while (rwy != activeRunways.end()) {
933             if (rwy->getRunwayName() == i->getRunway()) {
934                 break;
935             }
936             rwy++;
937         }
938         if (rwy != activeRunways.end()) {
939             rwy->setCleared(0);
940             rwy->updateDepartureCue();
941         } else {
942             SG_LOG(SG_GENERAL, SG_ALERT,
943                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
944         }
945     }
946     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
947         SG_LOG(SG_GENERAL, SG_ALERT,
948                "AI error: Aircraft without traffic record is signing off from tower");
949     } else {
950         i->getAircraft()->resetTakeOffStatus();
951         i = activeTraffic.erase(i);
952         //cerr << "Signing off from tower controller" << endl;
953     }
954 }
955
956 // NOTE:
957 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
958 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
959 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
960 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
961 // Note that this function is probably obsolete
962 bool FGTowerController::hasInstruction(int id)
963 {
964     TrafficVectorIterator i = activeTraffic.begin();
965     // Search search if the current id has an entry
966     // This might be faster using a map instead of a vector, but let's start by taking a safe route
967     if (activeTraffic.size()) {
968         //while ((i->getId() != id) && i != activeTraffic.end()) {
969         while (i != activeTraffic.end()) {
970             if (i->getId() == id) {
971                 break;
972             }
973             i++;
974         }
975     }
976     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
977         SG_LOG(SG_GENERAL, SG_ALERT,
978                "AI error: checking ATC instruction for aircraft without traffic record");
979     } else {
980         return i->hasInstruction();
981     }
982     return false;
983 }
984
985
986 FGATCInstruction FGTowerController::getInstruction(int id)
987 {
988     TrafficVectorIterator i = activeTraffic.begin();
989     // Search search if the current id has an entry
990     // This might be faster using a map instead of a vector, but let's start by taking a safe route
991     if (activeTraffic.size()) {
992         //while ((i->getId() != id) && i != activeTraffic.end()) {
993         while (i != activeTraffic.end()) {
994             if (i->getId() == id) {
995                 break;
996             }
997             i++;
998         }
999     }
1000     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1001         SG_LOG(SG_GENERAL, SG_ALERT,
1002                "AI error: requesting ATC instruction for aircraft without traffic record");
1003     } else {
1004         return i->getInstruction();
1005     }
1006     return FGATCInstruction();
1007 }
1008
1009 void FGTowerController::render(bool visible) {
1010     //cerr << "FGTowerController::render function not yet implemented" << endl;
1011 }
1012
1013 string FGTowerController::getName() {
1014     return string(parent->getId() + "-tower");
1015 }
1016
1017
1018
1019 /***************************************************************************
1020  * class FGStartupController
1021  *
1022  **************************************************************************/
1023 FGStartupController::FGStartupController(FGAirportDynamics *par):
1024     FGATCController()
1025 {
1026     parent = par;
1027 }
1028
1029 void FGStartupController::announcePosition(int id,
1030                                            FGAIFlightPlan * intendedRoute,
1031                                            int currentPosition, double lat,
1032                                            double lon, double heading,
1033                                            double speed, double alt,
1034                                            double radius, int leg,
1035                                            FGAIAircraft * ref)
1036 {
1037     init();
1038     TrafficVectorIterator i = activeTraffic.begin();
1039     // Search whether the current id alread has an entry
1040     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1041     if (activeTraffic.size()) {
1042         //while ((i->getId() != id) && i != activeTraffic.end()) {
1043         while (i != activeTraffic.end()) {
1044             if (i->getId() == id) {
1045                 break;
1046             }
1047             i++;
1048         }
1049     }
1050     // Add a new TrafficRecord if no one exsists for this aircraft.
1051     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1052         FGTrafficRecord rec;
1053         rec.setId(id);
1054
1055         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1056         rec.setRunway(intendedRoute->getRunway());
1057         rec.setLeg(leg);
1058         rec.setPositionAndIntentions(currentPosition, intendedRoute);
1059         //rec.setCallSign(callsign);
1060         rec.setAircraft(ref);
1061         rec.setHoldPosition(true);
1062         activeTraffic.push_back(rec);
1063     } else {
1064         i->setPositionAndIntentions(currentPosition, intendedRoute);
1065         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1066
1067     }
1068 }
1069
1070 // NOTE:
1071 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
1072 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
1073 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
1074 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
1075 // Note that this function is probably obsolete
1076 bool FGStartupController::hasInstruction(int id)
1077 {
1078     TrafficVectorIterator i = activeTraffic.begin();
1079     // Search search if the current id has an entry
1080     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1081     if (activeTraffic.size()) {
1082         //while ((i->getId() != id) && i != activeTraffic.end()) {
1083         while (i != activeTraffic.end()) {
1084             if (i->getId() == id) {
1085                 break;
1086             }
1087             i++;
1088         }
1089     }
1090     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1091         SG_LOG(SG_GENERAL, SG_ALERT,
1092                "AI error: checking ATC instruction for aircraft without traffic record");
1093     } else {
1094         return i->hasInstruction();
1095     }
1096     return false;
1097 }
1098
1099
1100 FGATCInstruction FGStartupController::getInstruction(int id)
1101 {
1102     TrafficVectorIterator i = activeTraffic.begin();
1103     // Search search if the current id has an entry
1104     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1105     if (activeTraffic.size()) {
1106         //while ((i->getId() != id) && i != activeTraffic.end()) {
1107         while (i != activeTraffic.end()) {
1108             if (i->getId() == id) {
1109                 break;
1110             }
1111             i++;
1112         }
1113     }
1114     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1115         SG_LOG(SG_GENERAL, SG_ALERT,
1116                "AI error: requesting ATC instruction for aircraft without traffic record");
1117     } else {
1118         return i->getInstruction();
1119     }
1120     return FGATCInstruction();
1121 }
1122
1123 void FGStartupController::signOff(int id)
1124 {
1125     TrafficVectorIterator i = activeTraffic.begin();
1126     // Search search if the current id alread has an entry
1127     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1128     if (activeTraffic.size()) {
1129         //while ((i->getId() != id) && i != activeTraffic.end()) {
1130         while (i != activeTraffic.end()) {
1131             if (i->getId() == id) {
1132                 break;
1133             }
1134             i++;
1135         }
1136     }
1137     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1138         SG_LOG(SG_GENERAL, SG_ALERT,
1139                "AI error: Aircraft without traffic record is signing off from tower");
1140     } else {
1141         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1142         i = activeTraffic.erase(i);
1143     }
1144 }
1145
1146 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1147                                AtcMsgDir msgDir)
1148 {
1149     int state = i->getState();
1150     if ((state == st) && available) {
1151         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1152             
1153             //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1154             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1155             int n = trans_num->getIntValue();
1156             if (n == 0) {
1157                 trans_num->setIntValue(-1);
1158                  // PopupCallback(n);
1159                  //cerr << "Selected transmission message " << n << endl;
1160                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1161                  atc->getATCDialog()->removeEntry(1);
1162             } else {
1163                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1164                 transmit(&(*i), &(*parent), msgId, msgDir, false);
1165                 return false;
1166             }
1167         }
1168         if (now > startTime) {
1169             //cerr << "Transmitting startup msg" << endl;
1170             transmit(&(*i), &(*parent), msgId, msgDir, true);
1171             i->updateState();
1172             lastTransmission = now;
1173             available = false;
1174             return true;
1175         }
1176     }
1177     return false;
1178 }
1179
1180 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1181                                                     double heading, double speed, double alt,
1182                                                     double dt)
1183 {
1184     TrafficVectorIterator i = activeTraffic.begin();
1185     // Search search if the current id has an entry
1186     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1187     TrafficVectorIterator current, closest;
1188     if (activeTraffic.size()) {
1189         //while ((i->getId() != id) && i != activeTraffic.end()) {
1190         while (i != activeTraffic.end()) {
1191             if (i->getId() == id) {
1192                 break;
1193             }
1194             i++;
1195         }
1196     }
1197 //    // update position of the current aircraft
1198
1199     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1200         SG_LOG(SG_GENERAL, SG_ALERT,
1201                "AI error: updating aircraft without traffic record");
1202     } else {
1203         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1204         current = i;
1205     }
1206     setDt(getDt() + dt);
1207
1208     int state = i->getState();
1209
1210     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1211     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1212     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1213     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1214     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1215     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1216     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1217
1218     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1219         available = true;
1220     }
1221
1222     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1223     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1224     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1225     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1226     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1227         i->nextFrequency();
1228     }
1229     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1230     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1231     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1232
1233
1234    
1235     if ((state == 8) && available) {
1236         if (now > startTime + 200) {
1237             if (i->pushBackAllowed()) {
1238                 i->allowRepeatedTransmissions();
1239                 transmit(&(*i), &(*parent), MSG_PERMIT_PUSHBACK_CLEARANCE,
1240                          ATC_GROUND_TO_AIR, true);
1241                 i->updateState();
1242             } else {
1243                 transmit(&(*i), &(*parent), MSG_HOLD_PUSHBACK_CLEARANCE,
1244                          ATC_GROUND_TO_AIR, true);
1245                 i->suppressRepeatedTransmissions();
1246             }
1247             lastTransmission = now;
1248             available = false;
1249         }
1250     }
1251     if ((state == 9) && available) {
1252         i->setHoldPosition(false);
1253     }
1254 }
1255
1256 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1257 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1258                             double lon, double elev, double hdg, double slope)
1259 {
1260     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1261     obj_pos = geod.makeZUpFrame();
1262     // hdg is not a compass heading, but a counter-clockwise rotation
1263     // around the Z axis
1264     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1265                                         0.0, 0.0, 1.0));
1266     obj_pos.preMult(osg::Matrix::rotate(slope * SGD_DEGREES_TO_RADIANS,
1267                                         0.0, 1.0, 0.0));
1268 }
1269
1270
1271 void FGStartupController::render(bool visible)
1272 {
1273
1274     SGMaterialLib *matlib = globals->get_matlib();
1275     if (group) {
1276         //int nr = ;
1277         globals->get_scenery()->get_scene_graph()->removeChild(group);
1278         //while (group->getNumChildren()) {
1279         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1280         //simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1281           //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1282            //geode->releaseGLObjects();
1283            //group->removeChild(geode);
1284            //delete geode;
1285         group = 0;
1286     }
1287     if (visible) {
1288         group = new osg::Group;
1289         FGScenery * local_scenery = globals->get_scenery();
1290         double elevation_meters = 0.0;
1291         double elevation_feet = 0.0;
1292
1293
1294         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1295         double dx = 0;
1296         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1297             // Handle start point
1298             int pos = i->getCurrentPosition();
1299             //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1300             if (pos > 0) {
1301                 FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1302                 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1303                 SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1304
1305                 double length = SGGeodesy::distanceM(start, end);
1306                 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1307
1308                 double az2, heading; //, distanceM;
1309                 SGGeodesy::inverse(start, end, heading, az2, length);
1310                 double coveredDistance = length * 0.5;
1311                 SGGeod center;
1312                 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1313                 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1314                 ///////////////////////////////////////////////////////////////////////////////
1315                 // Make a helper function out of this
1316                 osg::Matrix obj_pos;
1317                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1318                 obj_trans->setDataVariance(osg::Object::STATIC);
1319                 // Experimental: Calculate slope here, based on length, and the individual elevations
1320                 double elevationStart;
1321                 if (isUserAircraft((i)->getAircraft())) {
1322                     elevationStart = fgGetDouble("/position/ground-elev-m");
1323                 } else {
1324                     elevationStart = ((i)->getAircraft()->_getAltitude()); 
1325                 }
1326                 double elevationEnd   = segment->getEnd()->getElevation();
1327                 if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
1328                     SGGeod center2 = end;
1329                     center2.setElevationM(SG_MAX_ELEVATION_M);
1330                     if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
1331                         elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
1332                             //elevation_meters += 0.5;
1333                     }
1334                     else { 
1335                         elevationEnd = parent->getElevation();
1336                     }
1337                     segment->getEnd()->setElevation(elevationEnd);
1338                 }
1339
1340                 double elevationMean  = (elevationStart + elevationEnd) / 2.0;
1341                 double elevDiff       = elevationEnd - elevationStart;
1342                
1343                double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
1344                 
1345                //cerr << "1. Using mean elevation : " << elevationMean << " and " << slope << endl;
1346
1347                 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), elevationMean + 0.5, -(heading), slope );
1348 ;
1349
1350                 obj_trans->setMatrix( obj_pos );
1351                 //osg::Vec3 center(0, 0, 0)
1352
1353                 float width = length /2.0;
1354                 osg::Vec3 corner(-width, 0, 0.25f);
1355                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1356                 osg::Vec3 heightVec(0, 1, 0);
1357                 osg::Geometry* geometry;
1358                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1359                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1360                 geode->setName("test");
1361                 geode->addDrawable(geometry);
1362                 //osg::Node *custom_obj;
1363                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1364                 if (mat)
1365                     geode->setEffect(mat->get_effect());
1366                 obj_trans->addChild(geode);
1367                 // wire as much of the scene graph together as we can
1368                 //->addChild( obj_trans );
1369                 group->addChild( obj_trans );
1370                 /////////////////////////////////////////////////////////////////////
1371             } else {
1372                 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1373             }
1374             for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1375                 osg::Matrix obj_pos;
1376                 int k = (*j);
1377                 if (k > 0) {
1378                     //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1379                     osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1380                     obj_trans->setDataVariance(osg::Object::STATIC);
1381                     FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1382
1383                     double elevationStart = segment->getStart()->getElevation();
1384                     double elevationEnd   = segment->getEnd  ()->getElevation();
1385                     if ((elevationStart == 0) || (elevationStart == parent->getElevation())) {
1386                         SGGeod center2 = segment->getStart()->getGeod();
1387                         center2.setElevationM(SG_MAX_ELEVATION_M);
1388                         if (local_scenery->get_elevation_m( center2, elevationStart, NULL )) {
1389                             elevation_feet = elevationStart * SG_METER_TO_FEET + 0.5;
1390                             //elevation_meters += 0.5;
1391                         }
1392                         else { 
1393                             elevationStart = parent->getElevation();
1394                         }
1395                         segment->getStart()->setElevation(elevationStart);
1396                     }
1397                     if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
1398                         SGGeod center2 = segment->getEnd()->getGeod();
1399                         center2.setElevationM(SG_MAX_ELEVATION_M);
1400                         if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
1401                             elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
1402                             //elevation_meters += 0.5;
1403                         }
1404                         else { 
1405                             elevationEnd = parent->getElevation();
1406                         }
1407                         segment->getEnd()->setElevation(elevationEnd);
1408                     }
1409  
1410                     double elevationMean  = (elevationStart + elevationEnd) / 2.0;
1411                     double elevDiff       = elevationEnd - elevationStart;
1412                     double length         = segment->getLength();
1413                     double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
1414                 
1415                     //cerr << "2. Using mean elevation : " << elevationMean << " and " << slope << endl;
1416
1417
1418                     WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), elevationMean + 0.5, -(segment->getHeading()), slope );
1419
1420                     //WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1421
1422                     obj_trans->setMatrix( obj_pos );
1423                     //osg::Vec3 center(0, 0, 0)
1424
1425                     float width = segment->getLength() /2.0;
1426                     osg::Vec3 corner(-width, 0, 0.25f);
1427                     osg::Vec3 widthVec(2*width + 1, 0, 0);
1428                     osg::Vec3 heightVec(0, 1, 0);
1429                     osg::Geometry* geometry;
1430                     geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1431                     simgear::EffectGeode* geode = new simgear::EffectGeode;
1432                     geode->setName("test");
1433                     geode->addDrawable(geometry);
1434                     //osg::Node *custom_obj;
1435                     SGMaterial *mat = matlib->find("UnidirectionalTaper");
1436                     if (mat)
1437                         geode->setEffect(mat->get_effect());
1438                     obj_trans->addChild(geode);
1439                     // wire as much of the scene graph together as we can
1440                     //->addChild( obj_trans );
1441                     group->addChild( obj_trans );
1442                 } else {
1443                     //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1444                 }
1445             }
1446             //dx += 0.1;
1447         }
1448         globals->get_scenery()->get_scene_graph()->addChild(group);
1449     }
1450 }
1451
1452 string FGStartupController::getName() {
1453     return string(parent->getId() + "-startup");
1454 }
1455
1456
1457 /***************************************************************************
1458  * class FGApproachController
1459  *
1460  **************************************************************************/
1461 FGApproachController::FGApproachController(FGAirportDynamics *par):
1462 FGATCController()
1463 {
1464     parent = par;
1465 }
1466
1467 // 
1468 void FGApproachController::announcePosition(int id,
1469                                             FGAIFlightPlan * intendedRoute,
1470                                             int currentPosition,
1471                                             double lat, double lon,
1472                                             double heading, double speed,
1473                                             double alt, double radius,
1474                                             int leg, FGAIAircraft * ref)
1475 {
1476     init();
1477     TrafficVectorIterator i = activeTraffic.begin();
1478     // Search whether the current id alread has an entry
1479     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1480     if (activeTraffic.size()) {
1481         //while ((i->getId() != id) && i != activeTraffic.end()) {
1482         while (i != activeTraffic.end()) {
1483             if (i->getId() == id) {
1484                 break;
1485             }
1486             i++;
1487         }
1488     }
1489     // Add a new TrafficRecord if no one exsists for this aircraft.
1490     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1491         FGTrafficRecord rec;
1492         rec.setId(id);
1493
1494         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1495         rec.setRunway(intendedRoute->getRunway());
1496         rec.setLeg(leg);
1497         //rec.setCallSign(callsign);
1498         rec.setAircraft(ref);
1499         activeTraffic.push_back(rec);
1500     } else {
1501         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1502     }
1503 }
1504
1505 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1506                                                      double heading, double speed, double alt,
1507                                                      double dt)
1508 {
1509     TrafficVectorIterator i = activeTraffic.begin();
1510     // Search search if the current id has an entry
1511     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1512     TrafficVectorIterator current, closest;
1513     if (activeTraffic.size()) {
1514         //while ((i->getId() != id) && i != activeTraffic.end()) {
1515         while (i != activeTraffic.end()) {
1516             if (i->getId() == id) {
1517                 break;
1518             }
1519             i++;
1520         }
1521     }
1522 //    // update position of the current aircraft
1523     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1524         SG_LOG(SG_GENERAL, SG_ALERT,
1525                "AI error: updating aircraft without traffic record");
1526     } else {
1527         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1528         current = i;
1529         //cerr << "ApproachController: checking for speed" << endl;
1530         time_t time_diff =
1531             current->getAircraft()->
1532             checkForArrivalTime(string("final001"));
1533         if (time_diff > 15) {
1534             current->setSpeedAdjustment(current->getAircraft()->
1535                                         getPerformance()->vDescent() *
1536                                         1.35);
1537         } else if (time_diff > 5) {
1538             current->setSpeedAdjustment(current->getAircraft()->
1539                                         getPerformance()->vDescent() *
1540                                         1.2);
1541         } else if (time_diff < -15) {
1542             current->setSpeedAdjustment(current->getAircraft()->
1543                                         getPerformance()->vDescent() *
1544                                         0.65);
1545         } else if (time_diff < -5) {
1546             current->setSpeedAdjustment(current->getAircraft()->
1547                                         getPerformance()->vDescent() *
1548                                         0.8);
1549         } else {
1550             current->clearSpeedAdjustment();
1551         }
1552         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1553     }
1554     setDt(getDt() + dt);
1555 }
1556
1557 void FGApproachController::signOff(int id)
1558 {
1559     TrafficVectorIterator i = activeTraffic.begin();
1560     // Search search if the current id alread has an entry
1561     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1562     if (activeTraffic.size()) {
1563         //while ((i->getId() != id) && i != activeTraffic.end()) {
1564         while (i != activeTraffic.end()) {
1565             if (i->getId() == id) {
1566                 break;
1567             }
1568             i++;
1569         }
1570     }
1571     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1572         SG_LOG(SG_GENERAL, SG_ALERT,
1573                "AI error: Aircraft without traffic record is signing off from approach");
1574     } else {
1575         i = activeTraffic.erase(i);
1576     }
1577 }
1578
1579
1580
1581
1582 bool FGApproachController::hasInstruction(int id)
1583 {
1584     TrafficVectorIterator i = activeTraffic.begin();
1585     // Search search if the current id has an entry
1586     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1587     if (activeTraffic.size()) {
1588         //while ((i->getId() != id) && i != activeTraffic.end()) {
1589         while (i != activeTraffic.end()) {
1590             if (i->getId() == id) {
1591                 break;
1592             }
1593             i++;
1594         }
1595     }
1596     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1597         SG_LOG(SG_GENERAL, SG_ALERT,
1598                "AI error: checking ATC instruction for aircraft without traffic record");
1599     } else {
1600         return i->hasInstruction();
1601     }
1602     return false;
1603 }
1604
1605
1606 FGATCInstruction FGApproachController::getInstruction(int id)
1607 {
1608     TrafficVectorIterator i = activeTraffic.begin();
1609     // Search search if the current id has an entry
1610     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1611     if (activeTraffic.size()) {
1612         //while ((i->getId() != id) && i != activeTraffic.end()) {
1613         while (i != activeTraffic.end()) {
1614             if (i->getId() == id) {
1615                 break;
1616             }
1617             i++;
1618         }
1619     }
1620     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1621         SG_LOG(SG_GENERAL, SG_ALERT,
1622                "AI error: requesting ATC instruction for aircraft without traffic record");
1623     } else {
1624         return i->getInstruction();
1625     }
1626     return FGATCInstruction();
1627 }
1628
1629
1630 ActiveRunway *FGApproachController::getRunway(string name)
1631 {
1632     ActiveRunwayVecIterator rwy = activeRunways.begin();
1633     if (activeRunways.size()) {
1634         while (rwy != activeRunways.end()) {
1635             if (rwy->getRunwayName() == name) {
1636                 break;
1637             }
1638             rwy++;
1639         }
1640     }
1641     if (rwy == activeRunways.end()) {
1642         ActiveRunway aRwy(name, 0);
1643         activeRunways.push_back(aRwy);
1644         rwy = activeRunways.end() - 1;
1645     }
1646     return &(*rwy);
1647 }
1648
1649 void FGApproachController::render(bool visible) {
1650     //cerr << "FGApproachController::render function not yet implemented" << endl;
1651 }
1652
1653
1654
1655 string FGApproachController::getName() {
1656     return string(parent->getId() + "-approach");
1657 }