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"
60 /******************************************************************************
61 * the FGAISchedule class contains data members and code to maintain a
62 * schedule of Flights for an articically controlled aircraft.
63 *****************************************************************************/
64 FGAISchedule::FGAISchedule()
79 FGAISchedule::FGAISchedule(string mdl,
90 FGScheduledFlightVec flt)*/
91 FGAISchedule::FGAISchedule(string model,
108 flightIdentifier = flightId;
119 /*for (FGScheduledFlightVecIterator i = flt.begin();
122 flights.push_back(new FGScheduledFlight((*(*i))));*/
128 FGAISchedule::FGAISchedule(const FGAISchedule &other)
130 modelPath = other.modelPath;
131 homePort = other.homePort;
132 livery = other.livery;
133 registration = other.registration;
135 flightIdentifier = other.flightIdentifier;
136 flights = other.flights;
139 AIManagerRef = other.AIManagerRef;
140 acType = other.acType;
141 airline = other.airline;
142 m_class = other.m_class;
143 firstRun = other.firstRun;
144 radius = other.radius;
145 groundOffset = other.groundOffset;
146 flightType = other.flightType;
147 //score = other.score;
148 distanceToUser = other.distanceToUser;
149 currentDestination = other.currentDestination;
150 firstRun = other.firstRun;
154 FGAISchedule::~FGAISchedule()
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)
203 remainingTimeEnroute, deptime = 0;
208 SGVec3d newPos(0, 0, 0);
211 if (fgGetBool("/sim/traffic-manager/enabled") == false)
214 aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
215 // Out-of-work aircraft seeks employment. Willing to work irregular hours ...
216 //cerr << "About to find a flight " << endl;
217 if (flights.empty()) {
218 //execute this loop at least once.
219 SG_LOG(SG_GENERAL, SG_BULK, "Scheduling for : " << modelPath << " " << registration << " " << homePort);
220 FGScheduledFlight *flight = 0;
222 flight = findAvailableFlight(currentDestination, flightIdentifier);
224 currentDestination = flight->getArrivalAirport()->getId();
226 dep = flight->getDepartureTime();
227 arr = flight->getArrivalTime();
228 string depT = asctime(gmtime(&dep));
229 string arrT = asctime(gmtime(&arr));
231 depT = depT.substr(0,24);
232 arrT = arrT.substr(0,24);
233 SG_LOG(SG_GENERAL, SG_BULK, " " << flight->getCallSign() << ":"
234 << " " << flight->getDepartureAirport()->getId() << ":"
235 << " " << depT << ":"
236 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
237 << " " << arrT << ":");
238 flights.push_back(flight);
240 } while ((currentDestination != homePort) && (flight != 0));
241 SG_LOG(SG_GENERAL, SG_BULK, cerr << " Done " << endl);
243 //cerr << " Done " << endl;
244 // No flights available for this aircraft
245 if (flights.size() == 0) {
248 // Sort all the scheduled flights according to scheduled departure time.
249 // Because this is done at every update, we only need to check the status
250 // of the first listed flight.
251 //sort(flights.begin(), flights.end(), compareScheduledFlights);
253 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
254 deptime = now + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
255 // from cluttering the gate areas.
256 cerr << "Scheduling " << registration << " for instantaneous action flight " << endl;
261 deptime = (*flights.begin())->getDepartureTime();
262 FGScheduledFlightVecIterator i = flights.begin();
263 SG_LOG (SG_GENERAL, SG_DEBUG,"Traffic Manager: Processing registration " << registration << " with callsign " << (*i)->getCallSign());
266 // Check if this aircraft has been released.
267 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
268 if (tmgr->isReleased(AIManagerRef))
274 userLatitude = fgGetDouble("/position/latitude-deg");
275 userLongitude = fgGetDouble("/position/longitude-deg");
277 //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
278 // This flight entry is entirely in the past, do we need to
279 // push it forward in time to the next scheduled departure.
280 if (((*i)->getDepartureTime() < now) && ((*i)->getArrivalTime() < now))
282 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is in the Past");
283 //cerr << modelPath << " " << registration << ": Flights from the past belong to the past :-)" << endl;
285 // Don't just update: check whether we need to load a new leg. etc.
286 // This update occurs for distant aircraft, so we can update the current leg
287 // and detach it from the current list of aircraft.
289 i = flights.erase(i);
293 // Departure time in the past and arrival time in the future.
294 // This flight is in progress, so we need to calculate it's
295 // approximate position and -if in range- create an AIAircraft
297 //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
299 // Part of this flight is in the future.
300 if ((*i)->getArrivalTime() > now)
303 dep = (*i)->getDepartureAirport();
304 arr = (*i)->getArrivalAirport ();
309 SGVec3d a = SGVec3d::fromGeoc(SGGeoc::fromDegM(dep->getLongitude(),
310 dep->getLatitude(), 1));
311 SGVec3d b = SGVec3d::fromGeoc(SGGeoc::fromDegM(arr->getLongitude(),
312 arr->getLatitude(), 1));
313 SGVec3d _cross = cross(b, a);
315 angle = sgACos(dot(a, b));
317 // Okay, at this point we have the angle between departure and
318 // arrival airport, in degrees. From here we can interpolate the
319 // position of the aircraft by calculating the ratio between
320 // total time enroute and elapsed time enroute.
322 totalTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
323 if (now > (*i)->getDepartureTime())
325 //err << "Lat = " << lat << ", lon = " << lon << endl;
326 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
327 elapsedTimeEnroute = now - (*i)->getDepartureTime();
328 remainingTimeEnroute = (*i)->getArrivalTime() - now;
329 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is in progress.");
333 lat = dep->getLatitude();
334 lon = dep->getLongitude();
335 elapsedTimeEnroute = 0;
336 remainingTimeEnroute = totalTimeEnroute;
337 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is pending.");
339 angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
340 //cout << "a = " << a[0] << " " << a[1] << " " << a[2]
341 // << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;
343 sgdMakeRotMat4(matrix, angle, _cross.data());
344 for(int j = 0; j < 3; j++) {
345 for (int k = 0; k<3; k++) {
346 newPos[j] += matrix[j][k]*a[k];
351 if ((now > (*i)->getDepartureTime() && (dep != arr))) {
352 current = SGGeod::fromCart(newPos);
353 speed = SGGeodesy::distanceNm(current, arr->geod()) /
354 ((double) remainingTimeEnroute/3600.0);
356 current = dep->geod();
359 SGGeod user = SGGeod::fromDegM(userLongitude, userLatitude, (*i)->getCruiseAlt());
361 distanceToUser = SGGeodesy::distanceNm(current, user);
363 // If distance between user and simulated aircaft is less
364 // then 500nm, create this flight. At jet speeds 500 nm is roughly
365 // one hour flight time, so that would be a good approximate point
366 // to start a more detailed simulation of this aircraft.
367 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic manager: " << registration << " is scheduled for a flight from "
368 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
370 if (distanceToUser < TRAFFICTOAIDISTTOSTART)
372 string flightPlanName = dep->getId() + string("-") + arr->getId() +
374 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic manager: Creating AIModel");
376 //if ((i->getDepartureTime() < now))
378 // alt = i->getCruiseAlt() *100;
382 // alt = dep->_elevation+19;
385 // Only allow traffic to be created when the model path (or the AI version of mp) exists
386 SGPath mp(globals->get_fg_root());
389 mp.append(modelPath);
391 mp_ai.append(modelPath);
393 if (mp.exists() || mp_ai.exists())
395 FGAIAircraft *aircraft = new FGAIAircraft(this);
396 aircraft->setPerformance(m_class); //"jet_transport";
397 aircraft->setCompany(airline); //i->getAirline();
398 aircraft->setAcType(acType); //i->getAcType();
399 aircraft->setPath(modelPath.c_str());
400 //aircraft->setFlightPlan(flightPlanName);
401 aircraft->setLatitude(lat);
402 aircraft->setLongitude(lon);
403 aircraft->setAltitude((*i)->getCruiseAlt()*100); // convert from FL to feet
404 aircraft->setSpeed(speed);
405 aircraft->setBank(0);
407 courseToDest = SGGeodesy::courseDeg(current, arr->geod());
408 aircraft->SetFlightPlan(new FGAIFlightPlan(aircraft, flightPlanName, courseToDest, deptime,
409 dep, arr,true, radius,
410 (*i)->getCruiseAlt()*100,
411 lat, lon, speed, flightType, acType,
413 aimgr->attach(aircraft);
416 AIManagerRef = aircraft->getID();
417 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
418 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
419 //cerr << "Dep : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
420 //cerr << "Arr : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
421 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
422 //cerr << "Total time = " << (totalTimeEnroute/3600.0) << endl;
423 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
427 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
433 // Both departure and arrival time are in the future, so this
434 // the aircraft is parked at the departure airport.
435 // Currently this status is mostly ignored, but in future
436 // versions, code should go here that -if within user range-
437 // positions these aircraft at parking locations at the airport.
438 if (((*i)->getDepartureTime() > now) && ((*i)->getArrivalTime() > now))
440 dep = (*i)->getDepartureAirport();
444 //cerr << "Traffic schedule got to beyond last clause" << endl;
445 // EMH: prevent a warning, should this be 'true' instead?
446 // DT: YES. Originally, this code couldn't be reached, but
447 // when the "if(!(AIManagerManager))" clause is false we
448 // fall through right to the end. This is a valid flow.
449 // the actual value is pretty innocent, only it triggers
450 // warning in TrafficManager::update().
451 // (which was added as a sanity check for myself in the first place. :-)
456 bool FGAISchedule::next()
458 FGScheduledFlightVecIterator i = flights.begin();
460 //FIXME: remove first entry,
461 // load new flights until back at home airport
462 // Lock loaded flights
463 //sort(flights.begin(), flights.end(), compareScheduledFlights);
465 i = flights.erase(i);
466 //cerr << "Next: scheduling for : " << modelPath << " " << registration << endl;
467 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
469 currentDestination = flight->getArrivalAirport()->getId();
471 dep = flight->getDepartureTime();
472 arr = flight->getArrivalTime();
473 string depT = asctime(gmtime(&dep));
474 string arrT = asctime(gmtime(&arr));
476 depT = depT.substr(0,24);
477 arrT = arrT.substr(0,24);
478 //cerr << " " << flight->getCallSign() << ":"
479 // << " " << flight->getDepartureAirport()->getId() << ":"
480 // << " " << depT << ":"
481 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
482 // << " " << arrT << ":" << endl;
484 flights.push_back(flight);
489 //cerr << "FGAISchedule :: next needs updating" << endl;
493 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
496 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
498 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
499 FGScheduledFlightVecIterator fltBegin, fltEnd;
500 fltBegin = tmgr->getFirstFlight(req);
501 fltEnd = tmgr->getLastFlight(req);
504 //cerr << "Finding available flight " << endl;
506 // Traverse every registered flight
507 if (fltBegin == fltEnd) {
508 //cerr << "No Flights Scheduled for " << req << endl;
511 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
512 (*i)->adjustTime(now);
513 //sort(fltBegin, fltEnd, compareScheduledFlights);
514 //cerr << counter++ << endl;
516 sort(fltBegin, fltEnd, compareScheduledFlights);
517 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
520 if (!(*i)->isAvailable()) {
521 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
524 if (!((*i)->getRequirement() == req)) {
527 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
530 if (!(currentDestination.empty())) {
531 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
532 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
533 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
534 // (*i)->getArrivalAirport()->getId() << endl;
539 // So, if we actually get here, we have a winner
540 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
541 // (*i)->getArrivalAirport()->getId() << endl;
546 // if currentDestination has a value, does it match departure of next flight?
547 // is departure time later than planned arrival?
548 // is departure port valid?
549 // is arrival port valid?
550 //cerr << "Ack no flight found: " << endl;
554 double FGAISchedule::getSpeed()
556 FGScheduledFlightVecIterator i = flights.begin();
558 FGAirport* dep = (*i)->getDepartureAirport(),
559 *arr = (*i)->getArrivalAirport();
560 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
561 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
563 double speed = dist / (remainingTimeEnroute/3600.0);
564 SG_CLAMP_RANGE(speed, 300.0, 500.0);
568 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
570 //return (*a) < (*b);
574 // void FGAISchedule::setClosestDistanceToUser()
584 // elapsedTimeEnroute;
586 // double userLatitude = fgGetDouble("/position/latitude-deg");
587 // double userLongitude = fgGetDouble("/position/longitude-deg");
591 // #if defined( __CYGWIN__) || defined( __MINGW32__)
592 // #define HUGE HUGE_VAL
594 // distanceToUser = HUGE;
595 // FGScheduledFlightVecIterator i = flights.begin();
596 // while (i != flights.end())
598 // dep = i->getDepartureAirport();
602 // SGWayPoint user ( userLongitude,
604 // i->getCruiseAlt());
605 // SGWayPoint current (dep->getLongitude(),
606 // dep->getLatitude(),
608 // user.CourseAndDistance(current, &course, &dist);
609 // if (dist < distanceToUser)
611 // distanceToUser = dist;
612 // //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
616 // //return distToUser;