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