]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
-Minor fix: Only read traffic from data/Traffic/fgtraffic.xml if that path really...
[flightgear.git] / src / Traffic / TrafficMgr.cxx
1 /******************************************************************************
2  * TrafficMGr.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 /* This a prototype version of a top-level flight plan manager for Flightgear.
23  * It parses the fgtraffic.txt file and determine for a specific time/date, 
24  * where each aircraft listed in this file is at the current time. 
25  * 
26  * I'm currently assuming the following simplifications:
27  * 1) The earth is a perfect sphere
28  * 2) Each aircraft flies a perfect great circle route.
29  * 3) Each aircraft flies at a constant speed (with infinite accelerations and
30  *    decelerations) 
31  * 4) Each aircraft leaves at exactly the departure time. 
32  * 5) Each aircraft arrives at exactly the specified arrival time. 
33  *
34  *
35  *****************************************************************************/
36
37 #ifdef HAVE_CONFIG_H
38 #  include "config.h"
39 #endif
40
41 #include <stdlib.h>
42 #include <time.h>
43 #include <iostream>
44 #include <fstream>
45
46
47 #include <string>
48 #include <vector>
49 #include <algorithm>
50
51 #include <plib/sg.h>
52 #include <plib/ul.h>
53
54 #include <simgear/compiler.h>
55 #include <simgear/math/polar3d.hxx>
56 #include <simgear/math/sg_geodesy.hxx>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/props/props.hxx>
59 #include <simgear/route/waypoint.hxx>
60 #include <simgear/structure/subsystem_mgr.hxx>
61 #include <simgear/xml/easyxml.hxx>
62
63 #include <AIModel/AIAircraft.hxx>
64 #include <AIModel/AIFlightPlan.hxx>
65 #include <AIModel/AIBase.hxx>
66 #include <Airports/simple.hxx>
67 #include <Main/fg_init.hxx>
68
69
70
71 #include "TrafficMgr.hxx"
72
73 SG_USING_STD(sort);
74  
75 /******************************************************************************
76  * TrafficManager
77  *****************************************************************************/
78 FGTrafficManager::FGTrafficManager()
79 {
80   score = 0;
81   runCount = 0;
82 }
83
84 FGTrafficManager:: ~FGTrafficManager()
85 {
86   for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++)
87     {
88       delete (*sched);
89     }
90   scheduledAircraft.clear();
91   // for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
92 //     {
93 //       delete (*flt);
94 //     }
95 //   flights.clear();
96 }
97
98
99 void FGTrafficManager::init()
100
101   //cerr << "Initializing Schedules" << endl;
102   //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
103   //currAircraft = scheduledAircraft.begin();
104   //while (currAircraft != scheduledAircraft.end())
105   //  {
106   //    if (!(currAircraft->init()))
107   //    {
108   //      currAircraft=scheduledAircraft.erase(currAircraft);
109   //      //cerr << "Erasing " << currAircraft->getRegistration() << endl;
110   //    }
111   //   else 
112   //    {
113   //      currAircraft++;
114   //    }
115   //   }
116   // Sort by points: Aircraft with frequent visits to the
117   // startup airport will be processed first
118   ulDir* d, *d2;
119   ulDirEnt* dent, *dent2;
120   SGPath aircraftDir = globals->get_fg_root();
121
122   /* keep the following three lines (which mimicks the old "fixed path" behavior)
123    * until we have some AI models with traffic in the base package
124    */ 
125   SGPath path = aircraftDir;
126   path.append("Traffic/fgtraffic.xml");
127   if (path.exists())
128     readXML(path.str(),*this);
129
130   aircraftDir.append("AI/Aircraft");
131   if (aircraftDir.exists())
132     {
133       if((d = ulOpenDir(aircraftDir.c_str())) == NULL)
134         return;
135       while((dent = ulReadDir(d)) != NULL) {
136         //cerr << "Scanning : " << dent->d_name << endl;
137         if (string(dent->d_name) != string(".")  && 
138             string(dent->d_name) != string("..") &&
139             dent->d_isdir)
140           {
141             SGPath currACDir = aircraftDir;
142             currACDir.append(dent->d_name);
143             if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
144               return;
145             while ((dent2 = ulReadDir(d2)) != NULL) {
146               SGPath currFile = currACDir;
147               currFile.append(dent2->d_name);
148               if (currFile.extension() == string("xml"))
149                 {
150                   //cerr << "found " << dent2->d_name << " for parsing" << endl;
151                   SGPath currFile = currACDir;
152                   currFile.append(dent2->d_name);
153                   SG_LOG(SG_GENERAL, SG_INFO, "Scanning " << currFile.str() << " for traffic");
154                   readXML(currFile.str(),*this);
155                 }
156             }
157             ulCloseDir(d2);
158           }
159       }
160       ulCloseDir(d);
161     }
162   // Sort by points: Aircraft with frequent visits to the
163   // startup airport will be processed first
164   sort(scheduledAircraft.begin(), scheduledAircraft.end(), compareSchedules);
165   currAircraft = scheduledAircraft.begin();
166   currAircraftClosest = scheduledAircraft.begin();
167   //cerr << "Done initializing schedules" << endl;
168 }
169
170 void FGTrafficManager::update(double /*dt*/)
171 {
172   //SG_LOG( SG_GENERAL, SG_INFO, "Running TrafficManager::Update() ");
173   // Hack alert: Skip running for the first frames 1000 after 
174   // initialization to allow proper initialization of wheather stuff 
175   // and runway assignments
176   if (runCount < 1000)
177     {
178       runCount++;
179       return;
180     }
181   //runCount = 0;
182   time_t now = time(NULL) + fgGetLong("/sim/time/warp");
183   if (scheduledAircraft.size() == 0) {
184     //SG_LOG( SG_GENERAL, SG_INFO, "Returned Running TrafficManager::Update() ");
185     return;
186   }
187   if(currAircraft == scheduledAircraft.end())
188     {
189       //cerr << "resetting schedule " << endl;
190       currAircraft = scheduledAircraft.begin();
191     }
192   if (!((*currAircraft)->update(now)))
193     {
194       // after proper initialization, we shouldnt get here.
195       // But let's make sure
196       SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
197     }
198   currAircraft++;
199   //SG_LOG( SG_GENERAL, SG_INFO, "Done Running TrafficManager::Update() ");
200 }
201
202 void FGTrafficManager::release(int id)
203 {
204   releaseList.push_back(id);
205 }
206
207 bool FGTrafficManager::isReleased(int id)
208 {
209   IdListIterator i = releaseList.begin();
210   while (i != releaseList.end())
211     {
212       if ((*i) == id)
213         {
214           releaseList.erase(i);
215           return true;
216         }
217       i++;
218     }
219   return false;
220 }
221
222 void  FGTrafficManager::startXML () {
223   //cout << "Start XML" << endl;
224 }
225
226 void  FGTrafficManager::endXML () {
227   //cout << "End XML" << endl;
228 }
229
230 void  FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
231   const char * attval;
232   //cout << "Start element " << name << endl;
233   //FGTrafficManager temp;
234   //for (int i = 0; i < atts.size(); i++)
235   //  if (string(atts.getName(i)) == string("include"))
236   attval = atts.getValue("include");
237   if (attval != 0)
238       {
239         //cout << "including " << attval << endl;
240         SGPath path = 
241           globals->get_fg_root();
242         path.append("/Traffic/");
243         path.append(attval);
244         readXML(path.str(), *this);
245       }
246   //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
247 }
248
249 void  FGTrafficManager::endElement (const char * name) {
250   //cout << "End element " << name << endl;
251   string element(name);
252   if (element == string("model"))
253     mdl = value;
254   else if (element == string("livery"))
255     livery = value;
256   else if (element == string("registration"))
257     registration = value;
258   else if (element == string("airline"))
259     airline = value;
260   else if (element == string("actype"))
261     acType = value;
262   else if (element == string("flighttype"))
263     flighttype = value;
264   else if (element == string("radius"))
265     radius = atoi(value.c_str());
266   else if (element == string("offset"))
267     offset = atoi(value.c_str());
268   else if (element == string("performance-class"))
269     m_class = value;
270   else if (element == string("heavy"))
271     {
272       if(value == string("true"))
273         heavy = true;
274       else
275         heavy = false;
276     }
277   else if (element == string("callsign"))
278     callsign = value;
279   else if (element == string("fltrules"))
280     fltrules = value;
281   else if (element == string("port"))
282     port = value;
283   else if (element == string("time"))
284     timeString = value;
285   else if (element == string("departure"))
286     {
287       departurePort = port;
288       departureTime = timeString;
289     }
290   else if (element == string("cruise-alt"))
291     cruiseAlt = atoi(value.c_str());
292   else if (element == string("arrival"))
293     {
294       arrivalPort = port;
295       arrivalTime = timeString;
296     }
297   else if (element == string("repeat"))
298     repeat = value;
299   else if (element == string("flight"))
300     {
301       // We have loaded and parsed all the information belonging to this flight
302       // so we temporarily store it. 
303       //cerr << "Pusing back flight " << callsign << endl;
304       //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
305       //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
306
307       //Prioritize aircraft 
308       string apt = fgGetString("/sim/presets/airport-id");
309       //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
310       if (departurePort == apt) score++;
311       flights.push_back(new FGScheduledFlight(callsign,
312                                           fltrules,
313                                           departurePort,
314                                           arrivalPort,
315                                           cruiseAlt,
316                                           departureTime,
317                                           arrivalTime,
318                                           repeat));
319     }
320   else if (element == string("aircraft"))
321     {
322       //cerr << "Pushing back aircraft " << registration << endl;
323       scheduledAircraft.push_back(new FGAISchedule(mdl, 
324                                                livery, 
325                                                registration, 
326                                                heavy,
327                                                acType, 
328                                                airline, 
329                                                m_class, 
330                                                flighttype,
331                                                radius,
332                                                offset,
333                                                score,
334                                                flights));
335      //  while(flights.begin() != flights.end()) {
336 //      flights.pop_back();
337 //       }
338       for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
339     {
340       delete (*flt);
341     }
342   flights.clear();
343       SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : " 
344               << registration 
345               << " with prioritization score " 
346               << score);
347       score = 0;
348     }
349 }
350
351 void  FGTrafficManager::data (const char * s, int len) {
352   string token = string(s,len);
353   //cout << "Character data " << string(s,len) << endl;
354   if ((token.find(" ") == string::npos && (token.find('\n')) == string::npos))
355       value += token;
356   else
357     value = string("");
358 }
359
360 void  FGTrafficManager::pi (const char * target, const char * data) {
361   //cout << "Processing instruction " << target << ' ' << data << endl;
362 }
363
364 void  FGTrafficManager::warning (const char * message, int line, int column) {
365   SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
366 }
367
368 void  FGTrafficManager::error (const char * message, int line, int column) {
369   SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
370 }