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 *****************************************************************************/
40 #include <simgear/compiler.h>
41 #include <simgear/sg_inlines.h>
42 #include <simgear/math/sg_geodesy.hxx>
43 #include <simgear/props/props.hxx>
44 #include <simgear/route/waypoint.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/simple.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()
77 FGAISchedule::FGAISchedule(string mdl,
88 FGScheduledFlightVec flt)*/
89 FGAISchedule::FGAISchedule(string model,
106 flightIdentifier = flightId;
115 /*for (FGScheduledFlightVecIterator i = flt.begin();
118 flights.push_back(new FGScheduledFlight((*(*i))));*/
129 FGAISchedule::FGAISchedule(const FGAISchedule &other)
131 modelPath = other.modelPath;
132 homePort = other.homePort;
133 livery = other.livery;
134 registration = other.registration;
136 flightIdentifier = other.flightIdentifier;
137 flights = other.flights;
138 AIManagerRef = other.AIManagerRef;
139 acType = other.acType;
140 airline = other.airline;
141 m_class = other.m_class;
142 firstRun = other.firstRun;
143 radius = other.radius;
144 groundOffset = other.groundOffset;
145 flightType = other.flightType;
147 distanceToUser = other.distanceToUser;
148 currentDestination = other.currentDestination;
149 firstRun = other.firstRun;
150 runCount = other.runCount;
152 lastRun = other.lastRun;
153 initialized = other.initialized;
159 FGAISchedule::~FGAISchedule()
161 // remove related object from AI manager
164 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
166 aimgr->destroyObject(AIManagerRef);
170 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
177 bool FGAISchedule::init()
180 //SGTime* currTimeDate = globals->get_time_params();
182 //tm *temp = currTimeDate->getGmt();
184 //sgTimeFormatTime(&targetTimeDate, buffer);
185 //cout << "Scheduled Time " << buffer << endl;
186 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
187 /*for (FGScheduledFlightVecIterator i = flights.begin();
191 //i->adjustTime(now);
192 if (!((*i)->initializeAirports()))
195 //sort(flights.begin(), flights.end());
196 // Since time isn't initialized yet when this function is called,
197 // Find the closest possible airport.
198 // This should give a reasonable initialization order.
199 //setClosestDistanceToUser();
203 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
208 //remainingTimeEnroute,
213 scheduleFlights(now);
214 if (flights.empty()) { // No flights available for this aircraft
219 // Sort all the scheduled flights according to scheduled departure time.
220 // Because this is done at every update, we only need to check the status
221 // of the first listed flight.
222 //sort(flights.begin(), flights.end(), compareScheduledFlights);
225 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
226 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
227 // from cluttering the gate areas.
232 FGScheduledFlight* flight = flights.front();
234 deptime = flight->getDepartureTime();
235 //cerr << "Settiing departure time " << deptime << endl;
239 // Check if this aircraft has been released.
240 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
241 if (tmgr->isReleased(AIManagerRef)) {
244 return true; // in visual range, let the AIManager handle it
248 // This flight entry is entirely in the past, do we need to
249 // push it forward in time to the next scheduled departure.
250 if (flight->getArrivalTime() < now) {
251 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is in the Past");
252 // Don't just update: check whether we need to load a new leg. etc.
253 // This update occurs for distant aircraft, so we can update the current leg
254 // and detach it from the current list of aircraft.
256 flights.erase(flights.begin()); // pop_front(), effectively
260 FGAirport* dep = flight->getDepartureAirport();
261 FGAirport* arr = flight->getArrivalAirport();
266 double speed = 450.0;
268 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
269 if (flight->getDepartureTime() < now) {
270 elapsedTimeEnroute = now - flight->getDepartureTime();
271 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
272 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
274 // current pos is based on great-circle course between departure/arrival,
275 // with percentage of distance travelled, based upon percentage of time
277 double course, az2, distanceM;
278 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
279 double coveredDistance = distanceM * x;
281 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
283 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
284 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
287 //remainingTimeEnroute = totalTimeEnroute;
288 elapsedTimeEnroute = 0;
289 position = dep->geod();
290 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is pending, departure in "
291 << flight->getDepartureTime() - now << " seconds ");
294 // departure / arrival coincident
295 //remainingTimeEnroute = totalTimeEnroute = 0.0;
296 elapsedTimeEnroute = 0;
297 position = dep->geod();
300 // cartesian calculations are more numerically stable over the (potentially)
301 // large distances involved here: see bug #80
302 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
304 // If distance between user and simulated aircaft is less
305 // then 500nm, create this flight. At jet speeds 500 nm is roughly
306 // one hour flight time, so that would be a good approximate point
307 // to start a more detailed simulation of this aircraft.
308 SG_LOG (SG_GENERAL, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
309 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
311 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
312 return true; // out of visual range, for the moment.
314 return createAIAircraft(flight, speed, deptime);
317 bool FGAISchedule::validModelPath(const std::string& modelPath)
319 SGPath mp(globals->get_fg_root());
322 mp.append(modelPath);
324 mp_ai.append(modelPath);
326 return mp.exists() || mp_ai.exists();
329 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
331 FGAirport* dep = flight->getDepartureAirport();
332 FGAirport* arr = flight->getArrivalAirport();
333 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
334 SG_LOG(SG_GENERAL, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
336 // Only allow traffic to be created when the model path (or the AI version of mp) exists
337 SGPath mp(globals->get_fg_root());
340 mp.append(modelPath);
342 mp_ai.append(modelPath);
344 if (!mp.exists() && !mp_ai.exists()) {
345 SG_LOG(SG_GENERAL, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
349 FGAIAircraft *aircraft = new FGAIAircraft(this);
350 aircraft->setPerformance(m_class); //"jet_transport";
351 aircraft->setCompany(airline); //i->getAirline();
352 aircraft->setAcType(acType); //i->getAcType();
353 aircraft->setPath(modelPath.c_str());
354 //aircraft->setFlightPlan(flightPlanName);
355 aircraft->setLatitude(position.getLatitudeDeg());
356 aircraft->setLongitude(position.getLongitudeDeg());
357 aircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
358 aircraft->setSpeed(0);
359 aircraft->setBank(0);
361 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
362 FGAIFlightPlan *fp = new FGAIFlightPlan(aircraft, flightPlanName, courseToDest, deptime,
363 dep, arr, true, radius,
364 flight->getCruiseAlt()*100,
365 position.getLatitudeDeg(),
366 position.getLongitudeDeg(),
367 speedKnots, flightType, acType,
369 if (fp->isValidPlan()) {
370 aircraft->SetFlightPlan(fp);
371 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
372 aimgr->attach(aircraft);
373 AIManagerRef = aircraft->getID();
378 //hand back the flights that had already been scheduled
379 while (!flights.empty()) {
380 flights.front()->release();
381 flights.erase(flights.begin());
387 // Create an initial heading for user controlled aircraft.
388 void FGAISchedule::setHeading()
390 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
393 void FGAISchedule::scheduleFlights(time_t now)
395 if (!flights.empty()) {
398 //string startingPort;
399 string userPort = fgGetString("/sim/presets/airport-id");
400 SG_LOG(SG_GENERAL, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
401 FGScheduledFlight *flight = NULL;
403 if (currentDestination.empty()) {
404 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
406 flight = findAvailableFlight(currentDestination, flightIdentifier);
408 flight = findAvailableFlight(currentDestination, flightIdentifier);
413 currentDestination = flight->getArrivalAirport()->getId();
414 //cerr << "Current destination " << currentDestination << endl;
416 string departurePort = flight->getDepartureAirport()->getId();
417 if (userPort == departurePort) {
428 dep = flight->getDepartureTime();
429 arr = flight->getArrivalTime();
430 string depT = asctime(gmtime(&dep));
431 string arrT = asctime(gmtime(&arr));
433 depT = depT.substr(0,24);
434 arrT = arrT.substr(0,24);
435 SG_LOG(SG_GENERAL, SG_BULK, " Flight " << flight->getCallSign() << ":"
436 << " " << flight->getDepartureAirport()->getId() << ":"
437 << " " << depT << ":"
438 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
439 << " " << arrT << ":");
441 flights.push_back(flight);
442 } while (currentDestination != homePort);
443 SG_LOG(SG_GENERAL, SG_BULK, " Done ");
446 bool FGAISchedule::next()
448 if (!flights.empty()) {
449 flights.front()->release();
450 flights.erase(flights.begin());
453 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
458 currentDestination = flight->getArrivalAirport()->getId();
461 dep = flight->getDepartureTime();
462 arr = flight->getArrivalTime();
463 string depT = asctime(gmtime(&dep));
464 string arrT = asctime(gmtime(&arr));
466 depT = depT.substr(0,24);
467 arrT = arrT.substr(0,24);
468 //cerr << " " << flight->getCallSign() << ":"
469 // << " " << flight->getDepartureAirport()->getId() << ":"
470 // << " " << depT << ":"
471 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
472 // << " " << arrT << ":" << endl;
474 flights.push_back(flight);
478 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
480 time_t min, time_t max)
482 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
484 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
485 FGScheduledFlightVecIterator fltBegin, fltEnd;
486 fltBegin = tmgr->getFirstFlight(req);
487 fltEnd = tmgr->getLastFlight(req);
490 //cerr << "Finding available flight " << endl;
492 // Traverse every registered flight
493 if (fltBegin == fltEnd) {
494 //cerr << "No Flights Scheduled for " << req << endl;
497 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
498 (*i)->adjustTime(now);
499 //sort(fltBegin, fltEnd, compareScheduledFlights);
500 //cerr << counter++ << endl;
502 std::sort(fltBegin, fltEnd, compareScheduledFlights);
503 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
506 if (!(*i)->isAvailable()) {
507 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
510 if (!((*i)->getRequirement() == req)) {
513 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
516 if (!(currentDestination.empty())) {
517 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
518 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
519 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
520 // (*i)->getArrivalAirport()->getId() << endl;
524 if (flights.size()) {
525 time_t arrival = flights.back()->getArrivalTime();
526 int groundTime = groundTimeFromRadius();
527 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
531 time_t dep = (*i)->getDepartureTime();
532 if ((dep < min) || (dep > max))
536 // So, if we actually get here, we have a winner
537 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
538 // (*i)->getArrivalAirport()->getId() << endl;
543 // if currentDestination has a value, does it match departure of next flight?
544 // is departure time later than planned arrival?
545 // is departure port valid?
546 // is arrival port valid?
547 //cerr << "Ack no flight found: " << endl;
551 int FGAISchedule::groundTimeFromRadius()
555 else if (radius < 15)
557 else if (radius < 20)
559 else if (radius < 25)
561 else if (radius < 30)
568 double FGAISchedule::getSpeed()
570 FGScheduledFlightVecIterator i = flights.begin();
572 FGAirport* dep = (*i)->getDepartureAirport(),
573 *arr = (*i)->getArrivalAirport();
574 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
575 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
577 double speed = dist / (remainingTimeEnroute/3600.0);
578 SG_CLAMP_RANGE(speed, 300.0, 500.0);
582 void FGAISchedule::setScore ()
585 score = ((double) hits / (double) runCount);
587 if (homePort == fgGetString("/sim/presets/airport-id")) {
596 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
601 bool FGAISchedule::operator< (const FGAISchedule &other) const
603 //cerr << "Sorting " << registration << " and " << other.registration << endl;
604 double currentScore = score * (1.5 - lastRun);
605 double otherScore = other.score * (1.5 - other.lastRun);
606 return currentScore > otherScore;