1 /******************************************************************************
3 * Written by Durk Talsma, started May 5, 2004.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 ****************************************************************************
22 *****************************************************************************/
39 #include <boost/foreach.hpp>
41 #include <simgear/compiler.h>
42 #include <simgear/sg_inlines.h>
43 #include <simgear/math/sg_geodesy.hxx>
44 #include <simgear/props/props.hxx>
45 #include <simgear/structure/subsystem_mgr.hxx>
46 #include <simgear/xml/easyxml.hxx>
47 #include <simgear/timing/sg_time.hxx>
49 #include <AIModel/AIFlightPlan.hxx>
50 #include <AIModel/AIManager.hxx>
51 #include <AIModel/AIAircraft.hxx>
52 #include <Airports/airport.hxx>
53 #include <Main/globals.hxx>
54 #include <Main/fg_props.hxx>
56 #include "SchedFlight.hxx"
57 #include "TrafficMgr.hxx"
61 /******************************************************************************
62 * the FGAISchedule class contains data members and code to maintain a
63 * schedule of Flights for an artificially controlled aircraft.
64 *****************************************************************************/
65 FGAISchedule::FGAISchedule()
78 scheduleComplete(false)
83 FGAISchedule::FGAISchedule(const string& model,
87 const string& flightId,
107 scheduleComplete(false)
113 flightIdentifier = flightId;
118 /*for (FGScheduledFlightVecIterator i = flt.begin();
121 flights.push_back(new FGScheduledFlight((*(*i))));*/
124 FGAISchedule::FGAISchedule(const FGAISchedule &other)
126 modelPath = other.modelPath;
127 homePort = other.homePort;
128 livery = other.livery;
129 registration = other.registration;
131 flightIdentifier = other.flightIdentifier;
132 flights = other.flights;
133 aiAircraft = other.aiAircraft;
134 acType = other.acType;
135 airline = other.airline;
136 m_class = other.m_class;
137 firstRun = other.firstRun;
138 radius = other.radius;
139 groundOffset = other.groundOffset;
140 flightType = other.flightType;
142 distanceToUser = other.distanceToUser;
143 currentDestination = other.currentDestination;
144 firstRun = other.firstRun;
145 runCount = other.runCount;
147 lastRun = other.lastRun;
148 courseToDest = other.courseToDest;
149 initialized = other.initialized;
151 scheduleComplete = other.scheduleComplete;
156 FGAISchedule::~FGAISchedule()
158 // remove related object from AI manager
161 aiAircraft->setDie(true);
164 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
171 bool FGAISchedule::init()
174 //SGTime* currTimeDate = globals->get_time_params();
176 //tm *temp = currTimeDate->getGmt();
178 //sgTimeFormatTime(&targetTimeDate, buffer);
179 //cout << "Scheduled Time " << buffer << endl;
180 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
181 /*for (FGScheduledFlightVecIterator i = flights.begin();
185 //i->adjustTime(now);
186 if (!((*i)->initializeAirports()))
189 //sort(flights.begin(), flights.end());
190 // Since time isn't initialized yet when this function is called,
191 // Find the closest possible airport.
192 // This should give a reasonable initialization order.
193 //setClosestDistanceToUser();
198 * Returns true when processing is complete.
199 * Returns false when processing was aborted due to timeout, so
200 * more time required - and another call is requested (next sim iteration).
202 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
205 time_t totalTimeEnroute,
207 //remainingTimeEnroute,
211 return true; // processing complete
214 if (!scheduleComplete) {
215 scheduleComplete = scheduleFlights(now);
218 if (!scheduleComplete) {
219 return false; // not ready yet, continue processing in next iteration
222 if (flights.empty()) { // No flights available for this aircraft
224 return true; // processing complete
228 // Sort all the scheduled flights according to scheduled departure time.
229 // Because this is done at every update, we only need to check the status
230 // of the first listed flight.
231 //sort(flights.begin(), flights.end(), compareScheduledFlights);
234 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
235 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
236 // from cluttering the gate areas.
241 FGScheduledFlight* flight = flights.front();
243 deptime = flight->getDepartureTime();
244 //cerr << "Setting departure time " << deptime << endl;
248 if (aiAircraft->getDie()) {
251 return true; // in visual range, let the AIManager handle it
255 // This flight entry is entirely in the past, do we need to
256 // push it forward in time to the next scheduled departure.
257 if (flight->getArrivalTime() < now) {
258 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in the Past");
259 // Don't just update: check whether we need to load a new leg. etc.
260 // This update occurs for distant aircraft, so we can update the current leg
261 // and detach it from the current list of aircraft.
263 flights.erase(flights.begin()); // pop_front(), effectively
264 return true; // processing complete
267 FGAirport* dep = flight->getDepartureAirport();
268 FGAirport* arr = flight->getArrivalAirport();
270 return true; // processing complete
273 double speed = 450.0;
275 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
276 if (flight->getDepartureTime() < now) {
277 elapsedTimeEnroute = now - flight->getDepartureTime();
278 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
279 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
281 // current pos is based on great-circle course between departure/arrival,
282 // with percentage of distance travelled, based upon percentage of time
284 double course, az2, distanceM;
285 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
286 double coveredDistance = distanceM * x;
288 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
290 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
291 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
294 //remainingTimeEnroute = totalTimeEnroute;
295 elapsedTimeEnroute = 0;
296 position = dep->geod();
297 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is pending, departure in "
298 << flight->getDepartureTime() - now << " seconds ");
301 // departure / arrival coincident
302 //remainingTimeEnroute = totalTimeEnroute = 0.0;
303 elapsedTimeEnroute = 0;
304 position = dep->geod();
307 // cartesian calculations are more numerically stable over the (potentially)
308 // large distances involved here: see bug #80
309 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
312 // If distance between user and simulated aircraft is less
313 // then 500nm, create this flight. At jet speeds 500 nm is roughly
314 // one hour flight time, so that would be a good approximate point
315 // to start a more detailed simulation of this aircraft.
316 SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
317 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
319 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
320 return true; // out of visual range, for the moment.
323 if (!createAIAircraft(flight, speed, deptime)) {
328 return true; // processing complete
331 bool FGAISchedule::validModelPath(const std::string& modelPath)
333 return (resolveModelPath(modelPath) != SGPath());
336 SGPath FGAISchedule::resolveModelPath(const std::string& modelPath)
338 BOOST_FOREACH(SGPath aiPath, globals->get_data_paths("AI")) {
339 aiPath.append(modelPath);
340 if (aiPath.exists()) {
345 // check aircraft dirs
346 BOOST_FOREACH(std::string aircraftPath, globals->get_aircraft_paths()) {
347 SGPath mp(aircraftPath);
348 mp.append(modelPath);
357 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
359 FGAirport* dep = flight->getDepartureAirport();
360 FGAirport* arr = flight->getArrivalAirport();
361 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
362 SG_LOG(SG_AI, SG_DEBUG, "Traffic manager: Creating AIModel from:" << flightPlanName);
364 aiAircraft = new FGAIAircraft(this);
365 aiAircraft->setPerformance(acType, m_class); //"jet_transport";
366 aiAircraft->setCompany(airline); //i->getAirline();
367 aiAircraft->setAcType(acType); //i->getAcType();
368 aiAircraft->setPath(modelPath.c_str());
369 //aircraft->setFlightPlan(flightPlanName);
370 aiAircraft->setLatitude(position.getLatitudeDeg());
371 aiAircraft->setLongitude(position.getLongitudeDeg());
372 aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
373 aiAircraft->setSpeed(0);
374 aiAircraft->setBank(0);
376 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
377 FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
378 dep, arr, true, radius,
379 flight->getCruiseAlt()*100,
380 position.getLatitudeDeg(),
381 position.getLongitudeDeg(),
382 speedKnots, flightType, acType,
384 if (fp->isValidPlan()) {
385 aiAircraft->SetFlightPlan(fp);
386 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
387 aimgr->attach(aiAircraft);
392 //hand back the flights that had already been scheduled
393 while (!flights.empty()) {
394 flights.front()->release();
395 flights.erase(flights.begin());
401 // Create an initial heading for user controlled aircraft.
402 void FGAISchedule::setHeading()
404 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
407 void FGAISchedule::assign(FGScheduledFlight *ref) { flights.push_back(ref); }
409 bool FGAISchedule::scheduleFlights(time_t now)
411 //string startingPort;
412 const string& userPort = fgGetString("/sim/presets/airport-id");
413 SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
414 FGScheduledFlight *flight = NULL;
419 if (currentDestination.empty())
420 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
423 if ((!flight)||(!first)) {
424 flight = findAvailableFlight(currentDestination, flightIdentifier);
431 currentDestination = flight->getArrivalAirport()->getId();
432 //cerr << "Current destination " << currentDestination << endl;
434 const string& departurePort = flight->getDepartureAirport()->getId();
435 if (userPort == departurePort) {
445 if (sglog().would_log(SG_AI, SG_BULK))
448 dep = flight->getDepartureTime();
449 arr = flight->getArrivalTime();
450 string depT = asctime(gmtime(&dep));
451 string arrT = asctime(gmtime(&arr));
452 depT = depT.substr(0,24);
453 arrT = arrT.substr(0,24);
454 SG_LOG(SG_AI, SG_BULK, " Flight " << flight->getCallSign() << ":"
455 << " " << flight->getDepartureAirport()->getId() << ":"
456 << " " << depT << ":"
457 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
458 << " " << arrT << ":");
461 flights.push_back(flight);
463 // continue processing until complete, or preempt after timeout
464 } while ((currentDestination != homePort)&&
465 (start.elapsedMSec()<3.0));
467 if (flight && (currentDestination != homePort))
469 // processing preempted, need to continue in next iteration
473 SG_LOG(SG_AI, SG_BULK, " Done ");
477 bool FGAISchedule::next()
479 if (!flights.empty()) {
480 flights.front()->release();
481 flights.erase(flights.begin());
484 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
489 currentDestination = flight->getArrivalAirport()->getId();
492 dep = flight->getDepartureTime();
493 arr = flight->getArrivalTime();
494 string depT = asctime(gmtime(&dep));
495 string arrT = asctime(gmtime(&arr));
497 depT = depT.substr(0,24);
498 arrT = arrT.substr(0,24);
499 //cerr << " " << flight->getCallSign() << ":"
500 // << " " << flight->getDepartureAirport()->getId() << ":"
501 // << " " << depT << ":"
502 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
503 // << " " << arrT << ":" << endl;
505 flights.push_back(flight);
509 time_t FGAISchedule::getDepartureTime()
514 return (*flights.begin())->getDepartureTime ();
517 FGAirport *FGAISchedule::getDepartureAirport()
522 return (*flights.begin())->getDepartureAirport();
525 FGAirport *FGAISchedule::getArrivalAirport()
530 return (*flights.begin())->getArrivalAirport ();
533 int FGAISchedule::getCruiseAlt()
538 return (*flights.begin())->getCruiseAlt ();
541 std::string FGAISchedule::getCallSign()
544 return std::string();
546 return (*flights.begin())->getCallSign ();
549 std::string FGAISchedule::getFlightRules()
552 return std::string();
554 return (*flights.begin())->getFlightRules ();
557 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
559 time_t min, time_t max)
561 time_t now = globals->get_time_params()->get_cur_time();
563 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
564 FGScheduledFlightVecIterator fltBegin, fltEnd;
565 fltBegin = tmgr->getFirstFlight(req);
566 fltEnd = tmgr->getLastFlight(req);
569 //cerr << "Finding available flight " << endl;
571 // Traverse every registered flight
572 if (fltBegin == fltEnd) {
573 //cerr << "No Flights Scheduled for " << req << endl;
576 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
577 (*i)->adjustTime(now);
578 //sort(fltBegin, fltEnd, compareScheduledFlights);
579 //cerr << counter++ << endl;
581 std::sort(fltBegin, fltEnd, compareScheduledFlights);
582 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
585 if (!(*i)->isAvailable()) {
586 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
589 if (!((*i)->getRequirement() == req)) {
592 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
595 if (!(currentDestination.empty())) {
596 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
597 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
598 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
599 // (*i)->getArrivalAirport()->getId() << endl;
603 if (! flights.empty()) {
604 time_t arrival = flights.back()->getArrivalTime();
605 int groundTime = groundTimeFromRadius();
606 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
610 time_t dep = (*i)->getDepartureTime();
611 if ((dep < min) || (dep > max))
615 // So, if we actually get here, we have a winner
616 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
617 // (*i)->getArrivalAirport()->getId() << endl;
622 // if currentDestination has a value, does it match departure of next flight?
623 // is departure time later than planned arrival?
624 // is departure port valid?
625 // is arrival port valid?
626 //cerr << "Ack no flight found: " << endl;
630 int FGAISchedule::groundTimeFromRadius()
634 else if (radius < 15)
636 else if (radius < 20)
638 else if (radius < 25)
640 else if (radius < 30)
647 double FGAISchedule::getSpeed()
649 FGScheduledFlightVecIterator i = flights.begin();
651 FGAirport* dep = (*i)->getDepartureAirport(),
652 *arr = (*i)->getArrivalAirport();
653 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
654 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
657 if (remainingTimeEnroute > 0.01)
658 speed = dist / (remainingTimeEnroute/3600.0);
660 SG_CLAMP_RANGE(speed, 300.0, 500.0);
664 void FGAISchedule::setScore ()
667 score = ((double) hits / (double) runCount);
669 if (homePort == fgGetString("/sim/presets/airport-id")) {
678 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
683 bool FGAISchedule::operator< (const FGAISchedule &other) const
685 //cerr << "Sorting " << registration << " and " << other.registration << endl;
686 double currentScore = score * (1.5 - lastRun);
687 double otherScore = other.score * (1.5 - other.lastRun);
688 return currentScore > otherScore;