1 // trafficrecord.cxx - Implementation of AIModels ATC code.
3 // Written by Durk Talsma, started September 2006.
5 // Copyright (C) 2006 Durk Talsma.
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.
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.
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.
30 #include <osg/Geometry>
31 #include <osg/MatrixTransform>
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>
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>
53 /***************************************************************************
55 **************************************************************************/
56 time_t ActiveRunway::requestTimeSlot(time_t eta)
59 time_t separation = 90;
61 if (estimatedArrivalTimes.size() == 0) {
62 estimatedArrivalTimes.push_back(eta);
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;
71 i = estimatedArrivalTimes.begin();
72 if ((eta + separation) < (*i)) {
75 //cerr << "Storing at beginning" << endl;
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;
84 newEta = (*i) + separation;
85 //cerr << "Storing at end + separation" << endl;
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
93 //cerr << "Found potential slot after " << (*i) << endl;
94 if (eta > (*i) && (eta < (*j))) {
96 if (eta < ((*i) + separation)) {
97 newEta = (*i) + separation;
98 //cerr << "Using original" << (*i) << " + separation " << endl;
101 //cerr << "Using original after " << (*i) << endl;
103 } else if (eta < (*i)) {
105 newEta = (*i) + separation;
106 //cerr << "Using delayed slot after " << (*i) << endl;
109 if (((*j) - separation) < eta) {
111 if (((*i) + separation) < eta) {
113 cerr << "Using original after " << (*i) << endl;
115 newEta = (*i) + separation;
116 cerr << "Using " << (*i) << " + separation " << endl;
124 //cerr << ". done. New ETA : " << newEta << endl;
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()) {
133 //cerr << "Deleting timestamp " << (*i) << " (now = " << now << "). " << endl;
134 estimatedArrivalTimes.erase(i);
135 i = estimatedArrivalTimes.begin();
143 /***************************************************************************
145 **************************************************************************/
146 FGTrafficRecord::FGTrafficRecord():
147 id(0), waitsForId(0),
152 allowTransmission(true),
153 latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
157 void FGTrafficRecord::setPositionAndIntentions(int pos,
158 FGAIFlightPlan * route)
162 if (intentions.size()) {
163 intVecIterator i = intentions.begin();
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) << " ";
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);
183 if ((val) && (val != pos)) {
184 intentions.push_back(val);
189 //while (route->next(&legNr, &routeNr)) {
190 //intentions.push_back(routeNr);
192 //route->rewind(currentPos);
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.
200 ****************************************************************************/
202 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
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;
210 // else if (other.intentions.size())
212 // cerr << "Start check 2" << endl;
213 // intVecIterator i = other.intentions.begin();
214 // while (!((i == other.intentions.end()) || ((*i) == currentPos)))
216 // if (i != other.intentions.end()) {
217 // cerr << "Check Position and intentions: current matches other.intentions" << endl;
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) {
230 if (i != intentions.end()) {
231 //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
235 //cerr << "Done !!" << endl;
239 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
240 double hdg, double spd,
250 int FGTrafficRecord::crosses(FGGroundNetwork * net,
251 FGTrafficRecord & other)
253 if (checkPositionAndIntentions(other)
254 || (other.checkPositionAndIntentions(*this)))
257 int currentTargetNode = 0, otherTargetNode = 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++) {
267 if ((currentTargetNode ==
268 net->findSegment(*i)->getEnd()->getIndex())) {
269 //cerr << "Current crosses at " << currentTargetNode <<endl;
270 return currentTargetNode;
275 if (other.intentions.size()) {
276 for (i = other.intentions.begin(); i != other.intentions.end();
279 if (otherTargetNode ==
280 net->findSegment(*i)->getEnd()->getIndex()) {
281 //cerr << "Other crosses at " << currentTargetNode <<endl;
282 return otherTargetNode;
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();
291 //cerr << "finding segment " << *i << " and " << *j << endl;
292 if (((*i) > 0) && ((*j) > 0)) {
294 net->findSegment(*i)->getEnd()->getIndex();
296 net->findSegment(*j)->getEnd()->getIndex();
297 if (currentTargetNode == otherTargetNode) {
298 //cerr << "Routes will cross at " << currentTargetNode << endl;
299 return currentTargetNode;
308 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
309 FGTrafficRecord & other)
311 int node = -1, othernode = -1;
313 node = net->findSegment(currentPos)->getEnd()->getIndex();
314 if (other.currentPos > 0)
316 net->findSegment(other.currentPos)->getEnd()->getIndex();
317 if ((node == othernode) && (node != -1))
319 if (other.intentions.size()) {
320 for (intVecIterator i = other.intentions.begin();
321 i != other.intentions.end(); i++) {
323 othernode = net->findSegment(*i)->getEnd()->getIndex();
324 if ((node == othernode) && (node > -1))
329 //if (other.currentPos > 0)
330 // othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
331 //if (intentions.size())
333 // for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
337 // node = net->findSegment(*i)->getEnd()->getIndex();
338 // if ((node == othernode) && (node > -1))
347 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
348 FGTrafficRecord & other, int node)
350 // Check if current segment is the reverse segment for the other aircraft
352 //cerr << "Current segment " << currentPos << endl;
353 if ((currentPos > 0) && (other.currentPos > 0)) {
354 opp = net->findSegment(currentPos)->opposite();
356 if (opp->getIndex() == other.currentPos)
360 for (intVecIterator i = intentions.begin(); i != intentions.end();
362 if ((opp = net->findSegment(other.currentPos)->opposite())) {
364 if (opp->getIndex() ==
365 net->findSegment(*i)->getIndex()) {
366 if (net->findSegment(*i)->getStart()->getIndex() ==
369 //cerr << "Found the node " << node << endl;
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;
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) {
389 //cerr << "Found the node " << node << endl;
403 void FGTrafficRecord::setSpeedAdjustment(double spd)
405 instruction.setChangeSpeed(true);
406 instruction.setSpeed(spd);
409 void FGTrafficRecord::setHeadingAdjustment(double heading)
411 instruction.setChangeHeading(true);
412 instruction.setHeading(heading);
415 bool FGTrafficRecord::pushBackAllowed()
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?
421 double course, az2, dist;
422 SGGeod curr(SGGeod::fromDegM(getLongitude(),
423 getLatitude(), getAltitude()));
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;
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
442 /***************************************************************************
445 **************************************************************************/
446 FGATCInstruction::FGATCInstruction()
449 holdPosition = false;
451 changeHeading = false;
452 changeAltitude = false;
453 resolveCircularWait = false;
461 bool FGATCInstruction::hasInstruction()
463 return (holdPattern || holdPosition || changeSpeed || changeHeading
464 || changeAltitude || resolveCircularWait);
467 /***************************************************************************
470 **************************************************************************/
475 FGATCController::FGATCController()
477 //cerr << "running FGATController constructor" << endl;
480 lastTransmission = 0;
484 FGATCController::~FGATCController()
486 //cerr << "running FGATController destructor" << endl;
489 string FGATCController::getGateName(FGAIAircraft * ref)
491 return ref->atGate();
494 bool FGATCController::isUserAircraft(FGAIAircraft* ac)
496 return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false;
499 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
500 AtcMsgDir msgDir, bool audible)
502 string sender, receiver;
506 string atisInformation;
514 string transponderCode;
517 string instructionText;
520 sender = rec->getAircraft()->getTrafficRef()->getCallSign();
521 if (rec->getAircraft()->getTaxiClearanceRequest()) {
522 instructionText = "push-back and taxi";
524 instructionText = "taxi";
526 //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
527 switch (rec->getLeg()) {
530 freqId = rec->getNextFrequency();
532 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
533 getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
535 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
536 getDynamics()->getGroundFrequency(2);
538 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
539 getName() + "-Ground";
541 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
542 getDynamics()->getAtisSequence();
546 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
547 getName() + "-Tower";
550 // Swap sender and receiver value in case of a ground to air transmission
551 if (msgDir == ATC_GROUND_TO_AIR) {
557 case MSG_ANNOUNCE_ENGINE_START:
558 text = sender + ". Ready to Start up";
560 case MSG_REQUEST_ENGINE_START:
562 receiver + ", This is " + sender + ". Position " +
563 getGateName(rec->getAircraft()) + ". Information " +
564 atisInformation + ". " +
565 rec->getAircraft()->getTrafficRef()->getFlightRules() +
567 rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
568 getName() + ". Request start-up";
570 // Acknowledge engine startup permission
571 // Assign departure runway
572 // Assign SID, if necessery (TODO)
573 case MSG_PERMIT_ENGINE_START:
574 taxiFreqStr = formatATCFrequency3_2(taxiFreq);
576 heading = rec->getAircraft()->getTrafficRef()->getCourse();
577 fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
579 rec->getAircraft()->GetFlightPlan()->
580 getRunwayClassFromTrafficType(fltType);
582 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
583 getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
585 rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
586 fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
587 getDynamics()->getSID(activeRunway, heading);
588 rec->getAircraft()->GetFlightPlan()->setSID(fp);
590 SID = fp->getName() + " departure";
592 SID = "fly runway heading ";
594 //snprintf(buffer, 7, "%3.2f", heading);
595 fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
596 transponderCode = genTransponderCode(fltRules);
597 rec->getAircraft()->SetTransponderCode(transponderCode);
599 receiver + ". Start-up approved. " + atisInformation +
600 " correct, runway " + activeRunway + ", " + SID + ", squawk " +
601 transponderCode + ". " +
602 "For "+ instructionText + " clearance call " + taxiFreqStr + ". " +
603 sender + " control.";
605 case MSG_DENY_ENGINE_START:
606 text = receiver + ". Standby";
608 case MSG_ACKNOWLEDGE_ENGINE_START:
609 fp = rec->getAircraft()->GetFlightPlan()->getSID();
612 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
615 SID = "fly runway heading ";
617 taxiFreqStr = formatATCFrequency3_2(taxiFreq);
618 activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
619 transponderCode = rec->getAircraft()->GetTransponderCode();
622 receiver + ". Start-up approved. " + atisInformation +
623 " correct, runway " + activeRunway + ", " + SID + ", squawk " +
624 transponderCode + ". " +
625 "For " + instructionText + " clearance call " + taxiFreqStr + ". " +
628 case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
629 taxiFreqStr = formatATCFrequency3_2(taxiFreq);
630 text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
632 case MSG_INITIATE_CONTACT:
633 text = receiver + ". With you. " + sender;
635 case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
636 text = receiver + ". Roger. " + sender;
638 case MSG_REQUEST_PUSHBACK_CLEARANCE:
639 if (rec->getAircraft()->getTaxiClearanceRequest()) {
640 text = receiver + ". Request push-back. " + sender;
642 text = receiver + ". Request Taxi clearance. " + sender;
645 case MSG_PERMIT_PUSHBACK_CLEARANCE:
646 if (rec->getAircraft()->getTaxiClearanceRequest()) {
647 text = receiver + ". Push-back approved. " + sender;
649 text = receiver + ". Cleared to Taxi." + sender;
652 case MSG_HOLD_PUSHBACK_CLEARANCE:
653 text = receiver + ". Standby. " + sender;
655 case MSG_REQUEST_TAXI_CLEARANCE:
656 text = receiver + ". Ready to Taxi. " + sender;
658 case MSG_ISSUE_TAXI_CLEARANCE:
659 text = receiver + ". Cleared to taxi. " + sender;
661 case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
662 text = receiver + ". Cleared to taxi. " + sender;
664 case MSG_HOLD_POSITION:
665 text = receiver + ". Hold Position. " + sender;
667 case MSG_ACKNOWLEDGE_HOLD_POSITION:
668 text = receiver + ". Holding Position. " + sender;
670 case MSG_RESUME_TAXI:
671 text = receiver + ". Resume Taxiing. " + sender;
673 case MSG_ACKNOWLEDGE_RESUME_TAXI:
674 text = receiver + ". Continuing Taxi. " + sender;
677 text = text + sender + ". Transmitting unknown Message";
681 double onBoardRadioFreq0 =
682 fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
683 double onBoardRadioFreq1 =
684 fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
685 int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
686 int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
687 //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
689 // Display ATC message only when one of the radios is tuned
690 // the relevant frequency.
691 // Note that distance attenuation is currently not yet implemented
692 if ((onBoardRadioFreqI0 == stationFreq)
693 || (onBoardRadioFreqI1 == stationFreq)) {
694 if (rec->allowTransmissions()) {
695 fgSetString("/sim/messages/atc", text.c_str());
699 FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
700 atc->getATCDialog()->addEntry(1, text);
705 string FGATCController::formatATCFrequency3_2(int freq)
708 snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
709 return string(buffer);
712 // TODO: Set transponder codes according to real-world routes.
713 // The current version just returns a random string of four octal numbers.
714 string FGATCController::genTransponderCode(string fltRules)
716 if (fltRules == "VFR") {
717 return string("1200");
720 snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
722 return string(buffer);
726 void FGATCController::init()
729 FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
730 mgr->addController(this);
735 /***************************************************************************
736 * class FGTowerController
738 **************************************************************************/
739 FGTowerController::FGTowerController(FGAirportDynamics *par) :
746 void FGTowerController::announcePosition(int id,
747 FGAIFlightPlan * intendedRoute,
748 int currentPosition, double lat,
749 double lon, double heading,
750 double speed, double alt,
751 double radius, int leg,
755 TrafficVectorIterator i = activeTraffic.begin();
756 // Search whether the current id alread has an entry
757 // This might be faster using a map instead of a vector, but let's start by taking a safe route
758 if (activeTraffic.size()) {
759 //while ((i->getId() != id) && i != activeTraffic.end()) {
760 while (i != activeTraffic.end()) {
761 if (i->getId() == id) {
767 // Add a new TrafficRecord if no one exsists for this aircraft.
768 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
772 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
773 rec.setRunway(intendedRoute->getRunway());
775 //rec.setCallSign(callsign);
776 rec.setRadius(radius);
777 rec.setAircraft(ref);
778 activeTraffic.push_back(rec);
779 // Don't just schedule the aircraft for the tower controller, also assign if to the correct active runway.
780 ActiveRunwayVecIterator rwy = activeRunways.begin();
781 if (activeRunways.size()) {
782 while (rwy != activeRunways.end()) {
783 if (rwy->getRunwayName() == intendedRoute->getRunway()) {
789 if (rwy == activeRunways.end()) {
790 ActiveRunway aRwy(intendedRoute->getRunway(), id);
791 aRwy.addToDepartureCue(ref);
792 activeRunways.push_back(aRwy);
793 rwy = (activeRunways.end()-1);
795 rwy->addToDepartureCue(ref);
798 cerr << ref->getTrafficRef()->getCallSign() << " You are number " << rwy->getDepartureCueSize() << " for takeoff " << endl;
800 i->setPositionAndHeading(lat, lon, heading, speed, alt);
804 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
805 double heading, double speed, double alt,
808 TrafficVectorIterator i = activeTraffic.begin();
809 // Search whether the current id has an entry
810 // This might be faster using a map instead of a vector, but let's start by taking a safe route
811 TrafficVectorIterator current, closest;
812 if (activeTraffic.size()) {
813 //while ((i->getId() != id) && i != activeTraffic.end()) {
814 while (i != activeTraffic.end()) {
815 if (i->getId() == id) {
821 // // update position of the current aircraft
822 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
823 SG_LOG(SG_GENERAL, SG_ALERT,
824 "AI error: updating aircraft without traffic record");
826 i->setPositionAndHeading(lat, lon, heading, speed, alt);
831 // see if we already have a clearance record for the currently active runway
832 // NOTE: dd. 2011-08-07: Because the active runway has been constructed in the announcePosition function, we may safely assume that is
833 // already exists here. So, we can simplify the current code.
834 ActiveRunwayVecIterator rwy = activeRunways.begin();
835 while (rwy != activeRunways.end()) {
836 if (rwy->getRunwayName() == current->getRunway()) {
842 // only bother running the following code if the current aircraft is the
843 // first in line for depature
844 /* if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
845 if (rwy->getCleared()) {
846 if (id == rwy->getCleared()) {
847 current->setHoldPosition(false);
849 current->setHoldPosition(true);
852 // For now. At later stages, this will probably be the place to check for inbound traffc.
856 // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
857 if (current->getAircraft()->getTakeOffStatus() == 2) {
858 current->setHoldPosition(true);
859 int clearanceId = rwy->getCleared();
861 if (id == clearanceId) {
862 current->setHoldPosition(false);
865 if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
873 void FGTowerController::signOff(int id)
875 TrafficVectorIterator i = activeTraffic.begin();
876 // Search search if the current id alread has an entry
877 // This might be faster using a map instead of a vector, but let's start by taking a safe route
878 if (activeTraffic.size()) {
879 //while ((i->getId() != id) && i != activeTraffic.end()) {
880 while (i != activeTraffic.end()) {
881 if (i->getId() == id) {
887 // If this aircraft has left the runway, we can clear the departure record for this runway
888 ActiveRunwayVecIterator rwy = activeRunways.begin();
889 if (activeRunways.size()) {
890 //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
891 while (rwy != activeRunways.end()) {
892 if (rwy->getRunwayName() == i->getRunway()) {
897 if (rwy != activeRunways.end()) {
899 rwy->updateDepartureCue();
901 SG_LOG(SG_GENERAL, SG_ALERT,
902 "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
905 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
906 SG_LOG(SG_GENERAL, SG_ALERT,
907 "AI error: Aircraft without traffic record is signing off from tower");
909 i->getAircraft()->resetTakeOffStatus();
910 i = activeTraffic.erase(i);
911 //cerr << "Signing off from tower controller" << endl;
916 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
917 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
918 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
919 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
920 // Note that this function is probably obsolete
921 bool FGTowerController::hasInstruction(int id)
923 TrafficVectorIterator i = activeTraffic.begin();
924 // Search search if the current id has an entry
925 // This might be faster using a map instead of a vector, but let's start by taking a safe route
926 if (activeTraffic.size()) {
927 //while ((i->getId() != id) && i != activeTraffic.end()) {
928 while (i != activeTraffic.end()) {
929 if (i->getId() == id) {
935 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
936 SG_LOG(SG_GENERAL, SG_ALERT,
937 "AI error: checking ATC instruction for aircraft without traffic record");
939 return i->hasInstruction();
945 FGATCInstruction FGTowerController::getInstruction(int id)
947 TrafficVectorIterator i = activeTraffic.begin();
948 // Search search if the current id has an entry
949 // This might be faster using a map instead of a vector, but let's start by taking a safe route
950 if (activeTraffic.size()) {
951 //while ((i->getId() != id) && i != activeTraffic.end()) {
952 while (i != activeTraffic.end()) {
953 if (i->getId() == id) {
959 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
960 SG_LOG(SG_GENERAL, SG_ALERT,
961 "AI error: requesting ATC instruction for aircraft without traffic record");
963 return i->getInstruction();
965 return FGATCInstruction();
968 void FGTowerController::render(bool visible) {
969 //cerr << "FGTowerController::render function not yet implemented" << endl;
972 string FGTowerController::getName() {
973 return string(parent->getId() + "-tower");
978 /***************************************************************************
979 * class FGStartupController
981 **************************************************************************/
982 FGStartupController::FGStartupController(FGAirportDynamics *par):
988 void FGStartupController::announcePosition(int id,
989 FGAIFlightPlan * intendedRoute,
990 int currentPosition, double lat,
991 double lon, double heading,
992 double speed, double alt,
993 double radius, int leg,
997 TrafficVectorIterator i = activeTraffic.begin();
998 // Search whether the current id alread has an entry
999 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1000 if (activeTraffic.size()) {
1001 //while ((i->getId() != id) && i != activeTraffic.end()) {
1002 while (i != activeTraffic.end()) {
1003 if (i->getId() == id) {
1009 // Add a new TrafficRecord if no one exsists for this aircraft.
1010 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1011 FGTrafficRecord rec;
1014 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1015 rec.setRunway(intendedRoute->getRunway());
1017 rec.setPositionAndIntentions(currentPosition, intendedRoute);
1018 //rec.setCallSign(callsign);
1019 rec.setAircraft(ref);
1020 rec.setHoldPosition(true);
1021 activeTraffic.push_back(rec);
1023 i->setPositionAndIntentions(currentPosition, intendedRoute);
1024 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1030 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
1031 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
1032 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
1033 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
1034 // Note that this function is probably obsolete
1035 bool FGStartupController::hasInstruction(int id)
1037 TrafficVectorIterator i = activeTraffic.begin();
1038 // Search search if the current id has an entry
1039 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1040 if (activeTraffic.size()) {
1041 //while ((i->getId() != id) && i != activeTraffic.end()) {
1042 while (i != activeTraffic.end()) {
1043 if (i->getId() == id) {
1049 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1050 SG_LOG(SG_GENERAL, SG_ALERT,
1051 "AI error: checking ATC instruction for aircraft without traffic record");
1053 return i->hasInstruction();
1059 FGATCInstruction FGStartupController::getInstruction(int id)
1061 TrafficVectorIterator i = activeTraffic.begin();
1062 // Search search if the current id has an entry
1063 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1064 if (activeTraffic.size()) {
1065 //while ((i->getId() != id) && i != activeTraffic.end()) {
1066 while (i != activeTraffic.end()) {
1067 if (i->getId() == id) {
1073 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1074 SG_LOG(SG_GENERAL, SG_ALERT,
1075 "AI error: requesting ATC instruction for aircraft without traffic record");
1077 return i->getInstruction();
1079 return FGATCInstruction();
1082 void FGStartupController::signOff(int id)
1084 TrafficVectorIterator i = activeTraffic.begin();
1085 // Search search if the current id alread has an entry
1086 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1087 if (activeTraffic.size()) {
1088 //while ((i->getId() != id) && i != activeTraffic.end()) {
1089 while (i != activeTraffic.end()) {
1090 if (i->getId() == id) {
1096 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1097 SG_LOG(SG_GENERAL, SG_ALERT,
1098 "AI error: Aircraft without traffic record is signing off from tower");
1100 //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1101 i = activeTraffic.erase(i);
1105 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1108 int state = i->getState();
1109 if ((state == st) && available) {
1110 if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1112 //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1113 static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1114 int n = trans_num->getIntValue();
1116 trans_num->setIntValue(-1);
1117 // PopupCallback(n);
1118 //cerr << "Selected transmission message " << n << endl;
1119 FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1120 atc->getATCDialog()->removeEntry(1);
1122 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1123 transmit(&(*i), msgId, msgDir, false);
1127 if (now > startTime) {
1128 //cerr << "Transmitting startup msg" << endl;
1129 transmit(&(*i), msgId, msgDir, true);
1131 lastTransmission = now;
1139 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1140 double heading, double speed, double alt,
1143 TrafficVectorIterator i = activeTraffic.begin();
1144 // Search search if the current id has an entry
1145 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1146 TrafficVectorIterator current, closest;
1147 if (activeTraffic.size()) {
1148 //while ((i->getId() != id) && i != activeTraffic.end()) {
1149 while (i != activeTraffic.end()) {
1150 if (i->getId() == id) {
1156 // // update position of the current aircraft
1158 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1159 SG_LOG(SG_GENERAL, SG_ALERT,
1160 "AI error: updating aircraft without traffic record");
1162 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1165 setDt(getDt() + dt);
1167 int state = i->getState();
1169 // The user controlled aircraft should have crased here, because it doesn't have a traffic reference.
1170 // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1171 time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1172 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1173 //cerr << i->getAircraft()->getTrafficRef()->getCallSign()
1174 // << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1175 // << " at parking " << getGateName(i->getAircraft()) << endl;
1177 if ((now - lastTransmission) > 3 + (rand() % 15)) {
1181 checkTransmissionState(0, now, (startTime + 0 ), i, MSG_ANNOUNCE_ENGINE_START, ATC_AIR_TO_GROUND);
1182 checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START, ATC_AIR_TO_GROUND);
1183 checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START, ATC_GROUND_TO_AIR);
1184 checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START, ATC_AIR_TO_GROUND);
1185 if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY, ATC_AIR_TO_GROUND)) {
1188 checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT, ATC_AIR_TO_GROUND);
1189 checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT, ATC_GROUND_TO_AIR);
1190 checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE, ATC_AIR_TO_GROUND);
1194 if ((state == 8) && available) {
1195 if (now > startTime + 200) {
1196 if (i->pushBackAllowed()) {
1197 i->allowRepeatedTransmissions();
1198 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1199 ATC_GROUND_TO_AIR, true);
1202 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1203 ATC_GROUND_TO_AIR, true);
1204 i->suppressRepeatedTransmissions();
1206 lastTransmission = now;
1210 if ((state == 9) && available) {
1211 i->setHoldPosition(false);
1215 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1216 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1217 double lon, double elev, double hdg)
1219 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1220 obj_pos = geod.makeZUpFrame();
1221 // hdg is not a compass heading, but a counter-clockwise rotation
1222 // around the Z axis
1223 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1228 void FGStartupController::render(bool visible)
1231 SGMaterialLib *matlib = globals->get_matlib();
1234 globals->get_scenery()->get_scene_graph()->removeChild(group);
1235 //while (group->getNumChildren()) {
1236 // cerr << "Number of children: " << group->getNumChildren() << endl;
1237 simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1238 //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1239 //geode->releaseGLObjects();
1240 //group->removeChild(geode);
1245 group = new osg::Group;
1247 //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1249 for (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1250 // Handle start point
1251 int pos = i->getCurrentPosition();
1252 //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1254 FGTaxiSegment *segment = parent->getGroundNetwork()->findSegment(pos);
1255 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1256 SGGeod end (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1258 double length = SGGeodesy::distanceM(start, end);
1259 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1261 double az2, heading; //, distanceM;
1262 SGGeodesy::inverse(start, end, heading, az2, length);
1263 double coveredDistance = length * 0.5;
1265 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1266 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1267 ///////////////////////////////////////////////////////////////////////////////
1268 // Make a helper function out of this
1269 osg::Matrix obj_pos;
1270 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1271 obj_trans->setDataVariance(osg::Object::STATIC);
1273 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1275 obj_trans->setMatrix( obj_pos );
1276 //osg::Vec3 center(0, 0, 0)
1278 float width = length /2.0;
1279 osg::Vec3 corner(-width, 0, 0.25f);
1280 osg::Vec3 widthVec(2*width + 1, 0, 0);
1281 osg::Vec3 heightVec(0, 1, 0);
1282 osg::Geometry* geometry;
1283 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1284 simgear::EffectGeode* geode = new simgear::EffectGeode;
1285 geode->setName("test");
1286 geode->addDrawable(geometry);
1287 //osg::Node *custom_obj;
1288 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1290 geode->setEffect(mat->get_effect());
1291 obj_trans->addChild(geode);
1292 // wire as much of the scene graph together as we can
1293 //->addChild( obj_trans );
1294 group->addChild( obj_trans );
1295 /////////////////////////////////////////////////////////////////////
1297 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1299 for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1300 osg::Matrix obj_pos;
1303 //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1304 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1305 obj_trans->setDataVariance(osg::Object::STATIC);
1306 FGTaxiSegment *segment = parent->getGroundNetwork()->findSegment(k);
1307 WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1309 obj_trans->setMatrix( obj_pos );
1310 //osg::Vec3 center(0, 0, 0)
1312 float width = segment->getLength() /2.0;
1313 osg::Vec3 corner(-width, 0, 0.25f);
1314 osg::Vec3 widthVec(2*width + 1, 0, 0);
1315 osg::Vec3 heightVec(0, 1, 0);
1316 osg::Geometry* geometry;
1317 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1318 simgear::EffectGeode* geode = new simgear::EffectGeode;
1319 geode->setName("test");
1320 geode->addDrawable(geometry);
1321 //osg::Node *custom_obj;
1322 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1324 geode->setEffect(mat->get_effect());
1325 obj_trans->addChild(geode);
1326 // wire as much of the scene graph together as we can
1327 //->addChild( obj_trans );
1328 group->addChild( obj_trans );
1330 //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1335 globals->get_scenery()->get_scene_graph()->addChild(group);
1339 string FGStartupController::getName() {
1340 return string(parent->getId() + "-startup");
1344 /***************************************************************************
1345 * class FGApproachController
1347 **************************************************************************/
1348 FGApproachController::FGApproachController(FGAirportDynamics *par):
1355 void FGApproachController::announcePosition(int id,
1356 FGAIFlightPlan * intendedRoute,
1357 int currentPosition,
1358 double lat, double lon,
1359 double heading, double speed,
1360 double alt, double radius,
1361 int leg, FGAIAircraft * ref)
1364 TrafficVectorIterator i = activeTraffic.begin();
1365 // Search whether the current id alread has an entry
1366 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1367 if (activeTraffic.size()) {
1368 //while ((i->getId() != id) && i != activeTraffic.end()) {
1369 while (i != activeTraffic.end()) {
1370 if (i->getId() == id) {
1376 // Add a new TrafficRecord if no one exsists for this aircraft.
1377 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1378 FGTrafficRecord rec;
1381 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1382 rec.setRunway(intendedRoute->getRunway());
1384 //rec.setCallSign(callsign);
1385 rec.setAircraft(ref);
1386 activeTraffic.push_back(rec);
1388 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1392 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1393 double heading, double speed, double alt,
1396 TrafficVectorIterator i = activeTraffic.begin();
1397 // Search search if the current id has an entry
1398 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1399 TrafficVectorIterator current, closest;
1400 if (activeTraffic.size()) {
1401 //while ((i->getId() != id) && i != activeTraffic.end()) {
1402 while (i != activeTraffic.end()) {
1403 if (i->getId() == id) {
1409 // // update position of the current aircraft
1410 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1411 SG_LOG(SG_GENERAL, SG_ALERT,
1412 "AI error: updating aircraft without traffic record");
1414 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1416 //cerr << "ApproachController: checking for speed" << endl;
1418 current->getAircraft()->
1419 checkForArrivalTime(string("final001"));
1420 if (time_diff > 15) {
1421 current->setSpeedAdjustment(current->getAircraft()->
1422 getPerformance()->vDescent() *
1424 } else if (time_diff > 5) {
1425 current->setSpeedAdjustment(current->getAircraft()->
1426 getPerformance()->vDescent() *
1428 } else if (time_diff < -15) {
1429 current->setSpeedAdjustment(current->getAircraft()->
1430 getPerformance()->vDescent() *
1432 } else if (time_diff < -5) {
1433 current->setSpeedAdjustment(current->getAircraft()->
1434 getPerformance()->vDescent() *
1437 current->clearSpeedAdjustment();
1439 //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1441 setDt(getDt() + dt);
1444 void FGApproachController::signOff(int id)
1446 TrafficVectorIterator i = activeTraffic.begin();
1447 // Search search if the current id alread has an entry
1448 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1449 if (activeTraffic.size()) {
1450 //while ((i->getId() != id) && i != activeTraffic.end()) {
1451 while (i != activeTraffic.end()) {
1452 if (i->getId() == id) {
1458 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1459 SG_LOG(SG_GENERAL, SG_ALERT,
1460 "AI error: Aircraft without traffic record is signing off from approach");
1462 i = activeTraffic.erase(i);
1469 bool FGApproachController::hasInstruction(int id)
1471 TrafficVectorIterator i = activeTraffic.begin();
1472 // Search search if the current id has an entry
1473 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1474 if (activeTraffic.size()) {
1475 //while ((i->getId() != id) && i != activeTraffic.end()) {
1476 while (i != activeTraffic.end()) {
1477 if (i->getId() == id) {
1483 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1484 SG_LOG(SG_GENERAL, SG_ALERT,
1485 "AI error: checking ATC instruction for aircraft without traffic record");
1487 return i->hasInstruction();
1493 FGATCInstruction FGApproachController::getInstruction(int id)
1495 TrafficVectorIterator i = activeTraffic.begin();
1496 // Search search if the current id has an entry
1497 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1498 if (activeTraffic.size()) {
1499 //while ((i->getId() != id) && i != activeTraffic.end()) {
1500 while (i != activeTraffic.end()) {
1501 if (i->getId() == id) {
1507 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1508 SG_LOG(SG_GENERAL, SG_ALERT,
1509 "AI error: requesting ATC instruction for aircraft without traffic record");
1511 return i->getInstruction();
1513 return FGATCInstruction();
1517 ActiveRunway *FGApproachController::getRunway(string name)
1519 ActiveRunwayVecIterator rwy = activeRunways.begin();
1520 if (activeRunways.size()) {
1521 while (rwy != activeRunways.end()) {
1522 if (rwy->getRunwayName() == name) {
1528 if (rwy == activeRunways.end()) {
1529 ActiveRunway aRwy(name, 0);
1530 activeRunways.push_back(aRwy);
1531 rwy = activeRunways.end() - 1;
1536 void FGApproachController::render(bool visible) {
1537 //cerr << "FGApproachController::render function not yet implemented" << endl;
1542 string FGApproachController::getName() {
1543 return string(parent->getId() + "-approach");