]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Some fine tuning of the ATC messages related to ground to tower transfer.
[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, 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
521     //double commFreqD;
522     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
523     if (rec->getAircraft()->getTaxiClearanceRequest()) {
524         instructionText = "push-back and taxi";
525     } else {
526         instructionText = "taxi";
527     }
528     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
529     switch (rec->getLeg()) {
530     case 1:
531     case 2:
532         freqId = rec->getNextFrequency();
533         stationFreq =
534             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
535             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
536         taxiFreq =
537             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
538             getDynamics()->getGroundFrequency(2);
539         towerFreq = 
540             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
541             getDynamics()->getTowerFrequency(2);
542         receiver =
543             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
544             getName() + "-Ground";
545         atisInformation =
546             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
547             getDynamics()->getAtisSequence();
548         break;
549     case 3:
550         receiver =
551             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
552             getName() + "-Tower";
553         break;
554     }
555     // Swap sender and receiver value in case of a ground to air transmission
556     if (msgDir == ATC_GROUND_TO_AIR) {
557         string tmp = sender;
558         sender = receiver;
559         receiver = tmp;
560     }
561     switch (msgId) {
562     case MSG_ANNOUNCE_ENGINE_START:
563         text = sender + ". Ready to Start up";
564         break;
565     case MSG_REQUEST_ENGINE_START:
566         text =
567             receiver + ", This is " + sender + ". Position " +
568             getGateName(rec->getAircraft()) + ". Information " +
569             atisInformation + ". " +
570             rec->getAircraft()->getTrafficRef()->getFlightRules() +
571             " to " +
572             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
573             getName() + ". Request start-up";
574         break;
575         // Acknowledge engine startup permission
576         // Assign departure runway
577         // Assign SID, if necessery (TODO)
578     case MSG_PERMIT_ENGINE_START:
579         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
580
581         heading = rec->getAircraft()->getTrafficRef()->getCourse();
582         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
583         rwyClass =
584             rec->getAircraft()->GetFlightPlan()->
585             getRunwayClassFromTrafficType(fltType);
586
587         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
588             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
589                                            heading);
590         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
591         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
592             getDynamics()->getSID(activeRunway, heading);
593         rec->getAircraft()->GetFlightPlan()->setSID(fp);
594         if (fp) {
595             SID = fp->getName() + " departure";
596         } else {
597             SID = "fly runway heading ";
598         }
599         //snprintf(buffer, 7, "%3.2f", heading);
600         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
601         transponderCode = genTransponderCode(fltRules);
602         rec->getAircraft()->SetTransponderCode(transponderCode);
603         text =
604             receiver + ". Start-up approved. " + atisInformation +
605             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
606             transponderCode + ". " +
607             "For "+ instructionText + " clearance call " + taxiFreqStr + ". " +
608             sender + " control.";
609         break;
610     case MSG_DENY_ENGINE_START:
611         text = receiver + ". Standby";
612         break;
613     case MSG_ACKNOWLEDGE_ENGINE_START:
614         fp = rec->getAircraft()->GetFlightPlan()->getSID();
615         if (fp) {
616             SID =
617                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
618                 " departure";
619         } else {
620             SID = "fly runway heading ";
621         }
622         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
623         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
624         transponderCode = rec->getAircraft()->GetTransponderCode();
625
626         text =
627             receiver + ". Start-up approved. " + atisInformation +
628             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
629             transponderCode + ". " +
630             "For " + instructionText + " clearance call " + taxiFreqStr + ". " +
631             sender;
632         break;
633     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
634         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
635         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
636         break;
637     case MSG_INITIATE_CONTACT:
638         text = receiver + ". With you. " + sender;
639         break;
640     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
641         text = receiver + ". Roger. " + sender;
642         break;
643     case MSG_REQUEST_PUSHBACK_CLEARANCE:
644         if (rec->getAircraft()->getTaxiClearanceRequest()) {
645             text = receiver + ". Request push-back. " + sender;
646         } else {
647             text = receiver + ". Request Taxi clearance. " + sender;
648         }
649         break;
650     case MSG_PERMIT_PUSHBACK_CLEARANCE:
651         if (rec->getAircraft()->getTaxiClearanceRequest()) {
652             text = receiver + ". Push-back approved. " + sender;
653         } else {
654             text = receiver + ". Cleared to Taxi." + sender;
655         }
656         break;
657     case MSG_HOLD_PUSHBACK_CLEARANCE:
658         text = receiver + ". Standby. " + sender;
659         break;
660     case MSG_REQUEST_TAXI_CLEARANCE:
661         text = receiver + ". Ready to Taxi. " + sender;
662         break;
663     case MSG_ISSUE_TAXI_CLEARANCE:
664         text = receiver + ". Cleared to taxi. " + sender;
665         break;
666     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
667         text = receiver + ". Cleared to taxi. " + sender;
668         break;
669     case MSG_HOLD_POSITION:
670         text = receiver + ". Hold Position. " + sender;
671         break;
672     case MSG_ACKNOWLEDGE_HOLD_POSITION:
673         text = receiver + ". Holding Position. " + sender;
674         break;
675     case MSG_RESUME_TAXI:
676         text = receiver + ". Resume Taxiing. " + sender;
677         break;
678     case MSG_ACKNOWLEDGE_RESUME_TAXI:
679         text = receiver + ". Continuing Taxi. " + sender;
680         break;
681     case MSG_REPORT_RUNWAY_HOLD_SHORT:
682         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
683         //activeRunway = "test";
684         text = receiver + ". Holding short runway " 
685                         + activeRunway 
686                         + ". " + sender;
687         //text = "test1";
688         //cerr << "1 Currently at leg " << rec->getLeg() << endl;
689         break;
690     case MSG_ACKNOWLEDGE_REPORT_RUNWAY_HOLD_SHORT:
691         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
692         text = receiver + "Roger. Holding short runway " 
693         //                + activeRunway 
694                         + ". " + sender;
695         //text = "test2";
696         //cerr << "2 Currently at leg " << rec->getLeg() << endl;
697         break;
698     case MSG_SWITCH_TOWER_FREQUENCY:
699         towerFreqStr = formatATCFrequency3_2(towerFreq);
700         text = receiver + "Contact Tower at " + towerFreqStr + ". " + sender;
701         //text = "test3";
702         //cerr << "3 Currently at leg " << rec->getLeg() << endl;
703         break;
704     case MSG_ACKNOWLEDGE_SWITCH_TOWER_FREQUENCY:
705         towerFreqStr = formatATCFrequency3_2(towerFreq);
706         text = receiver + "Roger, switching to tower at " + towerFreqStr + ". " + sender;
707         //text = "test4";
708         //cerr << "4 Currently at leg " << rec->getLeg() << endl;
709         break;
710     default:
711         //text = "test3";
712         text = text + sender + ". Transmitting unknown Message";
713         break;
714     }
715     if (audible) {
716         double onBoardRadioFreq0 =
717             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
718         double onBoardRadioFreq1 =
719             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
720         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
721         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
722         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
723
724         // Display ATC message only when one of the radios is tuned
725         // the relevant frequency.
726         // Note that distance attenuation is currently not yet implemented
727         if ((onBoardRadioFreqI0 == stationFreq)
728             || (onBoardRadioFreqI1 == stationFreq)) {
729             if (rec->allowTransmissions()) {
730                 fgSetString("/sim/messages/atc", text.c_str());
731             }
732         }
733     } else {
734         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
735         atc->getATCDialog()->addEntry(1, text);
736         
737     }
738 }
739
740 string FGATCController::formatATCFrequency3_2(int freq)
741 {
742     char buffer[7];
743     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
744     return string(buffer);
745 }
746
747 // TODO: Set transponder codes according to real-world routes.
748 // The current version just returns a random string of four octal numbers. 
749 string FGATCController::genTransponderCode(string fltRules)
750 {
751     if (fltRules == "VFR") {
752         return string("1200");
753     } else {
754         char buffer[5];
755         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
756                  rand() % 8);
757         return string(buffer);
758     }
759 }
760
761 void FGATCController::init() 
762 {
763    if (!initialized) {
764        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
765        mgr->addController(this);
766        initialized = true;
767     }
768 }
769
770 /***************************************************************************
771  * class FGTowerController
772  *
773  **************************************************************************/
774 FGTowerController::FGTowerController(FGAirportDynamics *par) :
775 FGATCController()
776 {
777     parent = par;
778 }
779
780 // 
781 void FGTowerController::announcePosition(int id,
782                                          FGAIFlightPlan * intendedRoute,
783                                          int currentPosition, double lat,
784                                          double lon, double heading,
785                                          double speed, double alt,
786                                          double radius, int leg,
787                                          FGAIAircraft * ref)
788 {
789     init();
790     TrafficVectorIterator i = activeTraffic.begin();
791     // Search whether the current id alread has an entry
792     // This might be faster using a map instead of a vector, but let's start by taking a safe route
793     if (activeTraffic.size()) {
794         //while ((i->getId() != id) && i != activeTraffic.end()) {
795         while (i != activeTraffic.end()) {
796             if (i->getId() == id) {
797                 break;
798             }
799             i++;
800         }
801     }
802     // Add a new TrafficRecord if no one exsists for this aircraft.
803     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
804         FGTrafficRecord rec;
805         rec.setId(id);
806
807         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
808         rec.setRunway(intendedRoute->getRunway());
809         rec.setLeg(leg);
810         //rec.setCallSign(callsign);
811         rec.setRadius(radius);
812         rec.setAircraft(ref);
813         activeTraffic.push_back(rec);
814         // Don't just schedule the aircraft for the tower controller, also assign if to the correct active runway. 
815         ActiveRunwayVecIterator rwy = activeRunways.begin();
816         if (activeRunways.size()) {
817             while (rwy != activeRunways.end()) {
818                 if (rwy->getRunwayName() == intendedRoute->getRunway()) {
819                     break;
820                 }
821                 rwy++;
822             }
823         }
824         if (rwy == activeRunways.end()) {
825             ActiveRunway aRwy(intendedRoute->getRunway(), id);
826             aRwy.addToDepartureCue(ref);
827             activeRunways.push_back(aRwy);
828             rwy = (activeRunways.end()-1);
829         } else {
830             rwy->addToDepartureCue(ref);
831         }
832
833         //cerr << ref->getTrafficRef()->getCallSign() << " You are number " << rwy->getDepartureCueSize() <<  " for takeoff " << endl;
834     } else {
835         i->setPositionAndHeading(lat, lon, heading, speed, alt);
836     }
837 }
838
839 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
840                                                   double heading, double speed, double alt,
841                                                   double dt)
842 {
843     TrafficVectorIterator i = activeTraffic.begin();
844     // Search whether the current id has an entry
845     // This might be faster using a map instead of a vector, but let's start by taking a safe route
846     TrafficVectorIterator current, closest;
847     if (activeTraffic.size()) {
848         //while ((i->getId() != id) && i != activeTraffic.end()) {
849         while (i != activeTraffic.end()) {
850             if (i->getId() == id) {
851                 break;
852             }
853             i++;
854         }
855     }
856 //    // update position of the current aircraft
857     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
858         SG_LOG(SG_GENERAL, SG_ALERT,
859                "AI error: updating aircraft without traffic record");
860     } else {
861         i->setPositionAndHeading(lat, lon, heading, speed, alt);
862         current = i;
863     }
864     setDt(getDt() + dt);
865
866     // see if we already have a clearance record for the currently active runway
867     // NOTE: dd. 2011-08-07: Because the active runway has been constructed in the announcePosition function, we may safely assume that is
868     // already exists here. So, we can simplify the current code. 
869     ActiveRunwayVecIterator rwy = activeRunways.begin();
870     while (rwy != activeRunways.end()) {
871         if (rwy->getRunwayName() == current->getRunway()) {
872             break;
873         }
874         rwy++;
875     }
876
877     // only bother running the following code if the current aircraft is the
878     // first in line for depature
879     /* if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
880         if (rwy->getCleared()) {
881             if (id == rwy->getCleared()) {
882                 current->setHoldPosition(false);
883             } else {
884                 current->setHoldPosition(true);
885             }
886         } else {
887             // For now. At later stages, this will probably be the place to check for inbound traffc.
888             rwy->setCleared(id);
889         }
890     } */
891     // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
892     if (current->getAircraft()->getTakeOffStatus() == 2) {
893         current->setHoldPosition(true);
894         int clearanceId = rwy->getCleared();
895         if (clearanceId) {
896             if (id == clearanceId) {
897                 current->setHoldPosition(false);
898             }
899         } else {
900             if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
901                 rwy->setCleared(id);
902             }
903         }
904     }
905 }
906
907
908 void FGTowerController::signOff(int id)
909 {
910     TrafficVectorIterator i = activeTraffic.begin();
911     // Search search if the current id alread has an entry
912     // This might be faster using a map instead of a vector, but let's start by taking a safe route
913     if (activeTraffic.size()) {
914         //while ((i->getId() != id) && i != activeTraffic.end()) {
915         while (i != activeTraffic.end()) {
916             if (i->getId() == id) {
917                 break;
918             }
919             i++;
920         }
921     }
922     // If this aircraft has left the runway, we can clear the departure record for this runway
923     ActiveRunwayVecIterator rwy = activeRunways.begin();
924     if (activeRunways.size()) {
925         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
926         while (rwy != activeRunways.end()) {
927             if (rwy->getRunwayName() == i->getRunway()) {
928                 break;
929             }
930             rwy++;
931         }
932         if (rwy != activeRunways.end()) {
933             rwy->setCleared(0);
934             rwy->updateDepartureCue();
935         } else {
936             SG_LOG(SG_GENERAL, SG_ALERT,
937                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
938         }
939     }
940     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
941         SG_LOG(SG_GENERAL, SG_ALERT,
942                "AI error: Aircraft without traffic record is signing off from tower");
943     } else {
944         i->getAircraft()->resetTakeOffStatus();
945         i = activeTraffic.erase(i);
946         //cerr << "Signing off from tower controller" << endl;
947     }
948 }
949
950 // NOTE:
951 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
952 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
953 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
954 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
955 // Note that this function is probably obsolete
956 bool FGTowerController::hasInstruction(int id)
957 {
958     TrafficVectorIterator i = activeTraffic.begin();
959     // Search search if the current id has an entry
960     // This might be faster using a map instead of a vector, but let's start by taking a safe route
961     if (activeTraffic.size()) {
962         //while ((i->getId() != id) && i != activeTraffic.end()) {
963         while (i != activeTraffic.end()) {
964             if (i->getId() == id) {
965                 break;
966             }
967             i++;
968         }
969     }
970     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
971         SG_LOG(SG_GENERAL, SG_ALERT,
972                "AI error: checking ATC instruction for aircraft without traffic record");
973     } else {
974         return i->hasInstruction();
975     }
976     return false;
977 }
978
979
980 FGATCInstruction FGTowerController::getInstruction(int id)
981 {
982     TrafficVectorIterator i = activeTraffic.begin();
983     // Search search if the current id has an entry
984     // This might be faster using a map instead of a vector, but let's start by taking a safe route
985     if (activeTraffic.size()) {
986         //while ((i->getId() != id) && i != activeTraffic.end()) {
987         while (i != activeTraffic.end()) {
988             if (i->getId() == id) {
989                 break;
990             }
991             i++;
992         }
993     }
994     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
995         SG_LOG(SG_GENERAL, SG_ALERT,
996                "AI error: requesting ATC instruction for aircraft without traffic record");
997     } else {
998         return i->getInstruction();
999     }
1000     return FGATCInstruction();
1001 }
1002
1003 void FGTowerController::render(bool visible) {
1004     //cerr << "FGTowerController::render function not yet implemented" << endl;
1005 }
1006
1007 string FGTowerController::getName() {
1008     return string(parent->getId() + "-tower");
1009 }
1010
1011
1012
1013 /***************************************************************************
1014  * class FGStartupController
1015  *
1016  **************************************************************************/
1017 FGStartupController::FGStartupController(FGAirportDynamics *par):
1018     FGATCController()
1019 {
1020     parent = par;
1021 }
1022
1023 void FGStartupController::announcePosition(int id,
1024                                            FGAIFlightPlan * intendedRoute,
1025                                            int currentPosition, double lat,
1026                                            double lon, double heading,
1027                                            double speed, double alt,
1028                                            double radius, int leg,
1029                                            FGAIAircraft * ref)
1030 {
1031     init();
1032     TrafficVectorIterator i = activeTraffic.begin();
1033     // Search whether the current id alread has an entry
1034     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1035     if (activeTraffic.size()) {
1036         //while ((i->getId() != id) && i != activeTraffic.end()) {
1037         while (i != activeTraffic.end()) {
1038             if (i->getId() == id) {
1039                 break;
1040             }
1041             i++;
1042         }
1043     }
1044     // Add a new TrafficRecord if no one exsists for this aircraft.
1045     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1046         FGTrafficRecord rec;
1047         rec.setId(id);
1048
1049         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1050         rec.setRunway(intendedRoute->getRunway());
1051         rec.setLeg(leg);
1052         rec.setPositionAndIntentions(currentPosition, intendedRoute);
1053         //rec.setCallSign(callsign);
1054         rec.setAircraft(ref);
1055         rec.setHoldPosition(true);
1056         activeTraffic.push_back(rec);
1057     } else {
1058         i->setPositionAndIntentions(currentPosition, intendedRoute);
1059         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1060
1061     }
1062 }
1063
1064 // NOTE:
1065 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
1066 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
1067 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
1068 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
1069 // Note that this function is probably obsolete
1070 bool FGStartupController::hasInstruction(int id)
1071 {
1072     TrafficVectorIterator i = activeTraffic.begin();
1073     // Search search if the current id has an entry
1074     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1075     if (activeTraffic.size()) {
1076         //while ((i->getId() != id) && i != activeTraffic.end()) {
1077         while (i != activeTraffic.end()) {
1078             if (i->getId() == id) {
1079                 break;
1080             }
1081             i++;
1082         }
1083     }
1084     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1085         SG_LOG(SG_GENERAL, SG_ALERT,
1086                "AI error: checking ATC instruction for aircraft without traffic record");
1087     } else {
1088         return i->hasInstruction();
1089     }
1090     return false;
1091 }
1092
1093
1094 FGATCInstruction FGStartupController::getInstruction(int id)
1095 {
1096     TrafficVectorIterator i = activeTraffic.begin();
1097     // Search search if the current id has an entry
1098     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1099     if (activeTraffic.size()) {
1100         //while ((i->getId() != id) && i != activeTraffic.end()) {
1101         while (i != activeTraffic.end()) {
1102             if (i->getId() == id) {
1103                 break;
1104             }
1105             i++;
1106         }
1107     }
1108     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1109         SG_LOG(SG_GENERAL, SG_ALERT,
1110                "AI error: requesting ATC instruction for aircraft without traffic record");
1111     } else {
1112         return i->getInstruction();
1113     }
1114     return FGATCInstruction();
1115 }
1116
1117 void FGStartupController::signOff(int id)
1118 {
1119     TrafficVectorIterator i = activeTraffic.begin();
1120     // Search search if the current id alread has an entry
1121     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1122     if (activeTraffic.size()) {
1123         //while ((i->getId() != id) && i != activeTraffic.end()) {
1124         while (i != activeTraffic.end()) {
1125             if (i->getId() == id) {
1126                 break;
1127             }
1128             i++;
1129         }
1130     }
1131     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1132         SG_LOG(SG_GENERAL, SG_ALERT,
1133                "AI error: Aircraft without traffic record is signing off from tower");
1134     } else {
1135         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1136         i = activeTraffic.erase(i);
1137     }
1138 }
1139
1140 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1141                                AtcMsgDir msgDir)
1142 {
1143     int state = i->getState();
1144     if ((state == st) && available) {
1145         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1146             
1147             //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1148             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1149             int n = trans_num->getIntValue();
1150             if (n == 0) {
1151                 trans_num->setIntValue(-1);
1152                  // PopupCallback(n);
1153                  //cerr << "Selected transmission message " << n << endl;
1154                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1155                  atc->getATCDialog()->removeEntry(1);
1156             } else {
1157                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1158                 transmit(&(*i), msgId, msgDir, false);
1159                 return false;
1160             }
1161         }
1162         if (now > startTime) {
1163             //cerr << "Transmitting startup msg" << endl;
1164             transmit(&(*i), msgId, msgDir, true);
1165             i->updateState();
1166             lastTransmission = now;
1167             available = false;
1168             return true;
1169         }
1170     }
1171     return false;
1172 }
1173
1174 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1175                                                     double heading, double speed, double alt,
1176                                                     double dt)
1177 {
1178     TrafficVectorIterator i = activeTraffic.begin();
1179     // Search search if the current id has an entry
1180     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1181     TrafficVectorIterator current, closest;
1182     if (activeTraffic.size()) {
1183         //while ((i->getId() != id) && i != activeTraffic.end()) {
1184         while (i != activeTraffic.end()) {
1185             if (i->getId() == id) {
1186                 break;
1187             }
1188             i++;
1189         }
1190     }
1191 //    // update position of the current aircraft
1192
1193     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1194         SG_LOG(SG_GENERAL, SG_ALERT,
1195                "AI error: updating aircraft without traffic record");
1196     } else {
1197         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1198         current = i;
1199     }
1200     setDt(getDt() + dt);
1201
1202     int state = i->getState();
1203
1204     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1205     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1206     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1207     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1208     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1209     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1210     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1211
1212     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1213         available = true;
1214     }
1215
1216     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1217     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1218     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1219     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1220     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1221         i->nextFrequency();
1222     }
1223     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1224     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1225     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1226
1227
1228    
1229     if ((state == 8) && available) {
1230         if (now > startTime + 200) {
1231             if (i->pushBackAllowed()) {
1232                 i->allowRepeatedTransmissions();
1233                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1234                          ATC_GROUND_TO_AIR, true);
1235                 i->updateState();
1236             } else {
1237                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1238                          ATC_GROUND_TO_AIR, true);
1239                 i->suppressRepeatedTransmissions();
1240             }
1241             lastTransmission = now;
1242             available = false;
1243         }
1244     }
1245     if ((state == 9) && available) {
1246         i->setHoldPosition(false);
1247     }
1248 }
1249
1250 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1251 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1252                             double lon, double elev, double hdg)
1253 {
1254     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1255     obj_pos = geod.makeZUpFrame();
1256     // hdg is not a compass heading, but a counter-clockwise rotation
1257     // around the Z axis
1258     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1259                                         0.0, 0.0, 1.0));
1260 }
1261
1262
1263 void FGStartupController::render(bool visible)
1264 {
1265
1266     SGMaterialLib *matlib = globals->get_matlib();
1267     if (group) {
1268         //int nr = ;
1269         globals->get_scenery()->get_scene_graph()->removeChild(group);
1270         //while (group->getNumChildren()) {
1271         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1272         simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1273           //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1274            //geode->releaseGLObjects();
1275            //group->removeChild(geode);
1276            //delete geode;
1277         group = 0;
1278     }
1279     if (visible) {
1280         group = new osg::Group;
1281
1282         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1283         double dx = 0;
1284         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1285             // Handle start point
1286             int pos = i->getCurrentPosition();
1287             //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1288             if (pos > 0) {
1289                 FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1290                 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1291                 SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1292
1293                 double length = SGGeodesy::distanceM(start, end);
1294                 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1295
1296                 double az2, heading; //, distanceM;
1297                 SGGeodesy::inverse(start, end, heading, az2, length);
1298                 double coveredDistance = length * 0.5;
1299                 SGGeod center;
1300                 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1301                 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1302                 ///////////////////////////////////////////////////////////////////////////////
1303                 // Make a helper function out of this
1304                 osg::Matrix obj_pos;
1305                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1306                 obj_trans->setDataVariance(osg::Object::STATIC);
1307
1308                 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1309
1310                 obj_trans->setMatrix( obj_pos );
1311                 //osg::Vec3 center(0, 0, 0)
1312
1313                 float width = length /2.0;
1314                 osg::Vec3 corner(-width, 0, 0.25f);
1315                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1316                 osg::Vec3 heightVec(0, 1, 0);
1317                 osg::Geometry* geometry;
1318                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1319                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1320                 geode->setName("test");
1321                 geode->addDrawable(geometry);
1322                 //osg::Node *custom_obj;
1323                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1324                 if (mat)
1325                     geode->setEffect(mat->get_effect());
1326                 obj_trans->addChild(geode);
1327                 // wire as much of the scene graph together as we can
1328                 //->addChild( obj_trans );
1329                 group->addChild( obj_trans );
1330                 /////////////////////////////////////////////////////////////////////
1331             } else {
1332                 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1333             }
1334             for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1335                 osg::Matrix obj_pos;
1336                 int k = (*j);
1337                 if (k > 0) {
1338                     //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1339                     osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1340                     obj_trans->setDataVariance(osg::Object::STATIC);
1341                     FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1342                     WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1343
1344                     obj_trans->setMatrix( obj_pos );
1345                     //osg::Vec3 center(0, 0, 0)
1346
1347                     float width = segment->getLength() /2.0;
1348                     osg::Vec3 corner(-width, 0, 0.25f);
1349                     osg::Vec3 widthVec(2*width + 1, 0, 0);
1350                     osg::Vec3 heightVec(0, 1, 0);
1351                     osg::Geometry* geometry;
1352                     geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1353                     simgear::EffectGeode* geode = new simgear::EffectGeode;
1354                     geode->setName("test");
1355                     geode->addDrawable(geometry);
1356                     //osg::Node *custom_obj;
1357                     SGMaterial *mat = matlib->find("UnidirectionalTaper");
1358                     if (mat)
1359                         geode->setEffect(mat->get_effect());
1360                     obj_trans->addChild(geode);
1361                     // wire as much of the scene graph together as we can
1362                     //->addChild( obj_trans );
1363                     group->addChild( obj_trans );
1364                 } else {
1365                     //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1366                 }
1367             }
1368             //dx += 0.1;
1369         }
1370         globals->get_scenery()->get_scene_graph()->addChild(group);
1371     }
1372 }
1373
1374 string FGStartupController::getName() {
1375     return string(parent->getId() + "-startup");
1376 }
1377
1378
1379 /***************************************************************************
1380  * class FGApproachController
1381  *
1382  **************************************************************************/
1383 FGApproachController::FGApproachController(FGAirportDynamics *par):
1384 FGATCController()
1385 {
1386     parent = par;
1387 }
1388
1389 // 
1390 void FGApproachController::announcePosition(int id,
1391                                             FGAIFlightPlan * intendedRoute,
1392                                             int currentPosition,
1393                                             double lat, double lon,
1394                                             double heading, double speed,
1395                                             double alt, double radius,
1396                                             int leg, FGAIAircraft * ref)
1397 {
1398     init();
1399     TrafficVectorIterator i = activeTraffic.begin();
1400     // Search whether the current id alread has an entry
1401     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1402     if (activeTraffic.size()) {
1403         //while ((i->getId() != id) && i != activeTraffic.end()) {
1404         while (i != activeTraffic.end()) {
1405             if (i->getId() == id) {
1406                 break;
1407             }
1408             i++;
1409         }
1410     }
1411     // Add a new TrafficRecord if no one exsists for this aircraft.
1412     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1413         FGTrafficRecord rec;
1414         rec.setId(id);
1415
1416         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1417         rec.setRunway(intendedRoute->getRunway());
1418         rec.setLeg(leg);
1419         //rec.setCallSign(callsign);
1420         rec.setAircraft(ref);
1421         activeTraffic.push_back(rec);
1422     } else {
1423         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1424     }
1425 }
1426
1427 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1428                                                      double heading, double speed, double alt,
1429                                                      double dt)
1430 {
1431     TrafficVectorIterator i = activeTraffic.begin();
1432     // Search search if the current id has an entry
1433     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1434     TrafficVectorIterator current, closest;
1435     if (activeTraffic.size()) {
1436         //while ((i->getId() != id) && i != activeTraffic.end()) {
1437         while (i != activeTraffic.end()) {
1438             if (i->getId() == id) {
1439                 break;
1440             }
1441             i++;
1442         }
1443     }
1444 //    // update position of the current aircraft
1445     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1446         SG_LOG(SG_GENERAL, SG_ALERT,
1447                "AI error: updating aircraft without traffic record");
1448     } else {
1449         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1450         current = i;
1451         //cerr << "ApproachController: checking for speed" << endl;
1452         time_t time_diff =
1453             current->getAircraft()->
1454             checkForArrivalTime(string("final001"));
1455         if (time_diff > 15) {
1456             current->setSpeedAdjustment(current->getAircraft()->
1457                                         getPerformance()->vDescent() *
1458                                         1.35);
1459         } else if (time_diff > 5) {
1460             current->setSpeedAdjustment(current->getAircraft()->
1461                                         getPerformance()->vDescent() *
1462                                         1.2);
1463         } else if (time_diff < -15) {
1464             current->setSpeedAdjustment(current->getAircraft()->
1465                                         getPerformance()->vDescent() *
1466                                         0.65);
1467         } else if (time_diff < -5) {
1468             current->setSpeedAdjustment(current->getAircraft()->
1469                                         getPerformance()->vDescent() *
1470                                         0.8);
1471         } else {
1472             current->clearSpeedAdjustment();
1473         }
1474         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1475     }
1476     setDt(getDt() + dt);
1477 }
1478
1479 void FGApproachController::signOff(int id)
1480 {
1481     TrafficVectorIterator i = activeTraffic.begin();
1482     // Search search if the current id alread has an entry
1483     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1484     if (activeTraffic.size()) {
1485         //while ((i->getId() != id) && i != activeTraffic.end()) {
1486         while (i != activeTraffic.end()) {
1487             if (i->getId() == id) {
1488                 break;
1489             }
1490             i++;
1491         }
1492     }
1493     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1494         SG_LOG(SG_GENERAL, SG_ALERT,
1495                "AI error: Aircraft without traffic record is signing off from approach");
1496     } else {
1497         i = activeTraffic.erase(i);
1498     }
1499 }
1500
1501
1502
1503
1504 bool FGApproachController::hasInstruction(int id)
1505 {
1506     TrafficVectorIterator i = activeTraffic.begin();
1507     // Search search if the current id has an entry
1508     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1509     if (activeTraffic.size()) {
1510         //while ((i->getId() != id) && i != activeTraffic.end()) {
1511         while (i != activeTraffic.end()) {
1512             if (i->getId() == id) {
1513                 break;
1514             }
1515             i++;
1516         }
1517     }
1518     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1519         SG_LOG(SG_GENERAL, SG_ALERT,
1520                "AI error: checking ATC instruction for aircraft without traffic record");
1521     } else {
1522         return i->hasInstruction();
1523     }
1524     return false;
1525 }
1526
1527
1528 FGATCInstruction FGApproachController::getInstruction(int id)
1529 {
1530     TrafficVectorIterator i = activeTraffic.begin();
1531     // Search search if the current id has an entry
1532     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1533     if (activeTraffic.size()) {
1534         //while ((i->getId() != id) && i != activeTraffic.end()) {
1535         while (i != activeTraffic.end()) {
1536             if (i->getId() == id) {
1537                 break;
1538             }
1539             i++;
1540         }
1541     }
1542     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1543         SG_LOG(SG_GENERAL, SG_ALERT,
1544                "AI error: requesting ATC instruction for aircraft without traffic record");
1545     } else {
1546         return i->getInstruction();
1547     }
1548     return FGATCInstruction();
1549 }
1550
1551
1552 ActiveRunway *FGApproachController::getRunway(string name)
1553 {
1554     ActiveRunwayVecIterator rwy = activeRunways.begin();
1555     if (activeRunways.size()) {
1556         while (rwy != activeRunways.end()) {
1557             if (rwy->getRunwayName() == name) {
1558                 break;
1559             }
1560             rwy++;
1561         }
1562     }
1563     if (rwy == activeRunways.end()) {
1564         ActiveRunway aRwy(name, 0);
1565         activeRunways.push_back(aRwy);
1566         rwy = activeRunways.end() - 1;
1567     }
1568     return &(*rwy);
1569 }
1570
1571 void FGApproachController::render(bool visible) {
1572     //cerr << "FGApproachController::render function not yet implemented" << endl;
1573 }
1574
1575
1576
1577 string FGApproachController::getName() {
1578     return string(parent->getId() + "-approach");
1579 }