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()
75 FGAISchedule::FGAISchedule(string mdl,
86 FGScheduledFlightVec flt)*/
87 FGAISchedule::FGAISchedule(string model,
104 flightIdentifier = flightId;
113 /*for (FGScheduledFlightVecIterator i = flt.begin();
116 flights.push_back(new FGScheduledFlight((*(*i))));*/
126 FGAISchedule::FGAISchedule(const FGAISchedule &other)
128 modelPath = other.modelPath;
129 homePort = other.homePort;
130 livery = other.livery;
131 registration = other.registration;
133 flightIdentifier = other.flightIdentifier;
134 flights = other.flights;
135 aiAircraft = other.aiAircraft;
136 acType = other.acType;
137 airline = other.airline;
138 m_class = other.m_class;
139 firstRun = other.firstRun;
140 radius = other.radius;
141 groundOffset = other.groundOffset;
142 flightType = other.flightType;
144 distanceToUser = other.distanceToUser;
145 currentDestination = other.currentDestination;
146 firstRun = other.firstRun;
147 runCount = other.runCount;
149 lastRun = other.lastRun;
150 initialized = other.initialized;
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();
197 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
202 //remainingTimeEnroute,
207 scheduleFlights(now);
208 if (flights.empty()) { // No flights available for this aircraft
213 // Sort all the scheduled flights according to scheduled departure time.
214 // Because this is done at every update, we only need to check the status
215 // of the first listed flight.
216 //sort(flights.begin(), flights.end(), compareScheduledFlights);
219 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
220 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
221 // from cluttering the gate areas.
226 FGScheduledFlight* flight = flights.front();
228 deptime = flight->getDepartureTime();
229 //cerr << "Settiing departure time " << deptime << endl;
233 if (aiAircraft->getDie()) {
236 return true; // in visual range, let the AIManager handle it
240 // This flight entry is entirely in the past, do we need to
241 // push it forward in time to the next scheduled departure.
242 if (flight->getArrivalTime() < now) {
243 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in the Past");
244 // Don't just update: check whether we need to load a new leg. etc.
245 // This update occurs for distant aircraft, so we can update the current leg
246 // and detach it from the current list of aircraft.
248 flights.erase(flights.begin()); // pop_front(), effectively
252 FGAirport* dep = flight->getDepartureAirport();
253 FGAirport* arr = flight->getArrivalAirport();
258 double speed = 450.0;
260 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
261 if (flight->getDepartureTime() < now) {
262 elapsedTimeEnroute = now - flight->getDepartureTime();
263 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
264 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
266 // current pos is based on great-circle course between departure/arrival,
267 // with percentage of distance travelled, based upon percentage of time
269 double course, az2, distanceM;
270 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
271 double coveredDistance = distanceM * x;
273 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
275 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
276 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
279 //remainingTimeEnroute = totalTimeEnroute;
280 elapsedTimeEnroute = 0;
281 position = dep->geod();
282 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is pending, departure in "
283 << flight->getDepartureTime() - now << " seconds ");
286 // departure / arrival coincident
287 //remainingTimeEnroute = totalTimeEnroute = 0.0;
288 elapsedTimeEnroute = 0;
289 position = dep->geod();
292 // cartesian calculations are more numerically stable over the (potentially)
293 // large distances involved here: see bug #80
294 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
296 // If distance between user and simulated aircaft is less
297 // then 500nm, create this flight. At jet speeds 500 nm is roughly
298 // one hour flight time, so that would be a good approximate point
299 // to start a more detailed simulation of this aircraft.
300 SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
301 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
303 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
304 return true; // out of visual range, for the moment.
306 return createAIAircraft(flight, speed, deptime);
309 bool FGAISchedule::validModelPath(const std::string& modelPath)
311 SGPath mp(globals->get_fg_root());
314 mp.append(modelPath);
316 mp_ai.append(modelPath);
318 return mp.exists() || mp_ai.exists();
321 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
323 FGAirport* dep = flight->getDepartureAirport();
324 FGAirport* arr = flight->getArrivalAirport();
325 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
326 SG_LOG(SG_AI, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
328 // Only allow traffic to be created when the model path (or the AI version of mp) exists
329 SGPath mp(globals->get_fg_root());
332 mp.append(modelPath);
334 mp_ai.append(modelPath);
336 if (!mp.exists() && !mp_ai.exists()) {
337 SG_LOG(SG_AI, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
341 aiAircraft = new FGAIAircraft(this);
342 aiAircraft->setPerformance(acType, m_class); //"jet_transport";
343 aiAircraft->setCompany(airline); //i->getAirline();
344 aiAircraft->setAcType(acType); //i->getAcType();
345 aiAircraft->setPath(modelPath.c_str());
346 //aircraft->setFlightPlan(flightPlanName);
347 aiAircraft->setLatitude(position.getLatitudeDeg());
348 aiAircraft->setLongitude(position.getLongitudeDeg());
349 aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
350 aiAircraft->setSpeed(0);
351 aiAircraft->setBank(0);
353 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
354 FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
355 dep, arr, true, radius,
356 flight->getCruiseAlt()*100,
357 position.getLatitudeDeg(),
358 position.getLongitudeDeg(),
359 speedKnots, flightType, acType,
361 if (fp->isValidPlan()) {
362 aiAircraft->SetFlightPlan(fp);
363 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
364 aimgr->attach(aiAircraft);
369 //hand back the flights that had already been scheduled
370 while (!flights.empty()) {
371 flights.front()->release();
372 flights.erase(flights.begin());
378 // Create an initial heading for user controlled aircraft.
379 void FGAISchedule::setHeading()
381 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
384 void FGAISchedule::scheduleFlights(time_t now)
386 if (!flights.empty()) {
389 //string startingPort;
390 string userPort = fgGetString("/sim/presets/airport-id");
391 SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
392 FGScheduledFlight *flight = NULL;
394 if (currentDestination.empty()) {
395 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
397 flight = findAvailableFlight(currentDestination, flightIdentifier);
399 flight = findAvailableFlight(currentDestination, flightIdentifier);
404 currentDestination = flight->getArrivalAirport()->getId();
405 //cerr << "Current destination " << currentDestination << endl;
407 string departurePort = flight->getDepartureAirport()->getId();
408 if (userPort == departurePort) {
419 dep = flight->getDepartureTime();
420 arr = flight->getArrivalTime();
421 string depT = asctime(gmtime(&dep));
422 string arrT = asctime(gmtime(&arr));
424 depT = depT.substr(0,24);
425 arrT = arrT.substr(0,24);
426 SG_LOG(SG_AI, SG_BULK, " Flight " << flight->getCallSign() << ":"
427 << " " << flight->getDepartureAirport()->getId() << ":"
428 << " " << depT << ":"
429 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
430 << " " << arrT << ":");
432 flights.push_back(flight);
433 } while (currentDestination != homePort);
434 SG_LOG(SG_AI, SG_BULK, " Done ");
437 bool FGAISchedule::next()
439 if (!flights.empty()) {
440 flights.front()->release();
441 flights.erase(flights.begin());
444 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
449 currentDestination = flight->getArrivalAirport()->getId();
452 dep = flight->getDepartureTime();
453 arr = flight->getArrivalTime();
454 string depT = asctime(gmtime(&dep));
455 string arrT = asctime(gmtime(&arr));
457 depT = depT.substr(0,24);
458 arrT = arrT.substr(0,24);
459 //cerr << " " << flight->getCallSign() << ":"
460 // << " " << flight->getDepartureAirport()->getId() << ":"
461 // << " " << depT << ":"
462 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
463 // << " " << arrT << ":" << endl;
465 flights.push_back(flight);
469 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
471 time_t min, time_t max)
473 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
475 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
476 FGScheduledFlightVecIterator fltBegin, fltEnd;
477 fltBegin = tmgr->getFirstFlight(req);
478 fltEnd = tmgr->getLastFlight(req);
481 //cerr << "Finding available flight " << endl;
483 // Traverse every registered flight
484 if (fltBegin == fltEnd) {
485 //cerr << "No Flights Scheduled for " << req << endl;
488 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
489 (*i)->adjustTime(now);
490 //sort(fltBegin, fltEnd, compareScheduledFlights);
491 //cerr << counter++ << endl;
493 std::sort(fltBegin, fltEnd, compareScheduledFlights);
494 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
497 if (!(*i)->isAvailable()) {
498 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
501 if (!((*i)->getRequirement() == req)) {
504 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
507 if (!(currentDestination.empty())) {
508 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
509 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
510 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
511 // (*i)->getArrivalAirport()->getId() << endl;
515 if (flights.size()) {
516 time_t arrival = flights.back()->getArrivalTime();
517 int groundTime = groundTimeFromRadius();
518 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
522 time_t dep = (*i)->getDepartureTime();
523 if ((dep < min) || (dep > max))
527 // So, if we actually get here, we have a winner
528 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
529 // (*i)->getArrivalAirport()->getId() << endl;
534 // if currentDestination has a value, does it match departure of next flight?
535 // is departure time later than planned arrival?
536 // is departure port valid?
537 // is arrival port valid?
538 //cerr << "Ack no flight found: " << endl;
542 int FGAISchedule::groundTimeFromRadius()
546 else if (radius < 15)
548 else if (radius < 20)
550 else if (radius < 25)
552 else if (radius < 30)
559 double FGAISchedule::getSpeed()
561 FGScheduledFlightVecIterator i = flights.begin();
563 FGAirport* dep = (*i)->getDepartureAirport(),
564 *arr = (*i)->getArrivalAirport();
565 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
566 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
568 double speed = dist / (remainingTimeEnroute/3600.0);
569 SG_CLAMP_RANGE(speed, 300.0, 500.0);
573 void FGAISchedule::setScore ()
576 score = ((double) hits / (double) runCount);
578 if (homePort == fgGetString("/sim/presets/airport-id")) {
587 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
592 bool FGAISchedule::operator< (const FGAISchedule &other) const
594 //cerr << "Sorting " << registration << " and " << other.registration << endl;
595 double currentScore = score * (1.5 - lastRun);
596 double otherScore = other.score * (1.5 - other.lastRun);
597 return currentScore > otherScore;