]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/Schedule.cxx
482727cb3e72b5bfde5bae877722544b847fb5e8
[flightgear.git] / src / Traffic / Schedule.cxx
1 /******************************************************************************
2  * Schedule.cxx
3  * Written by Durk Talsma, started May 5, 2004.
4  *
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.
9  *
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.
14  *
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.
18  *
19  *
20  ****************************************************************************
21  *
22  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #define BOGUS 0xFFFF
29
30 #include <stdlib.h>
31 #include <time.h>
32 #include <iostream>
33 #include <fstream>
34
35
36 #include <string>
37 #include <vector>
38 #include <algorithm>
39 #include <boost/foreach.hpp>
40
41 #include <simgear/compiler.h>
42 #include <simgear/sg_inlines.h>
43 #include <simgear/math/sg_geodesy.hxx>
44 #include <simgear/props/props.hxx>
45 #include <simgear/structure/subsystem_mgr.hxx>
46 #include <simgear/xml/easyxml.hxx>
47
48 #include <AIModel/AIFlightPlan.hxx>
49 #include <AIModel/AIManager.hxx>
50 #include <AIModel/AIAircraft.hxx>
51 #include <Airports/airport.hxx>
52 #include <Main/fg_init.hxx>   // That's pretty ugly, but I need fgFindAirportID
53
54
55 #include "SchedFlight.hxx"
56 #include "TrafficMgr.hxx"
57
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()
63   : heavy(false),
64     radius(0),
65     groundOffset(0),
66     distanceToUser(0),
67     score(0),
68     runCount(0),
69     hits(0),
70     lastRun(0),
71     firstRun(false),
72     courseToDest(0),
73     initialized(false),
74     valid(false),
75     scheduleComplete(false)
76 {
77 }
78
79
80 FGAISchedule::FGAISchedule(const string& model,
81                            const string& lvry,
82                            const string& port,
83                            const string& reg,
84                            const string& flightId,
85                            bool   hvy, 
86                            const string& act,
87                            const string& arln,
88                            const string& mclass,
89                            const string& fltpe,
90                            double rad, 
91                            double grnd)
92     : heavy(hvy),
93       radius(rad),
94       groundOffset(grnd),
95       distanceToUser(0),
96       score(0),
97       runCount(0),
98       hits(0),
99       lastRun(0),
100       firstRun(true),
101       courseToDest(0),
102       initialized(false),
103       valid(true),
104       scheduleComplete(false)
105 {
106   modelPath        = model; 
107   livery           = lvry; 
108   homePort         = port;
109   registration     = reg;
110   flightIdentifier = flightId;
111   acType           = act;
112   airline          = arln;
113   m_class          = mclass;
114   flightType       = fltpe;
115   /*for (FGScheduledFlightVecIterator i = flt.begin();
116        i != flt.end();
117        i++)
118     flights.push_back(new FGScheduledFlight((*(*i))));*/
119 }
120
121 FGAISchedule::FGAISchedule(const FGAISchedule &other)
122 {
123   modelPath          = other.modelPath;
124   homePort           = other.homePort;
125   livery             = other.livery;
126   registration       = other.registration;
127   heavy              = other.heavy;
128   flightIdentifier   = other.flightIdentifier;
129   flights            = other.flights;
130   aiAircraft         = other.aiAircraft;
131   acType             = other.acType;
132   airline            = other.airline;
133   m_class            = other.m_class;
134   firstRun           = other.firstRun;
135   radius             = other.radius;
136   groundOffset       = other.groundOffset;
137   flightType         = other.flightType;
138   score              = other.score;
139   distanceToUser     = other.distanceToUser;
140   currentDestination = other.currentDestination;
141   firstRun           = other.firstRun;
142   runCount           = other.runCount;
143   hits               = other.hits;
144   lastRun            = other.lastRun;
145   courseToDest       = other.courseToDest;
146   initialized        = other.initialized;
147   valid              = other.valid;
148   scheduleComplete   = other.scheduleComplete;
149 }
150
151
152
153 FGAISchedule::~FGAISchedule()
154 {
155     // remove related object from AI manager
156     if (aiAircraft)
157     {
158       aiAircraft->setDie(true);
159     }
160
161 /*  for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
162     {
163       delete (*flt);
164     }
165   flights.clear();*/
166
167
168 bool FGAISchedule::init()
169 {
170   //tm targetTimeDate;
171   //SGTime* currTimeDate = globals->get_time_params();
172
173   //tm *temp = currTimeDate->getGmt();
174   //char buffer[512];
175   //sgTimeFormatTime(&targetTimeDate, buffer);
176   //cout << "Scheduled Time " << buffer << endl; 
177   //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
178   /*for (FGScheduledFlightVecIterator i = flights.begin(); 
179        i != flights.end(); 
180        i++)
181     {
182       //i->adjustTime(now);
183       if (!((*i)->initializeAirports()))
184         return false;
185     } */
186   //sort(flights.begin(), flights.end());
187   // Since time isn't initialized yet when this function is called,
188   // Find the closest possible airport.
189   // This should give a reasonable initialization order. 
190   //setClosestDistanceToUser();
191   return true;
192 }
193
194 /**
195  *  Returns true when processing is complete.
196  *  Returns false when processing was aborted due to timeout, so
197  *    more time required - and another call is requested (next sim iteration).
198  */
199 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
200 {
201
202   time_t totalTimeEnroute,
203          elapsedTimeEnroute,
204          //remainingTimeEnroute,
205          deptime = 0;
206
207   if (!valid) {
208     return true; // processing complete
209   }
210
211   if (!scheduleComplete) {
212       scheduleComplete = scheduleFlights(now);
213   }
214
215   if (!scheduleComplete) {
216       return false; // not ready yet, continue processing in next iteration
217   }
218
219   if (flights.empty()) { // No flights available for this aircraft
220       valid = false;
221       return true; // processing complete
222   }
223
224
225   // Sort all the scheduled flights according to scheduled departure time.
226   // Because this is done at every update, we only need to check the status
227   // of the first listed flight. 
228   //sort(flights.begin(), flights.end(), compareScheduledFlights);
229   
230   if (firstRun) {
231      if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
232          deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft 
233                                    // from cluttering the gate areas.
234      }
235      firstRun = false;
236   }
237   
238   FGScheduledFlight* flight = flights.front();
239   if (!deptime) {
240     deptime = flight->getDepartureTime();
241     //cerr << "Setting departure time " << deptime << endl;
242   }
243     
244   if (aiAircraft) {
245     if (aiAircraft->getDie()) {
246       aiAircraft = NULL;
247     } else {
248       return true; // in visual range, let the AIManager handle it
249     }
250   }
251   
252   // This flight entry is entirely in the past, do we need to 
253   // push it forward in time to the next scheduled departure. 
254   if (flight->getArrivalTime() < now) {
255     SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is in the Past");
256     // Don't just update: check whether we need to load a new leg. etc.
257     // This update occurs for distant aircraft, so we can update the current leg
258     // and detach it from the current list of aircraft. 
259     flight->update();
260     flights.erase(flights.begin()); // pop_front(), effectively
261     return true; // processing complete
262   }
263   
264   FGAirport* dep = flight->getDepartureAirport();
265   FGAirport* arr = flight->getArrivalAirport();
266   if (!dep || !arr) {
267     return true; // processing complete
268   }
269     
270   double speed = 450.0;
271   if (dep != arr) {
272     totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
273     if (flight->getDepartureTime() < now) {
274       elapsedTimeEnroute   = now - flight->getDepartureTime();
275       //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
276       double x = elapsedTimeEnroute / (double) totalTimeEnroute;
277       
278     // current pos is based on great-circle course between departure/arrival,
279     // with percentage of distance travelled, based upon percentage of time
280     // enroute elapsed.
281       double course, az2, distanceM;
282       SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
283       double coveredDistance = distanceM * x;
284       
285       SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
286       
287       SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is in progress, %=" << x);
288       speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
289     } else {
290     // not departed yet
291       //remainingTimeEnroute = totalTimeEnroute;
292       elapsedTimeEnroute = 0;
293       position = dep->geod();
294       SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is pending, departure in "
295         << flight->getDepartureTime() - now << " seconds ");
296     }
297   } else {
298     // departure / arrival coincident
299     //remainingTimeEnroute = totalTimeEnroute = 0.0;
300     elapsedTimeEnroute = 0;
301     position = dep->geod();
302   }
303     
304   // cartesian calculations are more numerically stable over the (potentially)
305   // large distances involved here: see bug #80
306   distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
307
308
309   // If distance between user and simulated aircraft is less
310   // then 500nm, create this flight. At jet speeds 500 nm is roughly
311   // one hour flight time, so that would be a good approximate point
312   // to start a more detailed simulation of this aircraft.
313   SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
314              << dep->getId() << " to " << arr->getId() << ". Current distance to user: " 
315              << distanceToUser);
316   if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
317     return true; // out of visual range, for the moment.
318   }
319
320   if (!createAIAircraft(flight, speed, deptime)) {
321       valid = false;
322   }
323
324
325     return true; // processing complete
326 }
327
328 bool FGAISchedule::validModelPath(const std::string& modelPath)
329 {
330     return (resolveModelPath(modelPath) != SGPath());
331 }
332
333 SGPath FGAISchedule::resolveModelPath(const std::string& modelPath)
334 {
335     BOOST_FOREACH(SGPath aiPath, globals->get_data_paths("AI")) {
336         aiPath.append(modelPath);
337         if (aiPath.exists()) {
338             return aiPath;
339         }
340     }
341     
342     // check aircraft dirs
343     BOOST_FOREACH(std::string aircraftPath, globals->get_aircraft_paths()) {
344         SGPath mp(aircraftPath);
345         mp.append(modelPath);
346         if (mp.exists()) {
347             return mp;
348         }
349     }
350
351     return SGPath();
352 }
353
354 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
355 {
356   FGAirport* dep = flight->getDepartureAirport();
357   FGAirport* arr = flight->getArrivalAirport();
358   string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
359   SG_LOG(SG_AI, SG_DEBUG, "Traffic manager: Creating AIModel from:" << flightPlanName);
360
361   aiAircraft = new FGAIAircraft(this);
362   aiAircraft->setPerformance(acType, m_class); //"jet_transport";
363   aiAircraft->setCompany(airline); //i->getAirline();
364   aiAircraft->setAcType(acType); //i->getAcType();
365   aiAircraft->setPath(modelPath.c_str());
366   //aircraft->setFlightPlan(flightPlanName);
367   aiAircraft->setLatitude(position.getLatitudeDeg());
368   aiAircraft->setLongitude(position.getLongitudeDeg());
369   aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
370   aiAircraft->setSpeed(0);
371   aiAircraft->setBank(0);
372       
373   courseToDest = SGGeodesy::courseDeg(position, arr->geod());
374   FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
375                                             dep, arr, true, radius, 
376                                             flight->getCruiseAlt()*100, 
377                                             position.getLatitudeDeg(), 
378                                             position.getLongitudeDeg(), 
379                                             speedKnots, flightType, acType, 
380                                             airline);
381   if (fp->isValidPlan()) {
382         aiAircraft->SetFlightPlan(fp);
383         FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
384         aimgr->attach(aiAircraft);
385         return true;
386   } else {
387         aiAircraft = NULL;
388         delete fp;
389         //hand back the flights that had already been scheduled
390         while (!flights.empty()) {
391             flights.front()->release();
392             flights.erase(flights.begin());
393         }
394         return false;
395   }
396 }
397
398 // Create an initial heading for user controlled aircraft.
399 void FGAISchedule::setHeading()  
400
401     courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
402 }
403
404 bool FGAISchedule::scheduleFlights(time_t now)
405 {
406   //string startingPort;
407   const string& userPort = fgGetString("/sim/presets/airport-id");
408   SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " <<  registration << " " << homePort);
409   FGScheduledFlight *flight = NULL;
410   SGTimeStamp start;
411   start.stamp();
412
413   bool first = true;
414   if (currentDestination.empty())
415     flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
416
417   do {
418     if ((!flight)||(!first)) {
419         flight = findAvailableFlight(currentDestination, flightIdentifier);
420     }
421     if (!flight) {
422       break;
423     }
424
425     first = false;
426     currentDestination = flight->getArrivalAirport()->getId();
427     //cerr << "Current destination " <<  currentDestination << endl;
428     if (!initialized) {
429         const string& departurePort = flight->getDepartureAirport()->getId();
430         if (userPort == departurePort) {
431             lastRun = 1;
432             hits++;
433         } else {
434             lastRun = 0;
435         }
436         //runCount++;
437         initialized = true;
438     }
439   
440     if (sglog().would_log(SG_AI, SG_BULK))
441     {
442         time_t arr, dep;
443         dep = flight->getDepartureTime();
444         arr = flight->getArrivalTime();
445         string depT = asctime(gmtime(&dep));
446         string arrT = asctime(gmtime(&arr));
447         depT = depT.substr(0,24);
448         arrT = arrT.substr(0,24);
449         SG_LOG(SG_AI, SG_BULK, "  Flight " << flight->getCallSign() << ":"
450                                  << "  "        << flight->getDepartureAirport()->getId() << ":"
451                                  << "  "        << depT << ":"
452                                  << " \""       << flight->getArrivalAirport()->getId() << "\"" << ":"
453                                  << "  "        << arrT << ":");
454     }
455   
456     flights.push_back(flight);
457
458     // continue processing until complete, or preempt after timeout
459   } while ((currentDestination != homePort)&&
460            (start.elapsedMSec()<3.0));
461
462   if (flight && (currentDestination != homePort))
463   {
464       // processing preempted, need to continue in next iteration
465       return false;
466   }
467
468   SG_LOG(SG_AI, SG_BULK, " Done ");
469   return true;
470 }
471
472 bool FGAISchedule::next()
473 {
474   if (!flights.empty()) {
475     flights.front()->release();
476     flights.erase(flights.begin());
477   }
478   
479   FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
480   if (!flight) {
481     return false;
482   }
483   
484   currentDestination = flight->getArrivalAirport()->getId();
485 /*
486   time_t arr, dep;
487   dep = flight->getDepartureTime();
488   arr = flight->getArrivalTime();
489   string depT = asctime(gmtime(&dep));
490   string arrT = asctime(gmtime(&arr));
491
492   depT = depT.substr(0,24);
493   arrT = arrT.substr(0,24);
494   //cerr << "  " << flight->getCallSign() << ":" 
495   //     << "  " << flight->getDepartureAirport()->getId() << ":"
496   //     << "  " << depT << ":"
497   //     << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
498   //     << "  " << arrT << ":" << endl;
499 */
500    flights.push_back(flight);
501    return true;
502 }
503
504 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string &currentDestination,
505                                                       const string &req,
506                                                      time_t min, time_t max)
507 {
508     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
509
510     FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
511     FGScheduledFlightVecIterator fltBegin, fltEnd;
512     fltBegin = tmgr->getFirstFlight(req);
513     fltEnd   = tmgr->getLastFlight(req);
514
515
516      //cerr << "Finding available flight " << endl;
517      // For Now:
518      // Traverse every registered flight
519      if (fltBegin == fltEnd) {
520           //cerr << "No Flights Scheduled for " << req << endl;
521      }
522      int counter = 0;
523      for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
524           (*i)->adjustTime(now);
525            //sort(fltBegin, fltEnd, compareScheduledFlights);
526            //cerr << counter++ << endl;
527      }
528      std::sort(fltBegin, fltEnd, compareScheduledFlights);
529      for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
530           //bool valid = true;
531           counter++;
532           if (!(*i)->isAvailable()) {
533                //cerr << (*i)->getCallSign() << "is no longer available" << endl;
534                continue;
535           }
536           if (!((*i)->getRequirement() == req)) {
537                continue;
538           }
539           if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
540               continue;
541           }
542           if (!(currentDestination.empty())) {
543               if (currentDestination != (*i)->getDepartureAirport()->getId()) {
544                    //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
545                    //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
546                    //          (*i)->getArrivalAirport()->getId() << endl;
547                    continue;
548               }
549           }
550           if (! flights.empty()) {
551             time_t arrival = flights.back()->getArrivalTime();
552             int groundTime = groundTimeFromRadius();
553             if ((*i)->getDepartureTime() < (arrival+(groundTime)))
554                 continue;
555           }
556           if (min != 0) {
557               time_t dep = (*i)->getDepartureTime();
558               if ((dep < min) || (dep > max))
559                   continue;
560           }
561
562           // So, if we actually get here, we have a winner
563           //cerr << "found flight: " << req << " : " << currentDestination << " : " <<       
564           //         (*i)->getArrivalAirport()->getId() << endl;
565           (*i)->lock();
566           return (*i);
567      }
568      // matches req?
569      // if currentDestination has a value, does it match departure of next flight?
570      // is departure time later than planned arrival?
571      // is departure port valid?
572      // is arrival port valid?
573      //cerr << "Ack no flight found: " << endl;
574      return NULL;
575 }
576
577 int FGAISchedule::groundTimeFromRadius()
578 {
579     if (radius < 10) 
580         return 15 * 60;
581     else if (radius < 15)
582         return 20 * 60;
583     else if (radius < 20)
584         return 30 * 60;
585     else if (radius < 25)
586         return 50 * 60;
587     else if (radius < 30)
588         return 90 * 60;
589     else 
590         return 120 * 60;
591 }
592
593
594 double FGAISchedule::getSpeed()
595 {
596   FGScheduledFlightVecIterator i = flights.begin();
597  
598   FGAirport* dep = (*i)->getDepartureAirport(),
599    *arr = (*i)->getArrivalAirport();
600   double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
601   double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
602
603   double speed = dist / (remainingTimeEnroute/3600.0);
604   SG_CLAMP_RANGE(speed, 300.0, 500.0);
605   return speed;
606 }
607
608 void FGAISchedule::setScore   () 
609
610     if (runCount) {
611         score = ((double) hits / (double) runCount);
612     } else {
613         if (homePort == fgGetString("/sim/presets/airport-id")) {
614             score = 0.1;
615         } else {
616             score = 0.0;
617         }
618     }
619     runCount++;
620 }
621
622 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
623
624   return (*a) < (*b); 
625
626
627 bool FGAISchedule::operator< (const FGAISchedule &other) const
628
629     //cerr << "Sorting " << registration << " and "  << other.registration << endl;
630     double currentScore = score       * (1.5 - lastRun);
631     double otherScore   = other.score * (1.5 - other.lastRun);
632     return currentScore > otherScore;
633 }
634