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>
48 #include <AIModel/AIFlightPlan.hxx>
49 #include <AIModel/AIManager.hxx>
50 #include <AIModel/AIAircraft.hxx>
51 #include <Airports/airport.hxx>
52 #include <Main/fg_init.hxx> // That's pretty ugly, but I need fgFindAirportID
55 #include "SchedFlight.hxx"
56 #include "TrafficMgr.hxx"
58 /******************************************************************************
59 * the FGAISchedule class contains data members and code to maintain a
60 * schedule of Flights for an artificially controlled aircraft.
61 *****************************************************************************/
62 FGAISchedule::FGAISchedule()
75 scheduleComplete(false)
80 FGAISchedule::FGAISchedule(const string& model,
84 const string& flightId,
104 scheduleComplete(false)
110 flightIdentifier = flightId;
115 /*for (FGScheduledFlightVecIterator i = flt.begin();
118 flights.push_back(new FGScheduledFlight((*(*i))));*/
121 FGAISchedule::FGAISchedule(const FGAISchedule &other)
123 modelPath = other.modelPath;
124 homePort = other.homePort;
125 livery = other.livery;
126 registration = other.registration;
128 flightIdentifier = other.flightIdentifier;
129 flights = other.flights;
130 aiAircraft = other.aiAircraft;
131 acType = other.acType;
132 airline = other.airline;
133 m_class = other.m_class;
134 firstRun = other.firstRun;
135 radius = other.radius;
136 groundOffset = other.groundOffset;
137 flightType = other.flightType;
139 distanceToUser = other.distanceToUser;
140 currentDestination = other.currentDestination;
141 firstRun = other.firstRun;
142 runCount = other.runCount;
144 lastRun = other.lastRun;
145 courseToDest = other.courseToDest;
146 initialized = other.initialized;
148 scheduleComplete = other.scheduleComplete;
153 FGAISchedule::~FGAISchedule()
155 // remove related object from AI manager
158 aiAircraft->setDie(true);
161 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
168 bool FGAISchedule::init()
171 //SGTime* currTimeDate = globals->get_time_params();
173 //tm *temp = currTimeDate->getGmt();
175 //sgTimeFormatTime(&targetTimeDate, buffer);
176 //cout << "Scheduled Time " << buffer << endl;
177 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
178 /*for (FGScheduledFlightVecIterator i = flights.begin();
182 //i->adjustTime(now);
183 if (!((*i)->initializeAirports()))
186 //sort(flights.begin(), flights.end());
187 // Since time isn't initialized yet when this function is called,
188 // Find the closest possible airport.
189 // This should give a reasonable initialization order.
190 //setClosestDistanceToUser();
195 * Returns true when processing is complete.
196 * Returns false when processing was aborted due to timeout, so
197 * more time required - and another call is requested (next sim iteration).
199 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
202 time_t totalTimeEnroute,
204 //remainingTimeEnroute,
208 return true; // processing complete
211 if (!scheduleComplete) {
212 scheduleComplete = scheduleFlights(now);
215 if (!scheduleComplete) {
216 return false; // not ready yet, continue processing in next iteration
219 if (flights.empty()) { // No flights available for this aircraft
221 return true; // processing complete
225 // Sort all the scheduled flights according to scheduled departure time.
226 // Because this is done at every update, we only need to check the status
227 // of the first listed flight.
228 //sort(flights.begin(), flights.end(), compareScheduledFlights);
231 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
232 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
233 // from cluttering the gate areas.
238 FGScheduledFlight* flight = flights.front();
240 deptime = flight->getDepartureTime();
241 //cerr << "Setting departure time " << deptime << endl;
245 if (aiAircraft->getDie()) {
248 return true; // in visual range, let the AIManager handle it
252 // This flight entry is entirely in the past, do we need to
253 // push it forward in time to the next scheduled departure.
254 if (flight->getArrivalTime() < now) {
255 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in the Past");
256 // Don't just update: check whether we need to load a new leg. etc.
257 // This update occurs for distant aircraft, so we can update the current leg
258 // and detach it from the current list of aircraft.
260 flights.erase(flights.begin()); // pop_front(), effectively
261 return true; // processing complete
264 FGAirport* dep = flight->getDepartureAirport();
265 FGAirport* arr = flight->getArrivalAirport();
267 return true; // processing complete
270 double speed = 450.0;
272 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
273 if (flight->getDepartureTime() < now) {
274 elapsedTimeEnroute = now - flight->getDepartureTime();
275 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
276 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
278 // current pos is based on great-circle course between departure/arrival,
279 // with percentage of distance travelled, based upon percentage of time
281 double course, az2, distanceM;
282 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
283 double coveredDistance = distanceM * x;
285 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
287 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
288 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
291 //remainingTimeEnroute = totalTimeEnroute;
292 elapsedTimeEnroute = 0;
293 position = dep->geod();
294 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is pending, departure in "
295 << flight->getDepartureTime() - now << " seconds ");
298 // departure / arrival coincident
299 //remainingTimeEnroute = totalTimeEnroute = 0.0;
300 elapsedTimeEnroute = 0;
301 position = dep->geod();
304 // cartesian calculations are more numerically stable over the (potentially)
305 // large distances involved here: see bug #80
306 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
309 // If distance between user and simulated aircraft is less
310 // then 500nm, create this flight. At jet speeds 500 nm is roughly
311 // one hour flight time, so that would be a good approximate point
312 // to start a more detailed simulation of this aircraft.
313 SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
314 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
316 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
317 return true; // out of visual range, for the moment.
320 if (!createAIAircraft(flight, speed, deptime)) {
325 return true; // processing complete
328 bool FGAISchedule::validModelPath(const std::string& modelPath)
330 return (resolveModelPath(modelPath) != SGPath());
333 SGPath FGAISchedule::resolveModelPath(const std::string& modelPath)
335 BOOST_FOREACH(SGPath aiPath, globals->get_data_paths("AI")) {
336 aiPath.append(modelPath);
337 if (aiPath.exists()) {
342 // check aircraft dirs
343 BOOST_FOREACH(std::string aircraftPath, globals->get_aircraft_paths()) {
344 SGPath mp(aircraftPath);
345 mp.append(modelPath);
354 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
356 FGAirport* dep = flight->getDepartureAirport();
357 FGAirport* arr = flight->getArrivalAirport();
358 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
359 SG_LOG(SG_AI, SG_DEBUG, "Traffic manager: Creating AIModel from:" << flightPlanName);
361 aiAircraft = new FGAIAircraft(this);
362 aiAircraft->setPerformance(acType, m_class); //"jet_transport";
363 aiAircraft->setCompany(airline); //i->getAirline();
364 aiAircraft->setAcType(acType); //i->getAcType();
365 aiAircraft->setPath(modelPath.c_str());
366 //aircraft->setFlightPlan(flightPlanName);
367 aiAircraft->setLatitude(position.getLatitudeDeg());
368 aiAircraft->setLongitude(position.getLongitudeDeg());
369 aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
370 aiAircraft->setSpeed(0);
371 aiAircraft->setBank(0);
373 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
374 FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
375 dep, arr, true, radius,
376 flight->getCruiseAlt()*100,
377 position.getLatitudeDeg(),
378 position.getLongitudeDeg(),
379 speedKnots, flightType, acType,
381 if (fp->isValidPlan()) {
382 aiAircraft->SetFlightPlan(fp);
383 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
384 aimgr->attach(aiAircraft);
389 //hand back the flights that had already been scheduled
390 while (!flights.empty()) {
391 flights.front()->release();
392 flights.erase(flights.begin());
398 // Create an initial heading for user controlled aircraft.
399 void FGAISchedule::setHeading()
401 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
404 bool FGAISchedule::scheduleFlights(time_t now)
406 //string startingPort;
407 const string& userPort = fgGetString("/sim/presets/airport-id");
408 SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
409 FGScheduledFlight *flight = NULL;
414 if (currentDestination.empty())
415 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
418 if ((!flight)||(!first)) {
419 flight = findAvailableFlight(currentDestination, flightIdentifier);
426 currentDestination = flight->getArrivalAirport()->getId();
427 //cerr << "Current destination " << currentDestination << endl;
429 const string& departurePort = flight->getDepartureAirport()->getId();
430 if (userPort == departurePort) {
440 if (sglog().would_log(SG_AI, SG_BULK))
443 dep = flight->getDepartureTime();
444 arr = flight->getArrivalTime();
445 string depT = asctime(gmtime(&dep));
446 string arrT = asctime(gmtime(&arr));
447 depT = depT.substr(0,24);
448 arrT = arrT.substr(0,24);
449 SG_LOG(SG_AI, SG_BULK, " Flight " << flight->getCallSign() << ":"
450 << " " << flight->getDepartureAirport()->getId() << ":"
451 << " " << depT << ":"
452 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
453 << " " << arrT << ":");
456 flights.push_back(flight);
458 // continue processing until complete, or preempt after timeout
459 } while ((currentDestination != homePort)&&
460 (start.elapsedMSec()<3.0));
462 if (flight && (currentDestination != homePort))
464 // processing preempted, need to continue in next iteration
468 SG_LOG(SG_AI, SG_BULK, " Done ");
472 bool FGAISchedule::next()
474 if (!flights.empty()) {
475 flights.front()->release();
476 flights.erase(flights.begin());
479 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
484 currentDestination = flight->getArrivalAirport()->getId();
487 dep = flight->getDepartureTime();
488 arr = flight->getArrivalTime();
489 string depT = asctime(gmtime(&dep));
490 string arrT = asctime(gmtime(&arr));
492 depT = depT.substr(0,24);
493 arrT = arrT.substr(0,24);
494 //cerr << " " << flight->getCallSign() << ":"
495 // << " " << flight->getDepartureAirport()->getId() << ":"
496 // << " " << depT << ":"
497 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
498 // << " " << arrT << ":" << endl;
500 flights.push_back(flight);
504 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
506 time_t min, time_t max)
508 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
510 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
511 FGScheduledFlightVecIterator fltBegin, fltEnd;
512 fltBegin = tmgr->getFirstFlight(req);
513 fltEnd = tmgr->getLastFlight(req);
516 //cerr << "Finding available flight " << endl;
518 // Traverse every registered flight
519 if (fltBegin == fltEnd) {
520 //cerr << "No Flights Scheduled for " << req << endl;
523 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
524 (*i)->adjustTime(now);
525 //sort(fltBegin, fltEnd, compareScheduledFlights);
526 //cerr << counter++ << endl;
528 std::sort(fltBegin, fltEnd, compareScheduledFlights);
529 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
532 if (!(*i)->isAvailable()) {
533 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
536 if (!((*i)->getRequirement() == req)) {
539 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
542 if (!(currentDestination.empty())) {
543 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
544 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
545 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
546 // (*i)->getArrivalAirport()->getId() << endl;
550 if (! flights.empty()) {
551 time_t arrival = flights.back()->getArrivalTime();
552 int groundTime = groundTimeFromRadius();
553 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
557 time_t dep = (*i)->getDepartureTime();
558 if ((dep < min) || (dep > max))
562 // So, if we actually get here, we have a winner
563 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
564 // (*i)->getArrivalAirport()->getId() << endl;
569 // if currentDestination has a value, does it match departure of next flight?
570 // is departure time later than planned arrival?
571 // is departure port valid?
572 // is arrival port valid?
573 //cerr << "Ack no flight found: " << endl;
577 int FGAISchedule::groundTimeFromRadius()
581 else if (radius < 15)
583 else if (radius < 20)
585 else if (radius < 25)
587 else if (radius < 30)
594 double FGAISchedule::getSpeed()
596 FGScheduledFlightVecIterator i = flights.begin();
598 FGAirport* dep = (*i)->getDepartureAirport(),
599 *arr = (*i)->getArrivalAirport();
600 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
601 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
603 double speed = dist / (remainingTimeEnroute/3600.0);
604 SG_CLAMP_RANGE(speed, 300.0, 500.0);
608 void FGAISchedule::setScore ()
611 score = ((double) hits / (double) runCount);
613 if (homePort == fgGetString("/sim/presets/airport-id")) {
622 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
627 bool FGAISchedule::operator< (const FGAISchedule &other) const
629 //cerr << "Sorting " << registration << " and " << other.registration << endl;
630 double currentScore = score * (1.5 - lastRun);
631 double otherScore = other.score * (1.5 - other.lastRun);
632 return currentScore > otherScore;