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 articically controlled aircraft.
61 *****************************************************************************/
62 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))));*/
122 FGAISchedule::FGAISchedule(const FGAISchedule &other)
124 modelPath = other.modelPath;
125 homePort = other.homePort;
126 livery = other.livery;
127 registration = other.registration;
129 flightIdentifier = other.flightIdentifier;
130 flights = other.flights;
131 AIManagerRef = other.AIManagerRef;
132 acType = other.acType;
133 airline = other.airline;
134 m_class = other.m_class;
135 firstRun = other.firstRun;
136 radius = other.radius;
137 groundOffset = other.groundOffset;
138 flightType = other.flightType;
139 //score = other.score;
140 distanceToUser = other.distanceToUser;
141 currentDestination = other.currentDestination;
142 firstRun = other.firstRun;
146 FGAISchedule::~FGAISchedule()
148 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
155 bool FGAISchedule::init()
158 //SGTime* currTimeDate = globals->get_time_params();
160 //tm *temp = currTimeDate->getGmt();
162 //sgTimeFormatTime(&targetTimeDate, buffer);
163 //cout << "Scheduled Time " << buffer << endl;
164 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
165 /*for (FGScheduledFlightVecIterator i = flights.begin();
169 //i->adjustTime(now);
170 if (!((*i)->initializeAirports()))
173 //sort(flights.begin(), flights.end());
174 // Since time isn't initialized yet when this function is called,
175 // Find the closest possible airport.
176 // This should give a reasonable initialization order.
177 //setClosestDistanceToUser();
181 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
183 if (!fgGetBool("/sim/traffic-manager/enabled"))
189 remainingTimeEnroute,
193 if (flights.empty()) { // No flights available for this aircraft
197 // Sort all the scheduled flights according to scheduled departure time.
198 // Because this is done at every update, we only need to check the status
199 // of the first listed flight.
200 //sort(flights.begin(), flights.end(), compareScheduledFlights);
203 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
204 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
205 // from cluttering the gate areas.
210 FGScheduledFlight* flight = flights.front();
212 deptime = flight->getDepartureTime();
213 //cerr << "Settiing departure time " << deptime << endl;
217 // Check if this aircraft has been released.
218 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
219 if (tmgr->isReleased(AIManagerRef)) {
222 return true; // in visual range, let the AIManager handle it
226 // This flight entry is entirely in the past, do we need to
227 // push it forward in time to the next scheduled departure.
228 if (flight->getArrivalTime() < now) {
229 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is in the Past");
230 // Don't just update: check whether we need to load a new leg. etc.
231 // This update occurs for distant aircraft, so we can update the current leg
232 // and detach it from the current list of aircraft.
234 flights.erase(flights.begin()); // pop_front(), effectively
238 FGAirport* dep = flight->getDepartureAirport();
239 FGAirport* arr = flight->getArrivalAirport();
244 double speed = 450.0;
246 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
247 if (flight->getDepartureTime() < now) {
248 elapsedTimeEnroute = now - flight->getDepartureTime();
249 remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
250 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
252 // current pos is based on great-circle course between departure/arrival,
253 // with percentage of distance travelled, based upon percentage of time
255 double course, az2, distanceM;
256 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
257 double coveredDistance = distanceM * x;
259 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
261 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
262 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
265 remainingTimeEnroute = totalTimeEnroute;
266 elapsedTimeEnroute = 0;
267 position = dep->geod();
268 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is pending, departure in "
269 << flight->getDepartureTime() - now << " seconds ");
272 // departure / arrival coincident
273 remainingTimeEnroute = totalTimeEnroute = 0.0;
274 elapsedTimeEnroute = 0;
275 position = dep->geod();
278 // cartesian calculations are more numerically stable over the (potentially)
279 // large distances involved here: see bug #80
280 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
282 // If distance between user and simulated aircaft is less
283 // then 500nm, create this flight. At jet speeds 500 nm is roughly
284 // one hour flight time, so that would be a good approximate point
285 // to start a more detailed simulation of this aircraft.
286 SG_LOG (SG_GENERAL, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
287 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
289 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
290 return true; // out of visual range, for the moment.
293 return createAIAircraft(flight, speed, deptime);
296 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
298 FGAirport* dep = flight->getDepartureAirport();
299 FGAirport* arr = flight->getArrivalAirport();
300 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
301 SG_LOG(SG_GENERAL, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
303 // Only allow traffic to be created when the model path (or the AI version of mp) exists
304 SGPath mp(globals->get_fg_root());
307 mp.append(modelPath);
309 mp_ai.append(modelPath);
311 if (!mp.exists() && !mp_ai.exists()) {
312 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
316 FGAIAircraft *aircraft = new FGAIAircraft(this);
317 aircraft->setPerformance(m_class); //"jet_transport";
318 aircraft->setCompany(airline); //i->getAirline();
319 aircraft->setAcType(acType); //i->getAcType();
320 aircraft->setPath(modelPath.c_str());
321 //aircraft->setFlightPlan(flightPlanName);
322 aircraft->setLatitude(position.getLatitudeDeg());
323 aircraft->setLongitude(position.getLongitudeDeg());
324 aircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
325 aircraft->setSpeed(speedKnots);
326 aircraft->setBank(0);
328 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
329 aircraft->SetFlightPlan(new FGAIFlightPlan(aircraft, flightPlanName, courseToDest, deptime,
330 dep, arr, true, radius,
331 flight->getCruiseAlt()*100,
332 position.getLatitudeDeg(),
333 position.getLongitudeDeg(),
334 speedKnots, flightType, acType,
338 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
339 aimgr->attach(aircraft);
340 AIManagerRef = aircraft->getID();
344 void FGAISchedule::scheduleFlights()
346 if (!flights.empty()) {
350 SG_LOG(SG_GENERAL, SG_BULK, "Scheduling for : " << modelPath << " " << registration << " " << homePort);
351 FGScheduledFlight *flight = NULL;
353 flight = findAvailableFlight(currentDestination, flightIdentifier);
358 currentDestination = flight->getArrivalAirport()->getId();
361 dep = flight->getDepartureTime();
362 arr = flight->getArrivalTime();
363 string depT = asctime(gmtime(&dep));
364 string arrT = asctime(gmtime(&arr));
366 depT = depT.substr(0,24);
367 arrT = arrT.substr(0,24);
368 SG_LOG(SG_GENERAL, SG_BULK, " " << flight->getCallSign() << ":"
369 << " " << flight->getDepartureAirport()->getId() << ":"
370 << " " << depT << ":"
371 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
372 << " " << arrT << ":");
374 flights.push_back(flight);
375 } while (currentDestination != homePort);
376 SG_LOG(SG_GENERAL, SG_BULK, " Done ");
379 bool FGAISchedule::next()
381 if (!flights.empty()) {
382 flights.front()->release();
383 flights.erase(flights.begin());
386 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
391 currentDestination = flight->getArrivalAirport()->getId();
394 dep = flight->getDepartureTime();
395 arr = flight->getArrivalTime();
396 string depT = asctime(gmtime(&dep));
397 string arrT = asctime(gmtime(&arr));
399 depT = depT.substr(0,24);
400 arrT = arrT.substr(0,24);
401 //cerr << " " << flight->getCallSign() << ":"
402 // << " " << flight->getDepartureAirport()->getId() << ":"
403 // << " " << depT << ":"
404 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
405 // << " " << arrT << ":" << endl;
407 flights.push_back(flight);
411 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
414 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
416 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
417 FGScheduledFlightVecIterator fltBegin, fltEnd;
418 fltBegin = tmgr->getFirstFlight(req);
419 fltEnd = tmgr->getLastFlight(req);
422 //cerr << "Finding available flight " << endl;
424 // Traverse every registered flight
425 if (fltBegin == fltEnd) {
426 //cerr << "No Flights Scheduled for " << req << endl;
429 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
430 (*i)->adjustTime(now);
431 //sort(fltBegin, fltEnd, compareScheduledFlights);
432 //cerr << counter++ << endl;
434 std::sort(fltBegin, fltEnd, compareScheduledFlights);
435 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
438 if (!(*i)->isAvailable()) {
439 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
442 if (!((*i)->getRequirement() == req)) {
445 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
448 if (!(currentDestination.empty())) {
449 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
450 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
451 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
452 // (*i)->getArrivalAirport()->getId() << endl;
457 // So, if we actually get here, we have a winner
458 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
459 // (*i)->getArrivalAirport()->getId() << endl;
464 // if currentDestination has a value, does it match departure of next flight?
465 // is departure time later than planned arrival?
466 // is departure port valid?
467 // is arrival port valid?
468 //cerr << "Ack no flight found: " << endl;
472 double FGAISchedule::getSpeed()
474 FGScheduledFlightVecIterator i = flights.begin();
476 FGAirport* dep = (*i)->getDepartureAirport(),
477 *arr = (*i)->getArrivalAirport();
478 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
479 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
481 double speed = dist / (remainingTimeEnroute/3600.0);
482 SG_CLAMP_RANGE(speed, 300.0, 500.0);
486 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
488 //return (*a) < (*b);
492 // void FGAISchedule::setClosestDistanceToUser()
502 // elapsedTimeEnroute;
504 // double userLatitude = fgGetDouble("/position/latitude-deg");
505 // double userLongitude = fgGetDouble("/position/longitude-deg");
509 // #if defined( __CYGWIN__) || defined( __MINGW32__)
510 // #define HUGE HUGE_VAL
512 // distanceToUser = HUGE;
513 // FGScheduledFlightVecIterator i = flights.begin();
514 // while (i != flights.end())
516 // dep = i->getDepartureAirport();
520 // SGWayPoint user ( userLongitude,
522 // i->getCruiseAlt());
523 // SGWayPoint current (dep->getLongitude(),
524 // dep->getLatitude(),
526 // user.CourseAndDistance(current, &course, &dist);
527 // if (dist < distanceToUser)
529 // distanceToUser = dist;
530 // //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
534 // //return distToUser;