]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Patch by Torsten Dryer: Remove the Ugly global dialog variable and remove rwy as...
[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         FGATCDialogNew::instance()->addEntry(1, text);
735     }
736 }
737
738 string FGATCController::formatATCFrequency3_2(int freq)
739 {
740     char buffer[7];
741     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
742     return string(buffer);
743 }
744
745 // TODO: Set transponder codes according to real-world routes.
746 // The current version just returns a random string of four octal numbers. 
747 string FGATCController::genTransponderCode(string fltRules)
748 {
749     if (fltRules == "VFR") {
750         return string("1200");
751     } else {
752         char buffer[5];
753         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
754                  rand() % 8);
755         return string(buffer);
756     }
757 }
758
759 void FGATCController::init() 
760 {
761    if (!initialized) {
762        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
763        mgr->addController(this);
764        initialized = true;
765     }
766 }
767
768 /***************************************************************************
769  * class FGTowerController
770  *
771  **************************************************************************/
772 FGTowerController::FGTowerController(FGAirportDynamics *par) :
773 FGATCController()
774 {
775     parent = par;
776 }
777
778 // 
779 void FGTowerController::announcePosition(int id,
780                                          FGAIFlightPlan * intendedRoute,
781                                          int currentPosition, double lat,
782                                          double lon, double heading,
783                                          double speed, double alt,
784                                          double radius, int leg,
785                                          FGAIAircraft * ref)
786 {
787     init();
788     TrafficVectorIterator i = activeTraffic.begin();
789     // Search whether the current id alread has an entry
790     // This might be faster using a map instead of a vector, but let's start by taking a safe route
791     if (activeTraffic.size()) {
792         //while ((i->getId() != id) && i != activeTraffic.end()) {
793         while (i != activeTraffic.end()) {
794             if (i->getId() == id) {
795                 break;
796             }
797             i++;
798         }
799     }
800     // Add a new TrafficRecord if no one exsists for this aircraft.
801     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
802         FGTrafficRecord rec;
803         rec.setId(id);
804
805         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
806         rec.setRunway(intendedRoute->getRunway());
807         rec.setLeg(leg);
808         //rec.setCallSign(callsign);
809         rec.setRadius(radius);
810         rec.setAircraft(ref);
811         activeTraffic.push_back(rec);
812         // Don't just schedule the aircraft for the tower controller, also assign if to the correct active runway. 
813         ActiveRunwayVecIterator rwy = activeRunways.begin();
814         if (activeRunways.size()) {
815             while (rwy != activeRunways.end()) {
816                 if (rwy->getRunwayName() == intendedRoute->getRunway()) {
817                     break;
818                 }
819                 rwy++;
820             }
821         }
822         if (rwy == activeRunways.end()) {
823             ActiveRunway aRwy(intendedRoute->getRunway(), id);
824             aRwy.addToDepartureCue(ref);
825             activeRunways.push_back(aRwy);
826             rwy = (activeRunways.end()-1);
827         } else {
828             rwy->addToDepartureCue(ref);
829         }
830
831         //cerr << ref->getTrafficRef()->getCallSign() << " You are number " << rwy->getDepartureCueSize() <<  " for takeoff " << endl;
832     } else {
833         i->setPositionAndHeading(lat, lon, heading, speed, alt);
834     }
835 }
836
837 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
838                                                   double heading, double speed, double alt,
839                                                   double dt)
840 {
841     TrafficVectorIterator i = activeTraffic.begin();
842     // Search whether the current id has an entry
843     // This might be faster using a map instead of a vector, but let's start by taking a safe route
844     TrafficVectorIterator current, closest;
845     if (activeTraffic.size()) {
846         //while ((i->getId() != id) && i != activeTraffic.end()) {
847         while (i != activeTraffic.end()) {
848             if (i->getId() == id) {
849                 break;
850             }
851             i++;
852         }
853     }
854 //    // update position of the current aircraft
855     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
856         SG_LOG(SG_GENERAL, SG_ALERT,
857                "AI error: updating aircraft without traffic record");
858     } else {
859         i->setPositionAndHeading(lat, lon, heading, speed, alt);
860         current = i;
861     }
862     setDt(getDt() + dt);
863
864     // see if we already have a clearance record for the currently active runway
865     // NOTE: dd. 2011-08-07: Because the active runway has been constructed in the announcePosition function, we may safely assume that is
866     // already exists here. So, we can simplify the current code. 
867     ActiveRunwayVecIterator rwy = activeRunways.begin();
868     while (rwy != activeRunways.end()) {
869         if (rwy->getRunwayName() == current->getRunway()) {
870             break;
871         }
872         rwy++;
873     }
874
875     // only bother running the following code if the current aircraft is the
876     // first in line for depature
877     /* if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
878         if (rwy->getCleared()) {
879             if (id == rwy->getCleared()) {
880                 current->setHoldPosition(false);
881             } else {
882                 current->setHoldPosition(true);
883             }
884         } else {
885             // For now. At later stages, this will probably be the place to check for inbound traffc.
886             rwy->setCleared(id);
887         }
888     } */
889     // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
890     if (current->getAircraft()->getTakeOffStatus() == 2) {
891         current->setHoldPosition(true);
892         int clearanceId = rwy->getCleared();
893         if (clearanceId) {
894             if (id == clearanceId) {
895                 current->setHoldPosition(false);
896             }
897         } else {
898             if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
899                 rwy->setCleared(id);
900             }
901         }
902     }
903 }
904
905
906 void FGTowerController::signOff(int id)
907 {
908     TrafficVectorIterator i = activeTraffic.begin();
909     // Search search if the current id alread has an entry
910     // This might be faster using a map instead of a vector, but let's start by taking a safe route
911     if (activeTraffic.size()) {
912         //while ((i->getId() != id) && i != activeTraffic.end()) {
913         while (i != activeTraffic.end()) {
914             if (i->getId() == id) {
915                 break;
916             }
917             i++;
918         }
919     }
920     // If this aircraft has left the runway, we can clear the departure record for this runway
921     ActiveRunwayVecIterator rwy = activeRunways.begin();
922     if (activeRunways.size()) {
923         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
924         while (rwy != activeRunways.end()) {
925             if (rwy->getRunwayName() == i->getRunway()) {
926                 break;
927             }
928             rwy++;
929         }
930         if (rwy != activeRunways.end()) {
931             rwy->setCleared(0);
932             rwy->updateDepartureCue();
933         } else {
934             SG_LOG(SG_GENERAL, SG_ALERT,
935                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
936         }
937     }
938     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
939         SG_LOG(SG_GENERAL, SG_ALERT,
940                "AI error: Aircraft without traffic record is signing off from tower");
941     } else {
942         i->getAircraft()->resetTakeOffStatus();
943         i = activeTraffic.erase(i);
944         //cerr << "Signing off from tower controller" << endl;
945     }
946 }
947
948 // NOTE:
949 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
950 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
951 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
952 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
953 // Note that this function is probably obsolete
954 bool FGTowerController::hasInstruction(int id)
955 {
956     TrafficVectorIterator i = activeTraffic.begin();
957     // Search search if the current id has an entry
958     // This might be faster using a map instead of a vector, but let's start by taking a safe route
959     if (activeTraffic.size()) {
960         //while ((i->getId() != id) && i != activeTraffic.end()) {
961         while (i != activeTraffic.end()) {
962             if (i->getId() == id) {
963                 break;
964             }
965             i++;
966         }
967     }
968     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
969         SG_LOG(SG_GENERAL, SG_ALERT,
970                "AI error: checking ATC instruction for aircraft without traffic record");
971     } else {
972         return i->hasInstruction();
973     }
974     return false;
975 }
976
977
978 FGATCInstruction FGTowerController::getInstruction(int id)
979 {
980     TrafficVectorIterator i = activeTraffic.begin();
981     // Search search if the current id has an entry
982     // This might be faster using a map instead of a vector, but let's start by taking a safe route
983     if (activeTraffic.size()) {
984         //while ((i->getId() != id) && i != activeTraffic.end()) {
985         while (i != activeTraffic.end()) {
986             if (i->getId() == id) {
987                 break;
988             }
989             i++;
990         }
991     }
992     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
993         SG_LOG(SG_GENERAL, SG_ALERT,
994                "AI error: requesting ATC instruction for aircraft without traffic record");
995     } else {
996         return i->getInstruction();
997     }
998     return FGATCInstruction();
999 }
1000
1001 void FGTowerController::render(bool visible) {
1002     //cerr << "FGTowerController::render function not yet implemented" << endl;
1003 }
1004
1005 string FGTowerController::getName() {
1006     return string(parent->getId() + "-tower");
1007 }
1008
1009
1010
1011 /***************************************************************************
1012  * class FGStartupController
1013  *
1014  **************************************************************************/
1015 FGStartupController::FGStartupController(FGAirportDynamics *par):
1016     FGATCController()
1017 {
1018     parent = par;
1019 }
1020
1021 void FGStartupController::announcePosition(int id,
1022                                            FGAIFlightPlan * intendedRoute,
1023                                            int currentPosition, double lat,
1024                                            double lon, double heading,
1025                                            double speed, double alt,
1026                                            double radius, int leg,
1027                                            FGAIAircraft * ref)
1028 {
1029     init();
1030     TrafficVectorIterator i = activeTraffic.begin();
1031     // Search whether the current id alread has an entry
1032     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1033     if (activeTraffic.size()) {
1034         //while ((i->getId() != id) && i != activeTraffic.end()) {
1035         while (i != activeTraffic.end()) {
1036             if (i->getId() == id) {
1037                 break;
1038             }
1039             i++;
1040         }
1041     }
1042     // Add a new TrafficRecord if no one exsists for this aircraft.
1043     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1044         FGTrafficRecord rec;
1045         rec.setId(id);
1046
1047         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1048         rec.setRunway(intendedRoute->getRunway());
1049         rec.setLeg(leg);
1050         rec.setPositionAndIntentions(currentPosition, intendedRoute);
1051         //rec.setCallSign(callsign);
1052         rec.setAircraft(ref);
1053         rec.setHoldPosition(true);
1054         activeTraffic.push_back(rec);
1055     } else {
1056         i->setPositionAndIntentions(currentPosition, intendedRoute);
1057         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1058
1059     }
1060 }
1061
1062 // NOTE:
1063 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
1064 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
1065 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
1066 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
1067 // Note that this function is probably obsolete
1068 bool FGStartupController::hasInstruction(int id)
1069 {
1070     TrafficVectorIterator i = activeTraffic.begin();
1071     // Search search if the current id has an entry
1072     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1073     if (activeTraffic.size()) {
1074         //while ((i->getId() != id) && i != activeTraffic.end()) {
1075         while (i != activeTraffic.end()) {
1076             if (i->getId() == id) {
1077                 break;
1078             }
1079             i++;
1080         }
1081     }
1082     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1083         SG_LOG(SG_GENERAL, SG_ALERT,
1084                "AI error: checking ATC instruction for aircraft without traffic record");
1085     } else {
1086         return i->hasInstruction();
1087     }
1088     return false;
1089 }
1090
1091
1092 FGATCInstruction FGStartupController::getInstruction(int id)
1093 {
1094     TrafficVectorIterator i = activeTraffic.begin();
1095     // Search search if the current id has an entry
1096     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1097     if (activeTraffic.size()) {
1098         //while ((i->getId() != id) && i != activeTraffic.end()) {
1099         while (i != activeTraffic.end()) {
1100             if (i->getId() == id) {
1101                 break;
1102             }
1103             i++;
1104         }
1105     }
1106     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1107         SG_LOG(SG_GENERAL, SG_ALERT,
1108                "AI error: requesting ATC instruction for aircraft without traffic record");
1109     } else {
1110         return i->getInstruction();
1111     }
1112     return FGATCInstruction();
1113 }
1114
1115 void FGStartupController::signOff(int id)
1116 {
1117     TrafficVectorIterator i = activeTraffic.begin();
1118     // Search search if the current id alread has an entry
1119     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1120     if (activeTraffic.size()) {
1121         //while ((i->getId() != id) && i != activeTraffic.end()) {
1122         while (i != activeTraffic.end()) {
1123             if (i->getId() == id) {
1124                 break;
1125             }
1126             i++;
1127         }
1128     }
1129     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1130         SG_LOG(SG_GENERAL, SG_ALERT,
1131                "AI error: Aircraft without traffic record is signing off from tower");
1132     } else {
1133         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1134         i = activeTraffic.erase(i);
1135     }
1136 }
1137
1138 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1139                                AtcMsgDir msgDir)
1140 {
1141     int state = i->getState();
1142     if ((state == st) && available) {
1143         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1144             
1145             //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1146             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1147             int n = trans_num->getIntValue();
1148             if (n == 0) {
1149                 trans_num->setIntValue(-1);
1150                  // PopupCallback(n);
1151                  //cerr << "Selected transmission message " << n << endl;
1152                  FGATCDialogNew::instance()->removeEntry(1);
1153             } else {
1154                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1155                 transmit(&(*i), msgId, msgDir, false);
1156                 return false;
1157             }
1158         }
1159         if (now > startTime) {
1160             //cerr << "Transmitting startup msg" << endl;
1161             transmit(&(*i), msgId, msgDir, true);
1162             i->updateState();
1163             lastTransmission = now;
1164             available = false;
1165             return true;
1166         }
1167     }
1168     return false;
1169 }
1170
1171 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1172                                                     double heading, double speed, double alt,
1173                                                     double dt)
1174 {
1175     TrafficVectorIterator i = activeTraffic.begin();
1176     // Search search if the current id has an entry
1177     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1178     TrafficVectorIterator current, closest;
1179     if (activeTraffic.size()) {
1180         //while ((i->getId() != id) && i != activeTraffic.end()) {
1181         while (i != activeTraffic.end()) {
1182             if (i->getId() == id) {
1183                 break;
1184             }
1185             i++;
1186         }
1187     }
1188 //    // update position of the current aircraft
1189
1190     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1191         SG_LOG(SG_GENERAL, SG_ALERT,
1192                "AI error: updating aircraft without traffic record");
1193     } else {
1194         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1195         current = i;
1196     }
1197     setDt(getDt() + dt);
1198
1199     int state = i->getState();
1200
1201     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1202     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1203     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1204     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1205     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1206     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1207     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1208
1209     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1210         available = true;
1211     }
1212
1213     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1214     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1215     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1216     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1217     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1218         i->nextFrequency();
1219     }
1220     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1221     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1222     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1223
1224
1225    
1226     if ((state == 8) && available) {
1227         if (now > startTime + 200) {
1228             if (i->pushBackAllowed()) {
1229                 i->allowRepeatedTransmissions();
1230                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1231                          ATC_GROUND_TO_AIR, true);
1232                 i->updateState();
1233             } else {
1234                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1235                          ATC_GROUND_TO_AIR, true);
1236                 i->suppressRepeatedTransmissions();
1237             }
1238             lastTransmission = now;
1239             available = false;
1240         }
1241     }
1242     if ((state == 9) && available) {
1243         i->setHoldPosition(false);
1244     }
1245 }
1246
1247 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1248 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1249                             double lon, double elev, double hdg, double slope)
1250 {
1251     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1252     obj_pos = geod.makeZUpFrame();
1253     // hdg is not a compass heading, but a counter-clockwise rotation
1254     // around the Z axis
1255     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1256                                         0.0, 0.0, 1.0));
1257     obj_pos.preMult(osg::Matrix::rotate(slope * SGD_DEGREES_TO_RADIANS,
1258                                         0.0, 1.0, 0.0));
1259 }
1260
1261
1262 void FGStartupController::render(bool visible)
1263 {
1264
1265     SGMaterialLib *matlib = globals->get_matlib();
1266     if (group) {
1267         //int nr = ;
1268         globals->get_scenery()->get_scene_graph()->removeChild(group);
1269         //while (group->getNumChildren()) {
1270         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1271         //simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1272           //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1273            //geode->releaseGLObjects();
1274            //group->removeChild(geode);
1275            //delete geode;
1276         group = 0;
1277     }
1278     if (visible) {
1279         group = new osg::Group;
1280         FGScenery * local_scenery = globals->get_scenery();
1281         double elevation_meters = 0.0;
1282         double elevation_feet = 0.0;
1283
1284
1285         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1286         double dx = 0;
1287         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1288             // Handle start point
1289             int pos = i->getCurrentPosition();
1290             //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1291             if (pos > 0) {
1292                 FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1293                 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1294                 SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1295
1296                 double length = SGGeodesy::distanceM(start, end);
1297                 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1298
1299                 double az2, heading; //, distanceM;
1300                 SGGeodesy::inverse(start, end, heading, az2, length);
1301                 double coveredDistance = length * 0.5;
1302                 SGGeod center;
1303                 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1304                 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1305                 ///////////////////////////////////////////////////////////////////////////////
1306                 // Make a helper function out of this
1307                 osg::Matrix obj_pos;
1308                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1309                 obj_trans->setDataVariance(osg::Object::STATIC);
1310                 // Experimental: Calculate slope here, based on length, and the individual elevations
1311                 double elevationStart;
1312                 if (isUserAircraft((i)->getAircraft())) {
1313                     elevationStart = fgGetDouble("/position/ground-elev-m");
1314                 } else {
1315                     elevationStart = ((i)->getAircraft()->_getAltitude()); 
1316                 }
1317                 double elevationEnd   = segment->getEnd()->getElevation();
1318                 if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
1319                     SGGeod center2 = end;
1320                     center2.setElevationM(SG_MAX_ELEVATION_M);
1321                     if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
1322                         elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
1323                             //elevation_meters += 0.5;
1324                     }
1325                     else { 
1326                         elevationEnd = parent->getElevation();
1327                     }
1328                     segment->getEnd()->setElevation(elevationEnd);
1329                 }
1330
1331                 double elevationMean  = (elevationStart + elevationEnd) / 2.0;
1332                 double elevDiff       = elevationEnd - elevationStart;
1333                
1334                double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
1335                 
1336                //cerr << "1. Using mean elevation : " << elevationMean << " and " << slope << endl;
1337
1338                 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), elevationMean + 0.5, -(heading), slope );
1339 ;
1340
1341                 obj_trans->setMatrix( obj_pos );
1342                 //osg::Vec3 center(0, 0, 0)
1343
1344                 float width = length /2.0;
1345                 osg::Vec3 corner(-width, 0, 0.25f);
1346                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1347                 osg::Vec3 heightVec(0, 1, 0);
1348                 osg::Geometry* geometry;
1349                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1350                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1351                 geode->setName("test");
1352                 geode->addDrawable(geometry);
1353                 //osg::Node *custom_obj;
1354                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1355                 if (mat)
1356                     geode->setEffect(mat->get_effect());
1357                 obj_trans->addChild(geode);
1358                 // wire as much of the scene graph together as we can
1359                 //->addChild( obj_trans );
1360                 group->addChild( obj_trans );
1361                 /////////////////////////////////////////////////////////////////////
1362             } else {
1363                 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1364             }
1365             for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1366                 osg::Matrix obj_pos;
1367                 int k = (*j);
1368                 if (k > 0) {
1369                     //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1370                     osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1371                     obj_trans->setDataVariance(osg::Object::STATIC);
1372                     FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1373
1374                     double elevationStart = segment->getStart()->getElevation();
1375                     double elevationEnd   = segment->getEnd  ()->getElevation();
1376                     if ((elevationStart == 0) || (elevationStart == parent->getElevation())) {
1377                         SGGeod center2 = segment->getStart()->getGeod();
1378                         center2.setElevationM(SG_MAX_ELEVATION_M);
1379                         if (local_scenery->get_elevation_m( center2, elevationStart, NULL )) {
1380                             elevation_feet = elevationStart * SG_METER_TO_FEET + 0.5;
1381                             //elevation_meters += 0.5;
1382                         }
1383                         else { 
1384                             elevationStart = parent->getElevation();
1385                         }
1386                         segment->getStart()->setElevation(elevationStart);
1387                     }
1388                     if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
1389                         SGGeod center2 = segment->getEnd()->getGeod();
1390                         center2.setElevationM(SG_MAX_ELEVATION_M);
1391                         if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
1392                             elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
1393                             //elevation_meters += 0.5;
1394                         }
1395                         else { 
1396                             elevationEnd = parent->getElevation();
1397                         }
1398                         segment->getEnd()->setElevation(elevationEnd);
1399                     }
1400  
1401                     double elevationMean  = (elevationStart + elevationEnd) / 2.0;
1402                     double elevDiff       = elevationEnd - elevationStart;
1403                     double length         = segment->getLength();
1404                     double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
1405                 
1406                     //cerr << "2. Using mean elevation : " << elevationMean << " and " << slope << endl;
1407
1408
1409                     WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), elevationMean + 0.5, -(segment->getHeading()), slope );
1410
1411                     //WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1412
1413                     obj_trans->setMatrix( obj_pos );
1414                     //osg::Vec3 center(0, 0, 0)
1415
1416                     float width = segment->getLength() /2.0;
1417                     osg::Vec3 corner(-width, 0, 0.25f);
1418                     osg::Vec3 widthVec(2*width + 1, 0, 0);
1419                     osg::Vec3 heightVec(0, 1, 0);
1420                     osg::Geometry* geometry;
1421                     geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1422                     simgear::EffectGeode* geode = new simgear::EffectGeode;
1423                     geode->setName("test");
1424                     geode->addDrawable(geometry);
1425                     //osg::Node *custom_obj;
1426                     SGMaterial *mat = matlib->find("UnidirectionalTaper");
1427                     if (mat)
1428                         geode->setEffect(mat->get_effect());
1429                     obj_trans->addChild(geode);
1430                     // wire as much of the scene graph together as we can
1431                     //->addChild( obj_trans );
1432                     group->addChild( obj_trans );
1433                 } else {
1434                     //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1435                 }
1436             }
1437             //dx += 0.1;
1438         }
1439         globals->get_scenery()->get_scene_graph()->addChild(group);
1440     }
1441 }
1442
1443 string FGStartupController::getName() {
1444     return string(parent->getId() + "-startup");
1445 }
1446
1447
1448 /***************************************************************************
1449  * class FGApproachController
1450  *
1451  **************************************************************************/
1452 FGApproachController::FGApproachController(FGAirportDynamics *par):
1453 FGATCController()
1454 {
1455     parent = par;
1456 }
1457
1458 // 
1459 void FGApproachController::announcePosition(int id,
1460                                             FGAIFlightPlan * intendedRoute,
1461                                             int currentPosition,
1462                                             double lat, double lon,
1463                                             double heading, double speed,
1464                                             double alt, double radius,
1465                                             int leg, FGAIAircraft * ref)
1466 {
1467     init();
1468     TrafficVectorIterator i = activeTraffic.begin();
1469     // Search whether the current id alread has an entry
1470     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1471     if (activeTraffic.size()) {
1472         //while ((i->getId() != id) && i != activeTraffic.end()) {
1473         while (i != activeTraffic.end()) {
1474             if (i->getId() == id) {
1475                 break;
1476             }
1477             i++;
1478         }
1479     }
1480     // Add a new TrafficRecord if no one exsists for this aircraft.
1481     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1482         FGTrafficRecord rec;
1483         rec.setId(id);
1484
1485         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1486         rec.setRunway(intendedRoute->getRunway());
1487         rec.setLeg(leg);
1488         //rec.setCallSign(callsign);
1489         rec.setAircraft(ref);
1490         activeTraffic.push_back(rec);
1491     } else {
1492         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1493     }
1494 }
1495
1496 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1497                                                      double heading, double speed, double alt,
1498                                                      double dt)
1499 {
1500     TrafficVectorIterator i = activeTraffic.begin();
1501     // Search search if the current id has an entry
1502     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1503     TrafficVectorIterator current, closest;
1504     if (activeTraffic.size()) {
1505         //while ((i->getId() != id) && i != activeTraffic.end()) {
1506         while (i != activeTraffic.end()) {
1507             if (i->getId() == id) {
1508                 break;
1509             }
1510             i++;
1511         }
1512     }
1513 //    // update position of the current aircraft
1514     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1515         SG_LOG(SG_GENERAL, SG_ALERT,
1516                "AI error: updating aircraft without traffic record");
1517     } else {
1518         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1519         current = i;
1520         //cerr << "ApproachController: checking for speed" << endl;
1521         time_t time_diff =
1522             current->getAircraft()->
1523             checkForArrivalTime(string("final001"));
1524         if (time_diff > 15) {
1525             current->setSpeedAdjustment(current->getAircraft()->
1526                                         getPerformance()->vDescent() *
1527                                         1.35);
1528         } else if (time_diff > 5) {
1529             current->setSpeedAdjustment(current->getAircraft()->
1530                                         getPerformance()->vDescent() *
1531                                         1.2);
1532         } else if (time_diff < -15) {
1533             current->setSpeedAdjustment(current->getAircraft()->
1534                                         getPerformance()->vDescent() *
1535                                         0.65);
1536         } else if (time_diff < -5) {
1537             current->setSpeedAdjustment(current->getAircraft()->
1538                                         getPerformance()->vDescent() *
1539                                         0.8);
1540         } else {
1541             current->clearSpeedAdjustment();
1542         }
1543         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1544     }
1545     setDt(getDt() + dt);
1546 }
1547
1548 void FGApproachController::signOff(int id)
1549 {
1550     TrafficVectorIterator i = activeTraffic.begin();
1551     // Search search if the current id alread has an entry
1552     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1553     if (activeTraffic.size()) {
1554         //while ((i->getId() != id) && i != activeTraffic.end()) {
1555         while (i != activeTraffic.end()) {
1556             if (i->getId() == id) {
1557                 break;
1558             }
1559             i++;
1560         }
1561     }
1562     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1563         SG_LOG(SG_GENERAL, SG_ALERT,
1564                "AI error: Aircraft without traffic record is signing off from approach");
1565     } else {
1566         i = activeTraffic.erase(i);
1567     }
1568 }
1569
1570
1571
1572
1573 bool FGApproachController::hasInstruction(int id)
1574 {
1575     TrafficVectorIterator i = activeTraffic.begin();
1576     // Search search if the current id has an entry
1577     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1578     if (activeTraffic.size()) {
1579         //while ((i->getId() != id) && i != activeTraffic.end()) {
1580         while (i != activeTraffic.end()) {
1581             if (i->getId() == id) {
1582                 break;
1583             }
1584             i++;
1585         }
1586     }
1587     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1588         SG_LOG(SG_GENERAL, SG_ALERT,
1589                "AI error: checking ATC instruction for aircraft without traffic record");
1590     } else {
1591         return i->hasInstruction();
1592     }
1593     return false;
1594 }
1595
1596
1597 FGATCInstruction FGApproachController::getInstruction(int id)
1598 {
1599     TrafficVectorIterator i = activeTraffic.begin();
1600     // Search search if the current id has an entry
1601     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1602     if (activeTraffic.size()) {
1603         //while ((i->getId() != id) && i != activeTraffic.end()) {
1604         while (i != activeTraffic.end()) {
1605             if (i->getId() == id) {
1606                 break;
1607             }
1608             i++;
1609         }
1610     }
1611     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1612         SG_LOG(SG_GENERAL, SG_ALERT,
1613                "AI error: requesting ATC instruction for aircraft without traffic record");
1614     } else {
1615         return i->getInstruction();
1616     }
1617     return FGATCInstruction();
1618 }
1619
1620
1621 ActiveRunway *FGApproachController::getRunway(string name)
1622 {
1623     ActiveRunwayVecIterator rwy = activeRunways.begin();
1624     if (activeRunways.size()) {
1625         while (rwy != activeRunways.end()) {
1626             if (rwy->getRunwayName() == name) {
1627                 break;
1628             }
1629             rwy++;
1630         }
1631     }
1632     if (rwy == activeRunways.end()) {
1633         ActiveRunway aRwy(name, 0);
1634         activeRunways.push_back(aRwy);
1635         rwy = activeRunways.end() - 1;
1636     }
1637     return &(*rwy);
1638 }
1639
1640 void FGApproachController::render(bool visible) {
1641     //cerr << "FGApproachController::render function not yet implemented" << endl;
1642 }
1643
1644
1645
1646 string FGApproachController::getName() {
1647     return string(parent->getId() + "-approach");
1648 }