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 slow 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(3);
527 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
528 getName() + "-Ground";
530 rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
531 getDynamics()->getAtisInformation();
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():
725 void FGTowerController::announcePosition(int id,
726 FGAIFlightPlan * intendedRoute,
727 int currentPosition, double lat,
728 double lon, double heading,
729 double speed, double alt,
730 double radius, int leg,
734 TrafficVectorIterator i = activeTraffic.begin();
735 // Search whether the current id alread has an entry
736 // This might be faster using a map instead of a vector, but let's start by taking a safe route
737 if (activeTraffic.size()) {
738 //while ((i->getId() != id) && i != activeTraffic.end()) {
739 while (i != activeTraffic.end()) {
740 if (i->getId() == id) {
746 // Add a new TrafficRecord if no one exsists for this aircraft.
747 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
751 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
752 rec.setRunway(intendedRoute->getRunway());
754 //rec.setCallSign(callsign);
755 rec.setAircraft(ref);
756 activeTraffic.push_back(rec);
758 i->setPositionAndHeading(lat, lon, heading, speed, alt);
762 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
763 double heading, double speed, double alt,
766 TrafficVectorIterator i = activeTraffic.begin();
767 // Search whether the current id has an entry
768 // This might be faster using a map instead of a vector, but let's start by taking a safe route
769 TrafficVectorIterator current, closest;
770 if (activeTraffic.size()) {
771 //while ((i->getId() != id) && i != activeTraffic.end()) {
772 while (i != activeTraffic.end()) {
773 if (i->getId() == id) {
779 // // update position of the current aircraft
780 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
781 SG_LOG(SG_GENERAL, SG_ALERT,
782 "AI error: updating aircraft without traffic record");
784 i->setPositionAndHeading(lat, lon, heading, speed, alt);
789 // // see if we already have a clearance record for the currently active runway
790 ActiveRunwayVecIterator rwy = activeRunways.begin();
791 // again, a map might be more efficient here
792 if (activeRunways.size()) {
793 //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
794 while (rwy != activeRunways.end()) {
795 if (rwy->getRunwayName() == current->getRunway()) {
801 if (rwy == activeRunways.end()) {
802 ActiveRunway aRwy(current->getRunway(), id);
803 activeRunways.push_back(aRwy); // Since there are no clearance records for this runway yet
804 current->setHoldPosition(false); // Clear the current aircraft to continue
806 // Okay, we have a clearance record for this runway, so check
807 // whether the clearence ID matches that of the current aircraft
808 if (id == rwy->getCleared()) {
809 current->setHoldPosition(false);
811 current->setHoldPosition(true);
817 void FGTowerController::signOff(int id)
819 TrafficVectorIterator i = activeTraffic.begin();
820 // Search search if the current id alread has an entry
821 // This might be faster using a map instead of a vector, but let's start by taking a safe route
822 if (activeTraffic.size()) {
823 //while ((i->getId() != id) && i != activeTraffic.end()) {
824 while (i != activeTraffic.end()) {
825 if (i->getId() == id) {
831 // If this aircraft has left the runway, we can clear the departure record for this runway
832 ActiveRunwayVecIterator rwy = activeRunways.begin();
833 if (activeRunways.size()) {
834 //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
835 while (rwy != activeRunways.end()) {
836 if (rwy->getRunwayName() == i->getRunway()) {
841 if (rwy != activeRunways.end()) {
842 rwy = activeRunways.erase(rwy);
844 SG_LOG(SG_GENERAL, SG_ALERT,
845 "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
848 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
849 SG_LOG(SG_GENERAL, SG_ALERT,
850 "AI error: Aircraft without traffic record is signing off from tower");
852 i = activeTraffic.erase(i);
857 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
858 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
859 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
860 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
861 // Note that this function is probably obsolete
862 bool FGTowerController::hasInstruction(int id)
864 TrafficVectorIterator i = activeTraffic.begin();
865 // Search search if the current id has an entry
866 // This might be faster using a map instead of a vector, but let's start by taking a safe route
867 if (activeTraffic.size()) {
868 //while ((i->getId() != id) && i != activeTraffic.end()) {
869 while (i != activeTraffic.end()) {
870 if (i->getId() == id) {
876 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
877 SG_LOG(SG_GENERAL, SG_ALERT,
878 "AI error: checking ATC instruction for aircraft without traffic record");
880 return i->hasInstruction();
886 FGATCInstruction FGTowerController::getInstruction(int id)
888 TrafficVectorIterator i = activeTraffic.begin();
889 // Search search if the current id has an entry
890 // This might be faster using a map instead of a vector, but let's start by taking a safe route
891 if (activeTraffic.size()) {
892 //while ((i->getId() != id) && i != activeTraffic.end()) {
893 while (i != activeTraffic.end()) {
894 if (i->getId() == id) {
900 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
901 SG_LOG(SG_GENERAL, SG_ALERT,
902 "AI error: requesting ATC instruction for aircraft without traffic record");
904 return i->getInstruction();
906 return FGATCInstruction();
909 void FGTowerController::render() {
910 cerr << "FGTowerController::render function not yet implemented" << endl;
914 /***************************************************************************
915 * class FGStartupController
917 **************************************************************************/
918 FGStartupController::FGStartupController(FGAirportDynamics *par):
924 void FGStartupController::announcePosition(int id,
925 FGAIFlightPlan * intendedRoute,
926 int currentPosition, double lat,
927 double lon, double heading,
928 double speed, double alt,
929 double radius, int leg,
933 TrafficVectorIterator i = activeTraffic.begin();
934 // Search whether the current id alread has an entry
935 // This might be faster using a map instead of a vector, but let's start by taking a safe route
936 if (activeTraffic.size()) {
937 //while ((i->getId() != id) && i != activeTraffic.end()) {
938 while (i != activeTraffic.end()) {
939 if (i->getId() == id) {
945 // Add a new TrafficRecord if no one exsists for this aircraft.
946 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
950 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
951 rec.setRunway(intendedRoute->getRunway());
953 rec.setPositionAndIntentions(currentPosition, intendedRoute);
954 //rec.setCallSign(callsign);
955 rec.setAircraft(ref);
956 rec.setHoldPosition(true);
957 activeTraffic.push_back(rec);
959 i->setPositionAndIntentions(currentPosition, intendedRoute);
960 i->setPositionAndHeading(lat, lon, heading, speed, alt);
966 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
967 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
968 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
969 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
970 // Note that this function is probably obsolete
971 bool FGStartupController::hasInstruction(int id)
973 TrafficVectorIterator i = activeTraffic.begin();
974 // Search search if the current id has an entry
975 // This might be faster using a map instead of a vector, but let's start by taking a safe route
976 if (activeTraffic.size()) {
977 //while ((i->getId() != id) && i != activeTraffic.end()) {
978 while (i != activeTraffic.end()) {
979 if (i->getId() == id) {
985 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
986 SG_LOG(SG_GENERAL, SG_ALERT,
987 "AI error: checking ATC instruction for aircraft without traffic record");
989 return i->hasInstruction();
995 FGATCInstruction FGStartupController::getInstruction(int id)
997 TrafficVectorIterator i = activeTraffic.begin();
998 // Search search if the current id 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 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1010 SG_LOG(SG_GENERAL, SG_ALERT,
1011 "AI error: requesting ATC instruction for aircraft without traffic record");
1013 return i->getInstruction();
1015 return FGATCInstruction();
1018 void FGStartupController::signOff(int id)
1020 TrafficVectorIterator i = activeTraffic.begin();
1021 // Search search if the current id alread has an entry
1022 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1023 if (activeTraffic.size()) {
1024 //while ((i->getId() != id) && i != activeTraffic.end()) {
1025 while (i != activeTraffic.end()) {
1026 if (i->getId() == id) {
1032 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1033 SG_LOG(SG_GENERAL, SG_ALERT,
1034 "AI error: Aircraft without traffic record is signing off from tower");
1036 i = activeTraffic.erase(i);
1040 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1043 int state = i->getState();
1044 if ((state == st) && available) {
1045 if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1047 cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1048 static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1049 int n = trans_num->getIntValue();
1051 trans_num->setIntValue(-1);
1052 // PopupCallback(n);
1053 cerr << "Selected transmission message" << n << endl;
1054 FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1055 atc->getATCDialog()->removeEntry(1);
1057 cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1058 transmit(&(*i), msgId, msgDir, false);
1062 if (now > startTime) {
1063 //cerr << "Transmitting startup msg" << endl;
1064 transmit(&(*i), msgId, msgDir, true);
1066 lastTransmission = now;
1074 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1075 double heading, double speed, double alt,
1078 TrafficVectorIterator i = activeTraffic.begin();
1079 // Search search if the current id has an entry
1080 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1081 TrafficVectorIterator current, closest;
1082 if (activeTraffic.size()) {
1083 //while ((i->getId() != id) && i != activeTraffic.end()) {
1084 while (i != activeTraffic.end()) {
1085 if (i->getId() == id) {
1091 // // update position of the current aircraft
1093 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1094 SG_LOG(SG_GENERAL, SG_ALERT,
1095 "AI error: updating aircraft without traffic record");
1097 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1100 setDt(getDt() + dt);
1102 int state = i->getState();
1104 // The user controlled aircraft should have crased here, because it doesn't have a traffic reference.
1105 // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1106 time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1107 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1108 //cerr << i->getAircraft()->getTrafficRef()->getCallSign()
1109 // << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1110 // << " at parking " << getGateName(i->getAircraft()) << endl;
1112 if ((now - lastTransmission) > 3 + (rand() % 15)) {
1116 checkTransmissionState(0, now, (startTime + 0 ), i, MSG_ANNOUNCE_ENGINE_START, ATC_AIR_TO_GROUND);
1117 checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START, ATC_AIR_TO_GROUND);
1118 checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START, ATC_GROUND_TO_AIR);
1119 checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START, ATC_AIR_TO_GROUND);
1120 if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY, ATC_AIR_TO_GROUND)) {
1123 checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT, ATC_AIR_TO_GROUND);
1124 checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT, ATC_GROUND_TO_AIR);
1125 checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE, ATC_AIR_TO_GROUND);
1129 if ((state == 8) && available) {
1130 if (now > startTime + 200) {
1131 if (i->pushBackAllowed()) {
1132 i->allowRepeatedTransmissions();
1133 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1134 ATC_GROUND_TO_AIR, true);
1137 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1138 ATC_GROUND_TO_AIR, true);
1139 i->suppressRepeatedTransmissions();
1141 lastTransmission = now;
1145 if ((state == 9) && available) {
1146 i->setHoldPosition(false);
1150 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1151 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1152 double lon, double elev, double hdg)
1154 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1155 obj_pos = geod.makeZUpFrame();
1156 // hdg is not a compass heading, but a counter-clockwise rotation
1157 // around the Z axis
1158 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1163 void FGStartupController::render()
1166 SGMaterialLib *matlib = globals->get_matlib();
1169 globals->get_scenery()->get_scene_graph()->removeChild(group);
1170 //while (group->getNumChildren()) {
1171 // cerr << "Number of children: " << group->getNumChildren() << endl;
1172 simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1173 //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1174 //geode->releaseGLObjects();
1175 //group->removeChild(geode);
1178 group = new osg::Group;
1180 //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1182 for (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1183 // Handle start point
1184 int pos = i->getCurrentPosition();
1186 FGTaxiSegment *segment = parent->getGroundNetwork()->findSegment(pos);
1187 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1188 SGGeod end (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1190 double length = SGGeodesy::distanceM(start, end);
1191 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1193 double az2, heading; //, distanceM;
1194 SGGeodesy::inverse(start, end, heading, az2, length);
1195 double coveredDistance = length * 0.5;
1197 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1198 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1199 ///////////////////////////////////////////////////////////////////////////////
1200 // Make a helper function out of this
1201 osg::Matrix obj_pos;
1202 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1203 obj_trans->setDataVariance(osg::Object::STATIC);
1205 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1207 obj_trans->setMatrix( obj_pos );
1208 //osg::Vec3 center(0, 0, 0)
1210 float width = length /2.0;
1211 osg::Vec3 corner(-width, 0, 0.25f);
1212 osg::Vec3 widthVec(2*width + 1, 0, 0);
1213 osg::Vec3 heightVec(0, 1, 0);
1214 osg::Geometry* geometry;
1215 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1216 simgear::EffectGeode* geode = new simgear::EffectGeode;
1217 geode->setName("test");
1218 geode->addDrawable(geometry);
1219 //osg::Node *custom_obj;
1220 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1222 geode->setEffect(mat->get_effect());
1223 obj_trans->addChild(geode);
1224 // wire as much of the scene graph together as we can
1225 //->addChild( obj_trans );
1226 group->addChild( obj_trans );
1227 /////////////////////////////////////////////////////////////////////
1229 cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1231 for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1232 osg::Matrix obj_pos;
1235 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1236 obj_trans->setDataVariance(osg::Object::STATIC);
1237 FGTaxiSegment *segment = parent->getGroundNetwork()->findSegment(k);
1238 WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1240 obj_trans->setMatrix( obj_pos );
1241 //osg::Vec3 center(0, 0, 0)
1243 float width = segment->getLength() /2.0;
1244 osg::Vec3 corner(-width, 0, 0.25f);
1245 osg::Vec3 widthVec(2*width + 1, 0, 0);
1246 osg::Vec3 heightVec(0, 1, 0);
1247 osg::Geometry* geometry;
1248 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1249 simgear::EffectGeode* geode = new simgear::EffectGeode;
1250 geode->setName("test");
1251 geode->addDrawable(geometry);
1252 //osg::Node *custom_obj;
1253 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1255 geode->setEffect(mat->get_effect());
1256 obj_trans->addChild(geode);
1257 // wire as much of the scene graph together as we can
1258 //->addChild( obj_trans );
1259 group->addChild( obj_trans );
1261 cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1266 globals->get_scenery()->get_scene_graph()->addChild(group);
1270 /***************************************************************************
1271 * class FGApproachController
1273 **************************************************************************/
1274 FGApproachController::FGApproachController():
1280 void FGApproachController::announcePosition(int id,
1281 FGAIFlightPlan * intendedRoute,
1282 int currentPosition,
1283 double lat, double lon,
1284 double heading, double speed,
1285 double alt, double radius,
1286 int leg, FGAIAircraft * ref)
1289 TrafficVectorIterator i = activeTraffic.begin();
1290 // Search whether the current id alread has an entry
1291 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1292 if (activeTraffic.size()) {
1293 //while ((i->getId() != id) && i != activeTraffic.end()) {
1294 while (i != activeTraffic.end()) {
1295 if (i->getId() == id) {
1301 // Add a new TrafficRecord if no one exsists for this aircraft.
1302 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1303 FGTrafficRecord rec;
1306 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1307 rec.setRunway(intendedRoute->getRunway());
1309 //rec.setCallSign(callsign);
1310 rec.setAircraft(ref);
1311 activeTraffic.push_back(rec);
1313 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1317 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1318 double heading, double speed, double alt,
1321 TrafficVectorIterator i = activeTraffic.begin();
1322 // Search search if the current id has an entry
1323 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1324 TrafficVectorIterator current, closest;
1325 if (activeTraffic.size()) {
1326 //while ((i->getId() != id) && i != activeTraffic.end()) {
1327 while (i != activeTraffic.end()) {
1328 if (i->getId() == id) {
1334 // // update position of the current aircraft
1335 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1336 SG_LOG(SG_GENERAL, SG_ALERT,
1337 "AI error: updating aircraft without traffic record");
1339 i->setPositionAndHeading(lat, lon, heading, speed, alt);
1341 //cerr << "ApproachController: checking for speed" << endl;
1343 current->getAircraft()->
1344 checkForArrivalTime(string("final001"));
1345 if (time_diff > 15) {
1346 current->setSpeedAdjustment(current->getAircraft()->
1347 getPerformance()->vDescent() *
1349 } else if (time_diff > 5) {
1350 current->setSpeedAdjustment(current->getAircraft()->
1351 getPerformance()->vDescent() *
1353 } else if (time_diff < -15) {
1354 current->setSpeedAdjustment(current->getAircraft()->
1355 getPerformance()->vDescent() *
1357 } else if (time_diff < -5) {
1358 current->setSpeedAdjustment(current->getAircraft()->
1359 getPerformance()->vDescent() *
1362 current->clearSpeedAdjustment();
1364 //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1366 setDt(getDt() + dt);
1369 void FGApproachController::signOff(int id)
1371 TrafficVectorIterator i = activeTraffic.begin();
1372 // Search search if the current id alread has an entry
1373 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1374 if (activeTraffic.size()) {
1375 //while ((i->getId() != id) && i != activeTraffic.end()) {
1376 while (i != activeTraffic.end()) {
1377 if (i->getId() == id) {
1383 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1384 SG_LOG(SG_GENERAL, SG_ALERT,
1385 "AI error: Aircraft without traffic record is signing off from approach");
1387 i = activeTraffic.erase(i);
1394 bool FGApproachController::hasInstruction(int id)
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 if (activeTraffic.size()) {
1400 //while ((i->getId() != id) && i != activeTraffic.end()) {
1401 while (i != activeTraffic.end()) {
1402 if (i->getId() == id) {
1408 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1409 SG_LOG(SG_GENERAL, SG_ALERT,
1410 "AI error: checking ATC instruction for aircraft without traffic record");
1412 return i->hasInstruction();
1418 FGATCInstruction FGApproachController::getInstruction(int id)
1420 TrafficVectorIterator i = activeTraffic.begin();
1421 // Search search if the current id has an entry
1422 // This might be faster using a map instead of a vector, but let's start by taking a safe route
1423 if (activeTraffic.size()) {
1424 //while ((i->getId() != id) && i != activeTraffic.end()) {
1425 while (i != activeTraffic.end()) {
1426 if (i->getId() == id) {
1432 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1433 SG_LOG(SG_GENERAL, SG_ALERT,
1434 "AI error: requesting ATC instruction for aircraft without traffic record");
1436 return i->getInstruction();
1438 return FGATCInstruction();
1442 ActiveRunway *FGApproachController::getRunway(string name)
1444 ActiveRunwayVecIterator rwy = activeRunways.begin();
1445 if (activeRunways.size()) {
1446 while (rwy != activeRunways.end()) {
1447 if (rwy->getRunwayName() == name) {
1453 if (rwy == activeRunways.end()) {
1454 ActiveRunway aRwy(name, 0);
1455 activeRunways.push_back(aRwy);
1456 rwy = activeRunways.end() - 1;
1461 void FGApproachController::render() {
1462 cerr << "FGApproachController::render function not yet implemented" << endl;