Debian Codegraph @

src/Airports/dynamics.cxx

raw symbols SCIP
1 /*
2 * SPDX-FileName: dynamics.cxx
3 * SPDX-FileComment: Code to manage the higher order airport ground activities
4 * SPDX-FileCopyrightText: Written by Durk Talsma, started December 2004
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include <config.h>
9
10 #include <algorithm>
11 #include <string>
12 #include <vector>
13
14 #include <simgear/compiler.h>
15 #include <simgear/structure/SGWeakPtr.hxx>
16
17 #include <AIModel/AIBase.hxx>
18 #include <AIModel/AIManager.hxx>
19 #include <Airports/groundnetwork.hxx>
20 #include <Airports/runways.hxx>
21 #include <Environment/environment.hxx>
22 #include <Environment/environment_mgr.hxx>
23 #include <Main/fg_props.hxx>
24 #include <Main/globals.hxx>
25 #include <Main/locale.hxx>
26 #include <Navaids/NavDataCache.hxx>
27 #include <simgear/debug/logstream.hxx>
28 #include <simgear/misc/sg_path.hxx>
29 #include <simgear/props/props.hxx>
30 #include <simgear/structure/subsystem_mgr.hxx>
31
32 #include "airport.hxx"
33 #include "dynamics.hxx"
34
35 using std::sort;
36 using std::string;
37 using std::vector;
38
39 // #define RUNWAY_FALLBACK_DEBUG
40
41 class ParkingAssignment::ParkingAssignmentPrivate
42 {
43 public:
44 ParkingAssignmentPrivate(FGParking* pk, FGAirportDynamics* dyn) : refCount(0),
45 parking(pk),
46 dynamics(dyn)
47 {
48 assert(pk);
49 assert(dyn);
50 retain(); // initial count of 1
51 }
52
53 ~ParkingAssignmentPrivate()
54 {
55 FGAirportDynamicsRef strongRef = dynamics.lock();
56 if (strongRef) {
57 strongRef->releaseParking(parking);
58 }
59 }
60
61 void release()
62 {
63 if ((--refCount) == 0) {
64 delete this;
65 }
66 }
67
68 void retain()
69 {
70 ++refCount;
71 }
72
73 unsigned int refCount;
74 FGParkingRef parking;
75
76 // we don't want an owning ref here, otherwise we
77 // have a circular ownership from AirportDynamics -> us
78 SGWeakPtr<FGAirportDynamics> dynamics;
79 };
80
81 ParkingAssignment::ParkingAssignment() : _sharedData(NULL)
82 {
83 }
84
85 ParkingAssignment::~ParkingAssignment()
86 {
87 if (_sharedData) {
88 _sharedData->release();
89 }
90 }
91
92 ParkingAssignment::ParkingAssignment(FGParking* pk, FGAirportDynamics* dyn) : _sharedData(NULL)
93 {
94 if (pk) {
95 _sharedData = new ParkingAssignmentPrivate(pk, dyn);
96 }
97 }
98
99 ParkingAssignment::ParkingAssignment(const ParkingAssignment& aOther) : _sharedData(aOther._sharedData)
100 {
101 if (_sharedData) {
102 _sharedData->retain();
103 }
104 }
105
106 void ParkingAssignment::operator=(const ParkingAssignment& aOther)
107 {
108 if (_sharedData == aOther._sharedData) {
109 return; // self-assignment, special case
110 }
111
112 if (_sharedData) {
113 _sharedData->release();
114 }
115
116 _sharedData = aOther._sharedData;
117 if (_sharedData) {
118 _sharedData->retain();
119 }
120 }
121
122 void ParkingAssignment::release()
123 {
124 if (_sharedData) {
125 _sharedData->release();
126 _sharedData = NULL;
127 }
128 }
129
130 bool ParkingAssignment::isValid() const
131 {
132 return (_sharedData != NULL);
133 }
134
135 FGParking* ParkingAssignment::parking() const
136 {
137 return _sharedData ? _sharedData->parking.ptr() : NULL;
138 }
139
140 ////////////////////////////////////////////////////////////////////////////////
141
142 /**
143 * @brief Helper to cache all AIObject positions near the airport when
144 * searching for available parkings. This allows us to reject parkings
145 * which we might not have marked as occupied, but which an object is
146 * neverthless close to; such as the primary user or MP aircraft.
147 */
148 class NearbyAIObjectCache
149 {
150 public:
151 explicit NearbyAIObjectCache(FGAirportRef apt) : m_airport(apt)
152 {
153 }
154
155 bool isAnythingNear(const SGVec3d& cart, double radiusM)
156 {
157 if (!m_populated) {
158 populate();
159 }
160
161 for (auto c : m_cache) {
162 const double d = dist(cart, c);
163 if (d < radiusM) {
164 return true;
165 }
166 }
167
168 return false;
169 }
170
171 private:
172 void populate()
173 {
174 SGVec3d cartAirportPos = m_airport->cart();
175 auto aiManager = globals->get_subsystem<FGAIManager>();
176 for (auto ai : aiManager->get_ai_list()) {
177 const auto cart = ai->getCartPos();
178
179 // 20km cutoff from airport centre
180 if (dist(cartAirportPos, cart) > 20000) {
181 continue;
182 }
183
184 m_cache.push_back(cart);
185 }
186 m_populated = true;
187 }
188
189 bool m_populated = false;
190 FGAirportRef m_airport;
191 std::vector<SGVec3d> m_cache;
192 };
193
194 ////////////////////////////////////////////////////////////////////////////////
195
196 FGAirportDynamics::FGAirportDynamics(FGAirport* ap) : _ap(ap), rwyPrefs(ap),
197 startupController(this),
198 towerController(this),
199 approachController(this),
200 groundController(this),
201 lastUpdate{0},
202 atisSequenceIndex(-1),
203 atisSequenceTimeStamp(0.0)
204 {
205 }
206
207 // Destructor
208 FGAirportDynamics::~FGAirportDynamics()
209 {
210 }
211
212
213 // Initialization required after XMLRead
214 void FGAirportDynamics::init()
215 {
216 groundController.setTowerController(&towerController);
217 groundController.init();
218 }
219
220 FGParking* FGAirportDynamics::innerGetAvailableParking(double radius, const std::string& flType,
221 const std::string& airline,
222 bool skipEmptyAirlineCode)
223 {
224 NearbyAIObjectCache nearCache(parent());
225 const FGParkingList& parkings(parent()->groundNetwork()->allParkings());
226 FGParkingList candidates;
227 for (auto parking : parkings) {
228 if (!isParkingAvailable(parking)) {
229 continue;
230 }
231
232 if (parking->getRadius() < radius) {
233 continue;
234 }
235
236 if (!flType.empty() && (parking->getType() != flType)) {
237 continue;
238 }
239
240 if (skipEmptyAirlineCode && parking->getCodes().empty()) {
241 continue;
242 }
243
244 if (!airline.empty() && !parking->getCodes().empty()) {
245 if (parking->getCodes().find(airline, 0) == std::string::npos) {
246 continue;
247 }
248 }
249
250 if (nearCache.isAnythingNear(parking->cart(), parking->getRadius())) {
251 continue;
252 }
253
254 candidates.push_back(parking);
255 }
256
257 if (candidates.empty()) {
258 return nullptr;
259 }
260
261 // sort by increasing radius, so we return the smallest radius candidate
262 // this avoids large spaces (A380 sized) being given to Fokkers/ATR-72s
263 std::sort(candidates.begin(), candidates.end(),
264 [](const FGParkingRef& a, const FGParkingRef& b) {
265 return a->getRadius() < b->getRadius();
266 });
267
268 setParkingAvailable(candidates.front(), false);
269 return candidates.front();
270 }
271
272 bool FGAirportDynamics::hasParking(FGParking* parking) const
273 {
274 return std::find(parent()->groundNetwork()->allParkings().begin(),
275 parent()->groundNetwork()->allParkings().end(),
276 parking) != parent()->groundNetwork()->allParkings().end();
277 }
278
279 bool FGAirportDynamics::hasParkings() const
280 {
281 return !parent()->groundNetwork()->allParkings().empty();
282 }
283
284 ParkingAssignment FGAirportDynamics::getAvailableParking(double radius,
285 const std::string& flType,
286 const std::string& acType,
287 const std::string& airline)
288 {
289 SG_UNUSED(acType); // sadly not used at the moment
290
291 // most exact seach - airline codes must be present and match
292 FGParking* result = innerGetAvailableParking(radius, flType, airline, true);
293 if (result) {
294 return ParkingAssignment(result, this);
295 }
296
297 // more tolerant - gates with empty airline codes are permitted
298 result = innerGetAvailableParking(radius, flType, airline, false);
299 if (result) {
300 return ParkingAssignment(result, this);
301 }
302
303 // fallback - ignore the airline code entirely
304 result = innerGetAvailableParking(radius, flType, std::string(), false);
305 return result ? ParkingAssignment(result, this) : ParkingAssignment();
306 }
307
308 ParkingAssignment FGAirportDynamics::getParkingByName(const std::string& name) const
309 {
310 const FGParkingList& parkings(parent()->groundNetwork()->allParkings());
311 FGParkingList::const_iterator it;
312 for (it = parkings.begin(); it != parkings.end(); ++it) {
313 if ((*it)->name() == name) {
314 return ParkingAssignment(*it, const_cast<FGAirportDynamics*>(this));
315 }
316 }
317
318 return ParkingAssignment();
319 }
320
321 ParkingAssignment FGAirportDynamics::getAvailableParkingByName(const std::string& name)
322 {
323 const FGParkingList& parkings(parent()->groundNetwork()->allParkings());
324 auto it = std::find_if(parkings.begin(), parkings.end(), [this, name](FGParkingRef parking) {
325 if (parking->name() != name)
326 return false;
327
328 return this->isParkingAvailable(parking);
329 });
330
331 if (it == parkings.end())
332 return {}; // no assignment possible
333
334 return {*it, this};
335 }
336
337 FGParkingRef FGAirportDynamics::getOccupiedParkingByName(const std::string& name) const
338 {
339 auto it = std::find_if(occupiedParkings.begin(), occupiedParkings.end(),
340 [name](const FGParkingRef& pk) { return pk->name() == name; });
341 if (it != occupiedParkings.end()) {
342 return *it;
343 }
344
345 return {};
346 }
347
348 void FGAirportDynamics::setParkingAvailable(FGParking* park, bool available)
349 {
350 if (available) {
351 releaseParking(park);
352 } else {
353 occupiedParkings.insert(park);
354 }
355 }
356
357 bool FGAirportDynamics::isParkingAvailable(FGParking* parking) const
358 {
359 return (occupiedParkings.find(parking) == occupiedParkings.end());
360 }
361
362 void FGAirportDynamics::releaseParking(FGParking* id)
363 {
364 ParkingSet::iterator it = occupiedParkings.find(id);
365 if (it == occupiedParkings.end()) {
366 return;
367 }
368
369 occupiedParkings.erase(it);
370 }
371
372 class GetParkingsPredicate
373 {
374 bool mustBeAvailable;
375 std::string type;
376 const FGAirportDynamics* dynamics;
377
378 public:
379 GetParkingsPredicate(bool b, const std::string& ty, const FGAirportDynamics* dyn) : mustBeAvailable(b),
380 type(ty),
381 dynamics(dyn)
382 {
383 }
384
385 bool operator()(const FGParkingRef& park) const
386 {
387 if (!type.empty() && (park->getType() != type))
388 return true;
389
390 if (mustBeAvailable && !dynamics->isParkingAvailable(park)) {
391 return true;
392 }
393
394 return false;
395 }
396 };
397
398 FGParkingList FGAirportDynamics::getParkings(bool onlyAvailable, const std::string& type) const
399 {
400 FGParkingList result(parent()->groundNetwork()->allParkings());
401
402 GetParkingsPredicate pred(onlyAvailable, type, this);
403 auto it = std::remove_if(result.begin(), result.end(), pred);
404 result.erase(it, result.end());
405 return result;
406 }
407
408 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
409 {
410 rwyPrefs = ref;
411 }
412
413 bool areRunwaysParallel(const FGRunwayRef& a, const FGRunwayRef& b)
414 {
415 double hdgDiff = (b->headingDeg() - a->headingDeg());
416 SG_NORMALIZE_RANGE(hdgDiff, -180.0, 180.0);
417 return (fabs(hdgDiff) < 5.0);
418 }
419
420 double runwayScore(const FGRunwayRef& rwy)
421 {
422 return rwy->lengthM() + rwy->widthM();
423 }
424
425 double runwayWindScore(const FGRunwayRef& runway, double windHeading,
426 double windSpeedKts)
427 {
428 double hdgDiff = fabs(windHeading - runway->headingDeg()) * SG_DEGREES_TO_RADIANS;
429 SGMiscd::normalizeAngle(hdgDiff);
430
431 double crossWind = windSpeedKts * sin(hdgDiff);
432 double tailWind = -windSpeedKts * cos(hdgDiff);
433
434 return -(crossWind + tailWind);
435 }
436
437 typedef std::vector<FGRunwayRef> RunwayVec;
438
439
440 class FallbackRunwayGroup
441 {
442 public:
443 explicit FallbackRunwayGroup(const FGRunwayRef& rwy) : _groupScore(0.0)
444 {
445 runways.push_back(rwy);
446 _leadRunwayScore = runwayScore(rwy);
447 _groupScore += _leadRunwayScore;
448 }
449
450 bool canAccept(const FGRunwayRef& rwy) const
451 {
452 if (!areRunwaysParallel(runways.front(), rwy)) {
453 return false;
454 }
455
456 return true;
457 }
458
459 void addRunway(const FGRunwayRef& rwy)
460 {
461 assert(areRunwaysParallel(runways.front(), rwy));
462 double score = runwayScore(rwy);
463 if (score < (0.5 * _leadRunwayScore)) {
464 // drop the runway completely. this is to drop short parallel
465 // runways from being active
466 return;
467 }
468
469 runways.push_back(rwy);
470 _groupScore += score;
471 }
472
473 void adjustScoreForWind(double windHeading, double windSpeedKts)
474 {
475 _basicScore = _groupScore;
476 RunwayVec::iterator it;
477 for (it = runways.begin(); it != runways.end(); ++it) {
478 _groupScore += runwayWindScore(*it, windHeading, windSpeedKts);
479 }
480 }
481
482 double groupScore() const
483 {
484 return _groupScore;
485 }
486
487 void getRunways(FGRunwayList& arrivals, FGRunwayList& departures)
488 {
489 // make the common cases very obvious
490 if (runways.size() == 1) {
491 arrivals.push_back(runways.front());
492 departures.push_back(runways.front());
493 return;
494 }
495
496
497 // because runways were sorted by score when building, they were added
498 // by score also, so we can use a simple algorithm to assign
499 for (unsigned int r = 0; r < runways.size(); ++r) {
500 if ((r % 2) == 0) {
501 arrivals.push_back(runways[r]);
502 } else {
503 departures.push_back(runways[r]);
504 }
505 }
506 }
507
508 std::string dump()
509 {
510 std::ostringstream os;
511 os << runways.front()->ident();
512 for (unsigned int r = 1; r < runways.size(); ++r) {
513 os << ", " << runways[r]->ident();
514 }
515
516 os << " (score=" << _basicScore << ", wind score=" << _groupScore << ")";
517 return os.str();
518 }
519
520 private:
521 RunwayVec runways;
522 double _groupScore,
523 _leadRunwayScore;
524 double _basicScore{0.0};
525 };
526
527 class WindExclusionCheck
528 {
529 public:
530 WindExclusionCheck(double windHeading, double windSpeedKts) : _windSpeedKts(windSpeedKts),
531 _windHeading(windHeading)
532 {
533 }
534
535 bool operator()(const FGRunwayRef& rwy) const
536 {
537 return (runwayWindScore(rwy, _windHeading, _windSpeedKts) > 30);
538 }
539
540 private:
541 double _windSpeedKts,
542 _windHeading;
543 };
544
545 class SortByScore
546 {
547 public:
548 bool operator()(const FGRunwayRef& a, const FGRunwayRef& b) const
549 {
550 return runwayScore(a) > runwayScore(b);
551 }
552 };
553
554 class GroupSortByScore
555 {
556 public:
557 bool operator()(const FallbackRunwayGroup& a, const FallbackRunwayGroup& b) const
558 {
559 return a.groupScore() > b.groupScore();
560 }
561 };
562
563 std::string FGAirportDynamics::fallbackGetActiveRunway(int action, double heading)
564 {
565 bool updateNeeded = false;
566 if (_lastFallbackUpdate == SGTimeStamp()) {
567 updateNeeded = true;
568 } else {
569 updateNeeded = (_lastFallbackUpdate.elapsedMSec() > (1000 * 60 * 15));
570 }
571
572 if (updateNeeded) {
573 double windSpeed = fgGetInt("/environment/metar/base-wind-speed-kt");
574 double windHeading = fgGetInt("/environment/metar/base-wind-dir-deg");
575
576 // discount runways based on cross / tail-wind
577 WindExclusionCheck windCheck(windHeading, windSpeed);
578 RunwayVec runways(parent()->getRunways());
579 auto it = std::remove_if(runways.begin(), runways.end(), windCheck);
580 runways.erase(it, runways.end());
581
582 // sort highest scored to lowest scored
583 std::sort(runways.begin(), runways.end(), SortByScore());
584
585 std::vector<FallbackRunwayGroup> groups;
586 std::vector<FallbackRunwayGroup>::iterator git;
587
588 for (it = runways.begin(); it != runways.end(); ++it) {
589 bool existingGroupDidAccept = false;
590 for (git = groups.begin(); git != groups.end(); ++git) {
591 if (git->canAccept(*it)) {
592 existingGroupDidAccept = true;
593 git->addRunway(*it);
594 break;
595 }
596 } // of existing groups iteration
597
598 if (!existingGroupDidAccept) {
599 // create a new group
600 groups.push_back(FallbackRunwayGroup(*it));
601 }
602 } // of group building phase
603
604 if (groups.empty()) {
605 SG_LOG(SG_AI, SG_DEV_WARN, "fallbackGetActiveRunway: airport " << parent()->ident() << " has no runways");
606 return {};
607 }
608
609 // select highest scored group based on cross/tail wind
610 for (git = groups.begin(); git != groups.end(); ++git) {
611 git->adjustScoreForWind(windHeading, windSpeed);
612 }
613
614 std::sort(groups.begin(), groups.end(), GroupSortByScore());
615
616 // debugging fallback runway assignments
617 #if defined(RUNWAY_FALLBACK_DEBUG)
618 {
619 ostringstream os;
620 os << parent()->ident() << " groups:";
621
622 for (git = groups.begin(); git != groups.end(); ++git) {
623 os << "\n\t" << git->dump();
624 }
625
626 std::string s = os.str();
627 SG_LOG(SG_AI, SG_INFO, s);
628 }
629 #endif
630
631 // assign takeoff and landing runways
632 FallbackRunwayGroup bestGroup = groups.front();
633
634 _lastFallbackUpdate.stamp();
635 _fallbackRunwayCounter = 0;
636 _fallbackDepartureRunways.clear();
637 _fallbackArrivalRunways.clear();
638 bestGroup.getRunways(_fallbackArrivalRunways, _fallbackDepartureRunways);
639
640 #if defined(RUNWAY_FALLBACK_DEBUG)
641 ostringstream os;
642 os << "\tArrival:" << _fallbackArrivalRunways.front()->ident();
643 for (unsigned int r = 1; r < _fallbackArrivalRunways.size(); ++r) {
644 os << ", " << _fallbackArrivalRunways[r]->ident();
645 }
646 os << "\n\tDeparture:" << _fallbackDepartureRunways.front()->ident();
647 for (unsigned int r = 1; r < _fallbackDepartureRunways.size(); ++r) {
648 os << ", " << _fallbackDepartureRunways[r]->ident();
649 }
650
651 std::string s = os.str();
652 SG_LOG(SG_AI, SG_INFO, parent()->ident() << " fallback runways assignments for " << static_cast<int>(windHeading) << "@" << static_cast<int>(windSpeed) << "\n"
653 << s);
654 #endif
655 }
656
657 _fallbackRunwayCounter++;
658 FGRunwayRef r;
659 // ensure we cycle through possible runways where they exist
660 if (action == 1) {
661 r = _fallbackDepartureRunways[_fallbackRunwayCounter % _fallbackDepartureRunways.size()];
662 } else {
663 r = _fallbackArrivalRunways[_fallbackRunwayCounter % _fallbackArrivalRunways.size()];
664 }
665
666 return r->ident();
667 }
668
669 bool FGAirportDynamics::innerGetActiveRunway(const std::string& trafficType,
670 int action, std::string& runway,
671 double heading)
672 {
673 if (!rwyPrefs.available()) {
674 runway = fallbackGetActiveRunway(action, heading);
675 return !runway.empty();
676 }
677
678 time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
679 if ((std::abs((long)(dayStart - lastUpdate)) > 600) || trafficType != prevTrafficType) {
680 landing.clear();
681 takeoff.clear();
682 lastUpdate = dayStart;
683 prevTrafficType = trafficType;
684 /*
685 FGEnvironment
686 stationweather =
687 globals->get_subsystem<FGEnvironmentMgr>()
688 ->getEnvironment(getLatitude(), getLongitude(),
689 getElevation());
690 */
691 double windSpeed = fgGetInt("/environment/metar/base-wind-speed-kt"); //stationweather.get_wind_speed_kt();
692 double windHeading = fgGetInt("/environment/metar/base-wind-dir-deg");
693 //stationweather.get_wind_from_heading_deg();
694 std::string scheduleName;
695 //cerr << "finding active Runway for : " << _ap->getId() << endl;
696 //cerr << "Wind Heading : " << windHeading << endl;
697 //cerr << "Wind Speed : " << windSpeed << endl;
698
699 //cerr << "Nr of seconds since day start << " << dayStart << endl;
700
701 ScheduleTime* currSched;
702 //cerr << "A"<< endl;
703 currSched = rwyPrefs.getSchedule(trafficType.c_str());
704 if (!(currSched))
705 return false;
706 //cerr << "B"<< endl;
707 scheduleName = currSched->getName(dayStart);
708 double maxTail = currSched->getTailWind();
709 double maxCross = currSched->getCrossWind();
710 //cerr << "Current Schedule = : " << scheduleName << endl;
711 if (scheduleName.empty())
712 return false;
713 //cerr << "C"<< endl;
714 RunwayGroup* currRunwayGroup = rwyPrefs.getGroup(scheduleName);
715 //cerr << "D"<< endl;
716 if (!(currRunwayGroup))
717 return false;
718
719 // Keep a history of the currently active runways, to ensure
720 // that an already established selection of runways will not
721 // be overridden once a more preferred selection becomes
722 // available as that can lead to random runway swapping.
723 if (trafficType == "com") {
724 currentlyActive = &comActive;
725 } else if (trafficType == "gen") {
726 currentlyActive = &genActive;
727 } else if (trafficType == "mil") {
728 currentlyActive = &milActive;
729 } else if (trafficType == "ul") {
730 currentlyActive = &ulActive;
731 }
732
733 //cerr << "Currently active selection for " << trafficType << ": ";
734 for (stringVecIterator it = currentlyActive->begin();
735 it != currentlyActive->end(); ++it) {
736 //cerr << (*it) << " ";
737 }
738 //cerr << endl;
739
740 currRunwayGroup->setActive(_ap,
741 windSpeed,
742 windHeading,
743 maxTail, maxCross, currentlyActive);
744
745 // Note that I SHOULD keep multiple lists in memory, one for
746 // general aviation, one for commercial and one for military
747 // traffic.
748 currentlyActive->clear();
749 int nrActiveRunways = currRunwayGroup->getNrActiveRunways();
750 //cerr << "Choosing runway for " << trafficType << endl;
751 for (int i = 0; i < nrActiveRunways; i++) {
752 std::string name;
753 std::string type = "unknown"; // initialize to something other than landing or takeoff
754
755 currRunwayGroup->getActive(i, name, type);
756 if (type == "landing") {
757 landing.push_back(name);
758 currentlyActive->push_back(name);
759 //cerr << "Landing " << name << endl;
760 }
761 if (type == "takeoff") {
762 takeoff.push_back(name);
763 currentlyActive->push_back(name);
764 //cerr << "takeoff " << name << endl;
765 }
766 }
767 //cerr << endl;
768 }
769
770 if (action == 1) // takeoff
771 {
772 int nr = takeoff.size();
773 if (nr) {
774 // Note that the randomization below, is just a placeholder to choose between
775 // multiple active runways for this action. This should be
776 // under ATC control.
777 runway = chooseRwyByHeading(takeoff, heading);
778 } else { // Fallback
779 runway = chooseRunwayFallback();
780 }
781 }
782
783 if (action == 2) // landing
784 {
785 if (!landing.empty()) {
786 runway = chooseRwyByHeading(landing, heading);
787 }
788
789 if (runway.empty()) { //fallback
790 runway = chooseRunwayFallback();
791 }
792 }
793
794 return true;
795 }
796
797 std::string FGAirportDynamics::chooseRwyByHeading(stringVec rwys,
798 double heading)
799 {
800 double bestError = 360.0;
801 double rwyHeading, headingError;
802 std::string runway;
803 for (stringVecIterator i = rwys.begin(); i != rwys.end(); ++i) {
804 if (!_ap->hasRunwayWithIdent(*i)) {
805 SG_LOG(SG_ATC, SG_WARN, "chooseRwyByHeading: runway " << *i << " not found at " << _ap->ident());
806 continue;
807 }
808
809 FGRunway* rwy = _ap->getRunwayByIdent((*i));
810 rwyHeading = rwy->headingDeg();
811 headingError = fabs(heading - rwyHeading);
812 if (headingError > 180)
813 headingError = fabs(headingError - 360);
814 if (headingError < bestError) {
815 runway = (*i);
816 bestError = headingError;
817 }
818 }
819 //cerr << "Using active runway " << runway << " for heading " << heading << endl;
820 return runway;
821 }
822
823 void FGAirportDynamics::getActiveRunway(const std::string& trafficType,
824 int action, std::string& runway,
825 double heading)
826 {
827 bool ok = innerGetActiveRunway(trafficType, action, runway, heading);
828 if (!ok || runway.empty()) {
829 runway = chooseRunwayFallback();
830 }
831 }
832
833 std::string FGAirportDynamics::chooseRunwayFallback()
834 {
835 FGRunway* rwy = _ap->getActiveRunwayForUsage();
836 if (!rwy) {
837 SG_LOG(SG_AI, SG_WARN, "FGAirportDynamics::chooseRunwayFallback failed at " << _ap->ident());
838
839 // let's use runway 0
840 return _ap->getRunwayByIndex(0)->ident();
841 }
842 return rwy->ident();
843 }
844
845 double FGAirportDynamics::getElevation() const
846 {
847 return _ap->getElevation();
848 }
849
850 const std::string FGAirportDynamics::getId() const
851 {
852 return _ap->getId();
853 }
854
855 // Experimental: Return a different ground frequency depending on the leg of the
856 // Flight. Leg should always have a minimum value of two when this function is called.
857 // Note that in this scheme, the assignment of various frequencies to various ground
858 // operations is completely arbitrary. As such, is a short cut I need to take now,
859 // so that at least I can start working on assigning different frequencies to different
860 // operations.
861
862 int FGAirportDynamics::getApproachFrequency(unsigned nr)
863 {
864 int approachFreq = 0;
865 if (nr < 2) {
866 SG_LOG(SG_ATC, SG_ALERT,
867 "Leg value is smaller than two at " << SG_ORIGIN);
868 }
869
870 const intVec& freqApproach(parent()->groundNetwork()->getApproachFrequencies());
871
872 if (freqApproach.size() == 0) {
873 return 0;
874 }
875 if ((freqApproach.size() > nr - 1) && (nr > 1)) {
876 approachFreq = freqApproach[nr - 1];
877 }
878 if ((freqApproach.size() < nr - 1) && (nr > 1)) {
879 approachFreq =
880 (freqApproach.size() <
881 (nr - 1))
882 ? freqApproach[freqApproach.size() -
883 1]
884 : freqApproach[nr - 2];
885 }
886 if ((freqApproach.size() >= nr - 1) && (nr > 1)) {
887 approachFreq = freqApproach[nr - 2];
888 }
889 return approachFreq;
890 }
891
892 int FGAirportDynamics::getGroundFrequency(unsigned leg)
893 {
894 //return freqGround.size() ? freqGround[0] : 0; };
895 //cerr << "Getting frequency for : " << leg << endl;
896 int groundFreq = 0;
897 if (leg < 1) {
898 SG_LOG(SG_ATC, SG_ALERT,
899 "Leg value is smaller than one at " << SG_ORIGIN);
900 }
901
902 const intVec& freqGround(parent()->groundNetwork()->getGroundFrequencies());
903
904 if (freqGround.size() == 0) {
905 return 0;
906 }
907
908 if ((freqGround.size() < leg) && (leg > 0)) {
909 groundFreq =
910 (freqGround.size() <=
911 (leg - 1))
912 ? freqGround[freqGround.size() -
913 1]
914 : freqGround[leg - 1];
915 }
916 if ((freqGround.size() >= leg) && (leg > 0)) {
917 groundFreq = freqGround[leg - 1];
918 }
919 return groundFreq;
920 }
921
922 int FGAirportDynamics::getTowerFrequency(unsigned nr)
923 {
924 int towerFreq = 0;
925 if (nr < 2) {
926 SG_LOG(SG_ATC, SG_ALERT,
927 "Leg value is smaller than two at " << SG_ORIGIN);
928 }
929
930 const intVec& freqTower(parent()->groundNetwork()->getTowerFrequencies());
931
932 if (freqTower.size() == 0) {
933 return 0;
934 }
935 if ((freqTower.size() > nr - 1) && (nr > 1)) {
936 towerFreq = freqTower[nr - 1];
937 }
938 if ((freqTower.size() < nr - 1) && (nr > 1)) {
939 towerFreq =
940 (freqTower.size() <
941 (nr - 1))
942 ? freqTower[freqTower.size() -
943 1]
944 : freqTower[nr - 2];
945 }
946 if ((freqTower.size() >= nr - 1) && (nr > 1)) {
947 towerFreq = freqTower[nr - 2];
948 }
949 return towerFreq;
950 }
951
952 const std::string FGAirportDynamics::getAtisSequence()
953 {
954 if (atisSequenceIndex == -1) {
955 updateAtisSequence(1, false);
956 }
957
958 char atisSequenceString[2];
959 atisSequenceString[0] = 'a' + atisSequenceIndex;
960 atisSequenceString[1] = 0;
961
962 return globals->get_locale()->getLocalizedString(atisSequenceString, "atc", "unknown");
963 }
964
965 int FGAirportDynamics::updateAtisSequence(int interval, bool forceUpdate)
966 {
967 double now = globals->get_sim_time_sec();
968 if (atisSequenceIndex == -1) {
969 // first computation
970 atisSequenceTimeStamp = now;
971 atisSequenceIndex = rand() % 26; // random initial sequence letters
972 return atisSequenceIndex;
973 }
974
975 int steps = static_cast<int>((now - atisSequenceTimeStamp) / interval);
976 atisSequenceTimeStamp += (interval * steps);
977 if (forceUpdate && (steps == 0)) {
978 ++steps; // a "special" ATIS update is required
979 }
980
981 atisSequenceIndex = (atisSequenceIndex + steps) % 26;
982 // return a huge value if no update occurred
983 return (atisSequenceIndex + (steps ? 0 : 26 * 1000));
984 }