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 *****************************************************************************/
42 #include <simgear/compiler.h>
43 #include <simgear/math/polar3d.hxx>
44 #include <simgear/math/sg_geodesy.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/route/waypoint.hxx>
47 #include <simgear/structure/subsystem_mgr.hxx>
48 #include <simgear/xml/easyxml.hxx>
50 #include <AIModel/AIFlightPlan.hxx>
51 #include <AIModel/AIManager.hxx>
52 #include <AIModel/AIAircraft.hxx>
53 #include <Airports/simple.hxx>
54 #include <Main/fg_init.hxx> // That's pretty ugly, but I need fgFindAirportID
57 #include "SchedFlight.hxx"
58 #include "TrafficMgr.hxx"
62 /******************************************************************************
63 * the FGAISchedule class contains data members and code to maintain a
64 * schedule of Flights for an articically controlled aircraft.
65 *****************************************************************************/
66 FGAISchedule::FGAISchedule()
80 FGAISchedule::FGAISchedule(string mdl,
91 FGScheduledFlightVec flt)
106 for (FGScheduledFlightVecIterator i = flt.begin();
109 flights.push_back(FGScheduledFlight((*i)));
115 FGAISchedule::FGAISchedule(const FGAISchedule &other)
117 modelPath = other.modelPath;
118 livery = other.livery;
119 registration = other.registration;
121 flights = other.flights;
124 AIManagerRef = other.AIManagerRef;
125 acType = other.acType;
126 airline = other.airline;
127 m_class = other.m_class;
128 firstRun = other.firstRun;
129 radius = other.radius;
130 groundOffset = other.groundOffset;
131 flightType = other.flightType;
133 distanceToUser = other.distanceToUser;
137 FGAISchedule::~FGAISchedule()
142 bool FGAISchedule::init()
145 //SGTime* currTimeDate = globals->get_time_params();
147 //tm *temp = currTimeDate->getGmt();
149 //sgTimeFormatTime(&targetTimeDate, buffer);
150 //cout << "Scheduled Time " << buffer << endl;
151 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
152 for (FGScheduledFlightVecIterator i = flights.begin();
156 //i->adjustTime(now);
157 if (!(i->initializeAirports()))
160 //sort(flights.begin(), flights.end());
161 // Since time isn't initialized yet when this function is called,
162 // Find the closest possible airport.
163 // This should give a reasonable initialization order.
164 //setClosestDistanceToUser();
168 bool FGAISchedule::update(time_t now)
180 double courseToUser, courseToDest;
181 double distanceToDest;
188 remainingTimeEnroute;
193 if (fgGetBool("/sim/traffic-manager/enabled") == false)
196 aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
197 // Before the flight status of this traffic entity is updated
198 // for the first time, we need to roll back it's flight schedule so
199 // so that all the flights are centered around this simulated week's time
200 // table. This is to avoid the situation where the first scheduled flight is
201 // in the future, causing the traffic manager to not generate traffic until
202 // simulated time has caught up with the real world time at initialization.
203 // This is to counter a more general initialization bug, caused by the fact
204 // that warp is not yet set when the schedule is initialized. This is
205 // especially a problem when using a negative time offset.
206 // i.e let's say we specify FlightGear to run with --time-offset=-24:00:00.
207 // Then the schedule will initialize using today, but we will fly yesterday.
208 // Thus, it would take a whole day of simulation before the traffic manager
213 AIManagerRef = BOGUS;
215 for (FGScheduledFlightVecIterator i = flights.begin();
224 // Sort all the scheduled flights according to scheduled departure time.
225 // Because this is done at every update, we only need to check the status
226 // of the first listed flight.
227 sort(flights.begin(), flights.end());
228 FGScheduledFlightVecIterator i = flights.begin();
231 // Check if this aircraft has been released.
232 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
233 if (tmgr->isReleased(AIManagerRef))
239 userLatitude = fgGetDouble("/position/latitude-deg");
240 userLongitude = fgGetDouble("/position/longitude-deg");
242 //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
243 // This flight entry is entirely in the past, do we need to
244 // push it forward in time to the next scheduled departure.
245 if ((i->getDepartureTime() < now) && (i->getArrivalTime() < now))
251 // Departure time in the past and arrival time in the future.
252 // This flight is in progress, so we need to calculate it's
253 // approximate position and -if in range- create an AIAircraft
255 //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
258 // Part of this flight is in the future.
259 if (i->getArrivalTime() > now)
261 dep = i->getDepartureAirport();
262 arr = i->getArrivalAirport ();
266 temp = sgPolarToCart3d(Point3D(dep->getLongitude() *
267 SG_DEGREES_TO_RADIANS,
269 SG_DEGREES_TO_RADIANS,
275 temp = sgPolarToCart3d(Point3D(arr->getLongitude() *
276 SG_DEGREES_TO_RADIANS,
278 SG_DEGREES_TO_RADIANS,
285 sgdVectorProductVec3(cross,b,a);
287 angle = sgACos(sgdScalarProductVec3(a,b));
289 // Okay, at this point we have the angle between departure and
290 // arrival airport, in degrees. From here we can interpolate the
291 // position of the aircraft by calculating the ratio between
292 // total time enroute and elapsed time enroute.
294 totalTimeEnroute = i->getArrivalTime() - i->getDepartureTime();
295 if (now > i->getDepartureTime())
297 //err << "Lat = " << lat << ", lon = " << lon << endl;
298 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
299 elapsedTimeEnroute = now - i->getDepartureTime();
300 remainingTimeEnroute = i->getArrivalTime() - now;
304 lat = dep->getLatitude();
305 lon = dep->getLongitude();
306 elapsedTimeEnroute = 0;
307 remainingTimeEnroute = totalTimeEnroute;
310 angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
313 //cout << "a = " << a[0] << " " << a[1] << " " << a[2]
314 // << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;
315 sgdMakeRotMat4(matrix, angle, cross);
316 for(int j = 0; j < 3; j++)
319 for (int k = 0; k<3; k++)
321 newPos[j] += matrix[j][k]*a[k];
325 temp = sgCartToPolar3d(Point3D(newPos[0], newPos[1],newPos[2]));
326 if (now > i->getDepartureTime())
328 //cerr << "Lat = " << lat << ", lon = " << lon << endl;
329 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
330 lat = temp.lat() * SG_RADIANS_TO_DEGREES;
331 lon = temp.lon() * SG_RADIANS_TO_DEGREES;
335 lat = dep->getLatitude();
336 lon = dep->getLongitude();
340 SGWayPoint current (lon,
343 SGWayPoint user ( userLongitude,
346 SGWayPoint dest ( arr->getLongitude(),
349 // We really only need distance to user
350 // and course to destination
351 user.CourseAndDistance(current, &courseToUser, &distanceToUser);
352 dest.CourseAndDistance(current, &courseToDest, &distanceToDest);
353 speed = (distanceToDest*SG_METER_TO_NM) /
354 ((double) remainingTimeEnroute/3600.0);
357 // If distance between user and simulated aircaft is less
358 // then 500nm, create this flight. At jet speeds 500 nm is roughly
359 // one hour flight time, so that would be a good approximate point
360 // to start a more detailed simulation of this aircraft.
361 //cerr << registration << " is currently enroute from "
362 // << dep->_id << " to " << arr->_id << "distance : "
363 // << distanceToUser*SG_METER_TO_NM << endl;
364 if ((distanceToUser*SG_METER_TO_NM) < TRAFFICTOAIDIST)
366 string flightPlanName = dep->getId() + string("-") + arr->getId() +
369 //if ((i->getDepartureTime() < now))
371 // alt = i->getCruiseAlt() *100;
375 // alt = dep->_elevation+19;
378 // Only allow traffic to be created when the model path exists
379 SGPath mp(globals->get_fg_root());
380 mp.append(modelPath);
383 FGAIAircraft *aircraft = new FGAIAircraft(this);
384 aircraft->setPerformance(m_class); //"jet_transport";
385 aircraft->setCompany(airline); //i->getAirline();
386 aircraft->setAcType(acType); //i->getAcType();
387 aircraft->setPath(modelPath.c_str());
388 //aircraft->setFlightPlan(flightPlanName);
389 aircraft->setLatitude(lat);
390 aircraft->setLongitude(lon);
391 aircraft->setAltitude(i->getCruiseAlt()*100); // convert from FL to feet
392 aircraft->setSpeed(speed);
393 aircraft->setBank(0);
394 aircraft->SetFlightPlan(new FGAIFlightPlan(flightPlanName, courseToDest, i->getDepartureTime(), dep,
395 arr,true, radius, i->getCruiseAlt()*100, lat, lon, speed, flightType, acType, airline));
396 aimgr->attach(aircraft);
399 AIManagerRef = aircraft->getID();
400 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
401 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
402 //cerr << "Dep : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
403 //cerr << "Arr : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
404 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
405 //cerr << "Total time = " << (totalTimeEnroute/3600.0) << endl;
406 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
410 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
416 // Both departure and arrival time are in the future, so this
417 // the aircraft is parked at the departure airport.
418 // Currently this status is mostly ignored, but in future
419 // versions, code should go here that -if within user range-
420 // positions these aircraft at parking locations at the airport.
421 if ((i->getDepartureTime() > now) && (i->getArrivalTime() > now))
423 dep = i->getDepartureAirport();
427 //cerr << "Traffic schedule got to beyond last clause" << endl;
428 // EMH: prevent a warning, should this be 'true' instead?
429 // DT: YES. Originally, this code couldn't be reached, but
430 // when the "if(!(AIManagerManager))" clause is false we
431 // fall through right to the end. This is a valid flow.
432 // the actual value is pretty innocent, only it triggers
433 // warning in TrafficManager::update().
434 // (which was added as a sanity check for myself in the first place. :-)
439 void FGAISchedule::next()
441 flights.begin()->update();
442 sort(flights.begin(), flights.end());
445 double FGAISchedule::getSpeed()
447 double courseToUser, courseToDest;
448 double distanceToUser, distanceToDest;
449 double speed, remainingTimeEnroute;
450 FGAirport *dep, *arr;
452 FGScheduledFlightVecIterator i = flights.begin();
453 dep = i->getDepartureAirport();
454 arr = i->getArrivalAirport ();
458 SGWayPoint dest ( dep->getLongitude(),
461 SGWayPoint curr ( arr->getLongitude(),
464 remainingTimeEnroute = i->getArrivalTime() - i->getDepartureTime();
465 dest.CourseAndDistance(curr, &courseToDest, &distanceToDest);
466 speed = (distanceToDest*SG_METER_TO_NM) /
467 ((double) remainingTimeEnroute/3600.0);
472 // void FGAISchedule::setClosestDistanceToUser()
482 // elapsedTimeEnroute;
484 // double userLatitude = fgGetDouble("/position/latitude-deg");
485 // double userLongitude = fgGetDouble("/position/longitude-deg");
489 // #if defined( __CYGWIN__) || defined( __MINGW32__)
490 // #define HUGE HUGE_VAL
492 // distanceToUser = HUGE;
493 // FGScheduledFlightVecIterator i = flights.begin();
494 // while (i != flights.end())
496 // dep = i->getDepartureAirport();
500 // SGWayPoint user ( userLongitude,
502 // i->getCruiseAlt());
503 // SGWayPoint current (dep->getLongitude(),
504 // dep->getLatitude(),
506 // user.CourseAndDistance(current, &course, &dist);
507 // if (dist < distanceToUser)
509 // distanceToUser = dist;
510 // //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
514 // //return distToUser;