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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 ****************************************************************************
22 *****************************************************************************/
40 #include <simgear/compiler.h>
41 #include <simgear/math/polar3d.hxx>
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()
77 FGAISchedule::FGAISchedule(string mdl,
87 FGScheduledFlightVec flt)
102 for (FGScheduledFlightVecIterator i = flt.begin();
105 flights.push_back(FGScheduledFlight((*i)));
110 FGAISchedule::FGAISchedule(const FGAISchedule &other)
112 modelPath = other.modelPath;
113 livery = other.livery;
114 registration = other.registration;
116 flights = other.flights;
119 AIManagerRef = other.AIManagerRef;
120 acType = other.acType;
121 airline = other.airline;
122 m_class = other.m_class;
123 firstRun = other.firstRun;
124 radius = other.radius;
125 groundOffset = other.groundOffset;
126 flightType = other.flightType;
127 distanceToUser = other.distanceToUser;
131 FGAISchedule::~FGAISchedule()
136 bool FGAISchedule::init()
139 //SGTime* currTimeDate = globals->get_time_params();
141 //tm *temp = currTimeDate->getGmt();
143 //sgTimeFormatTime(&targetTimeDate, buffer);
144 //cout << "Scheduled Time " << buffer << endl;
145 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
146 for (FGScheduledFlightVecIterator i = flights.begin();
150 //i->adjustTime(now);
151 if (!(i->initializeAirports()))
154 //sort(flights.begin(), flights.end());
155 // Since time isn't initialized yet when this function is called,
156 // Find the closest possible airport.
157 // This should give a reasonable initialization order.
158 setClosestDistanceToUser();
162 bool FGAISchedule::update(time_t now)
174 double courseToUser, courseToDest;
175 double distanceToDest;
182 remainingTimeEnroute;
187 if (fgGetBool("/sim/traffic-manager/enabled") == false)
190 aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
191 // Before the flight status of this traffic entity is updated
192 // for the first time, we need to roll back it's flight schedule so
193 // so that all the flights are centered around this simulated week's time
194 // table. This is to avoid the situation where the first scheduled flight is
195 // in the future, causing the traffic manager to not generate traffic until
196 // simulated time has caught up with the real world time at initialization.
197 // This is to counter a more general initialization bug, caused by the fact
198 // that warp is not yet set when the schedule is initialized. This is
199 // especially a problem when using a negative time offset.
200 // i.e let's say we specify FlightGear to run with --time-offset=-24:00:00.
201 // Then the schedule will initialize using today, but we will fly yesterday.
202 // Thus, it would take a whole day of simulation before the traffic manager
206 for (FGScheduledFlightVecIterator i = flights.begin();
215 // Sort all the scheduled flights according to scheduled departure time.
216 // Because this is done at every update, we only need to check the status
217 // of the first listed flight.
218 sort(flights.begin(), flights.end());
219 FGScheduledFlightVecIterator i = flights.begin();
222 // Check if this aircraft has been released.
223 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
224 if (tmgr->isReleased(AIManagerRef))
230 userLatitude = fgGetDouble("/position/latitude-deg");
231 userLongitude = fgGetDouble("/position/longitude-deg");
233 //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
234 // This flight entry is entirely in the past, do we need to
235 // push it forward in time to the next scheduled departure.
236 if ((i->getDepartureTime() < now) && (i->getArrivalTime() < now))
242 // Departure time in the past and arrival time in the future.
243 // This flight is in progress, so we need to calculate it's
244 // approximate position and -if in range- create an AIAircraft
246 //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
249 // Part of this flight is in the future.
250 if (i->getArrivalTime() > now)
252 dep = i->getDepartureAirport();
253 arr = i->getArrivalAirport ();
257 temp = sgPolarToCart3d(Point3D(dep->getLongitude() *
258 SG_DEGREES_TO_RADIANS,
260 SG_DEGREES_TO_RADIANS,
266 temp = sgPolarToCart3d(Point3D(arr->getLongitude() *
267 SG_DEGREES_TO_RADIANS,
269 SG_DEGREES_TO_RADIANS,
276 sgdVectorProductVec3(cross,b,a);
278 angle = sgACos(sgdScalarProductVec3(a,b));
280 // Okay, at this point we have the angle between departure and
281 // arrival airport, in degrees. From here we can interpolate the
282 // position of the aircraft by calculating the ratio between
283 // total time enroute and elapsed time enroute.
285 totalTimeEnroute = i->getArrivalTime() - i->getDepartureTime();
286 if (now > i->getDepartureTime())
288 //err << "Lat = " << lat << ", lon = " << lon << endl;
289 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
290 elapsedTimeEnroute = now - i->getDepartureTime();
291 remainingTimeEnroute = i->getArrivalTime() - now;
295 lat = dep->getLatitude();
296 lon = dep->getLongitude();
297 elapsedTimeEnroute = 0;
298 remainingTimeEnroute = totalTimeEnroute;
301 angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
304 //cout << "a = " << a[0] << " " << a[1] << " " << a[2]
305 // << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;
306 sgdMakeRotMat4(matrix, angle, cross);
307 for(int j = 0; j < 3; j++)
310 for (int k = 0; k<3; k++)
312 newPos[j] += matrix[j][k]*a[k];
316 temp = sgCartToPolar3d(Point3D(newPos[0], newPos[1],newPos[2]));
317 if (now > i->getDepartureTime())
319 //cerr << "Lat = " << lat << ", lon = " << lon << endl;
320 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
321 lat = temp.lat() * SG_RADIANS_TO_DEGREES;
322 lon = temp.lon() * SG_RADIANS_TO_DEGREES;
326 lat = dep->getLatitude();
327 lon = dep->getLongitude();
331 SGWayPoint current (lon,
334 SGWayPoint user ( userLongitude,
337 SGWayPoint dest ( arr->getLongitude(),
340 // We really only need distance to user
341 // and course to destination
342 user.CourseAndDistance(current, &courseToUser, &distanceToUser);
343 dest.CourseAndDistance(current, &courseToDest, &distanceToDest);
344 speed = (distanceToDest*SG_METER_TO_NM) /
345 ((double) remainingTimeEnroute/3600.0);
348 // If distance between user and simulated aircaft is less
349 // then 500nm, create this flight. At jet speeds 500 nm is roughly
350 // one hour flight time, so that would be a good approximate point
351 // to start a more detailed simulation of this aircraft.
352 //cerr << registration << " is currently enroute from "
353 // << dep->_id << " to " << arr->_id << "distance : "
354 // << distanceToUser*SG_METER_TO_NM << endl;
355 if ((distanceToUser*SG_METER_TO_NM) < TRAFFICTOAIDIST)
357 string flightPlanName = dep->getId() + string("-") + arr->getId() +
360 //if ((i->getDepartureTime() < now))
362 // alt = i->getCruiseAlt() *100;
366 // alt = dep->_elevation+19;
369 // Fixme: A non-existent model path results in an
370 // abort, due to an unhandled exeption, in fg main loop.
371 FGAIAircraft *aircraft = new FGAIAircraft(this);
372 aircraft->setPerformance(m_class); //"jet_transport";
373 aircraft->setCompany(airline); //i->getAirline();
374 aircraft->setAcType(acType); //i->getAcType();
375 aircraft->setPath(modelPath.c_str());
376 aircraft->setFlightPlan(flightPlanName);
377 aircraft->setLatitude(lat);
378 aircraft->setLongitude(lon);
379 aircraft->setAltitude(i->getCruiseAlt()*100); // convert from FL to feet
380 aircraft->setSpeed(speed);
381 aircraft->setBank(0);
382 aircraft->SetFlightPlan(new FGAIFlightPlan(modelPath, courseToDest, i->getDepartureTime(), dep,
383 arr,true, radius, i->getCruiseAlt()*100, lat, lon, speed, flightType, acType, airline));
384 aimgr->attach(aircraft);
387 AIManagerRef = aircraft->getID();
388 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
389 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
390 //cerr << "Dep : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
391 //cerr << "Arr : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
392 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
393 //cerr << "Total time = " << (totalTimeEnroute/3600.0) << endl;
394 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
400 // Both departure and arrival time are in the future, so this
401 // the aircraft is parked at the departure airport.
402 // Currently this status is mostly ignored, but in future
403 // versions, code should go here that -if within user range-
404 // positions these aircraft at parking locations at the airport.
405 if ((i->getDepartureTime() > now) && (i->getArrivalTime() > now))
407 dep = i->getDepartureAirport();
411 //cerr << "Traffic schedule got to beyond last clause" << endl;
412 // EMH: prevent a warning, should this be 'true' instead?
413 // DT: YES. Originally, this code couldn't be reached, but
414 // when the "if(!(AIManagerManager))" clause is false we
415 // fall through right to the end. This is a valid flow.
416 // the actual value is pretty innocent, only it triggers
417 // warning in TrafficManager::update().
418 // (which was added as a sanity check for myself in the first place. :-)
423 void FGAISchedule::next()
425 flights.begin()->update();
426 sort(flights.begin(), flights.end());
429 double FGAISchedule::getSpeed()
431 double courseToUser, courseToDest;
432 double distanceToUser, distanceToDest;
433 double speed, remainingTimeEnroute;
434 FGAirport *dep, *arr;
436 FGScheduledFlightVecIterator i = flights.begin();
437 dep = i->getDepartureAirport();
438 arr = i->getArrivalAirport ();
442 SGWayPoint dest ( dep->getLongitude(),
445 SGWayPoint curr ( arr->getLongitude(),
448 remainingTimeEnroute = i->getArrivalTime() - i->getDepartureTime();
449 dest.CourseAndDistance(curr, &courseToDest, &distanceToDest);
450 speed = (distanceToDest*SG_METER_TO_NM) /
451 ((double) remainingTimeEnroute/3600.0);
456 void FGAISchedule::setClosestDistanceToUser()
468 double userLatitude = fgGetDouble("/position/latitude-deg");
469 double userLongitude = fgGetDouble("/position/longitude-deg");
473 #if defined( __CYGWIN__) || defined( __MINGW32__)
474 #define HUGE HUGE_VAL
476 distanceToUser = HUGE;
477 FGScheduledFlightVecIterator i = flights.begin();
478 while (i != flights.end())
480 dep = i->getDepartureAirport();
484 SGWayPoint user ( userLongitude,
487 SGWayPoint current (dep->getLongitude(),
490 user.CourseAndDistance(current, &course, &dist);
491 if (dist < distanceToUser)
493 distanceToUser = dist;
494 //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;