| 1 | /* |
| 2 | * SPDX-FileName: AIAircraft.cxx |
| 3 | * SPDX-FileComment: AIBase derived class creates an AI aircraft |
| 4 | * SPDX-FileCopyrightText: Copyright (C) 2003 David P. Culp - [email protected] |
| 5 | * SPDX-License-Identifier: GPL-2.0-or-later |
| 6 | */ |
| 7 | |
| 8 | #include <Airports/airport.hxx> |
| 9 | #include <Airports/dynamics.hxx> |
| 10 | #include <Main/fg_props.hxx> |
| 11 | #include <Main/globals.hxx> |
| 12 | #include <Main/util.hxx> |
| 13 | #include <Scenery/scenery.hxx> |
| 14 | #include <Traffic/Schedule.hxx> |
| 15 | |
| 16 | #include <simgear/io/iostreams/sgstream.hxx> |
| 17 | #include <simgear/structure/exception.hxx> |
| 18 | #include <simgear/timing/sg_time.hxx> |
| 19 | |
| 20 | #include <cmath> |
| 21 | #include <ctime> |
| 22 | #include <iostream> |
| 23 | #include <signal.h> |
| 24 | #include <string> |
| 25 | |
| 26 | // defined in AIShip.cxx |
| 27 | extern double fgIsFinite(double x); |
| 28 | |
| 29 | #include "AIAircraft.hxx" |
| 30 | #include "AIFlightPlan.hxx" |
| 31 | #include "AIManager.hxx" |
| 32 | #include "performancedata.hxx" |
| 33 | #include "performancedb.hxx" |
| 34 | |
| 35 | #include <ATC/ATCController.hxx> |
| 36 | #include <ATC/trafficcontrol.hxx> |
| 37 | |
| 38 | |
| 39 | FGAIAircraft::FGAIAircraft(FGAISchedule* ref) : /* HOT must be disabled for AI Aircraft, |
| 40 | * otherwise traffic detection isn't working as expected.*/ |
| 41 | FGAIBaseAircraft(), |
| 42 | _performance(nullptr), |
| 43 | csvFile{std::make_unique<sg_ofstream>()} |
| 44 | { |
| 45 | trafficRef = ref; |
| 46 | if (trafficRef) { |
| 47 | groundOffset = trafficRef->getGroundOffset(); |
| 48 | setCallSign(trafficRef->getCallSign()); |
| 49 | tracked = getCallSign() == fgGetString("/ai/track-callsign") || fgGetString("/ai/track-callsign") == "ALL"; |
| 50 | } else { |
| 51 | groundOffset = 0; |
| 52 | } |
| 53 | |
| 54 | fp = nullptr; |
| 55 | controller = nullptr; |
| 56 | prevController = nullptr; |
| 57 | towerController = nullptr; |
| 58 | dt_count = 0; |
| 59 | dt_elev_count = 0; |
| 60 | use_perf_vs = true; |
| 61 | |
| 62 | no_roll = false; |
| 63 | tgt_speed = 0; |
| 64 | speed = 0; |
| 65 | groundTargetSpeed = 0; |
| 66 | spinCounter = 0; |
| 67 | |
| 68 | // set heading and altitude locks |
| 69 | hdg_lock = false; |
| 70 | alt_lock = false; |
| 71 | roll = 0; |
| 72 | headingChangeRate = 0.0; |
| 73 | headingError = 0; |
| 74 | minBearing = 360; |
| 75 | speedFraction = 1.0; |
| 76 | prevSpeed = 0.0; |
| 77 | prev_dist_to_go = 0.0; |
| 78 | |
| 79 | auto perfDB = globals->get_subsystem<PerformanceDB>(); |
| 80 | |
| 81 | if (perfDB) { |
| 82 | _performance = perfDB->getDefaultPerformance(); |
| 83 | } else { |
| 84 | SG_LOG(SG_AI, SG_DEV_ALERT, "no performance DB loaded"); |
| 85 | _performance = PerformanceData::getDefaultData(); |
| 86 | } |
| 87 | |
| 88 | takeOffStatus = AITakeOffStatus::NONE; |
| 89 | timeElapsed = 0; |
| 90 | |
| 91 | trackCache.remainingLength = 0; |
| 92 | trackCache.startWptName = "-"; |
| 93 | |
| 94 | tcasThreatNode = props->getNode("tcas/threat-level", true); |
| 95 | tcasRANode = props->getNode("tcas/ra-sense", true); |
| 96 | _searchOrder = ModelSearchOrder::PREFER_AI; |
| 97 | } |
| 98 | |
| 99 | void FGAIAircraft::lazyInitControlsNodes() |
| 100 | { |
| 101 | _controlsLateralModeNode = props->getNode("controls/flight/lateral-mode", true); |
| 102 | _controlsVerticalModeNode = props->getNode("controls/flight/vertical-mode", true); |
| 103 | _controlsTargetHeadingNode = props->getNode("controls/flight/target-hdg", true); |
| 104 | _controlsTargetRollNode = props->getNode("controls/flight/target-roll", true); |
| 105 | _controlsTargetAltitude = props->getNode("controls/flight/target-alt", true); |
| 106 | _controlsTargetPitch = props->getNode("controls/flight/target-pitch", true); |
| 107 | _controlsTargetSpeed = props->getNode("controls/flight/target-spd", true); |
| 108 | } |
| 109 | |
| 110 | FGAIAircraft::~FGAIAircraft() |
| 111 | { |
| 112 | assert(!controller); |
| 113 | if (controller) { |
| 114 | // we no longer signOff from controller here, controller should |
| 115 | // have been cleared using clearATCControllers |
| 116 | // see FLIGHTGEAR-15 on Sentry |
| 117 | SG_LOG(SG_AI, SG_ALERT, "Destruction of AIAircraft which was not unbound"); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | |
| 122 | void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) |
| 123 | { |
| 124 | if (!scFileNode) |
| 125 | return; |
| 126 | |
| 127 | FGAIBase::readFromScenario(scFileNode); |
| 128 | |
| 129 | setPerformance("", scFileNode->getStringValue("class", "jet_transport")); |
| 130 | setFlightPlan(scFileNode->getStringValue("flightplan"), |
| 131 | scFileNode->getBoolValue("repeat", false)); |
| 132 | setCallSign(scFileNode->getStringValue("callsign")); |
| 133 | tracked = getCallSign() == fgGetString("/ai/track-callsign") || fgGetString("/ai/track-callsign") == "ALL"; |
| 134 | } |
| 135 | |
| 136 | |
| 137 | void FGAIAircraft::bind() |
| 138 | { |
| 139 | FGAIBaseAircraft::bind(); |
| 140 | |
| 141 | tie("transponder-id", |
| 142 | SGRawValueMethods<FGAIAircraft, const char*>(*this, |
| 143 | &FGAIAircraft::_getTransponderCode)); |
| 144 | } |
| 145 | |
| 146 | void FGAIAircraft::update(double dt) |
| 147 | { |
| 148 | FGAIBase::update(dt); |
| 149 | Run(dt); |
| 150 | Transform(); |
| 151 | if (tracked && !csvFile->is_open()) { |
| 152 | char fname[160]; |
| 153 | time_t t = time(0); // get time now |
| 154 | snprintf(fname, sizeof(fname), "%s_%ld.csv", getCallSign().c_str(), t); |
| 155 | SGPath p = globals->get_download_dir() / fname; |
| 156 | csvFile->open(p); |
| 157 | dumpCSVHeader(csvFile); |
| 158 | } |
| 159 | if (tracked && csvFile->is_open()) { |
| 160 | dumpCSV(csvFile, csvIndex++); |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | void FGAIAircraft::unbind() |
| 165 | { |
| 166 | FGAIBase::unbind(); |
| 167 | clearATCController(); |
| 168 | } |
| 169 | |
| 170 | void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acClass) |
| 171 | { |
| 172 | auto perfDB = globals->get_subsystem<PerformanceDB>(); |
| 173 | if (perfDB) { |
| 174 | _performance = perfDB->getDataFor(acType, acClass); |
| 175 | } |
| 176 | |
| 177 | if (!_performance) { |
| 178 | SG_LOG(SG_AI, SG_DEV_ALERT, "no AI performance data found for: " << acType << "/" << acClass); |
| 179 | _performance = PerformanceData::getDefaultData(); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | void FGAIAircraft::Run(double dt) |
| 184 | { |
| 185 | // We currently have one situation in which an AIAircraft object is used that is not attached to the |
| 186 | // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world. |
| 187 | // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate |
| 188 | // enough |
| 189 | const bool isUserAircraft = (manager == nullptr); |
| 190 | |
| 191 | bool flightplanActive = true; |
| 192 | |
| 193 | // user aircraft speed, heading and position are synchronized in |
| 194 | // FGAIManager::fetchUserState() |
| 195 | if (!isUserAircraft) { |
| 196 | bool outOfSight = false; |
| 197 | updatePrimaryTargetValues(dt, flightplanActive, outOfSight); // target hdg, alt, speed |
| 198 | if (outOfSight) { |
| 199 | return; |
| 200 | } |
| 201 | } else { |
| 202 | updateUserFlightPlan(dt); |
| 203 | } |
| 204 | |
| 205 | if (!flightplanActive) { |
| 206 | groundTargetSpeed = 0; |
| 207 | } |
| 208 | |
| 209 | handleATCRequests(dt); // ATC also has a word to say |
| 210 | updateSecondaryTargetValues(dt); // target roll, vertical speed, pitch |
| 211 | updateActualState(dt); |
| 212 | |
| 213 | updateModelProperties(dt); |
| 214 | |
| 215 | |
| 216 | if (!isUserAircraft) { |
| 217 | UpdateRadar(manager); |
| 218 | invisible = !manager->isVisible(pos); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | |
| 223 | void FGAIAircraft::AccelTo(double speed) |
| 224 | { |
| 225 | tgt_speed = speed; |
| 226 | if (!isStationary()) { |
| 227 | _needsGroundElevation = true; |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | |
| 232 | void FGAIAircraft::PitchTo(double angle) |
| 233 | { |
| 234 | tgt_pitch = angle; |
| 235 | alt_lock = false; |
| 236 | } |
| 237 | |
| 238 | |
| 239 | void FGAIAircraft::RollTo(double angle) |
| 240 | { |
| 241 | tgt_roll = angle; |
| 242 | hdg_lock = false; |
| 243 | } |
| 244 | |
| 245 | |
| 246 | #if 0 |
| 247 | void FGAIAircraft::YawTo(double angle) { |
| 248 | tgt_yaw = angle; |
| 249 | } |
| 250 | #endif |
| 251 | |
| 252 | |
| 253 | void FGAIAircraft::ClimbTo(double alt_ft) |
| 254 | { |
| 255 | tgt_altitude_ft = alt_ft; |
| 256 | alt_lock = true; |
| 257 | } |
| 258 | |
| 259 | |
| 260 | void FGAIAircraft::TurnTo(double heading) |
| 261 | { |
| 262 | const double headingDiff = SGMiscd::normalizePeriodic(-180, 180, heading - tgt_heading); |
| 263 | |
| 264 | if (fabs(heading) < 0.1 && fabs(headingDiff) > 1) { |
| 265 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "|Heading reset to zero " << tgt_heading << " " << headingDiff << " at " << getGeodPos()); |
| 266 | } |
| 267 | tgt_heading = heading; |
| 268 | // SG_LOG(SG_AI, SG_BULK, "Turn tgt_heading to " << tgt_heading); |
| 269 | hdg_lock = true; |
| 270 | } |
| 271 | |
| 272 | |
| 273 | double FGAIAircraft::sign(double x) |
| 274 | { |
| 275 | if (x == 0.0) |
| 276 | return x; |
| 277 | else |
| 278 | return x / fabs(x); |
| 279 | } |
| 280 | |
| 281 | |
| 282 | void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) |
| 283 | { |
| 284 | if (flightplan.empty()) { |
| 285 | // this is the case for Nasal-scripted aircraft |
| 286 | return; |
| 287 | } |
| 288 | |
| 289 | std::unique_ptr<FGAIFlightPlan> plan(new FGAIFlightPlan(flightplan)); |
| 290 | if (plan->isValidPlan()) { |
| 291 | plan->setRepeat(repeat); |
| 292 | FGAIBase::setFlightPlan(std::move(plan)); |
| 293 | } else { |
| 294 | SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | void FGAIAircraft::ProcessFlightPlan(double dt, time_t now) |
| 299 | { |
| 300 | // the one behind you |
| 301 | FGAIWaypoint* prev = 0; |
| 302 | // the one ahead |
| 303 | FGAIWaypoint* curr = 0; |
| 304 | // the next plus 1 |
| 305 | FGAIWaypoint* next = 0; |
| 306 | /**The angle of the next turn.*/ |
| 307 | int nextTurnAngle = 0; |
| 308 | |
| 309 | prev = fp->getPreviousWaypoint(); |
| 310 | curr = fp->getCurrentWaypoint(); |
| 311 | next = fp->getNextWaypoint(); |
| 312 | nextTurnAngle = fp->getNextTurnAngle(); |
| 313 | |
| 314 | dt_count += dt; |
| 315 | |
| 316 | /////////////////////////////////////////////////////////////////////////// |
| 317 | // Initialize the flightplan |
| 318 | ////////////////////////////////////////////////////////////////////////// |
| 319 | if (!prev || repositioned) { |
| 320 | if (!fp->empty()) { |
| 321 | handleFirstWaypoint(); |
| 322 | } else { |
| 323 | SG_LOG(SG_AI, SG_WARN, getCallSign() << " didn't have a valid flightplan and was killed"); |
| 324 | setDie(true); |
| 325 | } |
| 326 | return; |
| 327 | } // end of initialization |
| 328 | if (!fpExecutable(now)) { |
| 329 | return; |
| 330 | } |
| 331 | dt_count = 0; |
| 332 | |
| 333 | double distanceToDescent; |
| 334 | // Not the best solution. Double adding of legs is possible |
| 335 | if (fp->getLastWaypoint() == fp->getNextWaypoint() && |
| 336 | reachedEndOfCruise(distanceToDescent)) { |
| 337 | if (!loadNextLeg(distanceToDescent)) { |
| 338 | setDie(true); |
| 339 | return; |
| 340 | } |
| 341 | fp->IncrementWaypoint(false); |
| 342 | fp->IncrementWaypoint(false); |
| 343 | prev = fp->getPreviousWaypoint(); |
| 344 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|EndofCruise Previous WP \t" << prev->getName()); |
| 345 | curr = fp->getCurrentWaypoint(); |
| 346 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|EndofCruise Current WP \t" << curr->getName()); |
| 347 | next = fp->getNextWaypoint(); |
| 348 | if (next) { |
| 349 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|EndofCruise Next WP \t" << next->getName()); |
| 350 | } |
| 351 | } |
| 352 | if (!curr) { |
| 353 | if (!next) { |
| 354 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "|No more WPs"); |
| 355 | } else { |
| 356 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "|No current WP" << next->getName()); |
| 357 | } |
| 358 | return; |
| 359 | } |
| 360 | |
| 361 | if (!leadPointReached(curr, next, nextTurnAngle)) { |
| 362 | controlHeading(curr, nullptr); |
| 363 | controlSpeed(curr, next); |
| 364 | } else { |
| 365 | if (curr->isFinished()) { //end of the flight plan |
| 366 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Flightplan ended"); |
| 367 | if (fp->getRepeat()) { |
| 368 | fp->restart(); |
| 369 | } else { |
| 370 | setDie(true); |
| 371 | } |
| 372 | return; |
| 373 | } |
| 374 | |
| 375 | if (next) { |
| 376 | // TODO: more intelligent method in AIFlightPlan, no need to send data it already has :-) |
| 377 | tgt_heading = fp->getBearing(curr, next); |
| 378 | spinCounter = 0; |
| 379 | SG_LOG(SG_AI, SG_BULK, "Set tgt_heading to " << tgt_heading); |
| 380 | } |
| 381 | |
| 382 | // TODO: let the fp handle this (loading of next leg) |
| 383 | fp->IncrementWaypoint(trafficRef != 0); |
| 384 | if (((!(fp->getNextWaypoint()))) && (trafficRef != 0)) { |
| 385 | if (!loadNextLeg()) { |
| 386 | setDie(true); |
| 387 | return; |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | prev = fp->getPreviousWaypoint(); |
| 392 | if (prev) { |
| 393 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Previous WP \t" << prev->getName() << "\t" << prev->getPos()); |
| 394 | } |
| 395 | curr = fp->getCurrentWaypoint(); |
| 396 | if (curr) { |
| 397 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Current WP \t" << curr->getName() << "\t" << curr->getPos()); |
| 398 | } |
| 399 | next = fp->getNextWaypoint(); |
| 400 | if (next) { |
| 401 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Next WP \t" << next->getName() << "\t" << next->getPos()); |
| 402 | } |
| 403 | |
| 404 | // Now that we have incremented the waypoints, execute some traffic manager specific code |
| 405 | if (trafficRef) { |
| 406 | // TODO: isn't this best executed right at the beginning? |
| 407 | if (!aiTrafficVisible()) { |
| 408 | setDie(true); |
| 409 | return; |
| 410 | } |
| 411 | |
| 412 | if (!handleAirportEndPoints(prev, now)) { |
| 413 | setDie(true); |
| 414 | return; |
| 415 | } |
| 416 | |
| 417 | announcePositionToController(); |
| 418 | if (fp && props) { |
| 419 | props->getChild("arrival-time-sec", 0, true)->setIntValue(fp->getArrivalTime()); |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | if (next && !curr->contains("END") && !curr->contains("PushBackPointlegend")) { |
| 424 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Setting Leaddistance"); |
| 425 | fp->setLeadDistance(tgt_speed, tgt_heading, curr, next); |
| 426 | } |
| 427 | |
| 428 | // Calculate a target altitude for any leg in which at least one waypoint is in the air. |
| 429 | |
| 430 | if (prev->getInAir() && curr->getInAir()) { |
| 431 | // Completely in-air leg, so calculate the target altitude and VS. |
| 432 | if (curr->getCrossat() > -1000.0) { |
| 433 | use_perf_vs = false; |
| 434 | double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 435 | double vert_dist_ft = curr->getCrossat() - altitude_ft; |
| 436 | double err_dist = prev->getCrossat() - altitude_ft; |
| 437 | tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist); |
| 438 | tgt_altitude_ft = curr->getCrossat(); |
| 439 | checkTcas(); |
| 440 | } else { |
| 441 | use_perf_vs = true; |
| 442 | tgt_altitude_ft = prev->getCrossat(); |
| 443 | } |
| 444 | } else if (curr->getInAir()) { |
| 445 | // Take-off leg (prev is on ground) |
| 446 | if (curr->getCrossat() > -1000.0) { |
| 447 | // Altitude restriction |
| 448 | use_perf_vs = false; |
| 449 | double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 450 | double vert_dist_ft = curr->getCrossat() - altitude_ft; |
| 451 | double err_dist = -altitude_ft; |
| 452 | tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist); |
| 453 | tgt_altitude_ft = curr->getCrossat(); |
| 454 | } else { |
| 455 | // no cross-at, so assume same as previous |
| 456 | use_perf_vs = true; |
| 457 | tgt_altitude_ft = prev->getCrossat(); |
| 458 | } |
| 459 | } else if (prev->getInAir()) { |
| 460 | // Landing Leg (curr is on ground). |
| 461 | |
| 462 | // Assume we want to touch down on the point, and not early! |
| 463 | use_perf_vs = false; |
| 464 | double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 465 | double vert_dist_ft = curr->getAltitude() - altitude_ft; |
| 466 | double err_dist = -altitude_ft; |
| 467 | tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist); |
| 468 | tgt_altitude_ft = curr->getAltitude(); |
| 469 | } |
| 470 | |
| 471 | AccelTo(prev->getSpeed()); |
| 472 | hdg_lock = alt_lock = true; |
| 473 | no_roll = (prev->getOn_ground() && curr->getOn_ground()); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err) |
| 478 | { |
| 479 | // err is negative when we passed too high |
| 480 | double vert_m = vert_ft * SG_FEET_TO_METER; |
| 481 | double speedMs = (speed * SG_NM_TO_METER) / 3600; |
| 482 | double vs = 0; |
| 483 | if (dist_m) { |
| 484 | vs = ((vert_m) / dist_m) * speedMs; |
| 485 | } |
| 486 | // Convert to feet per minute |
| 487 | vs *= (SG_METER_TO_FEET * 60); |
| 488 | return vs; |
| 489 | } |
| 490 | |
| 491 | void FGAIAircraft::clearATCController() |
| 492 | { |
| 493 | if (controller && !getDie()) { |
| 494 | //If we are dead we are automatically erased |
| 495 | controller->signOff(getID()); |
| 496 | } |
| 497 | |
| 498 | controller = nullptr; |
| 499 | prevController = nullptr; |
| 500 | towerController = nullptr; |
| 501 | } |
| 502 | |
| 503 | bool FGAIAircraft::isBlockedBy(FGAIAircraft* other) |
| 504 | { |
| 505 | if (!other) { |
| 506 | return false; |
| 507 | } |
| 508 | int azimuth = SGGeodesy::courseDeg(getGeodPos(), other->getGeodPos()); |
| 509 | const double headingDiff = SGMiscd::normalizePeriodic(-180, 180, hdg - azimuth); |
| 510 | |
| 511 | SG_LOG(SG_AI, SG_BULK, getCallSign() << " blocked by " << other->getCallSign() << azimuth << " Heading " << hdg << " Diff" << headingDiff); |
| 512 | return false; |
| 513 | } |
| 514 | |
| 515 | #if 0 |
| 516 | void FGAIAircraft::assertSpeed(double speed) |
| 517 | { |
| 518 | if ((speed < -50) || (speed > 1000)) { |
| 519 | SG_LOG(SG_AI, SG_DEBUG, getCallSign() << " " |
| 520 | << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " " |
| 521 | << "Departure airport " << trafficRef->getDepartureAirport() << " " |
| 522 | << "Leg " << fp->getLeg() << " " |
| 523 | << "target_speed << " << tgt_speed << " " |
| 524 | << "speedFraction << " << speedFraction << " " |
| 525 | << "Current speed << " << speed << " "); |
| 526 | } |
| 527 | } |
| 528 | #endif |
| 529 | |
| 530 | |
| 531 | void FGAIAircraft::checkTcas(void) |
| 532 | { |
| 533 | if (tcasThreatNode && tcasThreatNode->getIntValue() == 3) { |
| 534 | const int RASense = tcasRANode->getIntValue(); |
| 535 | if ((RASense > 0) && (tgt_vs < 4000)) { |
| 536 | // upward RA: climb! |
| 537 | tgt_vs = 4000; |
| 538 | } else if (RASense < 0) { |
| 539 | // downward RA: descend! |
| 540 | if (altitude_ft < 1000) { |
| 541 | // too low: level off |
| 542 | if (tgt_vs > 0) |
| 543 | tgt_vs = 0; |
| 544 | } else { |
| 545 | if (tgt_vs > -4000) |
| 546 | tgt_vs = -4000; |
| 547 | } |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | #if 0 |
| 553 | void FGAIAircraft::initializeFlightPlan() { |
| 554 | } |
| 555 | #endif |
| 556 | |
| 557 | const char* FGAIAircraft::_getTransponderCode() const |
| 558 | { |
| 559 | return transponderCode.c_str(); |
| 560 | } |
| 561 | |
| 562 | // NOTE: Check whether the new (delayed leg increment code has any effect on this code. |
| 563 | // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint. |
| 564 | |
| 565 | bool FGAIAircraft::loadNextLeg(double distance) |
| 566 | { |
| 567 | int leg; |
| 568 | if ((leg = fp->getLeg()) == AILeg::PARKING) { |
| 569 | FGAirport* oldArr = trafficRef->getArrivalAirport(); |
| 570 | if (!trafficRef->next()) { |
| 571 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|No following flight killing"); |
| 572 | |
| 573 | //FIXME I'm on leg 9 and don't even reach parking. |
| 574 | return false; |
| 575 | } |
| 576 | FGAirport* dep = trafficRef->getDepartureAirport(); |
| 577 | if (oldArr != dep) { |
| 578 | // as though we are first leg |
| 579 | repositioned = true; |
| 580 | } else { |
| 581 | repositioned = false; |
| 582 | } |
| 583 | setCallSign(trafficRef->getCallSign()); |
| 584 | tracked = getCallSign() == fgGetString("/ai/track-callsign") || fgGetString("/ai/track-callsign") == "ALL"; |
| 585 | leg = 0; |
| 586 | fp->setLeg(leg); |
| 587 | } |
| 588 | |
| 589 | FGAirport* dep = trafficRef->getDepartureAirport(); |
| 590 | FGAirport* arr = trafficRef->getArrivalAirport(); |
| 591 | if (!(dep && arr)) { |
| 592 | setDie(true); |
| 593 | } else { |
| 594 | double cruiseAlt = trafficRef->getCruiseAlt() * 100; |
| 595 | |
| 596 | int nextLeg = determineNextLeg(leg); |
| 597 | |
| 598 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Loading Leg:" << leg << " Next: " << nextLeg); |
| 599 | bool ok = fp->create(this, |
| 600 | dep, |
| 601 | arr, |
| 602 | nextLeg, |
| 603 | cruiseAlt, |
| 604 | trafficRef->getSpeed(), |
| 605 | _getLatitude(), |
| 606 | _getLongitude(), |
| 607 | false, |
| 608 | trafficRef->getRadius(), |
| 609 | trafficRef->getFlightType(), |
| 610 | acType, |
| 611 | company, |
| 612 | distance); |
| 613 | |
| 614 | if (!ok) { |
| 615 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "|Failed to create waypoints for leg:" << leg + 1); |
| 616 | } |
| 617 | } |
| 618 | return true; |
| 619 | } |
| 620 | |
| 621 | |
| 622 | // Note: This code is copied from David Luff's AILocalTraffic |
| 623 | // Warning - ground elev determination is CPU intensive |
| 624 | // Either this function or the logic of how often it is called |
| 625 | // will almost certainly change. |
| 626 | |
| 627 | void FGAIAircraft::getGroundElev(double dt) |
| 628 | { |
| 629 | dt_elev_count += dt; |
| 630 | |
| 631 | if (!needGroundElevation()) |
| 632 | return; |
| 633 | // Update minimally every three secs, but add some randomness |
| 634 | // to prevent all AI objects doing this in synchrony |
| 635 | if (dt_elev_count < (3.0) + (rand() % 10)) |
| 636 | return; |
| 637 | |
| 638 | dt_elev_count = 0; |
| 639 | |
| 640 | // Only do the proper hitlist stuff if we are within visible range of the viewer. |
| 641 | if (!invisible) { |
| 642 | double visibility_meters = fgGetDouble("/environment/visibility-m"); |
| 643 | if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) { |
| 644 | return; |
| 645 | } |
| 646 | |
| 647 | double range = 500.0; |
| 648 | if (globals->get_scenery()->schedule_scenery(pos, range, 5.0)) { |
| 649 | double alt; |
| 650 | if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0)) { |
| 651 | tgt_altitude_ft = alt * SG_METER_TO_FEET; |
| 652 | if (isStationary()) { |
| 653 | // aircraft is stationary and we obtained altitude for this spot - we're done. |
| 654 | _needsGroundElevation = false; |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | void FGAIAircraft::doGroundAltitude() |
| 662 | { |
| 663 | if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) { |
| 664 | tgt_vs = -500; |
| 665 | } else { |
| 666 | if ((fabs(altitude_ft - (tgt_altitude_ft + groundOffset)) > 1000.0) || |
| 667 | (isStationary())) |
| 668 | altitude_ft = (tgt_altitude_ft + groundOffset); |
| 669 | else |
| 670 | altitude_ft += 0.1 * ((tgt_altitude_ft + groundOffset) - altitude_ft); |
| 671 | tgt_vs = 0; |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | |
| 676 | void FGAIAircraft::announcePositionToController() |
| 677 | { |
| 678 | if (!trafficRef) { |
| 679 | return; |
| 680 | } |
| 681 | |
| 682 | int leg = fp->getLeg(); |
| 683 | if (!fp->getCurrentWaypoint()) { |
| 684 | // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153 |
| 685 | // throw an exception so this aircraft gets killed by the AIManager. |
| 686 | throw sg_exception("bad AI flight plan. No current WP"); |
| 687 | } |
| 688 | |
| 689 | // Note that leg has been incremented after creating the current leg, so we should use |
| 690 | // leg numbers here that are one higher than the number that is used to create the leg |
| 691 | // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening. |
| 692 | // Leg numbers are updated only once the aircraft passes the last waypoint created for |
| 693 | // that leg, so I should probably just use the original leg numbers here! |
| 694 | switch (leg) { |
| 695 | case AILeg::STARTUP_PUSHBACK: // Startup and Push back |
| 696 | if (trafficRef->getDepartureAirport()->getDynamics()) |
| 697 | controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController(); |
| 698 | break; |
| 699 | case AILeg::TAXI: // Taxiing to runway |
| 700 | if (trafficRef->getDepartureAirport()->getDynamics()->getGroundController()->exists()) |
| 701 | controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundController(); |
| 702 | break; |
| 703 | case AILeg::TAKEOFF: //Take off tower controller |
| 704 | if (trafficRef->getDepartureAirport()->getDynamics()) { |
| 705 | controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController(); |
| 706 | if (towerController) { |
| 707 | SG_LOG(SG_AI, SG_BULK, " : " << controller->getName() << "#" << towerController->getName() << (controller != towerController)); |
| 708 | } |
| 709 | towerController = nullptr; |
| 710 | } else { |
| 711 | SG_LOG(SG_AI, SG_BULK, "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId()); |
| 712 | } |
| 713 | break; |
| 714 | case AILeg::APPROACH: |
| 715 | if (trafficRef->getArrivalAirport()->getDynamics()) { |
| 716 | controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController(); |
| 717 | } |
| 718 | break; |
| 719 | case AILeg::PARKING_TAXI: // Taxiing for parking |
| 720 | if (trafficRef->getArrivalAirport()->getDynamics()->getGroundController()->exists()) |
| 721 | controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundController(); |
| 722 | break; |
| 723 | default: |
| 724 | if (prevController) { |
| 725 | SG_LOG(SG_AI, SG_BULK, "Will be signing off from " << prevController->getName()); |
| 726 | } |
| 727 | controller = nullptr; |
| 728 | break; |
| 729 | } |
| 730 | |
| 731 | if ((controller != prevController) && prevController && !getDie()) { |
| 732 | //If we are dead we are automatically erased |
| 733 | prevController->signOff(getID()); |
| 734 | } |
| 735 | prevController = controller; |
| 736 | if (controller) { |
| 737 | controller->announcePosition(getID(), fp.get(), fp->getCurrentWaypoint()->getRouteIndex(), |
| 738 | _getLatitude(), _getLongitude(), hdg, speed, altitude_ft, |
| 739 | trafficRef->getRadius(), leg, this); |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | void FGAIAircraft::scheduleForATCTowerDepartureControl() |
| 744 | { |
| 745 | if (!takeOffStatus) { |
| 746 | int leg = fp->getLeg(); |
| 747 | if (trafficRef) { |
| 748 | if (trafficRef->getDepartureAirport()->getDynamics()) { |
| 749 | towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController(); |
| 750 | } else { |
| 751 | SG_LOG(SG_AI, SG_WARN, "Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId()); |
| 752 | } |
| 753 | if (towerController) { |
| 754 | towerController->announcePosition(getID(), fp.get(), fp->getCurrentWaypoint()->getRouteIndex(), |
| 755 | _getLatitude(), _getLongitude(), hdg, speed, altitude_ft, |
| 756 | trafficRef->getRadius(), leg, this); |
| 757 | } |
| 758 | } |
| 759 | } |
| 760 | takeOffStatus = AITakeOffStatus::QUEUED; |
| 761 | } |
| 762 | |
| 763 | // Process ATC instructions and report back |
| 764 | |
| 765 | void FGAIAircraft::processATC(const FGATCInstruction& instruction) |
| 766 | { |
| 767 | if (instruction.getCheckForCircularWait()) { |
| 768 | // This is not exactly an elegant solution, |
| 769 | // but at least it gives me a chance to check |
| 770 | // if circular waits are resolved. |
| 771 | // For now, just take the offending aircraft |
| 772 | // out of the scene |
| 773 | setDie(true); |
| 774 | // a more proper way should be - of course - to |
| 775 | // let an offending aircraft take an evasive action |
| 776 | // for instance taxi back a little bit. |
| 777 | } |
| 778 | |
| 779 | if (instruction.getHoldPattern()) { |
| 780 | //holdtime = instruction.getHoldTime(); |
| 781 | } |
| 782 | |
| 783 | // Hold Position |
| 784 | if (instruction.getHoldPosition()) { |
| 785 | holdPos = true; |
| 786 | AccelTo(0.0); |
| 787 | } else { |
| 788 | holdPos = false; |
| 789 | |
| 790 | // Change speed Instruction. This can only be executed when there is no |
| 791 | // Hold position instruction. |
| 792 | if (instruction.getChangeSpeed()) { |
| 793 | AccelTo(instruction.getSpeed()); |
| 794 | } else { |
| 795 | if (fp) |
| 796 | AccelTo(fp->getPreviousWaypoint()->getSpeed()); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | if (instruction.getChangeHeading()) { |
| 801 | hdg_lock = false; |
| 802 | TurnTo(instruction.getHeading()); |
| 803 | } else { |
| 804 | if (fp) { |
| 805 | hdg_lock = true; |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | if (instruction.getChangeAltitude()) {} |
| 810 | } |
| 811 | |
| 812 | void FGAIAircraft::handleFirstWaypoint() |
| 813 | { |
| 814 | headingError = 0; |
| 815 | bool eraseWaypoints = trafficRef ? true : false; |
| 816 | |
| 817 | FGAIWaypoint* prev = 0; // the one behind you |
| 818 | FGAIWaypoint* curr = 0; // the one ahead |
| 819 | FGAIWaypoint* next = 0; // the next plus 1 |
| 820 | |
| 821 | spinCounter = 0; |
| 822 | |
| 823 | // TODO: fp should handle this |
| 824 | fp->IncrementWaypoint(eraseWaypoints); |
| 825 | if (!(fp->getNextWaypoint()) && trafficRef) { |
| 826 | if (!loadNextLeg()) { |
| 827 | setDie(true); |
| 828 | return; |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | prev = fp->getPreviousWaypoint(); //first waypoint |
| 833 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Previous WP \t" << prev->getName()); |
| 834 | curr = fp->getCurrentWaypoint(); //second waypoint |
| 835 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Current WP \t" << curr->getName()); |
| 836 | next = fp->getNextWaypoint(); //third waypoint (might not exist!) |
| 837 | if (next) { |
| 838 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Next WP \t" << next->getName()); |
| 839 | } |
| 840 | |
| 841 | setLatitude(prev->getLatitude()); |
| 842 | setLongitude(prev->getLongitude()); |
| 843 | if (fp->getLeg() == 1) { |
| 844 | setSpeed(0); |
| 845 | } else { |
| 846 | setSpeed(prev->getSpeed()); |
| 847 | } |
| 848 | setAltitude(prev->getAltitude()); |
| 849 | |
| 850 | if (prev->getSpeed() > 0.0) |
| 851 | setHeading(fp->getBearing(prev, curr)); |
| 852 | else { |
| 853 | // FIXME When going to parking it must be the heading of the parking |
| 854 | setHeading(fp->getBearing(curr, prev)); |
| 855 | } |
| 856 | |
| 857 | // If next doesn't exist, as in incrementally created flightplans for |
| 858 | // AI/Trafficmanager created plans, |
| 859 | // Make sure lead distance is initialized otherwise |
| 860 | // If we are ending in a parking |
| 861 | if (next && !curr->contains("END") && !curr->contains("PushBackPointlegend")) { |
| 862 | fp->setLeadDistance(tgt_speed, hdg, curr, next); |
| 863 | } |
| 864 | |
| 865 | if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate |
| 866 | { |
| 867 | use_perf_vs = false; |
| 868 | double vert_dist_ft = curr->getCrossat() - altitude_ft; |
| 869 | double err_dist = prev->getCrossat() - altitude_ft; |
| 870 | double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 871 | tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist); |
| 872 | checkTcas(); |
| 873 | tgt_altitude_ft = curr->getCrossat(); |
| 874 | } else { |
| 875 | use_perf_vs = true; |
| 876 | tgt_altitude_ft = prev->getAltitude(); |
| 877 | } |
| 878 | alt_lock = hdg_lock = true; |
| 879 | no_roll = prev->getOn_ground(); |
| 880 | if (no_roll) { |
| 881 | Transform(); // make sure aip is initialized. |
| 882 | getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value |
| 883 | doGroundAltitude(); |
| 884 | _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet) |
| 885 | } |
| 886 | // Make sure to announce the aircraft's position |
| 887 | announcePositionToController(); |
| 888 | prevSpeed = 0; |
| 889 | } |
| 890 | |
| 891 | /** |
| 892 | * Check Execution time (currently once every 100 ms) |
| 893 | * Add a bit of randomization to prevent the execution of all flight plans |
| 894 | * in synchrony, which can add significant periodic framerate flutter. |
| 895 | * |
| 896 | * @param now |
| 897 | * @return |
| 898 | */ |
| 899 | bool FGAIAircraft::fpExecutable(time_t now) |
| 900 | { |
| 901 | double rand_exec_time = (rand() % 100) / 100; |
| 902 | return (dt_count > (0.1 + rand_exec_time)) && (fp->isActive(now)); |
| 903 | } |
| 904 | |
| 905 | |
| 906 | /** |
| 907 | * Check to see if we've reached the lead point for our next turn |
| 908 | * |
| 909 | * @param curr the WP we are currently targeting at. |
| 910 | * @param next the WP that will follow. Used to detect passed WPs (heading diff curr/next > 120°) |
| 911 | * @param nextTurnAngle to detect sharp corners |
| 912 | * @return |
| 913 | */ |
| 914 | bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr, FGAIWaypoint* next, int nextTurnAngle) |
| 915 | { |
| 916 | double dist_to_go_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 917 | // Leaddistance should be ft |
| 918 | double lead_distance_m = fp->getLeadDistance() * SG_FEET_TO_METER; |
| 919 | const double arrivalDist = fabs(10.0 * fp->getCurrentWaypoint()->getSpeed()); |
| 920 | // arrive at pushback end |
| 921 | if ((dist_to_go_m < arrivalDist) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) { |
| 922 | // tgt_speed = -(dist_to_go_m / 10.0); |
| 923 | tgt_speed = -std::sqrt((pow(arrivalDist, 2) - pow(arrivalDist - dist_to_go_m, 2))); |
| 924 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|tgt_speed " << tgt_speed); |
| 925 | if (tgt_speed > -1) { |
| 926 | // Speed is int and cannot go below 1 knot |
| 927 | tgt_speed = -1; |
| 928 | } |
| 929 | |
| 930 | if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) { |
| 931 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Set speed of WP from " << fp->getPreviousWaypoint()->getSpeed() << " to " << tgt_speed); |
| 932 | fp->getPreviousWaypoint()->setSpeed(tgt_speed); |
| 933 | } |
| 934 | } |
| 935 | // arrive at parking |
| 936 | if ((dist_to_go_m < arrivalDist) && (speed > 0) && (tgt_speed > 0) && fp->getCurrentWaypoint()->contains("END")) { |
| 937 | tgt_speed = (dist_to_go_m / 10.0); |
| 938 | if (tgt_speed < 1) { |
| 939 | // Speed is int and cannot go below 1 knot |
| 940 | tgt_speed = 1; |
| 941 | } |
| 942 | |
| 943 | if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) { |
| 944 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Set speed of WP from " << fp->getPreviousWaypoint()->getSpeed() << " to " << tgt_speed); |
| 945 | fp->getPreviousWaypoint()->setSpeed(tgt_speed); |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | if (lead_distance_m < fabs(2 * speed) * SG_FEET_TO_METER) { |
| 950 | //don't skip over the waypoint |
| 951 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Set lead_distance_m due to speed " << lead_distance_m << " to " << fabs(2 * speed) * SG_FEET_TO_METER); |
| 952 | lead_distance_m = fabs(2 * speed) * SG_FEET_TO_METER; |
| 953 | fp->setLeadDistance(lead_distance_m * SG_METER_TO_FEET); |
| 954 | } |
| 955 | |
| 956 | double bearing = 0; |
| 957 | // don't do bearing calculations for ground traffic |
| 958 | bearing = getBearing(fp->getBearing(pos, curr)); |
| 959 | double nextBearing = bearing; |
| 960 | if (next) { |
| 961 | nextBearing = getBearing(fp->getBearing(pos, next)); |
| 962 | } |
| 963 | if (onGround() && fabs(nextTurnAngle) > 50) { |
| 964 | //don't skip over the waypoint |
| 965 | const int multiplicator = 4; |
| 966 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Set lead_distance_m due to next turn angle " << lead_distance_m << " to " << fabs(multiplicator * speed) * SG_FEET_TO_METER << " dist_to_go_m " << dist_to_go_m << " Next turn angle : " << fabs(nextTurnAngle)); |
| 967 | lead_distance_m = fabs(multiplicator * speed) * SG_FEET_TO_METER; |
| 968 | fp->setLeadDistance(lead_distance_m * SG_METER_TO_FEET); |
| 969 | } |
| 970 | if (bearing < minBearing) { |
| 971 | minBearing = bearing; |
| 972 | if (minBearing < 10) { |
| 973 | minBearing = 10; |
| 974 | } |
| 975 | if ((minBearing < 360.0) && (minBearing > 10.0)) { |
| 976 | speedFraction = 0.5 + (cos(minBearing * SG_DEGREES_TO_RADIANS) * 0.5); |
| 977 | } else { |
| 978 | speedFraction = 1.0; |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | // We are traveling straight and have passed the waypoint. This would result in a loop. |
| 983 | if (next && abs(nextTurnAngle) < 5) { |
| 984 | double bearingTowardsCurrent = fp->getBearing(this->getGeodPos(), curr); |
| 985 | double headingDiffCurrent = SGMiscd::normalizePeriodic(-180, 180, hdg - bearingTowardsCurrent); |
| 986 | double bearingTowardsNext = fp->getBearing(this->getGeodPos(), next); |
| 987 | double headingDiffNext = SGMiscd::normalizePeriodic(-180, 180, hdg - bearingTowardsNext); |
| 988 | if (abs(headingDiffCurrent) > 80 && speed > 0) { |
| 989 | if (trafficRef != nullptr) { |
| 990 | if (fp->getLeg() <= AILeg::CLIMB) { |
| 991 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "| possible missed WP at " << trafficRef->getDepartureAirport()->getId() << " " << curr->getName()); |
| 992 | } else { |
| 993 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "| possible missed WP at " << trafficRef->getArrivalAirport()->getId() << " " << curr->getName()); |
| 994 | } |
| 995 | } else { |
| 996 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "| possible missed WP " << curr->getName()); |
| 997 | } |
| 998 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "| headingDiffCurrent " << headingDiffCurrent << " headingDiffNext " << headingDiffNext); |
| 999 | } |
| 1000 | } |
| 1001 | if ((dist_to_go_m < lead_distance_m) || |
| 1002 | ((dist_to_go_m > prev_dist_to_go) && (bearing > (minBearing * 1.1)))) { |
| 1003 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Leadpoint reached Bearing : " << bearing << "\tNext Bearing : " << nextBearing << " Next Turn Angle : " << fabs(nextTurnAngle)); |
| 1004 | minBearing = 360; |
| 1005 | speedFraction = 1.0; |
| 1006 | prev_dist_to_go = HUGE_VAL; |
| 1007 | return true; |
| 1008 | } else { |
| 1009 | if (prev_dist_to_go == dist_to_go_m && fabs(groundTargetSpeed) > 0 && this->atGate().empty()) { |
| 1010 | //FIXME must be suppressed when parked |
| 1011 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Aircraft stuck. Speed " << speed); |
| 1012 | stuckCounter++; |
| 1013 | if (stuckCounter > AI_STUCK_LIMIT) { |
| 1014 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "|Stuck flight killed on leg " << fp->getLeg()); |
| 1015 | setDie(true); |
| 1016 | } |
| 1017 | } else { |
| 1018 | stuckCounter = 0; |
| 1019 | } |
| 1020 | prev_dist_to_go = dist_to_go_m; |
| 1021 | return false; |
| 1022 | } |
| 1023 | } |
| 1024 | |
| 1025 | |
| 1026 | bool FGAIAircraft::aiTrafficVisible() |
| 1027 | { |
| 1028 | SGVec3d cartPos = SGVec3d::fromGeod(pos); |
| 1029 | const double d2 = (TRAFFIC_TO_AI_DIST_TO_DIE * SG_NM_TO_METER) * |
| 1030 | (TRAFFIC_TO_AI_DIST_TO_DIE * SG_NM_TO_METER); |
| 1031 | return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2); |
| 1032 | } |
| 1033 | |
| 1034 | |
| 1035 | /** |
| 1036 | * Handle release of parking gate, once were taxiing. Also ensure service time at the gate |
| 1037 | * in the case of an arrival. |
| 1038 | * |
| 1039 | * @param prev |
| 1040 | * @return |
| 1041 | */ |
| 1042 | |
| 1043 | // TODO: the trafficRef is the right place for the method |
| 1044 | bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) |
| 1045 | { |
| 1046 | using namespace std::string_literals; |
| 1047 | |
| 1048 | // prepare routing from one airport to another |
| 1049 | FGAirport* dep = trafficRef->getDepartureAirport(); |
| 1050 | FGAirport* arr = trafficRef->getArrivalAirport(); |
| 1051 | |
| 1052 | if (!(dep && arr)) |
| 1053 | return false; |
| 1054 | if (!prev) |
| 1055 | return false; |
| 1056 | |
| 1057 | // This waypoint marks the fact that the aircraft has passed the initial taxi |
| 1058 | // departure waypoint, so it can release the parking. |
| 1059 | if (prev->contains("PushBackPoint"s)) { |
| 1060 | // clearing the parking assignment will release the gate |
| 1061 | fp->setGate(ParkingAssignment()); |
| 1062 | AccelTo(0.0); |
| 1063 | } |
| 1064 | if (prev->contains("legend"s)) { |
| 1065 | int nextLeg = determineNextLeg(fp->getLeg()); |
| 1066 | while (nextLeg != fp->getLeg()) { |
| 1067 | fp->incrementLeg(); |
| 1068 | } |
| 1069 | } |
| 1070 | if (prev->contains("DepartureHold"s)) { |
| 1071 | //std::cerr << "Passing point DepartureHold" << std::endl; |
| 1072 | scheduleForATCTowerDepartureControl(); |
| 1073 | } |
| 1074 | if (prev->contains("Accel"s)) { |
| 1075 | takeOffStatus = AITakeOffStatus::CLEARED_FOR_TAKEOFF; |
| 1076 | } |
| 1077 | |
| 1078 | // This is the last taxi waypoint, and marks the the end of the flight plan |
| 1079 | // so, the schedule should update and wait for the next departure time. |
| 1080 | if (prev->contains("END"s)) { |
| 1081 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|Reached " << prev->getName()); |
| 1082 | |
| 1083 | //FIXME Heading Error should be reset |
| 1084 | time_t nextDeparture = trafficRef->getDepartureTime(); |
| 1085 | // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior |
| 1086 | if (nextDeparture < (now + 1200)) { |
| 1087 | nextDeparture = now + 1200; |
| 1088 | } |
| 1089 | fp->setTime(nextDeparture); |
| 1090 | } |
| 1091 | |
| 1092 | return true; |
| 1093 | } |
| 1094 | |
| 1095 | |
| 1096 | /** |
| 1097 | * Check difference between target bearing and current heading and correct if necessary. |
| 1098 | * |
| 1099 | * @param curr |
| 1100 | */ |
| 1101 | void FGAIAircraft::controlHeading(FGAIWaypoint* curr, FGAIWaypoint* next) |
| 1102 | { |
| 1103 | const double calc_bearing = speed < 0 ? SGMiscd::normalizePeriodic(0, 360, fp->getBearing(pos, curr) + 180.0) : fp->getBearing(pos, curr); |
| 1104 | |
| 1105 | // when moving forward we want to aim for an average heading |
| 1106 | if (next && speed > 0) { |
| 1107 | const double calcNextBearing = fp->getBearing(pos, next); |
| 1108 | if (fgIsFinite(calc_bearing) && fgIsFinite(calcNextBearing)) { |
| 1109 | double averageHeading = calc_bearing + (calcNextBearing - calc_bearing) / 2; |
| 1110 | averageHeading = SGMiscd::normalizePeriodic(0, 360, averageHeading); |
| 1111 | double hdg_error = averageHeading - tgt_heading; |
| 1112 | if (fabs(hdg_error) > 0.01) { |
| 1113 | TurnTo(averageHeading); |
| 1114 | } |
| 1115 | } else { |
| 1116 | SG_LOG(SG_AI, SG_WARN, "calc_bearing is not a finite number : " |
| 1117 | << "Speed " << speed << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg() << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude()); |
| 1118 | SG_LOG(SG_AI, SG_WARN, "waypoint name: '" << curr->getName() << "'"); |
| 1119 | ; |
| 1120 | } |
| 1121 | } else { |
| 1122 | if (fgIsFinite(calc_bearing)) { |
| 1123 | double hdg_error = calc_bearing - tgt_heading; |
| 1124 | if (fabs(hdg_error) > 0.01) { |
| 1125 | TurnTo(calc_bearing); |
| 1126 | } |
| 1127 | } else { |
| 1128 | SG_LOG(SG_AI, SG_WARN, "calc_bearing is not a finite number : " |
| 1129 | << "Speed " << speed << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg() << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude()); |
| 1130 | SG_LOG(SG_AI, SG_WARN, "waypoint name: '" << curr->getName() << "'"); |
| 1131 | ; |
| 1132 | } |
| 1133 | } |
| 1134 | } |
| 1135 | |
| 1136 | |
| 1137 | /** |
| 1138 | * Update the lead distance calculation if speed has changed sufficiently |
| 1139 | * to prevent spinning (hopefully); |
| 1140 | * |
| 1141 | * @param curr |
| 1142 | * @param next |
| 1143 | */ |
| 1144 | void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) |
| 1145 | { |
| 1146 | double speed_diff = speed - prevSpeed; |
| 1147 | |
| 1148 | if (fabs(speed_diff) > 10) { |
| 1149 | prevSpeed = speed; |
| 1150 | if (next) { |
| 1151 | if (!curr->contains("END") && !curr->contains("PushBackPointlegend")) { |
| 1152 | if (speed_diff > 0 && tgt_speed >= 5) { |
| 1153 | fp->setLeadDistance(speed, tgt_heading, curr, next); |
| 1154 | } else { |
| 1155 | fp->setLeadDistance(tgt_speed, tgt_heading, curr, next); |
| 1156 | } |
| 1157 | } |
| 1158 | } |
| 1159 | } |
| 1160 | } |
| 1161 | |
| 1162 | /** |
| 1163 | * Update target values (heading, alt, speed) depending on flight plan or control properties |
| 1164 | */ |
| 1165 | void FGAIAircraft::updatePrimaryTargetValues(double dt, bool& flightplanActive, bool& aiOutOfSight) |
| 1166 | { |
| 1167 | if (fp && fp->isValidPlan()) // AI object has a flightplan |
| 1168 | { |
| 1169 | // TODO: make this a function of AIBase |
| 1170 | time_t now = globals->get_time_params()->get_cur_time(); |
| 1171 | |
| 1172 | //std::cerr << "UpdateTArgetValues() " << std::endl; |
| 1173 | ProcessFlightPlan(dt, now); |
| 1174 | |
| 1175 | // Do execute Ground elev for inactive aircraft, so they |
| 1176 | // Are repositioned to the correct ground altitude when the user flies within visibility range. |
| 1177 | // In addition, check whether we are out of user range, so this aircraft |
| 1178 | // can be deleted. |
| 1179 | if (onGround()) { |
| 1180 | Transform(); // make sure aip is initialized. |
| 1181 | getGroundElev(dt); |
| 1182 | doGroundAltitude(); |
| 1183 | // Transform(); |
| 1184 | pos.setElevationFt(altitude_ft); |
| 1185 | } |
| 1186 | if (trafficRef) { |
| 1187 | aiOutOfSight = !aiTrafficVisible(); |
| 1188 | if (aiOutOfSight) { |
| 1189 | setDie(true); |
| 1190 | aiOutOfSight = true; |
| 1191 | return; |
| 1192 | } |
| 1193 | } |
| 1194 | timeElapsed = now - fp->getStartTime(); |
| 1195 | flightplanActive = fp->isActive(now); |
| 1196 | } else { |
| 1197 | // no flight plan, update target heading, speed, and altitude |
| 1198 | // from control properties. These default to the initial |
| 1199 | // settings in the config file, but can be changed "on the |
| 1200 | // fly". |
| 1201 | |
| 1202 | if (!_controlsLateralModeNode) { |
| 1203 | lazyInitControlsNodes(); |
| 1204 | } |
| 1205 | |
| 1206 | |
| 1207 | const std::string& lat_mode = _controlsLateralModeNode->getStringValue(); |
| 1208 | if (lat_mode == "roll") { |
| 1209 | const double angle = _controlsTargetRollNode->getDoubleValue(); |
| 1210 | RollTo(angle); |
| 1211 | } else { |
| 1212 | const double angle = _controlsTargetHeadingNode->getDoubleValue(); |
| 1213 | TurnTo(angle); |
| 1214 | } |
| 1215 | |
| 1216 | std::string vert_mode = _controlsVerticalModeNode->getStringValue(); |
| 1217 | if (vert_mode == "alt") { |
| 1218 | const double alt = _controlsTargetAltitude->getDoubleValue(); |
| 1219 | ClimbTo(alt); |
| 1220 | } else { |
| 1221 | const double angle = _controlsTargetPitch->getDoubleValue(); |
| 1222 | PitchTo(angle); |
| 1223 | } |
| 1224 | |
| 1225 | AccelTo(_controlsTargetSpeed->getDoubleValue()); |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | void FGAIAircraft::updateHeading(double dt) |
| 1230 | { |
| 1231 | // adjust heading based on current bank angle |
| 1232 | if (roll == 0.0) |
| 1233 | roll = 0.01; |
| 1234 | |
| 1235 | if (roll != 0.0) { |
| 1236 | // If on ground, calculate heading change directly |
| 1237 | if (onGround()) { |
| 1238 | const double headingDiff = SGMiscd::normalizePeriodic(-180, 180, hdg - tgt_heading); |
| 1239 | |
| 1240 | // When pushback behind us we still want to move but ... |
| 1241 | groundTargetSpeed = tgt_speed * cos(headingDiff * SG_DEGREES_TO_RADIANS); |
| 1242 | |
| 1243 | if (sign(groundTargetSpeed) != sign(tgt_speed) && fabs(tgt_speed) > 0) { |
| 1244 | if (fabs(speed) < 2 && fp->isActive(globals->get_time_params()->get_cur_time())) { |
| 1245 | // This seems to happen in case there is a change from forward to pushback. |
| 1246 | // which should never happen. |
| 1247 | SG_LOG(SG_AI, SG_BULK, "Oh dear " << _callsign << " might get stuck aka next point is behind us. Speed is " << speed); |
| 1248 | stuckCounter++; |
| 1249 | if (stuckCounter > AI_STUCK_LIMIT) { |
| 1250 | SG_LOG(SG_AI, SG_WARN, "Stuck flight " << _callsign << " killed on leg " << fp->getLeg() << " because point behind"); |
| 1251 | setDie(true); |
| 1252 | } |
| 1253 | } |
| 1254 | // Negative Cosinus means angle > 90° |
| 1255 | groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode |
| 1256 | } |
| 1257 | |
| 1258 | // Only update the target values when we're not moving because otherwise we might introduce an enormous target change rate while waiting a the gate, or holding. |
| 1259 | if (speed != 0) { |
| 1260 | if (fabs(headingDiff) > 30.0) { |
| 1261 | // invert if pushed backward |
| 1262 | if (sign(headingChangeRate) == sign(headingDiff)) { |
| 1263 | // left/right change |
| 1264 | headingChangeRate = 10.0 * dt * sign(headingDiff) * -1; |
| 1265 | } else { |
| 1266 | headingChangeRate -= 10.0 * dt * sign(headingDiff); |
| 1267 | } |
| 1268 | |
| 1269 | // Clamp the maximum steering rate to 30 degrees per second, |
| 1270 | // But only do this when the heading error is decreasing. |
| 1271 | // FIXME |
| 1272 | if ((headingDiff < headingError)) { |
| 1273 | if (headingChangeRate > 30) |
| 1274 | headingChangeRate = 30; |
| 1275 | else if (headingChangeRate < -30) |
| 1276 | headingChangeRate = -30; |
| 1277 | } |
| 1278 | } else { |
| 1279 | if (sign(headingChangeRate) == sign(headingDiff)) { |
| 1280 | // left/right change |
| 1281 | headingChangeRate = 3 * dt * sign(headingDiff) * -1; |
| 1282 | } else { |
| 1283 | headingChangeRate -= 3 * dt * sign(headingDiff); |
| 1284 | } |
| 1285 | /* |
| 1286 | if (headingChangeRate > headingDiff || |
| 1287 | headingChangeRate < headingDiff) { |
| 1288 | headingChangeRate = headingDiff*sign(roll); |
| 1289 | } |
| 1290 | else { |
| 1291 | headingChangeRate += dt * sign(roll); |
| 1292 | } |
| 1293 | */ |
| 1294 | } |
| 1295 | } |
| 1296 | |
| 1297 | hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15); |
| 1298 | |
| 1299 | headingError = headingDiff; |
| 1300 | // SG_LOG(SG_AI, SG_BULK, "Headingerror " << headingError ); |
| 1301 | if (fabs(headingError) < 1.0) { |
| 1302 | hdg = tgt_heading; |
| 1303 | } |
| 1304 | } else { |
| 1305 | if (fabs(speed) > 1.0) { |
| 1306 | turn_radius_ft = 0.088362 * speed * speed / tan(fabs(roll) / SG_RADIANS_TO_DEGREES); |
| 1307 | } else { |
| 1308 | // Check if turn_radius_ft == 0; this might lead to a division by 0. |
| 1309 | turn_radius_ft = 1.0; |
| 1310 | } |
| 1311 | double turn_circum_ft = SGD_2PI * turn_radius_ft; |
| 1312 | double dist_covered_ft = speed * 1.686 * dt; |
| 1313 | double alpha = dist_covered_ft / turn_circum_ft * 360.0; |
| 1314 | hdg += alpha * sign(roll); |
| 1315 | } |
| 1316 | while (hdg > 360.0) { |
| 1317 | hdg -= 360.0; |
| 1318 | spinCounter++; |
| 1319 | } |
| 1320 | while (hdg < 0.0) { |
| 1321 | hdg += 360.0; |
| 1322 | spinCounter--; |
| 1323 | } |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | |
| 1328 | void FGAIAircraft::updateBankAngleTarget() |
| 1329 | { |
| 1330 | // adjust target bank angle if heading lock engaged |
| 1331 | if (hdg_lock) { |
| 1332 | double bank_sense = 0.0; |
| 1333 | double diff = fabs(hdg - tgt_heading); |
| 1334 | if (diff > 180) |
| 1335 | diff = fabs(diff - 360); |
| 1336 | |
| 1337 | double sum = hdg + diff; |
| 1338 | if (sum > 360.0) |
| 1339 | sum -= 360.0; |
| 1340 | if (fabs(sum - tgt_heading) < 1.0) { |
| 1341 | bank_sense = 1.0; // right turn |
| 1342 | } else { |
| 1343 | bank_sense = -1.0; // left turn |
| 1344 | } |
| 1345 | if (diff < _performance->maximumBankAngle()) { |
| 1346 | tgt_roll = diff * bank_sense; |
| 1347 | } else { |
| 1348 | tgt_roll = _performance->maximumBankAngle() * bank_sense; |
| 1349 | } |
| 1350 | if ((fabs((double)spinCounter) > 1) && (diff > _performance->maximumBankAngle())) { |
| 1351 | tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around. |
| 1352 | // The only way to resolve this is to make them slow down. |
| 1353 | } |
| 1354 | } |
| 1355 | } |
| 1356 | |
| 1357 | void FGAIAircraft::updateVerticalSpeedTarget(double dt) |
| 1358 | { |
| 1359 | // adjust target Altitude, based on ground elevation when on ground |
| 1360 | if (onGround()) { |
| 1361 | getGroundElev(dt); |
| 1362 | doGroundAltitude(); |
| 1363 | } else if (alt_lock) { |
| 1364 | // find target vertical speed |
| 1365 | if (use_perf_vs) { |
| 1366 | if (altitude_ft < tgt_altitude_ft) { |
| 1367 | tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate()); |
| 1368 | } else { |
| 1369 | tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate()); |
| 1370 | } |
| 1371 | } else if (fp->getCurrentWaypoint()) { |
| 1372 | double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft; |
| 1373 | double err_dist = 0; |
| 1374 | double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint()); |
| 1375 | tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist); |
| 1376 | } else { |
| 1377 | // avoid crashes when fp has no current waypoint |
| 1378 | // eg see FLIGHTGEAR-68 on sentry; we crashed in getCrossat() |
| 1379 | tgt_vs = 0.0; |
| 1380 | } |
| 1381 | } |
| 1382 | |
| 1383 | checkTcas(); |
| 1384 | } |
| 1385 | |
| 1386 | void FGAIAircraft::updatePitchAngleTarget() |
| 1387 | { |
| 1388 | // if on ground and above vRotate -> initial rotation |
| 1389 | if (onGround() && (speed > _performance->vRotate())) |
| 1390 | tgt_pitch = 8.0; // some rough B737 value |
| 1391 | |
| 1392 | // TODO: pitch angle on approach and landing |
| 1393 | |
| 1394 | // match pitch angle to vertical speed |
| 1395 | else if (tgt_vs > 0) { |
| 1396 | tgt_pitch = tgt_vs * 0.005; |
| 1397 | } else { |
| 1398 | tgt_pitch = tgt_vs * 0.002; |
| 1399 | } |
| 1400 | } |
| 1401 | |
| 1402 | const std::string& FGAIAircraft::atGate() |
| 1403 | { |
| 1404 | if ((fp->getLeg() < 3) && trafficRef) { |
| 1405 | if (fp->getParkingGate()) { |
| 1406 | return fp->getParkingGate()->ident(); |
| 1407 | } |
| 1408 | } |
| 1409 | |
| 1410 | static const std::string empty{}; |
| 1411 | return empty; |
| 1412 | } |
| 1413 | |
| 1414 | int FGAIAircraft::determineNextLeg(int leg) |
| 1415 | { |
| 1416 | if (leg == AILeg::APPROACH) { |
| 1417 | time_t now = globals->get_time_params()->get_cur_time(); |
| 1418 | if (controller == nullptr || controller->getInstruction(getID()).getRunwaySlot() > now) { |
| 1419 | return AILeg::HOLD; |
| 1420 | } else { |
| 1421 | return AILeg::LANDING; |
| 1422 | } |
| 1423 | } else { |
| 1424 | return leg + 1; |
| 1425 | } |
| 1426 | } |
| 1427 | |
| 1428 | void FGAIAircraft::handleATCRequests(double dt) |
| 1429 | { |
| 1430 | if (!this->getTrafficRef()) { |
| 1431 | return; |
| 1432 | } |
| 1433 | |
| 1434 | // TODO: implement NullController for having no ATC to save the conditionals |
| 1435 | if (controller) { |
| 1436 | controller->updateAircraftInformation(getID(), |
| 1437 | pos, |
| 1438 | hdg, |
| 1439 | speed, |
| 1440 | altitude_ft, |
| 1441 | dt); |
| 1442 | processATC(controller->getInstruction(getID())); |
| 1443 | } |
| 1444 | if (towerController) { |
| 1445 | towerController->updateAircraftInformation(getID(), |
| 1446 | pos, |
| 1447 | hdg, |
| 1448 | speed, |
| 1449 | altitude_ft, |
| 1450 | dt); |
| 1451 | } |
| 1452 | } |
| 1453 | |
| 1454 | void FGAIAircraft::updateUserFlightPlan(double dt) |
| 1455 | { |
| 1456 | // If the aircraft leaves the airport proximity increase the flightplan leg to sign off |
| 1457 | // from the tower controller and free the runway #2358 The user doesn't |
| 1458 | // need to fly out straight |
| 1459 | if (fp) { |
| 1460 | switch (fp->getLeg()) { |
| 1461 | case AILeg::TAKEOFF: { |
| 1462 | auto current = fp->getCurrentWaypoint(); |
| 1463 | auto last = fp->getLastWaypoint(); |
| 1464 | int legDistance = SGGeodesy::distanceM(current->getPos(), last->getPos()); |
| 1465 | int currDist = SGGeodesy::distanceM(getGeodPos(), current->getPos()); |
| 1466 | int lastDist = SGGeodesy::distanceM(getGeodPos(), last->getPos()); |
| 1467 | SG_LOG(SG_ATC, SG_BULK, "Signing off from Tower " |
| 1468 | << "\t currDist\t" << currDist << "\t legDistance\t" << legDistance << "\t" << lastDist << "\t" << getGeodPos().getLatitudeDeg() << "\t" << getGeodPos().getLongitudeDeg() << "\t" << current->getPos().getLatitudeDeg() << "\t" << current->getPos().getLongitudeDeg()); |
| 1469 | if (currDist > legDistance) { |
| 1470 | // We are definitely beyond the airport |
| 1471 | fp->incrementLeg(); |
| 1472 | } |
| 1473 | } break; |
| 1474 | default: |
| 1475 | break; |
| 1476 | } |
| 1477 | // TODO: |
| 1478 | } |
| 1479 | } |
| 1480 | |
| 1481 | void FGAIAircraft::updateActualState(double dt) |
| 1482 | { |
| 1483 | //update current state |
| 1484 | // TODO: have a single tgt_speed and check speed limit on ground on setting tgt_speed |
| 1485 | double distance = speed * SG_KT_TO_MPS * dt; |
| 1486 | pos = SGGeodesy::direct(pos, hdg, distance); |
| 1487 | |
| 1488 | if (onGround()) |
| 1489 | speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos); |
| 1490 | else |
| 1491 | speed = _performance->actualSpeed(this, (tgt_speed * speedFraction), dt, false); |
| 1492 | |
| 1493 | updateHeading(dt); |
| 1494 | roll = _performance->actualBankAngle(this, tgt_roll, dt); |
| 1495 | |
| 1496 | // adjust altitude (meters) based on current vertical speed (fpm) |
| 1497 | altitude_ft += vs_fps * dt; |
| 1498 | pos.setElevationFt(altitude_ft); |
| 1499 | |
| 1500 | vs_fps = _performance->actualVerticalSpeed(this, tgt_vs, dt) / 60; |
| 1501 | pitch = _performance->actualPitch(this, tgt_pitch, dt); |
| 1502 | } |
| 1503 | |
| 1504 | void FGAIAircraft::updateSecondaryTargetValues(double dt) |
| 1505 | { |
| 1506 | // derived target state values |
| 1507 | updateBankAngleTarget(); |
| 1508 | updateVerticalSpeedTarget(dt); |
| 1509 | updatePitchAngleTarget(); |
| 1510 | // TODO: calculate wind correction angle (tgt_yaw) |
| 1511 | } |
| 1512 | |
| 1513 | |
| 1514 | bool FGAIAircraft::reachedEndOfCruise(double& distance) |
| 1515 | { |
| 1516 | FGAIWaypoint* curr = fp->getCurrentWaypoint(); |
| 1517 | if (!curr) { |
| 1518 | SG_LOG(SG_AI, SG_WARN, "FGAIAircraft::reachedEndOfCruise: no current waypoint"); |
| 1519 | |
| 1520 | // return true (=done) here, so we don't just get stuck on this forever |
| 1521 | return true; |
| 1522 | } |
| 1523 | |
| 1524 | if (curr->getName() == std::string("BOD")) { |
| 1525 | // Sentry: FLIGHTGEAR-893 |
| 1526 | if (!trafficRef->getArrivalAirport()) { |
| 1527 | SG_LOG(SG_AI, SG_WARN, trafficRef->getCallSign() << "FGAIAircraft::reachedEndOfCruise: no arrival airport"); |
| 1528 | setDie(true); |
| 1529 | // return 'done' here, we are broken |
| 1530 | return true; |
| 1531 | } |
| 1532 | |
| 1533 | double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 1534 | double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s |
| 1535 | double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s |
| 1536 | |
| 1537 | double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) * SG_FEET_TO_METER; |
| 1538 | double descentTimeNeeded = verticalDistance / descentRate; |
| 1539 | double distanceCoveredByDescent = descentSpeed * descentTimeNeeded; |
| 1540 | |
| 1541 | if (tracked) { |
| 1542 | SG_LOG(SG_AI, SG_BULK, "Checking for end of cruise stage for :" << trafficRef->getCallSign()); |
| 1543 | SG_LOG(SG_AI, SG_BULK, "Descent rate : " << descentRate); |
| 1544 | SG_LOG(SG_AI, SG_BULK, "Descent speed : " << descentSpeed); |
| 1545 | SG_LOG(SG_AI, SG_BULK, "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation()); |
| 1546 | SG_LOG(SG_AI, SG_BULK, "DecentTimeNeeded : " << descentTimeNeeded); |
| 1547 | SG_LOG(SG_AI, SG_BULK, "DistanceCovered : " << distanceCoveredByDescent); |
| 1548 | } |
| 1549 | |
| 1550 | distance = distanceCoveredByDescent; |
| 1551 | if (dist < distanceCoveredByDescent) { |
| 1552 | SG_LOG(SG_AI, SG_BULK, getCallSign() << "|End Of Cruise"); |
| 1553 | return true; |
| 1554 | } else { |
| 1555 | return false; |
| 1556 | } |
| 1557 | } else { |
| 1558 | return false; |
| 1559 | } |
| 1560 | } |
| 1561 | |
| 1562 | void FGAIAircraft::resetPositionFromFlightPlan() |
| 1563 | { |
| 1564 | if (fp->empty()) { |
| 1565 | return; |
| 1566 | } |
| 1567 | // the one behind you |
| 1568 | FGAIWaypoint* prev = nullptr; |
| 1569 | // the one ahead |
| 1570 | FGAIWaypoint* curr = nullptr; |
| 1571 | // the next plus 1 |
| 1572 | FGAIWaypoint* next = nullptr; |
| 1573 | |
| 1574 | prev = fp->getPreviousWaypoint(); |
| 1575 | curr = fp->getCurrentWaypoint(); |
| 1576 | next = fp->getNextWaypoint(); |
| 1577 | |
| 1578 | if (curr == nullptr || next == nullptr) { |
| 1579 | SG_LOG(SG_AI, SG_WARN, getCallSign() << "|Repositioned without curr/next"); |
| 1580 | return; |
| 1581 | } |
| 1582 | |
| 1583 | setLatitude(prev->getLatitude()); |
| 1584 | setLongitude(prev->getLongitude()); |
| 1585 | setHeading(fp->getBearing(curr, next)); |
| 1586 | setAltitude(prev->getAltitude()); |
| 1587 | setSpeed(prev->getSpeed()); |
| 1588 | } |
| 1589 | |
| 1590 | /** |
| 1591 | * Returns a normalised bearing |
| 1592 | */ |
| 1593 | |
| 1594 | double FGAIAircraft::getBearing(double crse) |
| 1595 | { |
| 1596 | double hdgDiff = fabs(hdg - crse); |
| 1597 | if (hdgDiff > 180) |
| 1598 | hdgDiff = fabs(hdgDiff - 360); |
| 1599 | return hdgDiff; |
| 1600 | } |
| 1601 | |
| 1602 | time_t FGAIAircraft::checkForArrivalTime(const std::string& wptName) |
| 1603 | { |
| 1604 | FGAIWaypoint* curr = 0; |
| 1605 | curr = fp->getCurrentWaypoint(); |
| 1606 | |
| 1607 | // don't recalculate tracklength unless the start/stop waypoint has changed |
| 1608 | if (curr && |
| 1609 | ((curr->getName() != trackCache.startWptName) || |
| 1610 | (wptName != trackCache.finalWptName))) { |
| 1611 | trackCache.remainingLength = fp->checkTrackLength(wptName); |
| 1612 | trackCache.startWptName = curr->getName(); |
| 1613 | trackCache.finalWptName = wptName; |
| 1614 | } |
| 1615 | double tracklength = trackCache.remainingLength; |
| 1616 | if (tracklength > 0.1) { |
| 1617 | tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr); |
| 1618 | } else { |
| 1619 | return 0; |
| 1620 | } |
| 1621 | time_t now = globals->get_time_params()->get_cur_time(); |
| 1622 | time_t arrivalTime = fp->getArrivalTime(); |
| 1623 | |
| 1624 | time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0); |
| 1625 | time_t secondsToGo = arrivalTime - now; |
| 1626 | if (tracked) { |
| 1627 | SG_LOG(SG_AI, SG_BULK, "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength); |
| 1628 | } |
| 1629 | return (ete - secondsToGo); // Positive when we're too slow... |
| 1630 | } |
| 1631 | |
| 1632 | time_t FGAIAircraft::calcDeparture() |
| 1633 | { |
| 1634 | time_t departure = this->checkForArrivalTime("DepartureHold"); |
| 1635 | if (!departure) { |
| 1636 | departure = globals->get_time_params()->get_cur_time(); |
| 1637 | } |
| 1638 | return departure; |
| 1639 | } |
| 1640 | |
| 1641 | double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt) |
| 1642 | { |
| 1643 | double delta = target - cur; |
| 1644 | double maxDelta = maxDeltaSec * dt; |
| 1645 | |
| 1646 | // if delta is > maxDelta, use maxDelta, but with the sign of delta. |
| 1647 | return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta); |
| 1648 | } |
| 1649 | |
| 1650 | // Drive various properties in a semi-realistic fashion. |
| 1651 | // Note that we assume that the properties are set at |
| 1652 | // a waypoint rather than in the leg before. So we need |
| 1653 | // to use the previous waypoint (i.e. the one just passed) |
| 1654 | // rather than the current one (i.e. the next one on the route) |
| 1655 | void FGAIAircraft::updateModelProperties(double dt) |
| 1656 | { |
| 1657 | if ((!fp) || (!fp->getPreviousWaypoint())) { |
| 1658 | return; |
| 1659 | } |
| 1660 | |
| 1661 | double targetGearPos = fp->getPreviousWaypoint()->getGear_down() ? 1.0 : 0.0; |
| 1662 | double gearPos = GearPos(); |
| 1663 | |
| 1664 | if (gearPos != targetGearPos) { |
| 1665 | gearPos = gearPos + limitRateOfChange(gearPos, targetGearPos, 0.1, dt); |
| 1666 | if (gearPos < 0.001) { |
| 1667 | gearPos = 0.0; |
| 1668 | } else if (gearPos > 0.999) { |
| 1669 | gearPos = 1.0; |
| 1670 | } |
| 1671 | GearPos(gearPos); |
| 1672 | } |
| 1673 | |
| 1674 | double targetFlapsPos = fp->getPreviousWaypoint()->getFlaps(); |
| 1675 | double flapsPos = FlapsPos(); |
| 1676 | |
| 1677 | if (flapsPos != targetFlapsPos) { |
| 1678 | flapsPos = flapsPos + limitRateOfChange(flapsPos, targetFlapsPos, 0.05, dt); |
| 1679 | if (flapsPos < 0.001) { |
| 1680 | flapsPos = 0.0; |
| 1681 | } else if (flapsPos > 0.999) { |
| 1682 | flapsPos = 1.0; |
| 1683 | } |
| 1684 | FlapsPos(flapsPos); |
| 1685 | } |
| 1686 | |
| 1687 | SpeedBrakePos(fp->getPreviousWaypoint()->getSpeedBrakes()); |
| 1688 | SpoilerPos(fp->getPreviousWaypoint()->getSpoilers()); |
| 1689 | CabinLight(fp->getPreviousWaypoint()->getCabinLight()); |
| 1690 | BeaconLight(fp->getPreviousWaypoint()->getBeaconLight()); |
| 1691 | LandingLight(fp->getPreviousWaypoint()->getLandingLight()); |
| 1692 | NavLight(fp->getPreviousWaypoint()->getNavLight()); |
| 1693 | StrobeLight(fp->getPreviousWaypoint()->getStrobeLight()); |
| 1694 | TaxiLight(fp->getPreviousWaypoint()->getTaxiLight()); |
| 1695 | } |
| 1696 | |
| 1697 | void FGAIAircraft::dumpCSVHeader(const std::unique_ptr<sg_ofstream>& o) |
| 1698 | { |
| 1699 | (*o) << "Index\t"; |
| 1700 | (*o) << "Lat\t"; |
| 1701 | (*o) << "Lon\t"; |
| 1702 | (*o) << "Alt\t"; |
| 1703 | (*o) << "Callsign\t"; |
| 1704 | (*o) << "headingDiff\t"; |
| 1705 | (*o) << "headingChangeRate\t"; |
| 1706 | (*o) << "headingError\t"; |
| 1707 | (*o) << "hdg\t"; |
| 1708 | (*o) << "tgt_heading\t"; |
| 1709 | (*o) << "tgt_speed\t"; |
| 1710 | (*o) << "minBearing\t"; |
| 1711 | (*o) << "speedFraction\t"; |
| 1712 | (*o) << "groundOffset\t"; |
| 1713 | (*o) << "speed\t"; |
| 1714 | (*o) << "groundTargetSpeed\t"; |
| 1715 | (*o) << "getVerticalSpeedFPM\t"; |
| 1716 | (*o) << "getTrueHeadingDeg\t"; |
| 1717 | (*o) << "bearingToWP\t"; |
| 1718 | |
| 1719 | (*o) << "Name\t"; |
| 1720 | (*o) << "WP Lat\t"; |
| 1721 | (*o) << "WP Lon\t"; |
| 1722 | (*o) << "Dist\t"; |
| 1723 | (*o) << "Next Lat\t"; |
| 1724 | (*o) << "Next Lon\t"; |
| 1725 | (*o) << "Departuretime\t"; |
| 1726 | (*o) << "Time\t"; |
| 1727 | (*o) << "Startup diff\t"; |
| 1728 | (*o) << "Departure\t"; |
| 1729 | (*o) << "Arrival\t"; |
| 1730 | (*o) << "dist_to_go_m\t"; |
| 1731 | (*o) << "leadInAngle\t"; |
| 1732 | (*o) << "Leaddistance\t"; |
| 1733 | (*o) << "Leg\t"; |
| 1734 | (*o) << "Num WP\t"; |
| 1735 | (*o) << "no_roll\t"; |
| 1736 | (*o) << "roll\t"; |
| 1737 | (*o) << "repositioned\t"; |
| 1738 | (*o) << "stuckCounter\t"; |
| 1739 | (*o) << std::endl; |
| 1740 | } |
| 1741 | |
| 1742 | void FGAIAircraft::dumpCSV(const std::unique_ptr<sg_ofstream>& o, int lineIndex) |
| 1743 | { |
| 1744 | const double headingDiff = SGMiscd::normalizePeriodic(-180, 180, hdg - tgt_heading); |
| 1745 | |
| 1746 | (*o) << lineIndex << "\t"; |
| 1747 | (*o) << std::setprecision(12); |
| 1748 | (*o) << this->getGeodPos().getLatitudeDeg() << "\t"; |
| 1749 | (*o) << this->getGeodPos().getLongitudeDeg() << "\t"; |
| 1750 | (*o) << this->getGeodPos().getElevationFt() << "\t"; |
| 1751 | (*o) << this->getCallSign() << "\t"; |
| 1752 | (*o) << headingDiff << "\t"; |
| 1753 | (*o) << headingChangeRate << "\t"; |
| 1754 | (*o) << headingError << "\t"; |
| 1755 | (*o) << hdg << "\t"; |
| 1756 | (*o) << tgt_heading << "\t"; |
| 1757 | (*o) << tgt_speed << "\t"; |
| 1758 | (*o) << minBearing << "\t"; |
| 1759 | (*o) << speedFraction << "\t"; |
| 1760 | (*o) << groundOffset << "\t"; |
| 1761 | |
| 1762 | (*o) << round(this->getSpeed()) << "\t"; |
| 1763 | (*o) << groundTargetSpeed << "\t"; |
| 1764 | (*o) << round(this->getVerticalSpeedFPM()) << "\t"; |
| 1765 | (*o) << this->getTrueHeadingDeg() << "\t"; |
| 1766 | FGAIFlightPlan* fp = this->GetFlightPlan(); |
| 1767 | if (fp) { |
| 1768 | FGAIWaypoint* currentWP = fp->getCurrentWaypoint(); |
| 1769 | FGAIWaypoint* nextWP = fp->getNextWaypoint(); |
| 1770 | if (currentWP) { |
| 1771 | (*o) << fp->getBearing(this->getGeodPos(), currentWP) << "\t"; |
| 1772 | (*o) << currentWP->getName() << "\t"; |
| 1773 | (*o) << currentWP->getPos().getLatitudeDeg() << "\t"; |
| 1774 | (*o) << currentWP->getPos().getLongitudeDeg() << "\t"; |
| 1775 | } |
| 1776 | if (nextWP) { |
| 1777 | (*o) << nextWP->getPos().getLatitudeDeg() << "\t"; |
| 1778 | (*o) << nextWP->getPos().getLongitudeDeg() << "\t"; |
| 1779 | } else { |
| 1780 | (*o) << "\t\t"; |
| 1781 | } |
| 1782 | if (currentWP) { |
| 1783 | (*o) << SGGeodesy::distanceM(this->getGeodPos(), currentWP->getPos()) << "\t"; |
| 1784 | (*o) << fp->getStartTime() << "\t"; |
| 1785 | (*o) << globals->get_time_params()->get_cur_time() << "\t"; |
| 1786 | (*o) << fp->getStartTime() - globals->get_time_params()->get_cur_time() << "\t"; |
| 1787 | (*o) << (fp->departureAirport().get() ? fp->departureAirport().get()->getId() : "") << "\t"; |
| 1788 | (*o) << (fp->arrivalAirport().get() ? fp->arrivalAirport().get()->getId() : "") << "\t"; |
| 1789 | if (nextWP) { |
| 1790 | double dist_to_go_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), currentWP); |
| 1791 | (*o) << dist_to_go_m << "\t"; |
| 1792 | double inbound = bearing; |
| 1793 | double outbound = fp->getBearing(currentWP, nextWP); |
| 1794 | double leadInAngle = fabs(inbound - outbound); |
| 1795 | if (leadInAngle > 180.0) leadInAngle = 360.0 - leadInAngle; |
| 1796 | (*o) << leadInAngle << "\t"; |
| 1797 | } |
| 1798 | } else { |
| 1799 | (*o) << "No WP\t\t\t\t\t\t\t\t"; |
| 1800 | } |
| 1801 | if (fp->isValidPlan()) { |
| 1802 | (*o) << fp->getLeadDistance() * SG_FEET_TO_METER << "\t"; |
| 1803 | (*o) << fp->getLeg() << "\t"; |
| 1804 | (*o) << fp->getNrOfWayPoints() << "\t"; |
| 1805 | } else { |
| 1806 | (*o) << "FP NotValid\t\t"; |
| 1807 | } |
| 1808 | } |
| 1809 | (*o) << this->onGround() << "\t"; |
| 1810 | (*o) << roll << "\t"; |
| 1811 | (*o) << repositioned << "\t"; |
| 1812 | (*o) << stuckCounter << "\t"; |
| 1813 | (*o) << std::endl; |
| 1814 | } |
| 1815 | |
| 1816 | #if 0 |
| 1817 | std::string FGAIAircraft::getTimeString(int timeOffset) |
| 1818 | { |
| 1819 | char ret[11]; |
| 1820 | time_t rawtime; |
| 1821 | time (&rawtime); |
| 1822 | rawtime = rawtime + timeOffset; |
| 1823 | tm* timeinfo = gmtime(&rawtime); |
| 1824 | strftime(ret, 11, "%w/%H:%M:%S", timeinfo); |
| 1825 | return ret; |
| 1826 | } |
| 1827 | #endif |