]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Merge branch 'next' into durk-atc
[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 slow 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 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
198 {
199     bool result = false;
200     //cerr << "Start check 1" << endl;
201     if (currentPos == other.currentPos) {
202         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
203         result = true;
204     }
205     //  else if (other.intentions.size()) 
206     //     {
207     //       cerr << "Start check 2" << endl;
208     //       intVecIterator i = other.intentions.begin(); 
209     //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
210     //     i++;
211     //       if (i != other.intentions.end()) {
212     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
213     //     result = true;
214     //       }
215     else if (intentions.size()) {
216         //cerr << "Start check 3" << endl;
217         intVecIterator i = intentions.begin();
218         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
219         while (i != intentions.end()) {
220             if ((*i) == other.currentPos) {
221                 break;
222             }
223             i++;
224         }
225         if (i != intentions.end()) {
226             //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
227             result = true;
228         }
229     }
230     //cerr << "Done !!" << endl;
231     return result;
232 }
233
234 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
235                                             double hdg, double spd,
236                                             double alt)
237 {
238     latitude = lat;
239     longitude = lon;
240     heading = hdg;
241     speed = spd;
242     altitude = alt;
243 }
244
245 int FGTrafficRecord::crosses(FGGroundNetwork * net,
246                              FGTrafficRecord & other)
247 {
248     if (checkPositionAndIntentions(other)
249         || (other.checkPositionAndIntentions(*this)))
250         return -1;
251     intVecIterator i, j;
252     int currentTargetNode = 0, otherTargetNode = 0;
253     if (currentPos > 0)
254         currentTargetNode = net->findSegment(currentPos)->getEnd()->getIndex(); // OKAY,... 
255     if (other.currentPos > 0)
256         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
257     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
258         return currentTargetNode;
259     if (intentions.size()) {
260         for (i = intentions.begin(); i != intentions.end(); i++) {
261             if ((*i) > 0) {
262                 if ((currentTargetNode ==
263                      net->findSegment(*i)->getEnd()->getIndex())) {
264                     //cerr << "Current crosses at " << currentTargetNode <<endl;
265                     return currentTargetNode;
266                 }
267             }
268         }
269     }
270     if (other.intentions.size()) {
271         for (i = other.intentions.begin(); i != other.intentions.end();
272              i++) {
273             if ((*i) > 0) {
274                 if (otherTargetNode ==
275                     net->findSegment(*i)->getEnd()->getIndex()) {
276                     //cerr << "Other crosses at " << currentTargetNode <<endl;
277                     return otherTargetNode;
278                 }
279             }
280         }
281     }
282     if (intentions.size() && other.intentions.size()) {
283         for (i = intentions.begin(); i != intentions.end(); i++) {
284             for (j = other.intentions.begin(); j != other.intentions.end();
285                  j++) {
286                 //cerr << "finding segment " << *i << " and " << *j << endl;
287                 if (((*i) > 0) && ((*j) > 0)) {
288                     currentTargetNode =
289                         net->findSegment(*i)->getEnd()->getIndex();
290                     otherTargetNode =
291                         net->findSegment(*j)->getEnd()->getIndex();
292                     if (currentTargetNode == otherTargetNode) {
293                         //cerr << "Routes will cross at " << currentTargetNode << endl;
294                         return currentTargetNode;
295                     }
296                 }
297             }
298         }
299     }
300     return -1;
301 }
302
303 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
304                               FGTrafficRecord & other)
305 {
306     int node = -1, othernode = -1;
307     if (currentPos > 0)
308         node = net->findSegment(currentPos)->getEnd()->getIndex();
309     if (other.currentPos > 0)
310         othernode =
311             net->findSegment(other.currentPos)->getEnd()->getIndex();
312     if ((node == othernode) && (node != -1))
313         return true;
314     if (other.intentions.size()) {
315         for (intVecIterator i = other.intentions.begin();
316              i != other.intentions.end(); i++) {
317             if (*i > 0) {
318                 othernode = net->findSegment(*i)->getEnd()->getIndex();
319                 if ((node == othernode) && (node > -1))
320                     return true;
321             }
322         }
323     }
324     //if (other.currentPos > 0)
325     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
326     //if (intentions.size())
327     //  {
328     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
329     //    {
330     //      if (*i > 0) 
331     //        {
332     //          node = net->findSegment(*i)->getEnd()->getIndex();
333     //          if ((node == othernode) && (node > -1))
334     //            return true;
335     //        }
336     //    }
337     //  }
338     return false;
339 }
340
341
342 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
343                                  FGTrafficRecord & other, int node)
344 {
345     // Check if current segment is the reverse segment for the other aircraft
346     FGTaxiSegment *opp;
347     //cerr << "Current segment " << currentPos << endl;
348     if ((currentPos > 0) && (other.currentPos > 0)) {
349         opp = net->findSegment(currentPos)->opposite();
350         if (opp) {
351             if (opp->getIndex() == other.currentPos)
352                 return true;
353         }
354
355         for (intVecIterator i = intentions.begin(); i != intentions.end();
356              i++) {
357             if ((opp = net->findSegment(other.currentPos)->opposite())) {
358                 if ((*i) > 0)
359                     if (opp->getIndex() ==
360                         net->findSegment(*i)->getIndex()) {
361                         if (net->findSegment(*i)->getStart()->getIndex() ==
362                             node) {
363                             {
364                                 //cerr << "Found the node " << node << endl;
365                                 return true;
366                             }
367                         }
368                     }
369             }
370             if (other.intentions.size()) {
371                 for (intVecIterator j = other.intentions.begin();
372                      j != other.intentions.end(); j++) {
373                     // cerr << "Current segment 1 " << (*i) << endl;
374                     if ((*i) > 0) {
375                         if ((opp = net->findSegment(*i)->opposite())) {
376                             if (opp->getIndex() ==
377                                 net->findSegment(*j)->getIndex()) {
378                                 //cerr << "Nodes " << net->findSegment(*i)->getIndex()
379                                 //   << " and  " << net->findSegment(*j)->getIndex()
380                                 //   << " are opposites " << endl;
381                                 if (net->findSegment(*i)->getStart()->
382                                     getIndex() == node) {
383                                     {
384                                         //cerr << "Found the node " << node << endl;
385                                         return true;
386                                     }
387                                 }
388                             }
389                         }
390                     }
391                 }
392             }
393         }
394     }
395     return false;
396 }
397
398 void FGTrafficRecord::setSpeedAdjustment(double spd)
399 {
400     instruction.setChangeSpeed(true);
401     instruction.setSpeed(spd);
402 }
403
404 void FGTrafficRecord::setHeadingAdjustment(double heading)
405 {
406     instruction.setChangeHeading(true);
407     instruction.setHeading(heading);
408 }
409
410 bool FGTrafficRecord::pushBackAllowed()
411 {
412     // With the user ATC / AI integration, checking whether the user's aircraft is near no longer works, because
413     // this will effectively block the user's aircraft itself from receiving pushback clearance. 
414     // So, what can we do?
415     /*
416     double course, az2, dist;
417     SGGeod curr(SGGeod::fromDegM(getLongitude(),
418                                  getLatitude(), getAltitude()));
419
420     double userLatitude = fgGetDouble("/position/latitude-deg");
421     double userLongitude = fgGetDouble("/position/longitude-deg");
422     SGGeod user(SGGeod::fromDeg(userLongitude, userLatitude));
423     SGGeodesy::inverse(curr, user, course, az2, dist);
424     //cerr << "Distance to user : " << dist << endl;
425     return (dist > 250);
426     */
427
428
429     // In essence, we should check whether the pusbback route itself, as well as the associcated
430     // taxiways near the pushback point are free of traffic. 
431     // To do so, we need to 
432     return true;
433 }
434
435
436
437 /***************************************************************************
438  * FGATCInstruction
439  *
440  **************************************************************************/
441 FGATCInstruction::FGATCInstruction()
442 {
443     holdPattern = false;
444     holdPosition = false;
445     changeSpeed = false;
446     changeHeading = false;
447     changeAltitude = false;
448     resolveCircularWait = false;
449
450     speed = 0;
451     heading = 0;
452     alt = 0;
453 }
454
455
456 bool FGATCInstruction::hasInstruction()
457 {
458     return (holdPattern || holdPosition || changeSpeed || changeHeading
459             || changeAltitude || resolveCircularWait);
460 }
461
462 /***************************************************************************
463  * FGATCController
464  *
465  **************************************************************************/
466
467
468
469
470 FGATCController::FGATCController()
471 {
472     //cerr << "running FGATController constructor" << endl;
473     dt_count = 0;
474     available = true;
475     lastTransmission = 0;
476     initialized = false;
477 }
478
479 FGATCController::~FGATCController()
480 {
481      //cerr << "running FGATController destructor" << endl;
482 }
483
484 string FGATCController::getGateName(FGAIAircraft * ref)
485 {
486     return ref->atGate();
487 }
488
489 bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
490
491     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
492 };
493
494 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
495                                AtcMsgDir msgDir, bool audible)
496 {
497     string sender, receiver;
498     int stationFreq = 0;
499     int taxiFreq = 0;
500     int freqId = 0;
501     string atisInformation;
502     string text;
503     string taxiFreqStr;
504     double heading = 0;
505     string activeRunway;
506     string fltType;
507     string rwyClass;
508     string SID;
509     string transponderCode;
510     FGAIFlightPlan *fp;
511     string fltRules;
512
513     //double commFreqD;
514     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
515     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
516     switch (rec->getLeg()) {
517     case 1:
518     case 2:
519         freqId = rec->getNextFrequency();
520         stationFreq =
521             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
522             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
523         taxiFreq =
524             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
525             getDynamics()->getGroundFrequency(2);
526         receiver =
527             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
528             getName() + "-Ground";
529         atisInformation =
530             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
531             getDynamics()->getAtisSequence();
532         break;
533     case 3:
534         receiver =
535             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
536             getName() + "-Tower";
537         break;
538     }
539     // Swap sender and receiver value in case of a ground to air transmission
540     if (msgDir == ATC_GROUND_TO_AIR) {
541         string tmp = sender;
542         sender = receiver;
543         receiver = tmp;
544     }
545     switch (msgId) {
546     case MSG_ANNOUNCE_ENGINE_START:
547         text = sender + ". Ready to Start up";
548         break;
549     case MSG_REQUEST_ENGINE_START:
550         text =
551             receiver + ", This is " + sender + ". Position " +
552             getGateName(rec->getAircraft()) + ". Information " +
553             atisInformation + ". " +
554             rec->getAircraft()->getTrafficRef()->getFlightRules() +
555             " to " +
556             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
557             getName() + ". Request start-up";
558         break;
559         // Acknowledge engine startup permission
560         // Assign departure runway
561         // Assign SID, if necessery (TODO)
562     case MSG_PERMIT_ENGINE_START:
563         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
564
565         heading = rec->getAircraft()->getTrafficRef()->getCourse();
566         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
567         rwyClass =
568             rec->getAircraft()->GetFlightPlan()->
569             getRunwayClassFromTrafficType(fltType);
570
571         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
572             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
573                                            heading);
574         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
575         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
576             getDynamics()->getSID(activeRunway, heading);
577         rec->getAircraft()->GetFlightPlan()->setSID(fp);
578         if (fp) {
579             SID = fp->getName() + " departure";
580         } else {
581             SID = "fly runway heading ";
582         }
583         //snprintf(buffer, 7, "%3.2f", heading);
584         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
585         transponderCode = genTransponderCode(fltRules);
586         rec->getAircraft()->SetTransponderCode(transponderCode);
587         text =
588             receiver + ". Start-up approved. " + atisInformation +
589             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
590             transponderCode + ". " +
591             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
592             sender + " control.";
593         break;
594     case MSG_DENY_ENGINE_START:
595         text = receiver + ". Standby";
596         break;
597     case MSG_ACKNOWLEDGE_ENGINE_START:
598         fp = rec->getAircraft()->GetFlightPlan()->getSID();
599         if (fp) {
600             SID =
601                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
602                 " departure";
603         } else {
604             SID = "fly runway heading ";
605         }
606         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
607         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
608         transponderCode = rec->getAircraft()->GetTransponderCode();
609         text =
610             receiver + ". Start-up approved. " + atisInformation +
611             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
612             transponderCode + ". " +
613             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
614             sender;
615         break;
616     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
617         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
618         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
619         break;
620     case MSG_INITIATE_CONTACT:
621         text = receiver + ". With you. " + sender;
622         break;
623     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
624         text = receiver + ". Roger. " + sender;
625         break;
626     case MSG_REQUEST_PUSHBACK_CLEARANCE:
627         text = receiver + ". Request push-back. " + sender;
628         break;
629     case MSG_PERMIT_PUSHBACK_CLEARANCE:
630         text = receiver + ". Push-back approved. " + sender;
631         break;
632     case MSG_HOLD_PUSHBACK_CLEARANCE:
633         text = receiver + ". Standby. " + sender;
634         break;
635     case MSG_REQUEST_TAXI_CLEARANCE:
636         text = receiver + ". Ready to Taxi. " + sender;
637         break;
638     case MSG_ISSUE_TAXI_CLEARANCE:
639         text = receiver + ". Cleared to taxi. " + sender;
640         break;
641     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
642         text = receiver + ". Cleared to taxi. " + sender;
643         break;
644     case MSG_HOLD_POSITION:
645         text = receiver + ". Hold Position. " + sender;
646         break;
647     case MSG_ACKNOWLEDGE_HOLD_POSITION:
648         text = receiver + ". Holding Position. " + sender;
649         break;
650     case MSG_RESUME_TAXI:
651         text = receiver + ". Resume Taxiing. " + sender;
652         break;
653     case MSG_ACKNOWLEDGE_RESUME_TAXI:
654         text = receiver + ". Continuing Taxi. " + sender;
655         break;
656     default:
657         text = text + sender + ". Transmitting unknown Message";
658         break;
659     }
660     if (audible) {
661         double onBoardRadioFreq0 =
662             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
663         double onBoardRadioFreq1 =
664             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
665         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
666         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
667         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
668
669         // Display ATC message only when one of the radios is tuned
670         // the relevant frequency.
671         // Note that distance attenuation is currently not yet implemented
672         if ((onBoardRadioFreqI0 == stationFreq)
673             || (onBoardRadioFreqI1 == stationFreq)) {
674             if (rec->allowTransmissions()) {
675                 fgSetString("/sim/messages/atc", text.c_str());
676             }
677         }
678     } else {
679         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
680         atc->getATCDialog()->addEntry(1, text);
681         
682     }
683 }
684
685 string FGATCController::formatATCFrequency3_2(int freq)
686 {
687     char buffer[7];
688     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
689     return string(buffer);
690 }
691
692 // TODO: Set transponder codes according to real-world routes.
693 // The current version just returns a random string of four octal numbers. 
694 string FGATCController::genTransponderCode(string fltRules)
695 {
696     if (fltRules == "VFR") {
697         return string("1200");
698     } else {
699         char buffer[5];
700         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
701                  rand() % 8);
702         return string(buffer);
703     }
704 }
705
706 void FGATCController::init() 
707 {
708    if (!initialized) {
709        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
710        mgr->addController(this);
711        initialized = true;
712     }
713 }
714
715 /***************************************************************************
716  * class FGTowerController
717  *
718  **************************************************************************/
719 FGTowerController::FGTowerController(FGAirportDynamics *par) :
720 FGATCController()
721 {
722     parent = par;
723 }
724
725 // 
726 void FGTowerController::announcePosition(int id,
727                                          FGAIFlightPlan * intendedRoute,
728                                          int currentPosition, double lat,
729                                          double lon, double heading,
730                                          double speed, double alt,
731                                          double radius, int leg,
732                                          FGAIAircraft * ref)
733 {
734     init();
735     TrafficVectorIterator i = activeTraffic.begin();
736     // Search whether the current id alread has an entry
737     // This might be faster using a map instead of a vector, but let's start by taking a safe route
738     if (activeTraffic.size()) {
739         //while ((i->getId() != id) && i != activeTraffic.end()) {
740         while (i != activeTraffic.end()) {
741             if (i->getId() == id) {
742                 break;
743             }
744             i++;
745         }
746     }
747     // Add a new TrafficRecord if no one exsists for this aircraft.
748     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
749         FGTrafficRecord rec;
750         rec.setId(id);
751
752         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
753         rec.setRunway(intendedRoute->getRunway());
754         rec.setLeg(leg);
755         //rec.setCallSign(callsign);
756         rec.setAircraft(ref);
757         activeTraffic.push_back(rec);
758     } else {
759         i->setPositionAndHeading(lat, lon, heading, speed, alt);
760     }
761 }
762
763 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
764                                                   double heading, double speed, double alt,
765                                                   double dt)
766 {
767     TrafficVectorIterator i = activeTraffic.begin();
768     // Search whether the current id has an entry
769     // This might be faster using a map instead of a vector, but let's start by taking a safe route
770     TrafficVectorIterator current, closest;
771     if (activeTraffic.size()) {
772         //while ((i->getId() != id) && i != activeTraffic.end()) {
773         while (i != activeTraffic.end()) {
774             if (i->getId() == id) {
775                 break;
776             }
777             i++;
778         }
779     }
780 //    // update position of the current aircraft
781     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
782         SG_LOG(SG_GENERAL, SG_ALERT,
783                "AI error: updating aircraft without traffic record");
784     } else {
785         i->setPositionAndHeading(lat, lon, heading, speed, alt);
786         current = i;
787     }
788     setDt(getDt() + dt);
789
790 //    // see if we already have a clearance record for the currently active runway
791     ActiveRunwayVecIterator rwy = activeRunways.begin();
792     // again, a map might be more efficient here
793     if (activeRunways.size()) {
794         //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
795         while (rwy != activeRunways.end()) {
796             if (rwy->getRunwayName() == current->getRunway()) {
797                 break;
798             }
799             rwy++;
800         }
801     }
802     if (rwy == activeRunways.end()) {
803         ActiveRunway aRwy(current->getRunway(), id);
804         activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
805         current->setHoldPosition(false);        // Clear the current aircraft to continue
806     } else {
807         // Okay, we have a clearance record for this runway, so check
808         // whether the clearence ID matches that of the current aircraft
809         if (id == rwy->getCleared()) {
810             current->setHoldPosition(false);
811         } else {
812             current->setHoldPosition(true);
813         }
814     }
815 }
816
817
818 void FGTowerController::signOff(int id)
819 {
820     TrafficVectorIterator i = activeTraffic.begin();
821     // Search search if the current id alread has an entry
822     // This might be faster using a map instead of a vector, but let's start by taking a safe route
823     if (activeTraffic.size()) {
824         //while ((i->getId() != id) && i != activeTraffic.end()) {
825         while (i != activeTraffic.end()) {
826             if (i->getId() == id) {
827                 break;
828             }
829             i++;
830         }
831     }
832     // If this aircraft has left the runway, we can clear the departure record for this runway
833     ActiveRunwayVecIterator rwy = activeRunways.begin();
834     if (activeRunways.size()) {
835         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
836         while (rwy != activeRunways.end()) {
837             if (rwy->getRunwayName() == i->getRunway()) {
838                 break;
839             }
840             rwy++;
841         }
842         if (rwy != activeRunways.end()) {
843             rwy = activeRunways.erase(rwy);
844         } else {
845             SG_LOG(SG_GENERAL, SG_ALERT,
846                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
847         }
848     }
849     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
850         SG_LOG(SG_GENERAL, SG_ALERT,
851                "AI error: Aircraft without traffic record is signing off from tower");
852     } else {
853         i = activeTraffic.erase(i);
854         //cerr << "Signing off from tower controller" << endl;
855     }
856 }
857
858 // NOTE:
859 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
860 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
861 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
862 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
863 // Note that this function is probably obsolete
864 bool FGTowerController::hasInstruction(int id)
865 {
866     TrafficVectorIterator i = activeTraffic.begin();
867     // Search search if the current id has an entry
868     // This might be faster using a map instead of a vector, but let's start by taking a safe route
869     if (activeTraffic.size()) {
870         //while ((i->getId() != id) && i != activeTraffic.end()) {
871         while (i != activeTraffic.end()) {
872             if (i->getId() == id) {
873                 break;
874             }
875             i++;
876         }
877     }
878     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
879         SG_LOG(SG_GENERAL, SG_ALERT,
880                "AI error: checking ATC instruction for aircraft without traffic record");
881     } else {
882         return i->hasInstruction();
883     }
884     return false;
885 }
886
887
888 FGATCInstruction FGTowerController::getInstruction(int id)
889 {
890     TrafficVectorIterator i = activeTraffic.begin();
891     // Search search if the current id has an entry
892     // This might be faster using a map instead of a vector, but let's start by taking a safe route
893     if (activeTraffic.size()) {
894         //while ((i->getId() != id) && i != activeTraffic.end()) {
895         while (i != activeTraffic.end()) {
896             if (i->getId() == id) {
897                 break;
898             }
899             i++;
900         }
901     }
902     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
903         SG_LOG(SG_GENERAL, SG_ALERT,
904                "AI error: requesting ATC instruction for aircraft without traffic record");
905     } else {
906         return i->getInstruction();
907     }
908     return FGATCInstruction();
909 }
910
911 void FGTowerController::render(bool visible) {
912     //cerr << "FGTowerController::render function not yet implemented" << endl;
913 }
914
915 string FGTowerController::getName() {
916     return string(parent->getId() + "-tower");
917 }
918
919
920
921 /***************************************************************************
922  * class FGStartupController
923  *
924  **************************************************************************/
925 FGStartupController::FGStartupController(FGAirportDynamics *par):
926     FGATCController()
927 {
928     parent = par;
929 }
930
931 void FGStartupController::announcePosition(int id,
932                                            FGAIFlightPlan * intendedRoute,
933                                            int currentPosition, double lat,
934                                            double lon, double heading,
935                                            double speed, double alt,
936                                            double radius, int leg,
937                                            FGAIAircraft * ref)
938 {
939     init();
940     TrafficVectorIterator i = activeTraffic.begin();
941     // Search whether the current id alread has an entry
942     // This might be faster using a map instead of a vector, but let's start by taking a safe route
943     if (activeTraffic.size()) {
944         //while ((i->getId() != id) && i != activeTraffic.end()) {
945         while (i != activeTraffic.end()) {
946             if (i->getId() == id) {
947                 break;
948             }
949             i++;
950         }
951     }
952     // Add a new TrafficRecord if no one exsists for this aircraft.
953     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
954         FGTrafficRecord rec;
955         rec.setId(id);
956
957         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
958         rec.setRunway(intendedRoute->getRunway());
959         rec.setLeg(leg);
960         rec.setPositionAndIntentions(currentPosition, intendedRoute);
961         //rec.setCallSign(callsign);
962         rec.setAircraft(ref);
963         rec.setHoldPosition(true);
964         activeTraffic.push_back(rec);
965     } else {
966         i->setPositionAndIntentions(currentPosition, intendedRoute);
967         i->setPositionAndHeading(lat, lon, heading, speed, alt);
968
969     }
970 }
971
972 // NOTE:
973 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
974 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
975 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
976 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
977 // Note that this function is probably obsolete
978 bool FGStartupController::hasInstruction(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: checking ATC instruction for aircraft without traffic record");
995     } else {
996         return i->hasInstruction();
997     }
998     return false;
999 }
1000
1001
1002 FGATCInstruction FGStartupController::getInstruction(int id)
1003 {
1004     TrafficVectorIterator i = activeTraffic.begin();
1005     // Search search if the current id has an entry
1006     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1007     if (activeTraffic.size()) {
1008         //while ((i->getId() != id) && i != activeTraffic.end()) {
1009         while (i != activeTraffic.end()) {
1010             if (i->getId() == id) {
1011                 break;
1012             }
1013             i++;
1014         }
1015     }
1016     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1017         SG_LOG(SG_GENERAL, SG_ALERT,
1018                "AI error: requesting ATC instruction for aircraft without traffic record");
1019     } else {
1020         return i->getInstruction();
1021     }
1022     return FGATCInstruction();
1023 }
1024
1025 void FGStartupController::signOff(int id)
1026 {
1027     TrafficVectorIterator i = activeTraffic.begin();
1028     // Search search if the current id alread has an entry
1029     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1030     if (activeTraffic.size()) {
1031         //while ((i->getId() != id) && i != activeTraffic.end()) {
1032         while (i != activeTraffic.end()) {
1033             if (i->getId() == id) {
1034                 break;
1035             }
1036             i++;
1037         }
1038     }
1039     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1040         SG_LOG(SG_GENERAL, SG_ALERT,
1041                "AI error: Aircraft without traffic record is signing off from tower");
1042     } else {
1043         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1044         i = activeTraffic.erase(i);
1045     }
1046 }
1047
1048 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1049                                AtcMsgDir msgDir)
1050 {
1051     int state = i->getState();
1052     if ((state == st) && available) {
1053         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1054             
1055             //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1056             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1057             int n = trans_num->getIntValue();
1058             if (n == 0) {
1059                 trans_num->setIntValue(-1);
1060                  // PopupCallback(n);
1061                  //cerr << "Selected transmission message " << n << endl;
1062                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1063                  atc->getATCDialog()->removeEntry(1);
1064             } else {
1065                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1066                 transmit(&(*i), msgId, msgDir, false);
1067                 return false;
1068             }
1069         }
1070         if (now > startTime) {
1071             //cerr << "Transmitting startup msg" << endl;
1072             transmit(&(*i), msgId, msgDir, true);
1073             i->updateState();
1074             lastTransmission = now;
1075             available = false;
1076             return true;
1077         }
1078     }
1079     return false;
1080 }
1081
1082 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1083                                                     double heading, double speed, double alt,
1084                                                     double dt)
1085 {
1086     TrafficVectorIterator i = activeTraffic.begin();
1087     // Search search if the current id has an entry
1088     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1089     TrafficVectorIterator current, closest;
1090     if (activeTraffic.size()) {
1091         //while ((i->getId() != id) && i != activeTraffic.end()) {
1092         while (i != activeTraffic.end()) {
1093             if (i->getId() == id) {
1094                 break;
1095             }
1096             i++;
1097         }
1098     }
1099 //    // update position of the current aircraft
1100
1101     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1102         SG_LOG(SG_GENERAL, SG_ALERT,
1103                "AI error: updating aircraft without traffic record");
1104     } else {
1105         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1106         current = i;
1107     }
1108     setDt(getDt() + dt);
1109
1110     int state = i->getState();
1111
1112     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1113     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1114     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1115     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1116     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1117     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1118     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1119
1120     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1121         available = true;
1122     }
1123
1124     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1125     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1126     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1127     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1128     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1129         i->nextFrequency();
1130     }
1131     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1132     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1133     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1134
1135
1136    
1137     if ((state == 8) && available) {
1138         if (now > startTime + 200) {
1139             if (i->pushBackAllowed()) {
1140                 i->allowRepeatedTransmissions();
1141                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1142                          ATC_GROUND_TO_AIR, true);
1143                 i->updateState();
1144             } else {
1145                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1146                          ATC_GROUND_TO_AIR, true);
1147                 i->suppressRepeatedTransmissions();
1148             }
1149             lastTransmission = now;
1150             available = false;
1151         }
1152     }
1153     if ((state == 9) && available) {
1154         i->setHoldPosition(false);
1155     }
1156 }
1157
1158 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1159 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1160                             double lon, double elev, double hdg)
1161 {
1162     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1163     obj_pos = geod.makeZUpFrame();
1164     // hdg is not a compass heading, but a counter-clockwise rotation
1165     // around the Z axis
1166     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1167                                         0.0, 0.0, 1.0));
1168 }
1169
1170
1171 void FGStartupController::render(bool visible)
1172 {
1173
1174     SGMaterialLib *matlib = globals->get_matlib();
1175     if (group) {
1176         //int nr = ;
1177         globals->get_scenery()->get_scene_graph()->removeChild(group);
1178         //while (group->getNumChildren()) {
1179         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1180         simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1181           //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1182            //geode->releaseGLObjects();
1183            //group->removeChild(geode);
1184            //delete geode;
1185         group = 0;
1186     }
1187     if (visible) {
1188         group = new osg::Group;
1189
1190         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1191         double dx = 0;
1192         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1193             // Handle start point
1194             int pos = i->getCurrentPosition();
1195             //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1196             if (pos > 0) {
1197                 FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1198                 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1199                 SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1200
1201                 double length = SGGeodesy::distanceM(start, end);
1202                 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1203
1204                 double az2, heading; //, distanceM;
1205                 SGGeodesy::inverse(start, end, heading, az2, length);
1206                 double coveredDistance = length * 0.5;
1207                 SGGeod center;
1208                 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1209                 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1210                 ///////////////////////////////////////////////////////////////////////////////
1211                 // Make a helper function out of this
1212                 osg::Matrix obj_pos;
1213                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1214                 obj_trans->setDataVariance(osg::Object::STATIC);
1215
1216                 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1217
1218                 obj_trans->setMatrix( obj_pos );
1219                 //osg::Vec3 center(0, 0, 0)
1220
1221                 float width = length /2.0;
1222                 osg::Vec3 corner(-width, 0, 0.25f);
1223                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1224                 osg::Vec3 heightVec(0, 1, 0);
1225                 osg::Geometry* geometry;
1226                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1227                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1228                 geode->setName("test");
1229                 geode->addDrawable(geometry);
1230                 //osg::Node *custom_obj;
1231                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1232                 if (mat)
1233                     geode->setEffect(mat->get_effect());
1234                 obj_trans->addChild(geode);
1235                 // wire as much of the scene graph together as we can
1236                 //->addChild( obj_trans );
1237                 group->addChild( obj_trans );
1238                 /////////////////////////////////////////////////////////////////////
1239             } else {
1240                 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1241             }
1242             for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1243                 osg::Matrix obj_pos;
1244                 int k = (*j);
1245                 if (k > 0) {
1246                     //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1247                     osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1248                     obj_trans->setDataVariance(osg::Object::STATIC);
1249                     FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1250                     WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1251
1252                     obj_trans->setMatrix( obj_pos );
1253                     //osg::Vec3 center(0, 0, 0)
1254
1255                     float width = segment->getLength() /2.0;
1256                     osg::Vec3 corner(-width, 0, 0.25f);
1257                     osg::Vec3 widthVec(2*width + 1, 0, 0);
1258                     osg::Vec3 heightVec(0, 1, 0);
1259                     osg::Geometry* geometry;
1260                     geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1261                     simgear::EffectGeode* geode = new simgear::EffectGeode;
1262                     geode->setName("test");
1263                     geode->addDrawable(geometry);
1264                     //osg::Node *custom_obj;
1265                     SGMaterial *mat = matlib->find("UnidirectionalTaper");
1266                     if (mat)
1267                         geode->setEffect(mat->get_effect());
1268                     obj_trans->addChild(geode);
1269                     // wire as much of the scene graph together as we can
1270                     //->addChild( obj_trans );
1271                     group->addChild( obj_trans );
1272                 } else {
1273                     //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1274                 }
1275             }
1276             //dx += 0.1;
1277         }
1278         globals->get_scenery()->get_scene_graph()->addChild(group);
1279     }
1280 }
1281
1282 string FGStartupController::getName() {
1283     return string(parent->getId() + "-startup");
1284 }
1285
1286
1287 /***************************************************************************
1288  * class FGApproachController
1289  *
1290  **************************************************************************/
1291 FGApproachController::FGApproachController(FGAirportDynamics *par):
1292 FGATCController()
1293 {
1294     parent = par;
1295 }
1296
1297 // 
1298 void FGApproachController::announcePosition(int id,
1299                                             FGAIFlightPlan * intendedRoute,
1300                                             int currentPosition,
1301                                             double lat, double lon,
1302                                             double heading, double speed,
1303                                             double alt, double radius,
1304                                             int leg, FGAIAircraft * ref)
1305 {
1306     init();
1307     TrafficVectorIterator i = activeTraffic.begin();
1308     // Search whether the current id alread has an entry
1309     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1310     if (activeTraffic.size()) {
1311         //while ((i->getId() != id) && i != activeTraffic.end()) {
1312         while (i != activeTraffic.end()) {
1313             if (i->getId() == id) {
1314                 break;
1315             }
1316             i++;
1317         }
1318     }
1319     // Add a new TrafficRecord if no one exsists for this aircraft.
1320     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1321         FGTrafficRecord rec;
1322         rec.setId(id);
1323
1324         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1325         rec.setRunway(intendedRoute->getRunway());
1326         rec.setLeg(leg);
1327         //rec.setCallSign(callsign);
1328         rec.setAircraft(ref);
1329         activeTraffic.push_back(rec);
1330     } else {
1331         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1332     }
1333 }
1334
1335 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1336                                                      double heading, double speed, double alt,
1337                                                      double dt)
1338 {
1339     TrafficVectorIterator i = activeTraffic.begin();
1340     // Search search if the current id has an entry
1341     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1342     TrafficVectorIterator current, closest;
1343     if (activeTraffic.size()) {
1344         //while ((i->getId() != id) && i != activeTraffic.end()) {
1345         while (i != activeTraffic.end()) {
1346             if (i->getId() == id) {
1347                 break;
1348             }
1349             i++;
1350         }
1351     }
1352 //    // update position of the current aircraft
1353     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1354         SG_LOG(SG_GENERAL, SG_ALERT,
1355                "AI error: updating aircraft without traffic record");
1356     } else {
1357         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1358         current = i;
1359         //cerr << "ApproachController: checking for speed" << endl;
1360         time_t time_diff =
1361             current->getAircraft()->
1362             checkForArrivalTime(string("final001"));
1363         if (time_diff > 15) {
1364             current->setSpeedAdjustment(current->getAircraft()->
1365                                         getPerformance()->vDescent() *
1366                                         1.35);
1367         } else if (time_diff > 5) {
1368             current->setSpeedAdjustment(current->getAircraft()->
1369                                         getPerformance()->vDescent() *
1370                                         1.2);
1371         } else if (time_diff < -15) {
1372             current->setSpeedAdjustment(current->getAircraft()->
1373                                         getPerformance()->vDescent() *
1374                                         0.65);
1375         } else if (time_diff < -5) {
1376             current->setSpeedAdjustment(current->getAircraft()->
1377                                         getPerformance()->vDescent() *
1378                                         0.8);
1379         } else {
1380             current->clearSpeedAdjustment();
1381         }
1382         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1383     }
1384     setDt(getDt() + dt);
1385 }
1386
1387 void FGApproachController::signOff(int id)
1388 {
1389     TrafficVectorIterator i = activeTraffic.begin();
1390     // Search search if the current id alread has an entry
1391     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1392     if (activeTraffic.size()) {
1393         //while ((i->getId() != id) && i != activeTraffic.end()) {
1394         while (i != activeTraffic.end()) {
1395             if (i->getId() == id) {
1396                 break;
1397             }
1398             i++;
1399         }
1400     }
1401     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1402         SG_LOG(SG_GENERAL, SG_ALERT,
1403                "AI error: Aircraft without traffic record is signing off from approach");
1404     } else {
1405         i = activeTraffic.erase(i);
1406     }
1407 }
1408
1409
1410
1411
1412 bool FGApproachController::hasInstruction(int id)
1413 {
1414     TrafficVectorIterator i = activeTraffic.begin();
1415     // Search search if the current id has an entry
1416     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1417     if (activeTraffic.size()) {
1418         //while ((i->getId() != id) && i != activeTraffic.end()) {
1419         while (i != activeTraffic.end()) {
1420             if (i->getId() == id) {
1421                 break;
1422             }
1423             i++;
1424         }
1425     }
1426     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1427         SG_LOG(SG_GENERAL, SG_ALERT,
1428                "AI error: checking ATC instruction for aircraft without traffic record");
1429     } else {
1430         return i->hasInstruction();
1431     }
1432     return false;
1433 }
1434
1435
1436 FGATCInstruction FGApproachController::getInstruction(int id)
1437 {
1438     TrafficVectorIterator i = activeTraffic.begin();
1439     // Search search if the current id has an entry
1440     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1441     if (activeTraffic.size()) {
1442         //while ((i->getId() != id) && i != activeTraffic.end()) {
1443         while (i != activeTraffic.end()) {
1444             if (i->getId() == id) {
1445                 break;
1446             }
1447             i++;
1448         }
1449     }
1450     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1451         SG_LOG(SG_GENERAL, SG_ALERT,
1452                "AI error: requesting ATC instruction for aircraft without traffic record");
1453     } else {
1454         return i->getInstruction();
1455     }
1456     return FGATCInstruction();
1457 }
1458
1459
1460 ActiveRunway *FGApproachController::getRunway(string name)
1461 {
1462     ActiveRunwayVecIterator rwy = activeRunways.begin();
1463     if (activeRunways.size()) {
1464         while (rwy != activeRunways.end()) {
1465             if (rwy->getRunwayName() == name) {
1466                 break;
1467             }
1468             rwy++;
1469         }
1470     }
1471     if (rwy == activeRunways.end()) {
1472         ActiveRunway aRwy(name, 0);
1473         activeRunways.push_back(aRwy);
1474         rwy = activeRunways.end() - 1;
1475     }
1476     return &(*rwy);
1477 }
1478
1479 void FGApproachController::render(bool visible) {
1480     //cerr << "FGApproachController::render function not yet implemented" << endl;
1481 }
1482
1483
1484
1485 string FGApproachController::getName() {
1486     return string(parent->getId() + "-approach");
1487 }