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/structure/subsystem_mgr.hxx>
45 #include <simgear/xml/easyxml.hxx>
47 #include <AIModel/AIFlightPlan.hxx>
48 #include <AIModel/AIManager.hxx>
49 #include <AIModel/AIAircraft.hxx>
50 #include <Airports/simple.hxx>
51 #include <Main/fg_init.hxx> // That's pretty ugly, but I need fgFindAirportID
54 #include "SchedFlight.hxx"
55 #include "TrafficMgr.hxx"
57 /******************************************************************************
58 * the FGAISchedule class contains data members and code to maintain a
59 * schedule of Flights for an artificially controlled aircraft.
60 *****************************************************************************/
61 FGAISchedule::FGAISchedule()
78 FGAISchedule::FGAISchedule(const string& model,
82 const string& flightId,
107 flightIdentifier = flightId;
112 /*for (FGScheduledFlightVecIterator i = flt.begin();
115 flights.push_back(new FGScheduledFlight((*(*i))));*/
118 FGAISchedule::FGAISchedule(const FGAISchedule &other)
120 modelPath = other.modelPath;
121 homePort = other.homePort;
122 livery = other.livery;
123 registration = other.registration;
125 flightIdentifier = other.flightIdentifier;
126 flights = other.flights;
127 aiAircraft = other.aiAircraft;
128 acType = other.acType;
129 airline = other.airline;
130 m_class = other.m_class;
131 firstRun = other.firstRun;
132 radius = other.radius;
133 groundOffset = other.groundOffset;
134 flightType = other.flightType;
136 distanceToUser = other.distanceToUser;
137 currentDestination = other.currentDestination;
138 firstRun = other.firstRun;
139 runCount = other.runCount;
141 lastRun = other.lastRun;
142 initialized = other.initialized;
148 FGAISchedule::~FGAISchedule()
150 // remove related object from AI manager
153 aiAircraft->setDie(true);
156 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
163 bool FGAISchedule::init()
166 //SGTime* currTimeDate = globals->get_time_params();
168 //tm *temp = currTimeDate->getGmt();
170 //sgTimeFormatTime(&targetTimeDate, buffer);
171 //cout << "Scheduled Time " << buffer << endl;
172 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
173 /*for (FGScheduledFlightVecIterator i = flights.begin();
177 //i->adjustTime(now);
178 if (!((*i)->initializeAirports()))
181 //sort(flights.begin(), flights.end());
182 // Since time isn't initialized yet when this function is called,
183 // Find the closest possible airport.
184 // This should give a reasonable initialization order.
185 //setClosestDistanceToUser();
189 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
194 //remainingTimeEnroute,
199 scheduleFlights(now);
200 if (flights.empty()) { // No flights available for this aircraft
205 // Sort all the scheduled flights according to scheduled departure time.
206 // Because this is done at every update, we only need to check the status
207 // of the first listed flight.
208 //sort(flights.begin(), flights.end(), compareScheduledFlights);
211 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
212 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
213 // from cluttering the gate areas.
218 FGScheduledFlight* flight = flights.front();
220 deptime = flight->getDepartureTime();
221 //cerr << "Setting departure time " << deptime << endl;
225 if (aiAircraft->getDie()) {
228 return true; // in visual range, let the AIManager handle it
232 // This flight entry is entirely in the past, do we need to
233 // push it forward in time to the next scheduled departure.
234 if (flight->getArrivalTime() < now) {
235 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in the Past");
236 // Don't just update: check whether we need to load a new leg. etc.
237 // This update occurs for distant aircraft, so we can update the current leg
238 // and detach it from the current list of aircraft.
240 flights.erase(flights.begin()); // pop_front(), effectively
244 FGAirport* dep = flight->getDepartureAirport();
245 FGAirport* arr = flight->getArrivalAirport();
250 double speed = 450.0;
252 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
253 if (flight->getDepartureTime() < now) {
254 elapsedTimeEnroute = now - flight->getDepartureTime();
255 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
256 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
258 // current pos is based on great-circle course between departure/arrival,
259 // with percentage of distance travelled, based upon percentage of time
261 double course, az2, distanceM;
262 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
263 double coveredDistance = distanceM * x;
265 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
267 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
268 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
271 //remainingTimeEnroute = totalTimeEnroute;
272 elapsedTimeEnroute = 0;
273 position = dep->geod();
274 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is pending, departure in "
275 << flight->getDepartureTime() - now << " seconds ");
278 // departure / arrival coincident
279 //remainingTimeEnroute = totalTimeEnroute = 0.0;
280 elapsedTimeEnroute = 0;
281 position = dep->geod();
284 // cartesian calculations are more numerically stable over the (potentially)
285 // large distances involved here: see bug #80
286 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
288 // If distance between user and simulated aircaft is less
289 // then 500nm, create this flight. At jet speeds 500 nm is roughly
290 // one hour flight time, so that would be a good approximate point
291 // to start a more detailed simulation of this aircraft.
292 SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
293 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
295 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
296 return true; // out of visual range, for the moment.
298 return createAIAircraft(flight, speed, deptime);
301 bool FGAISchedule::validModelPath(const std::string& modelPath)
303 SGPath mp(globals->get_fg_root());
306 mp.append(modelPath);
308 mp_ai.append(modelPath);
310 return mp.exists() || mp_ai.exists();
313 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
315 FGAirport* dep = flight->getDepartureAirport();
316 FGAirport* arr = flight->getArrivalAirport();
317 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
318 SG_LOG(SG_AI, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
320 // Only allow traffic to be created when the model path (or the AI version of mp) exists
321 SGPath mp(globals->get_fg_root());
324 mp.append(modelPath);
326 mp_ai.append(modelPath);
328 if (!mp.exists() && !mp_ai.exists()) {
329 SG_LOG(SG_AI, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
333 aiAircraft = new FGAIAircraft(this);
334 aiAircraft->setPerformance(acType, m_class); //"jet_transport";
335 aiAircraft->setCompany(airline); //i->getAirline();
336 aiAircraft->setAcType(acType); //i->getAcType();
337 aiAircraft->setPath(modelPath.c_str());
338 //aircraft->setFlightPlan(flightPlanName);
339 aiAircraft->setLatitude(position.getLatitudeDeg());
340 aiAircraft->setLongitude(position.getLongitudeDeg());
341 aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
342 aiAircraft->setSpeed(0);
343 aiAircraft->setBank(0);
345 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
346 FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
347 dep, arr, true, radius,
348 flight->getCruiseAlt()*100,
349 position.getLatitudeDeg(),
350 position.getLongitudeDeg(),
351 speedKnots, flightType, acType,
353 if (fp->isValidPlan()) {
354 aiAircraft->SetFlightPlan(fp);
355 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
356 aimgr->attach(aiAircraft);
361 //hand back the flights that had already been scheduled
362 while (!flights.empty()) {
363 flights.front()->release();
364 flights.erase(flights.begin());
370 // Create an initial heading for user controlled aircraft.
371 void FGAISchedule::setHeading()
373 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
376 void FGAISchedule::scheduleFlights(time_t now)
378 if (!flights.empty()) {
381 //string startingPort;
382 string userPort = fgGetString("/sim/presets/airport-id");
383 SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
384 FGScheduledFlight *flight = NULL;
386 if (currentDestination.empty()) {
387 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
389 flight = findAvailableFlight(currentDestination, flightIdentifier);
391 flight = findAvailableFlight(currentDestination, flightIdentifier);
396 currentDestination = flight->getArrivalAirport()->getId();
397 //cerr << "Current destination " << currentDestination << endl;
399 string departurePort = flight->getDepartureAirport()->getId();
400 if (userPort == departurePort) {
411 dep = flight->getDepartureTime();
412 arr = flight->getArrivalTime();
413 string depT = asctime(gmtime(&dep));
414 string arrT = asctime(gmtime(&arr));
416 depT = depT.substr(0,24);
417 arrT = arrT.substr(0,24);
418 SG_LOG(SG_AI, SG_BULK, " Flight " << flight->getCallSign() << ":"
419 << " " << flight->getDepartureAirport()->getId() << ":"
420 << " " << depT << ":"
421 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
422 << " " << arrT << ":");
424 flights.push_back(flight);
425 } while (currentDestination != homePort);
426 SG_LOG(SG_AI, SG_BULK, " Done ");
429 bool FGAISchedule::next()
431 if (!flights.empty()) {
432 flights.front()->release();
433 flights.erase(flights.begin());
436 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
441 currentDestination = flight->getArrivalAirport()->getId();
444 dep = flight->getDepartureTime();
445 arr = flight->getArrivalTime();
446 string depT = asctime(gmtime(&dep));
447 string arrT = asctime(gmtime(&arr));
449 depT = depT.substr(0,24);
450 arrT = arrT.substr(0,24);
451 //cerr << " " << flight->getCallSign() << ":"
452 // << " " << flight->getDepartureAirport()->getId() << ":"
453 // << " " << depT << ":"
454 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
455 // << " " << arrT << ":" << endl;
457 flights.push_back(flight);
461 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
463 time_t min, time_t max)
465 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
467 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
468 FGScheduledFlightVecIterator fltBegin, fltEnd;
469 fltBegin = tmgr->getFirstFlight(req);
470 fltEnd = tmgr->getLastFlight(req);
473 //cerr << "Finding available flight " << endl;
475 // Traverse every registered flight
476 if (fltBegin == fltEnd) {
477 //cerr << "No Flights Scheduled for " << req << endl;
480 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
481 (*i)->adjustTime(now);
482 //sort(fltBegin, fltEnd, compareScheduledFlights);
483 //cerr << counter++ << endl;
485 std::sort(fltBegin, fltEnd, compareScheduledFlights);
486 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
489 if (!(*i)->isAvailable()) {
490 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
493 if (!((*i)->getRequirement() == req)) {
496 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
499 if (!(currentDestination.empty())) {
500 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
501 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
502 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
503 // (*i)->getArrivalAirport()->getId() << endl;
507 if (flights.size()) {
508 time_t arrival = flights.back()->getArrivalTime();
509 int groundTime = groundTimeFromRadius();
510 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
514 time_t dep = (*i)->getDepartureTime();
515 if ((dep < min) || (dep > max))
519 // So, if we actually get here, we have a winner
520 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
521 // (*i)->getArrivalAirport()->getId() << endl;
526 // if currentDestination has a value, does it match departure of next flight?
527 // is departure time later than planned arrival?
528 // is departure port valid?
529 // is arrival port valid?
530 //cerr << "Ack no flight found: " << endl;
534 int FGAISchedule::groundTimeFromRadius()
538 else if (radius < 15)
540 else if (radius < 20)
542 else if (radius < 25)
544 else if (radius < 30)
551 double FGAISchedule::getSpeed()
553 FGScheduledFlightVecIterator i = flights.begin();
555 FGAirport* dep = (*i)->getDepartureAirport(),
556 *arr = (*i)->getArrivalAirport();
557 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
558 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
560 double speed = dist / (remainingTimeEnroute/3600.0);
561 SG_CLAMP_RANGE(speed, 300.0, 500.0);
565 void FGAISchedule::setScore ()
568 score = ((double) hits / (double) runCount);
570 if (homePort == fgGetString("/sim/presets/airport-id")) {
579 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
584 bool FGAISchedule::operator< (const FGAISchedule &other) const
586 //cerr << "Sorting " << registration << " and " << other.registration << endl;
587 double currentScore = score * (1.5 - lastRun);
588 double otherScore = other.score * (1.5 - other.lastRun);
589 return currentScore > otherScore;