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 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
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;
205 // else if (other.intentions.size())
207 // cerr << "Start check 2" << endl;
208 // intVecIterator i = other.intentions.begin();
209 // while (!((i == other.intentions.end()) || ((*i) == currentPos)))
211 // if (i != other.intentions.end()) {
212 // cerr << "Check Position and intentions: current matches other.intentions" << endl;
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) {
225 if (i != intentions.end()) {
226 //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
230 //cerr << "Done !!" << endl;
234 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
235 double hdg, double spd,
245 int FGTrafficRecord::crosses(FGGroundNetwork * net,
246 FGTrafficRecord & other)
248 if (checkPositionAndIntentions(other)
249 || (other.checkPositionAndIntentions(*this)))
252 int currentTargetNode = 0, otherTargetNode = 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++) {
262 if ((currentTargetNode ==
263 net->findSegment(*i)->getEnd()->getIndex())) {
264 //cerr << "Current crosses at " << currentTargetNode <<endl;
265 return currentTargetNode;
270 if (other.intentions.size()) {
271 for (i = other.intentions.begin(); i != other.intentions.end();
274 if (otherTargetNode ==
275 net->findSegment(*i)->getEnd()->getIndex()) {
276 //cerr << "Other crosses at " << currentTargetNode <<endl;
277 return otherTargetNode;
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();
286 //cerr << "finding segment " << *i << " and " << *j << endl;
287 if (((*i) > 0) && ((*j) > 0)) {
289 net->findSegment(*i)->getEnd()->getIndex();
291 net->findSegment(*j)->getEnd()->getIndex();
292 if (currentTargetNode == otherTargetNode) {
293 //cerr << "Routes will cross at " << currentTargetNode << endl;
294 return currentTargetNode;
303 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
304 FGTrafficRecord & other)
306 int node = -1, othernode = -1;
308 node = net->findSegment(currentPos)->getEnd()->getIndex();
309 if (other.currentPos > 0)
311 net->findSegment(other.currentPos)->getEnd()->getIndex();
312 if ((node == othernode) && (node != -1))
314 if (other.intentions.size()) {
315 for (intVecIterator i = other.intentions.begin();
316 i != other.intentions.end(); i++) {
318 othernode = net->findSegment(*i)->getEnd()->getIndex();
319 if ((node == othernode) && (node > -1))
324 //if (other.currentPos > 0)
325 // othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
326 //if (intentions.size())
328 // for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
332 // node = net->findSegment(*i)->getEnd()->getIndex();
333 // if ((node == othernode) && (node > -1))
342 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
343 FGTrafficRecord & other, int node)
345 // Check if current segment is the reverse segment for the other aircraft
347 //cerr << "Current segment " << currentPos << endl;
348 if ((currentPos > 0) && (other.currentPos > 0)) {
349 opp = net->findSegment(currentPos)->opposite();
351 if (opp->getIndex() == other.currentPos)
355 for (intVecIterator i = intentions.begin(); i != intentions.end();
357 if ((opp = net->findSegment(other.currentPos)->opposite())) {
359 if (opp->getIndex() ==
360 net->findSegment(*i)->getIndex()) {
361 if (net->findSegment(*i)->getStart()->getIndex() ==
364 //cerr << "Found the node " << node << endl;
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;
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) {
384 //cerr << "Found the node " << node << endl;
398 void FGTrafficRecord::setSpeedAdjustment(double spd)
400 instruction.setChangeSpeed(true);
401 instruction.setSpeed(spd);
404 void FGTrafficRecord::setHeadingAdjustment(double heading)
406 instruction.setChangeHeading(true);
407 instruction.setHeading(heading);
410 bool FGTrafficRecord::pushBackAllowed()
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?
416 double course, az2, dist;
417 SGGeod curr(SGGeod::fromDegM(getLongitude(),
418 getLatitude(), getAltitude()));
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;
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
437 /***************************************************************************
440 **************************************************************************/
441 FGATCInstruction::FGATCInstruction()
444 holdPosition = false;
446 changeHeading = false;
447 changeAltitude = false;
448 resolveCircularWait = false;
456 bool FGATCInstruction::hasInstruction()
458 return (holdPattern || holdPosition || changeSpeed || changeHeading
459 || changeAltitude || resolveCircularWait);
462 /***************************************************************************
465 **************************************************************************/
470 FGATCController::FGATCController()
472 //cerr << "running FGATController constructor" << endl;
475 lastTransmission = 0;
479 FGATCController::~FGATCController()
481 //cerr << "running FGATController destructor" << endl;
484 string FGATCController::getGateName(FGAIAircraft * ref)
486 return ref->atGate();
489 bool FGATCController::isUserAircraft(FGAIAircraft* ac)
491 return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false;
494 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
495 AtcMsgDir msgDir, bool audible)
497 string sender, receiver;
501 string atisInformation;
509 string transponderCode;
514 sender = rec->getAircraft()->getTrafficRef()->getCallSign();
515 //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
516 switch (rec->getLeg()) {
519 freqId = rec->getNextFrequency();
521 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
522 getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
524 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
525 getDynamics()->getGroundFrequency(2);
527 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
528 getName() + "-Ground";
530 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
531 getDynamics()->getAtisSequence();
535 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
536 getName() + "-Tower";
539 // Swap sender and receiver value in case of a ground to air transmission
540 if (msgDir == ATC_GROUND_TO_AIR) {
546 case MSG_ANNOUNCE_ENGINE_START:
547 text = sender + ". Ready to Start up";
549 case MSG_REQUEST_ENGINE_START:
551 receiver + ", This is " + sender + ". Position " +
552 getGateName(rec->getAircraft()) + ". Information " +
553 atisInformation + ". " +
554 rec->getAircraft()->getTrafficRef()->getFlightRules() +
556 rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
557 getName() + ". Request start-up";
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);
565 heading = rec->getAircraft()->getTrafficRef()->getCourse();
566 fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
568 rec->getAircraft()->GetFlightPlan()->
569 getRunwayClassFromTrafficType(fltType);
571 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
572 getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
574 rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
575 fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
576 getDynamics()->getSID(activeRunway, heading);
577 rec->getAircraft()->GetFlightPlan()->setSID(fp);
579 SID = fp->getName() + " departure";
581 SID = "fly runway heading ";
583 //snprintf(buffer, 7, "%3.2f", heading);
584 fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
585 transponderCode = genTransponderCode(fltRules);
586 rec->getAircraft()->SetTransponderCode(transponderCode);
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.";
594 case MSG_DENY_ENGINE_START:
595 text = receiver + ". Standby";
597 case MSG_ACKNOWLEDGE_ENGINE_START:
598 fp = rec->getAircraft()->GetFlightPlan()->getSID();
601 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
604 SID = "fly runway heading ";
606 taxiFreqStr = formatATCFrequency3_2(taxiFreq);
607 activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
608 transponderCode = rec->getAircraft()->GetTransponderCode();
610 receiver + ". Start-up approved. " + atisInformation +
611 " correct, runway " + activeRunway + ", " + SID + ", squawk " +
612 transponderCode + ". " +
613 "For push-back and taxi clearance call " + taxiFreqStr + ". " +
616 case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
617 taxiFreqStr = formatATCFrequency3_2(taxiFreq);
618 text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
620 case MSG_INITIATE_CONTACT:
621 text = receiver + ". With you. " + sender;
623 case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
624 text = receiver + ". Roger. " + sender;
626 case MSG_REQUEST_PUSHBACK_CLEARANCE:
627 text = receiver + ". Request push-back. " + sender;
629 case MSG_PERMIT_PUSHBACK_CLEARANCE:
630 text = receiver + ". Push-back approved. " + sender;
632 case MSG_HOLD_PUSHBACK_CLEARANCE:
633 text = receiver + ". Standby. " + sender;
635 case MSG_REQUEST_TAXI_CLEARANCE:
636 text = receiver + ". Ready to Taxi. " + sender;
638 case MSG_ISSUE_TAXI_CLEARANCE:
639 text = receiver + ". Cleared to taxi. " + sender;
641 case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
642 text = receiver + ". Cleared to taxi. " + sender;
644 case MSG_HOLD_POSITION:
645 text = receiver + ". Hold Position. " + sender;
647 case MSG_ACKNOWLEDGE_HOLD_POSITION:
648 text = receiver + ". Holding Position. " + sender;
650 case MSG_RESUME_TAXI:
651 text = receiver + ". Resume Taxiing. " + sender;
653 case MSG_ACKNOWLEDGE_RESUME_TAXI:
654 text = receiver + ". Continuing Taxi. " + sender;
657 text = text + sender + ". Transmitting unknown Message";
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;
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());
679 FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
680 atc->getATCDialog()->addEntry(1, text);
685 string FGATCController::formatATCFrequency3_2(int freq)
688 snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
689 return string(buffer);
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)
696 if (fltRules == "VFR") {
697 return string("1200");
700 snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
702 return string(buffer);
706 void FGATCController::init()
709 FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
710 mgr->addController(this);
715 /***************************************************************************
716 * class FGTowerController
718 **************************************************************************/
719 FGTowerController::FGTowerController(FGAirportDynamics *par) :
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,
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) {
747 // Add a new TrafficRecord if no one exsists for this aircraft.
748 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
752 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
753 rec.setRunway(intendedRoute->getRunway());
755 //rec.setCallSign(callsign);
756 rec.setAircraft(ref);
757 activeTraffic.push_back(rec);
758 cerr << ref->getTrafficRef()->getCallSign() << " You are number " << activeTraffic.size() << " for takeoff " << endl;
760 i->setPositionAndHeading(lat, lon, heading, speed, alt);
764 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
765 double heading, double speed, double alt,
768 TrafficVectorIterator i = activeTraffic.begin();
769 // Search whether the current id has an entry
770 // This might be faster using a map instead of a vector, but let's start by taking a safe route
771 TrafficVectorIterator current, closest;
772 if (activeTraffic.size()) {
773 //while ((i->getId() != id) && i != activeTraffic.end()) {
774 while (i != activeTraffic.end()) {
775 if (i->getId() == id) {
781 // // update position of the current aircraft
782 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
783 SG_LOG(SG_GENERAL, SG_ALERT,
784 "AI error: updating aircraft without traffic record");
786 i->setPositionAndHeading(lat, lon, heading, speed, alt);
791 // // see if we already have a clearance record for the currently active runway
792 ActiveRunwayVecIterator rwy = activeRunways.begin();
793 // again, a map might be more efficient here
794 if (activeRunways.size()) {
795 //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
796 while (rwy != activeRunways.end()) {
797 if (rwy->getRunwayName() == current->getRunway()) {
803 if (rwy == activeRunways.end()) {
804 ActiveRunway aRwy(current->getRunway(), id);
805 activeRunways.push_back(aRwy); // Since there are no clearance records for this runway yet
806 current->setHoldPosition(false); // Clear the current aircraft to continue
808 // Okay, we have a clearance record for this runway, so check
809 // whether the clearence ID matches that of the current aircraft
810 if (id == rwy->getCleared()) {
811 current->setHoldPosition(false);
813 current->setHoldPosition(true);
819 void FGTowerController::signOff(int id)
821 TrafficVectorIterator i = activeTraffic.begin();
822 // Search search if the current id alread has an entry
823 // This might be faster using a map instead of a vector, but let's start by taking a safe route
824 if (activeTraffic.size()) {
825 //while ((i->getId() != id) && i != activeTraffic.end()) {
826 while (i != activeTraffic.end()) {
827 if (i->getId() == id) {
833 // If this aircraft has left the runway, we can clear the departure record for this runway
834 ActiveRunwayVecIterator rwy = activeRunways.begin();
835 if (activeRunways.size()) {
836 //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
837 while (rwy != activeRunways.end()) {
838 if (rwy->getRunwayName() == i->getRunway()) {
843 if (rwy != activeRunways.end()) {
844 rwy = activeRunways.erase(rwy);
846 SG_LOG(SG_GENERAL, SG_ALERT,
847 "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
850 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
851 SG_LOG(SG_GENERAL, SG_ALERT,
852 "AI error: Aircraft without traffic record is signing off from tower");
854 i = activeTraffic.erase(i);
855 //cerr << "Signing off from tower controller" << endl;
860 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
861 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
862 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
863 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
864 // Note that this function is probably obsolete
865 bool FGTowerController::hasInstruction(int id)
867 TrafficVectorIterator i = activeTraffic.begin();
868 // Search search if the current id has an entry
869 // This might be faster using a map instead of a vector, but let's start by taking a safe route
870 if (activeTraffic.size()) {
871 //while ((i->getId() != id) && i != activeTraffic.end()) {
872 while (i != activeTraffic.end()) {
873 if (i->getId() == id) {
879 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
880 SG_LOG(SG_GENERAL, SG_ALERT,
881 "AI error: checking ATC instruction for aircraft without traffic record");
883 return i->hasInstruction();
889 FGATCInstruction FGTowerController::getInstruction(int id)
891 TrafficVectorIterator i = activeTraffic.begin();
892 // Search search if the current id has an entry
893 // This might be faster using a map instead of a vector, but let's start by taking a safe route
894 if (activeTraffic.size()) {
895 //while ((i->getId() != id) && i != activeTraffic.end()) {
896 while (i != activeTraffic.end()) {
897 if (i->getId() == id) {
903 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
904 SG_LOG(SG_GENERAL, SG_ALERT,
905 "AI error: requesting ATC instruction for aircraft without traffic record");
907 return i->getInstruction();
909 return FGATCInstruction();
912 void FGTowerController::render(bool visible) {
913 //cerr << "FGTowerController::render function not yet implemented" << endl;
916 string FGTowerController::getName() {
917 return string(parent->getId() + "-tower");
922 /***************************************************************************
923 * class FGStartupController
925 **************************************************************************/
926 FGStartupController::FGStartupController(FGAirportDynamics *par):
932 void FGStartupController::announcePosition(int id,
933 FGAIFlightPlan * intendedRoute,
934 int currentPosition, double lat,
935 double lon, double heading,
936 double speed, double alt,
937 double radius, int leg,
941 TrafficVectorIterator i = activeTraffic.begin();
942 // Search whether the current id alread has an entry
943 // This might be faster using a map instead of a vector, but let's start by taking a safe route
944 if (activeTraffic.size()) {
945 //while ((i->getId() != id) && i != activeTraffic.end()) {
946 while (i != activeTraffic.end()) {
947 if (i->getId() == id) {
953 // Add a new TrafficRecord if no one exsists for this aircraft.
954 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
958 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
959 rec.setRunway(intendedRoute->getRunway());
961 rec.setPositionAndIntentions(currentPosition, intendedRoute);
962 //rec.setCallSign(callsign);
963 rec.setAircraft(ref);
964 rec.setHoldPosition(true);
965 activeTraffic.push_back(rec);
967 i->setPositionAndIntentions(currentPosition, intendedRoute);
968 i->setPositionAndHeading(lat, lon, heading, speed, alt);
974 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
975 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
976 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
977 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
978 // Note that this function is probably obsolete
979 bool FGStartupController::hasInstruction(int id)
981 TrafficVectorIterator i = activeTraffic.begin();
982 // Search search if the current id has an entry
983 // This might be faster using a map instead of a vector, but let's start by taking a safe route
984 if (activeTraffic.size()) {
985 //while ((i->getId() != id) && i != activeTraffic.end()) {
986 while (i != activeTraffic.end()) {
987 if (i->getId() == id) {
993 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
994 SG_LOG(SG_GENERAL, SG_ALERT,
995 "AI error: checking ATC instruction for aircraft without traffic record");
997 return i->hasInstruction();
1003 FGATCInstruction FGStartupController::getInstruction(int id)
1005 TrafficVectorIterator i = activeTraffic.begin();
1006 // Search search if the current id has an entry
1007 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1008 if (activeTraffic.size()) {
1009 //while ((i->getId() != id) && i != activeTraffic.end()) {
1010 while (i != activeTraffic.end()) {
1011 if (i->getId() == id) {
1017 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1018 SG_LOG(SG_GENERAL, SG_ALERT,
1019 "AI error: requesting ATC instruction for aircraft without traffic record");
1021 return i->getInstruction();
1023 return FGATCInstruction();
1026 void FGStartupController::signOff(int id)
1028 TrafficVectorIterator i = activeTraffic.begin();
1029 // Search search if the current id alread has an entry
1030 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1031 if (activeTraffic.size()) {
1032 //while ((i->getId() != id) && i != activeTraffic.end()) {
1033 while (i != activeTraffic.end()) {
1034 if (i->getId() == id) {
1040 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1041 SG_LOG(SG_GENERAL, SG_ALERT,
1042 "AI error: Aircraft without traffic record is signing off from tower");
1044 //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1045 i = activeTraffic.erase(i);
1049 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1052 int state = i->getState();
1053 if ((state == st) && available) {
1054 if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1056 //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1057 static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1058 int n = trans_num->getIntValue();
1060 trans_num->setIntValue(-1);
1061 // PopupCallback(n);
1062 //cerr << "Selected transmission message " << n << endl;
1063 FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1064 atc->getATCDialog()->removeEntry(1);
1066 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1067 transmit(&(*i), msgId, msgDir, false);
1071 if (now > startTime) {
1072 //cerr << "Transmitting startup msg" << endl;
1073 transmit(&(*i), msgId, msgDir, true);
1075 lastTransmission = now;
1083 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1084 double heading, double speed, double alt,
1087 TrafficVectorIterator i = activeTraffic.begin();
1088 // Search search if the current id has an entry
1089 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1090 TrafficVectorIterator current, closest;
1091 if (activeTraffic.size()) {
1092 //while ((i->getId() != id) && i != activeTraffic.end()) {
1093 while (i != activeTraffic.end()) {
1094 if (i->getId() == id) {
1100 // // update position of the current aircraft
1102 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1103 SG_LOG(SG_GENERAL, SG_ALERT,
1104 "AI error: updating aircraft without traffic record");
1106 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1109 setDt(getDt() + dt);
1111 int state = i->getState();
1113 // The user controlled aircraft should have crased here, because it doesn't have a traffic reference.
1114 // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1115 time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1116 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1117 //cerr << i->getAircraft()->getTrafficRef()->getCallSign()
1118 // << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1119 // << " at parking " << getGateName(i->getAircraft()) << endl;
1121 if ((now - lastTransmission) > 3 + (rand() % 15)) {
1125 checkTransmissionState(0, now, (startTime + 0 ), i, MSG_ANNOUNCE_ENGINE_START, ATC_AIR_TO_GROUND);
1126 checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START, ATC_AIR_TO_GROUND);
1127 checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START, ATC_GROUND_TO_AIR);
1128 checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START, ATC_AIR_TO_GROUND);
1129 if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY, ATC_AIR_TO_GROUND)) {
1132 checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT, ATC_AIR_TO_GROUND);
1133 checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT, ATC_GROUND_TO_AIR);
1134 checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE, ATC_AIR_TO_GROUND);
1138 if ((state == 8) && available) {
1139 if (now > startTime + 200) {
1140 if (i->pushBackAllowed()) {
1141 i->allowRepeatedTransmissions();
1142 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1143 ATC_GROUND_TO_AIR, true);
1146 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1147 ATC_GROUND_TO_AIR, true);
1148 i->suppressRepeatedTransmissions();
1150 lastTransmission = now;
1154 if ((state == 9) && available) {
1155 i->setHoldPosition(false);
1159 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1160 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1161 double lon, double elev, double hdg)
1163 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1164 obj_pos = geod.makeZUpFrame();
1165 // hdg is not a compass heading, but a counter-clockwise rotation
1166 // around the Z axis
1167 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1172 void FGStartupController::render(bool visible)
1175 SGMaterialLib *matlib = globals->get_matlib();
1178 globals->get_scenery()->get_scene_graph()->removeChild(group);
1179 //while (group->getNumChildren()) {
1180 // cerr << "Number of children: " << group->getNumChildren() << endl;
1181 simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1182 //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1183 //geode->releaseGLObjects();
1184 //group->removeChild(geode);
1189 group = new osg::Group;
1191 //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1193 for (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1194 // Handle start point
1195 int pos = i->getCurrentPosition();
1196 //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1198 FGTaxiSegment *segment = parent->getGroundNetwork()->findSegment(pos);
1199 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1200 SGGeod end (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1202 double length = SGGeodesy::distanceM(start, end);
1203 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1205 double az2, heading; //, distanceM;
1206 SGGeodesy::inverse(start, end, heading, az2, length);
1207 double coveredDistance = length * 0.5;
1209 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1210 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1211 ///////////////////////////////////////////////////////////////////////////////
1212 // Make a helper function out of this
1213 osg::Matrix obj_pos;
1214 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1215 obj_trans->setDataVariance(osg::Object::STATIC);
1217 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1219 obj_trans->setMatrix( obj_pos );
1220 //osg::Vec3 center(0, 0, 0)
1222 float width = length /2.0;
1223 osg::Vec3 corner(-width, 0, 0.25f);
1224 osg::Vec3 widthVec(2*width + 1, 0, 0);
1225 osg::Vec3 heightVec(0, 1, 0);
1226 osg::Geometry* geometry;
1227 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1228 simgear::EffectGeode* geode = new simgear::EffectGeode;
1229 geode->setName("test");
1230 geode->addDrawable(geometry);
1231 //osg::Node *custom_obj;
1232 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1234 geode->setEffect(mat->get_effect());
1235 obj_trans->addChild(geode);
1236 // wire as much of the scene graph together as we can
1237 //->addChild( obj_trans );
1238 group->addChild( obj_trans );
1239 /////////////////////////////////////////////////////////////////////
1241 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1243 for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1244 osg::Matrix obj_pos;
1247 //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1248 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1249 obj_trans->setDataVariance(osg::Object::STATIC);
1250 FGTaxiSegment *segment = parent->getGroundNetwork()->findSegment(k);
1251 WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1253 obj_trans->setMatrix( obj_pos );
1254 //osg::Vec3 center(0, 0, 0)
1256 float width = segment->getLength() /2.0;
1257 osg::Vec3 corner(-width, 0, 0.25f);
1258 osg::Vec3 widthVec(2*width + 1, 0, 0);
1259 osg::Vec3 heightVec(0, 1, 0);
1260 osg::Geometry* geometry;
1261 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1262 simgear::EffectGeode* geode = new simgear::EffectGeode;
1263 geode->setName("test");
1264 geode->addDrawable(geometry);
1265 //osg::Node *custom_obj;
1266 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1268 geode->setEffect(mat->get_effect());
1269 obj_trans->addChild(geode);
1270 // wire as much of the scene graph together as we can
1271 //->addChild( obj_trans );
1272 group->addChild( obj_trans );
1274 //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1279 globals->get_scenery()->get_scene_graph()->addChild(group);
1283 string FGStartupController::getName() {
1284 return string(parent->getId() + "-startup");
1288 /***************************************************************************
1289 * class FGApproachController
1291 **************************************************************************/
1292 FGApproachController::FGApproachController(FGAirportDynamics *par):
1299 void FGApproachController::announcePosition(int id,
1300 FGAIFlightPlan * intendedRoute,
1301 int currentPosition,
1302 double lat, double lon,
1303 double heading, double speed,
1304 double alt, double radius,
1305 int leg, FGAIAircraft * ref)
1308 TrafficVectorIterator i = activeTraffic.begin();
1309 // Search whether the current id alread has an entry
1310 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1311 if (activeTraffic.size()) {
1312 //while ((i->getId() != id) && i != activeTraffic.end()) {
1313 while (i != activeTraffic.end()) {
1314 if (i->getId() == id) {
1320 // Add a new TrafficRecord if no one exsists for this aircraft.
1321 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1322 FGTrafficRecord rec;
1325 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1326 rec.setRunway(intendedRoute->getRunway());
1328 //rec.setCallSign(callsign);
1329 rec.setAircraft(ref);
1330 activeTraffic.push_back(rec);
1332 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1336 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1337 double heading, double speed, double alt,
1340 TrafficVectorIterator i = activeTraffic.begin();
1341 // Search search if the current id has an entry
1342 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1343 TrafficVectorIterator current, closest;
1344 if (activeTraffic.size()) {
1345 //while ((i->getId() != id) && i != activeTraffic.end()) {
1346 while (i != activeTraffic.end()) {
1347 if (i->getId() == id) {
1353 // // update position of the current aircraft
1354 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1355 SG_LOG(SG_GENERAL, SG_ALERT,
1356 "AI error: updating aircraft without traffic record");
1358 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1360 //cerr << "ApproachController: checking for speed" << endl;
1362 current->getAircraft()->
1363 checkForArrivalTime(string("final001"));
1364 if (time_diff > 15) {
1365 current->setSpeedAdjustment(current->getAircraft()->
1366 getPerformance()->vDescent() *
1368 } else if (time_diff > 5) {
1369 current->setSpeedAdjustment(current->getAircraft()->
1370 getPerformance()->vDescent() *
1372 } else if (time_diff < -15) {
1373 current->setSpeedAdjustment(current->getAircraft()->
1374 getPerformance()->vDescent() *
1376 } else if (time_diff < -5) {
1377 current->setSpeedAdjustment(current->getAircraft()->
1378 getPerformance()->vDescent() *
1381 current->clearSpeedAdjustment();
1383 //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1385 setDt(getDt() + dt);
1388 void FGApproachController::signOff(int id)
1390 TrafficVectorIterator i = activeTraffic.begin();
1391 // Search search if the current id alread has an entry
1392 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1393 if (activeTraffic.size()) {
1394 //while ((i->getId() != id) && i != activeTraffic.end()) {
1395 while (i != activeTraffic.end()) {
1396 if (i->getId() == id) {
1402 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1403 SG_LOG(SG_GENERAL, SG_ALERT,
1404 "AI error: Aircraft without traffic record is signing off from approach");
1406 i = activeTraffic.erase(i);
1413 bool FGApproachController::hasInstruction(int id)
1415 TrafficVectorIterator i = activeTraffic.begin();
1416 // Search search if the current id has an entry
1417 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1418 if (activeTraffic.size()) {
1419 //while ((i->getId() != id) && i != activeTraffic.end()) {
1420 while (i != activeTraffic.end()) {
1421 if (i->getId() == id) {
1427 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1428 SG_LOG(SG_GENERAL, SG_ALERT,
1429 "AI error: checking ATC instruction for aircraft without traffic record");
1431 return i->hasInstruction();
1437 FGATCInstruction FGApproachController::getInstruction(int id)
1439 TrafficVectorIterator i = activeTraffic.begin();
1440 // Search search if the current id has an entry
1441 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1442 if (activeTraffic.size()) {
1443 //while ((i->getId() != id) && i != activeTraffic.end()) {
1444 while (i != activeTraffic.end()) {
1445 if (i->getId() == id) {
1451 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1452 SG_LOG(SG_GENERAL, SG_ALERT,
1453 "AI error: requesting ATC instruction for aircraft without traffic record");
1455 return i->getInstruction();
1457 return FGATCInstruction();
1461 ActiveRunway *FGApproachController::getRunway(string name)
1463 ActiveRunwayVecIterator rwy = activeRunways.begin();
1464 if (activeRunways.size()) {
1465 while (rwy != activeRunways.end()) {
1466 if (rwy->getRunwayName() == name) {
1472 if (rwy == activeRunways.end()) {
1473 ActiveRunway aRwy(name, 0);
1474 activeRunways.push_back(aRwy);
1475 rwy = activeRunways.end() - 1;
1480 void FGApproachController::render(bool visible) {
1481 //cerr << "FGApproachController::render function not yet implemented" << endl;
1486 string FGApproachController::getName() {
1487 return string(parent->getId() + "-approach");