TransectStyleComplexItem.cc 34.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "TransectStyleComplexItem.h"
#include "JsonHelper.h"
#include "MissionController.h"
#include "QGCGeo.h"
#include "QGroundControlQmlGlobal.h"
#include "QGCQGeoCoordinate.h"
#include "SettingsManager.h"
#include "AppSettings.h"
#include "QGCQGeoCoordinate.h"
19
#include <valgrind/callgrind.h>
20 21 22 23 24 25 26 27 28 29

#include <QPolygonF>

QGC_LOGGING_CATEGORY(TransectStyleComplexItemLog, "TransectStyleComplexItemLog")

const char* TransectStyleComplexItem::turnAroundDistanceName =              "TurnAroundDistance";
const char* TransectStyleComplexItem::turnAroundDistanceMultiRotorName =    "TurnAroundDistanceMultiRotor";
const char* TransectStyleComplexItem::cameraTriggerInTurnAroundName =       "CameraTriggerInTurnAround";
const char* TransectStyleComplexItem::hoverAndCaptureName =                 "HoverAndCapture";
const char* TransectStyleComplexItem::refly90DegreesName =                  "Refly90Degrees";
30 31 32
const char* TransectStyleComplexItem::terrainAdjustToleranceName =          "TerrainAdjustTolerance";
const char* TransectStyleComplexItem::terrainAdjustMaxClimbRateName =       "TerrainAdjustMaxClimbRate";
const char* TransectStyleComplexItem::terrainAdjustMaxDescentRateName =     "TerrainAdjustMaxDescentRate";
33

34 35
const char* TransectStyleComplexItem::_jsonTransectStyleComplexItemKey =    "TransectStyleComplexItem";
const char* TransectStyleComplexItem::_jsonCameraCalcKey =                  "CameraCalc";
DonLakeFlyer's avatar
DonLakeFlyer committed
36
const char* TransectStyleComplexItem::_jsonVisualTransectPointsKey =        "VisualTransectPoints";
37
const char* TransectStyleComplexItem::_jsonItemsKey =                       "Items";
38
const char* TransectStyleComplexItem::_jsonFollowTerrainKey =               "FollowTerrain";
39
const char* TransectStyleComplexItem::_jsonCameraShotsKey =                 "CameraShots";
40

41
const int   TransectStyleComplexItem::_terrainQueryTimeoutMsecs =           1000;
42

43 44
TransectStyleComplexItem::TransectStyleComplexItem(Vehicle* vehicle, bool flyView, QString settingsGroup, QObject* parent)
    : ComplexMissionItem                (vehicle, flyView, parent)
45
    , _sequenceNumber                   (0)
46
    , _terrainPolyPathQuery             (nullptr)
47 48 49
    , _ignoreRecalc                     (false)
    , _complexDistance                  (0)
    , _cameraShots                      (0)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
50
    , _cruiseSpeed                      (0)
51
    , _cameraCalc                       (vehicle, settingsGroup)
52
    , _followTerrain                    (false)
53
    , _loadedMissionItemsParent         (nullptr)
54
    , _metaDataMap                      (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/TransectStyle.SettingsGroup.json"), this))
55 56 57 58 59 60 61
    , _turnAroundDistanceFact           (settingsGroup, _metaDataMap[_vehicle->multiRotor() ? turnAroundDistanceMultiRotorName : turnAroundDistanceName])
    , _cameraTriggerInTurnAroundFact    (settingsGroup, _metaDataMap[cameraTriggerInTurnAroundName])
    , _hoverAndCaptureFact              (settingsGroup, _metaDataMap[hoverAndCaptureName])
    , _refly90DegreesFact               (settingsGroup, _metaDataMap[refly90DegreesName])
    , _terrainAdjustToleranceFact       (settingsGroup, _metaDataMap[terrainAdjustToleranceName])
    , _terrainAdjustMaxClimbRateFact    (settingsGroup, _metaDataMap[terrainAdjustMaxClimbRateName])
    , _terrainAdjustMaxDescentRateFact  (settingsGroup, _metaDataMap[terrainAdjustMaxDescentRateName])
62
{
63 64 65 66
    _terrainQueryTimer.setInterval(_terrainQueryTimeoutMsecs);
    _terrainQueryTimer.setSingleShot(true);
    connect(&_terrainQueryTimer, &QTimer::timeout, this, &TransectStyleComplexItem::_reallyQueryTransectsPathHeightInfo);

67 68 69
    connect(&_turnAroundDistanceFact,                   &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
    connect(&_hoverAndCaptureFact,                      &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
    connect(&_refly90DegreesFact,                       &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
70 71 72 73
    connect(this,                      &TransectStyleComplexItem::followTerrainChanged, this, &TransectStyleComplexItem::_rebuildTransects);
    connect(&_terrainAdjustMaxClimbRateFact,            &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
    connect(&_terrainAdjustMaxDescentRateFact,          &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
    connect(&_terrainAdjustToleranceFact,               &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
74 75 76 77
    connect(&_surveyAreaPolygon,                        &QGCMapPolygon::pathChanged,    this, &TransectStyleComplexItem::_rebuildTransects);
    connect(&_cameraTriggerInTurnAroundFact,            &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
    connect(_cameraCalc.adjustedFootprintSide(),        &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
    connect(_cameraCalc.adjustedFootprintFrontal(),     &Fact::valueChanged,            this, &TransectStyleComplexItem::_rebuildTransects);
78

79 80 81 82
    connect(&_turnAroundDistanceFact,                   &Fact::valueChanged,            this, &TransectStyleComplexItem::complexDistanceChanged);
    connect(&_hoverAndCaptureFact,                      &Fact::valueChanged,            this, &TransectStyleComplexItem::complexDistanceChanged);
    connect(&_refly90DegreesFact,                       &Fact::valueChanged,            this, &TransectStyleComplexItem::complexDistanceChanged);
    connect(&_surveyAreaPolygon,                        &QGCMapPolygon::pathChanged,    this, &TransectStyleComplexItem::complexDistanceChanged);
83

84 85 86 87
    connect(&_turnAroundDistanceFact,                   &Fact::valueChanged,            this, &TransectStyleComplexItem::greatestDistanceToChanged);
    connect(&_hoverAndCaptureFact,                      &Fact::valueChanged,            this, &TransectStyleComplexItem::greatestDistanceToChanged);
    connect(&_refly90DegreesFact,                       &Fact::valueChanged,            this, &TransectStyleComplexItem::greatestDistanceToChanged);
    connect(&_surveyAreaPolygon,                        &QGCMapPolygon::pathChanged,    this, &TransectStyleComplexItem::greatestDistanceToChanged);
88

89 90 91 92
    connect(&_turnAroundDistanceFact,                   &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
    connect(&_cameraTriggerInTurnAroundFact,            &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
    connect(&_hoverAndCaptureFact,                      &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
    connect(&_refly90DegreesFact,                       &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
93 94 95 96
    connect(this,                      &TransectStyleComplexItem::followTerrainChanged, this, &TransectStyleComplexItem::_setDirty);
    connect(&_terrainAdjustMaxClimbRateFact,            &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
    connect(&_terrainAdjustMaxDescentRateFact,          &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
    connect(&_terrainAdjustToleranceFact,               &Fact::valueChanged,            this, &TransectStyleComplexItem::_setDirty);
97 98 99 100 101 102 103
    connect(&_surveyAreaPolygon,                        &QGCMapPolygon::pathChanged,    this, &TransectStyleComplexItem::_setDirty);

    connect(&_surveyAreaPolygon,                        &QGCMapPolygon::dirtyChanged,   this, &TransectStyleComplexItem::_setIfDirty);
    connect(&_cameraCalc,                               &CameraCalc::dirtyChanged,      this, &TransectStyleComplexItem::_setIfDirty);

    connect(&_surveyAreaPolygon,                        &QGCMapPolygon::pathChanged,    this, &TransectStyleComplexItem::coveredAreaChanged);

104 105 106 107 108 109 110
    connect(&_cameraCalc,                               &CameraCalc::distanceToSurfaceRelativeChanged, this, &TransectStyleComplexItem::coordinateHasRelativeAltitudeChanged);
    connect(&_cameraCalc,                               &CameraCalc::distanceToSurfaceRelativeChanged, this, &TransectStyleComplexItem::exitCoordinateHasRelativeAltitudeChanged);

    connect(this,                                       &TransectStyleComplexItem::visualTransectPointsChanged, this, &TransectStyleComplexItem::complexDistanceChanged);
    connect(this,                                       &TransectStyleComplexItem::visualTransectPointsChanged, this, &TransectStyleComplexItem::greatestDistanceToChanged);

    connect(this,                                       &TransectStyleComplexItem::followTerrainChanged, this, &TransectStyleComplexItem::_followTerrainChanged);
111

112 113 114 115
    connect(_cameraCalc.distanceToSurface(), &Fact::rawValueChanged, this, &TransectStyleComplexItem::_updateTransectAltitude);
    connect(_cameraCalc.distanceToSurface(), &Fact::rawValueChanged, this, &TransectStyleComplexItem::_clearLoadedMissionItems);


116
    setDirty(false);
117 118 119 120 121 122 123 124 125 126 127 128
}

void TransectStyleComplexItem::_setCameraShots(int cameraShots)
{
    if (_cameraShots != cameraShots) {
        _cameraShots = cameraShots;
        emit cameraShotsChanged();
    }
}

void TransectStyleComplexItem::setDirty(bool dirty)
{
129 130 131 132
    if (!dirty) {
        _surveyAreaPolygon.setDirty(false);
        _cameraCalc.setDirty(false);
    }
133 134 135 136 137 138 139 140
    if (_dirty != dirty) {
        _dirty = dirty;
        emit dirtyChanged(_dirty);
    }
}

void TransectStyleComplexItem::_save(QJsonObject& complexObject)
{
141 142 143 144 145 146 147
    QJsonObject innerObject;

    innerObject[JsonHelper::jsonVersionKey] =       1;
    innerObject[turnAroundDistanceName] =           _turnAroundDistanceFact.rawValue().toDouble();
    innerObject[cameraTriggerInTurnAroundName] =    _cameraTriggerInTurnAroundFact.rawValue().toBool();
    innerObject[hoverAndCaptureName] =              _hoverAndCaptureFact.rawValue().toBool();
    innerObject[refly90DegreesName] =               _refly90DegreesFact.rawValue().toBool();
148
    innerObject[_jsonFollowTerrainKey] =            _followTerrain;
149
    innerObject[_jsonCameraShotsKey] =              _cameraShots;
150 151 152 153 154 155

    if (_followTerrain) {
        innerObject[terrainAdjustToleranceName] =       _terrainAdjustToleranceFact.rawValue().toDouble();
        innerObject[terrainAdjustMaxClimbRateName] =    _terrainAdjustMaxClimbRateFact.rawValue().toDouble();
        innerObject[terrainAdjustMaxDescentRateName] =  _terrainAdjustMaxDescentRateFact.rawValue().toDouble();
    }
156 157 158

    QJsonObject cameraCalcObject;
    _cameraCalc.save(cameraCalcObject);
159 160 161 162 163
    innerObject[_jsonCameraCalcKey] = cameraCalcObject;

    QJsonValue  transectPointsJson;

    // Save transects polyline
164
    JsonHelper::saveGeoCoordinateArray(_visualTransectPoints, false /* writeAltitude */, transectPointsJson);
DonLakeFlyer's avatar
DonLakeFlyer committed
165
    innerObject[_jsonVisualTransectPointsKey] = transectPointsJson;
166 167 168 169 170 171

    // Save the interal mission items
    QJsonArray  missionItemsJsonArray;
    QObject* missionItemParent = new QObject();
    QList<MissionItem*> missionItems;
    appendMissionItems(missionItems, missionItemParent);
172
    for (const MissionItem* missionItem: missionItems) {
173 174 175 176 177 178 179 180
        QJsonObject missionItemJsonObject;
        missionItem->save(missionItemJsonObject);
        missionItemsJsonArray.append(missionItemJsonObject);
    }
    missionItemParent->deleteLater();
    innerObject[_jsonItemsKey] = missionItemsJsonArray;

    complexObject[_jsonTransectStyleComplexItemKey] = innerObject;
181 182 183 184 185 186 187 188 189 190 191 192 193
}

void TransectStyleComplexItem::setSequenceNumber(int sequenceNumber)
{
    if (_sequenceNumber != sequenceNumber) {
        _sequenceNumber = sequenceNumber;
        emit sequenceNumberChanged(sequenceNumber);
        emit lastSequenceNumberChanged(lastSequenceNumber());
    }
}

bool TransectStyleComplexItem::_load(const QJsonObject& complexObject, QString& errorString)
{
194

195
    QList<JsonHelper::KeyValidateInfo> keyInfoList = {
196 197 198 199 200 201 202 203 204
        { _jsonTransectStyleComplexItemKey, QJsonValue::Object, true },
    };
    if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) {
        return false;
    }

    // The TransectStyleComplexItem is a sub-object of the main complex item object
    QJsonObject innerObject = complexObject[_jsonTransectStyleComplexItemKey].toObject();

205 206 207 208 209 210 211 212
    if (innerObject.contains(JsonHelper::jsonVersionKey)) {
        int version = innerObject[JsonHelper::jsonVersionKey].toInt();
        if (version != 1) {
            errorString = tr("TransectStyleComplexItem version %2 not supported").arg(version);
            return false;
        }
    }

213 214
    QList<JsonHelper::KeyValidateInfo> innerKeyInfoList = {
        { JsonHelper::jsonVersionKey,       QJsonValue::Double, true },
215 216 217 218 219
        { turnAroundDistanceName,           QJsonValue::Double, true },
        { cameraTriggerInTurnAroundName,    QJsonValue::Bool,   true },
        { hoverAndCaptureName,              QJsonValue::Bool,   true },
        { refly90DegreesName,               QJsonValue::Bool,   true },
        { _jsonCameraCalcKey,               QJsonValue::Object, true },
220
        { _jsonVisualTransectPointsKey,     QJsonValue::Array,  true },
221
        { _jsonItemsKey,                    QJsonValue::Array,  true },
222
        { _jsonFollowTerrainKey,            QJsonValue::Bool,   true },
223
        { _jsonCameraShotsKey,              QJsonValue::Double, false },    // Not required since it was missing from initial implementation
224
    };
225
    if (!JsonHelper::validateKeys(innerObject, innerKeyInfoList, errorString)) {
226 227 228
        return false;
    }

DonLakeFlyer's avatar
DonLakeFlyer committed
229 230
    // Load visual transect points
    if (!JsonHelper::loadGeoCoordinateArray(innerObject[_jsonVisualTransectPointsKey], false /* altitudeRequired */, _visualTransectPoints, errorString)) {
231 232
        return false;
    }
DonLakeFlyer's avatar
DonLakeFlyer committed
233 234
    _coordinate = _visualTransectPoints.count() ? _visualTransectPoints.first().value<QGeoCoordinate>() : QGeoCoordinate();
    _exitCoordinate = _visualTransectPoints.count() ? _visualTransectPoints.last().value<QGeoCoordinate>() : QGeoCoordinate();
235

236 237 238 239 240
    // Load CameraCalc data
    if (!_cameraCalc.load(innerObject[_jsonCameraCalcKey].toObject(), errorString)) {
        return false;
    }

241 242 243
    // Load generated mission items
    _loadedMissionItemsParent = new QObject(this);
    QJsonArray missionItemsJsonArray = innerObject[_jsonItemsKey].toArray();
244
    for (const QJsonValue& missionItemJson: missionItemsJsonArray) {
245 246 247 248 249 250 251 252 253 254 255 256 257 258
        MissionItem* missionItem = new MissionItem(_loadedMissionItemsParent);
        if (!missionItem->load(missionItemJson.toObject(), 0 /* sequenceNumber */, errorString)) {
            _loadedMissionItemsParent->deleteLater();
            _loadedMissionItemsParent = NULL;
            return false;
        }
        _loadedMissionItems.append(missionItem);
    }


    // Load TransectStyleComplexItem individual values
    _turnAroundDistanceFact.setRawValue         (innerObject[turnAroundDistanceName].toDouble());
    _cameraTriggerInTurnAroundFact.setRawValue  (innerObject[cameraTriggerInTurnAroundName].toBool());
    _hoverAndCaptureFact.setRawValue            (innerObject[hoverAndCaptureName].toBool());
259 260 261
    _refly90DegreesFact.setRawValue             (innerObject[refly90DegreesName].toBool());
    _followTerrain = innerObject[_jsonFollowTerrainKey].toBool();

262 263 264 265 266 267
    // These two keys where not included in initial implementation so they are optional. Without them the values will be
    // incorrect when loaded though.
    if (innerObject.contains(_jsonCameraShotsKey)) {
        _cameraShots = innerObject[_jsonCameraShotsKey].toInt();
    }

268 269 270 271 272 273 274 275 276 277 278 279 280 281
    if (_followTerrain) {
        QList<JsonHelper::KeyValidateInfo> followTerrainKeyInfoList = {
            { terrainAdjustToleranceName,       QJsonValue::Double, true },
            { terrainAdjustMaxClimbRateName,    QJsonValue::Double, true },
            { terrainAdjustMaxDescentRateName,  QJsonValue::Double, true },
        };
        if (!JsonHelper::validateKeys(innerObject, followTerrainKeyInfoList, errorString)) {
            return false;
        }

        _terrainAdjustToleranceFact.setRawValue         (innerObject[terrainAdjustToleranceName].toDouble());
        _terrainAdjustMaxClimbRateFact.setRawValue      (innerObject[terrainAdjustMaxClimbRateName].toDouble());
        _terrainAdjustMaxDescentRateFact.setRawValue    (innerObject[terrainAdjustMaxDescentRateName].toDouble());
    }
282 283 284 285 286 287 288

    return true;
}

double TransectStyleComplexItem::greatestDistanceTo(const QGeoCoordinate &other) const
{
    double greatestDistance = 0.0;
289 290
    for (int i=0; i<_visualTransectPoints.count(); i++) {
        QGeoCoordinate vertex = _visualTransectPoints[i].value<QGeoCoordinate>();
291 292 293 294 295 296 297 298 299
        double distance = vertex.distanceTo(other);
        if (distance > greatestDistance) {
            greatestDistance = distance;
        }
    }

    return greatestDistance;
}

300
void TransectStyleComplexItem::setMissionFlightStatus(const MissionController::MissionFlightStatus_t &missionFlightStatus)
301 302 303 304 305 306 307 308 309 310 311 312 313
{
    ComplexMissionItem::setMissionFlightStatus(missionFlightStatus);
    if (!qFuzzyCompare(_cruiseSpeed, missionFlightStatus.vehicleSpeed)) {
        _cruiseSpeed = missionFlightStatus.vehicleSpeed;
        emit timeBetweenShotsChanged();
    }
}

void TransectStyleComplexItem::_setDirty(void)
{
    setDirty(true);
}

314 315 316 317 318 319 320
void TransectStyleComplexItem::_setIfDirty(bool dirty)
{
    if (dirty) {
        setDirty(true);
    }
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
void TransectStyleComplexItem::applyNewAltitude(double newAltitude)
{
    Q_UNUSED(newAltitude);
    // FIXME: NYI
    //_altitudeFact.setRawValue(newAltitude);
}

void TransectStyleComplexItem::_updateCoordinateAltitudes(void)
{
    emit coordinateChanged(coordinate());
    emit exitCoordinateChanged(exitCoordinate());
}

double TransectStyleComplexItem::coveredArea(void) const
{
    return _surveyAreaPolygon.area();
}

bool TransectStyleComplexItem::_hasTurnaround(void) const
{
    return _turnaroundDistance() > 0;
}

double TransectStyleComplexItem::_turnaroundDistance(void) const
{
    return _turnAroundDistanceFact.rawValue().toDouble();
}

bool TransectStyleComplexItem::hoverAndCaptureAllowed(void) const
{
    return _vehicle->multiRotor() || _vehicle->vtol();
}

354 355
void TransectStyleComplexItem::_rebuildTransects(void)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
356 357 358 359
    if (_ignoreRecalc) {
        return;
    }

360
    //CALLGRIND_TOGGLE_COLLECT;    
361
    //auto startTime = std::chrono::high_resolution_clock::now();
362
    _rebuildTransectsPhase1();    
363 364
    //auto delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - startTime).count();
    //qWarning() << "TransectStyleComplexItem::_rebuildTransects(): time: " << delta << " us";
365
    //CALLGRIND_TOGGLE_COLLECT;
366

DonLakeFlyer's avatar
DonLakeFlyer committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    if (_followTerrain) {
        // Query the terrain data. Once available terrain heights will be calculated
        _queryTransectsPathHeightInfo();
    } else {
        // Not following terrain, just add requested altitude to coords
        double requestedAltitude = _cameraCalc.distanceToSurface()->rawValue().toDouble();

        for (int i=0; i<_transects.count(); i++) {
            QList<CoordInfo_t>& transect = _transects[i];

            for (int j=0; j<transect.count(); j++) {
                QGeoCoordinate& coord = transect[j].coord;

                coord.setAltitude(requestedAltitude);
            }
        }
    }
384

385 386 387 388 389 390 391
    // Calc bounding cube
    double north = 0.0;
    double south = 180.0;
    double east  = 0.0;
    double west  = 360.0;
    double bottom = 100000.;
    double top = 0.;
392 393
    // Generate the visuals transect representation
    _visualTransectPoints.clear();
394 395
    for (const QList<CoordInfo_t>& transect: _transects) {
        for (const CoordInfo_t& coordInfo: transect) {
396
            _visualTransectPoints.append(QVariant::fromValue(coordInfo.coord));
397 398 399 400 401 402 403 404
            double lat = coordInfo.coord.latitude()  + 90.0;
            double lon = coordInfo.coord.longitude() + 180.0;
            north   = fmax(north, lat);
            south   = fmin(south, lat);
            east    = fmax(east,  lon);
            west    = fmin(west,  lon);
            bottom  = fmin(bottom, coordInfo.coord.altitude());
            top     = fmax(top, coordInfo.coord.altitude());
405 406
        }
    }
407 408 409 410
    //-- Update bounding cube for airspace management control
    _setBoundingCube(QGCGeoBoundingCube(
        QGeoCoordinate(north - 90.0, west - 180.0, bottom),
        QGeoCoordinate(south - 90.0, east - 180.0, top)));
411 412
    emit visualTransectPointsChanged();

DonLakeFlyer's avatar
DonLakeFlyer committed
413 414 415 416 417
    _coordinate = _visualTransectPoints.count() ? _visualTransectPoints.first().value<QGeoCoordinate>() : QGeoCoordinate();
    _exitCoordinate = _visualTransectPoints.count() ? _visualTransectPoints.last().value<QGeoCoordinate>() : QGeoCoordinate();
    emit coordinateChanged(_coordinate);
    emit exitCoordinateChanged(_exitCoordinate);

418 419
    _recalcComplexDistance();
    _recalcCameraShots();
420 421

    emit lastSequenceNumberChanged(lastSequenceNumber());
422
    emit timeBetweenShotsChanged();
423
    emit additionalTimeDelayChanged();
424
}
425

426 427 428 429
void TransectStyleComplexItem::_updateTransectAltitude()
{
    double altitude = _cameraCalc.distanceToSurface()->rawValue().toDouble();
    if (altitude > 0)
430 431 432 433
        for (int h = 0; h < _transects.length(); h++){
            QList<CoordInfo_t> &list = _transects[h];
            for (int i = 0; i < list.length(); i++) {
                CoordInfo_t &vertex = list[i];
434
                vertex.coord.setAltitude(altitude);
435 436 437 438 439 440 441 442 443 444 445
            }
        }
}

void TransectStyleComplexItem::_clearLoadedMissionItems()
{
    if (_loadedMissionItemsParent){
        _loadedMissionItems.clear();
        _loadedMissionItemsParent->deleteLater();
        _loadedMissionItemsParent = nullptr;
    }
446 447
}

448 449 450 451
void TransectStyleComplexItem::_queryTransectsPathHeightInfo(void)
{
    _transectsPathHeightInfo.clear();

452
    if (_transects.count()) {
453
        // We don't actually send the query until this timer times out. This way we only send
454
        // the latest request if we get a bunch in a row.
455 456 457 458 459 460
        _terrainQueryTimer.start();
    }
}

void TransectStyleComplexItem::_reallyQueryTransectsPathHeightInfo(void)
{
461 462 463 464 465 466 467 468 469 470 471 472 473 474
    // Clear any previous query
    if (_terrainPolyPathQuery) {
        // FIXME: We should really be blowing away any previous query here. But internally that is difficult to implement so instead we let
        // it complete and drop the results.
#if 0
        // Toss previous query
        _terrainPolyPathQuery->deleteLater();
#else
        // Let the signal fall on the floor
        disconnect(_terrainPolyPathQuery, &TerrainPolyPathQuery::terrainDataReceived, this, &TransectStyleComplexItem::_polyPathTerrainData);
#endif
        _terrainPolyPathQuery = NULL;
    }

475 476 477 478
    // Append all transects into a single PolyPath query

    QList<QGeoCoordinate> transectPoints;

479 480
    for (const QList<CoordInfo_t>& transect: _transects) {
        for (const CoordInfo_t& coordInfo: transect) {
481 482 483 484 485
            transectPoints.append(coordInfo.coord);
        }
    }

    if (transectPoints.count() > 1) {
486
        _terrainPolyPathQuery = new TerrainPolyPathQuery(this);
DonLakeFlyer's avatar
DonLakeFlyer committed
487
        connect(_terrainPolyPathQuery, &TerrainPolyPathQuery::terrainDataReceived, this, &TransectStyleComplexItem::_polyPathTerrainData);
488
        _terrainPolyPathQuery->requestData(transectPoints);
489 490 491 492 493
    }
}

void TransectStyleComplexItem::_polyPathTerrainData(bool success, const QList<TerrainPathQuery::PathHeightInfo_t>& rgPathHeightInfo)
{
494 495
    _transectsPathHeightInfo.clear();

496
    if (success) {
497 498 499 500 501 502 503 504 505 506 507 508 509
        // Break out into individual transects
        int pathHeightIndex = 0;
        for (int i=0; i<_transects.count(); i++) {
            _transectsPathHeightInfo.append(QList<TerrainPathQuery::PathHeightInfo_t>());
            int cPathHeight = _transects[i].count() - 1;
            while (cPathHeight-- > 0) {
                _transectsPathHeightInfo[i].append(rgPathHeightInfo[pathHeightIndex++]);
            }
            pathHeightIndex++;  // There is an extra on between each transect
        }

        // Now that we have terrain data we can adjust
        _adjustTransectsForTerrain();
510
    }
511 512 513 514 515 516

    if (_terrainPolyPathQuery != sender()) {
        qWarning() << "TransectStyleComplexItem::_polyPathTerrainData _terrainPolyPathQuery != sender()";
    }
    disconnect(_terrainPolyPathQuery, &TerrainPolyPathQuery::terrainDataReceived, this, &TransectStyleComplexItem::_polyPathTerrainData);
    _terrainPolyPathQuery = NULL;
517 518 519 520 521
}

bool TransectStyleComplexItem::readyForSave(void) const
{
    // Make sure we have the terrain data we need
522
    return _followTerrain ? _transectsPathHeightInfo.count() : true;
523 524
}

525
void TransectStyleComplexItem::_adjustTransectsForTerrain(void)
526
{
527 528 529 530 531 532
    if (_followTerrain) {
        if (!readyForSave()) {
            qCWarning(TransectStyleComplexItemLog) << "_adjustTransectPointsForTerrain called when terrain data not ready";
            qgcApp()->showMessage(tr("INTERNAL ERROR: TransectStyleComplexItem::_adjustTransectPointsForTerrain called when terrain data not ready. Plan will be incorrect."));
            return;
        }
533

534 535 536
        // First step is add all interstitial points at max resolution
        for (int i=0; i<_transects.count(); i++) {
            _addInterstitialTerrainPoints(_transects[i], _transectsPathHeightInfo[i]);
537
        }
538 539 540

        for (int i=0; i<_transects.count(); i++) {
            _adjustForMaxRates(_transects[i]);
541 542
        }

543 544 545
        for (int i=0; i<_transects.count(); i++) {
            _adjustForTolerance(_transects[i]);
        }
546

547 548
        emit lastSequenceNumberChanged(lastSequenceNumber());
    }
549 550 551 552 553 554
}

/// Returns the altitude in between the two points on a line.
///     @param precentTowardsTo Example: .25 = twenty five percent along the distance of from to to
double TransectStyleComplexItem::_altitudeBetweenCoords(const QGeoCoordinate& fromCoord, const QGeoCoordinate& toCoord, double percentTowardsTo)
{
555 556
    double fromAlt = fromCoord.altitude();
    double toAlt = toCoord.altitude();
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    double altDiff = toAlt - fromAlt;
    return fromAlt + (altDiff * percentTowardsTo);
}

/// Determine the maximum height within the PathHeightInfo
///     @param fromIndex First height index to consider
///     @param fromIndex Last height index to consider
///     @param[out] maxHeight Maximum height
/// @return index within PathHeightInfo_t.heights which contains maximum height, -1 no height data in between from and to indices
int TransectStyleComplexItem::_maxPathHeight(const TerrainPathQuery::PathHeightInfo_t& pathHeightInfo, int fromIndex, int toIndex, double& maxHeight)
{
    maxHeight = qQNaN();

    if (toIndex - fromIndex < 2) {
        return -1;
    }

    fromIndex++;
    toIndex--;

    int maxIndex = fromIndex;
    maxHeight = pathHeightInfo.heights[fromIndex];

    for (int i=fromIndex; i<=toIndex; i++) {
        if (pathHeightInfo.heights[i] > maxHeight) {
            maxIndex = i;
            maxHeight = pathHeightInfo.heights[i];
        }
    }

    return maxIndex;
}

590
void TransectStyleComplexItem::_adjustForMaxRates(QList<CoordInfo_t>& transect)
591
{
592
    double maxClimbRate = _terrainAdjustMaxClimbRateFact.rawValue().toDouble();
593
    double maxDescentRate = _terrainAdjustMaxDescentRateFact.rawValue().toDouble();
594 595 596 597 598 599
    double flightSpeed = _missionFlightStatus.vehicleSpeed;

    if (qIsNaN(flightSpeed) || (maxClimbRate == 0 && maxDescentRate == 0)) {
        if (qIsNaN(flightSpeed)) {
            qWarning() << "TransectStyleComplexItem::_adjustForMaxRates called with flightSpeed = NaN";
        }
600 601 602
        return;
    }

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    if (maxClimbRate > 0) {
        // Adjust climb rates
        bool climbRateAdjusted;
        do {
            //qDebug() << "climbrate pass";
            climbRateAdjusted = false;
            for (int i=0; i<transect.count() - 1; i++) {
                QGeoCoordinate& fromCoord = transect[i].coord;
                QGeoCoordinate& toCoord = transect[i+1].coord;

                double altDifference = toCoord.altitude() - fromCoord.altitude();
                double distance = fromCoord.distanceTo(toCoord);
                double seconds = distance / flightSpeed;
                double climbRate = altDifference / seconds;

                //qDebug() << QString("Index:%1 altDifference:%2 distance:%3 seconds:%4 climbRate:%5").arg(i).arg(altDifference).arg(distance).arg(seconds).arg(climbRate);

                if (climbRate > 0 && climbRate - maxClimbRate > 0.1) {
                    double maxAltitudeDelta = maxClimbRate * seconds;
                    fromCoord.setAltitude(toCoord.altitude() - maxAltitudeDelta);
                    //qDebug() << "Adjusting";
                    climbRateAdjusted = true;
                }
626
            }
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
        } while (climbRateAdjusted);
    }

    if (maxDescentRate > 0) {
        // Adjust descent rates
        bool descentRateAdjusted;
        maxDescentRate = -maxDescentRate;
        do {
            //qDebug() << "descent rate pass";
            descentRateAdjusted = false;
            for (int i=1; i<transect.count(); i++) {
                QGeoCoordinate& fromCoord = transect[i-1].coord;
                QGeoCoordinate& toCoord = transect[i].coord;

                double altDifference = toCoord.altitude() - fromCoord.altitude();
                double distance = fromCoord.distanceTo(toCoord);
                double seconds = distance / flightSpeed;
                double descentRate = altDifference / seconds;

                //qDebug() << QString("Index:%1 altDifference:%2 distance:%3 seconds:%4 descentRate:%5").arg(i).arg(altDifference).arg(distance).arg(seconds).arg(descentRate);

                if (descentRate < 0 && descentRate - maxDescentRate < -0.1) {
                    double maxAltitudeDelta = maxDescentRate * seconds;
                    toCoord.setAltitude(fromCoord.altitude() + maxAltitudeDelta);
                    //qDebug() << "Adjusting";
                    descentRateAdjusted = true;
                }
654
            }
655 656
        } while (descentRateAdjusted);
    }
657 658 659 660 661 662
}

void TransectStyleComplexItem::_adjustForTolerance(QList<CoordInfo_t>& transect)
{
    QList<CoordInfo_t> adjustedPoints;

663 664
    double tolerance = _terrainAdjustToleranceFact.rawValue().toDouble();

665 666 667
    int coordIndex = 0;
    while (coordIndex < transect.count()) {
        const CoordInfo_t& fromCoordInfo = transect[coordIndex];
668

669
        adjustedPoints.append(fromCoordInfo);
670

671 672 673 674 675 676 677 678 679 680 681 682 683
        // Walk forward until we fall out of tolerence or find a fixed point
        while (++coordIndex < transect.count()) {
            const CoordInfo_t& toCoordInfo = transect[coordIndex];
            if (toCoordInfo.coordType != CoordTypeInteriorTerrainAdded || qAbs(fromCoordInfo.coord.altitude() - toCoordInfo.coord.altitude()) > tolerance) {
                adjustedPoints.append(toCoordInfo);
                coordIndex++;
                break;
            }
        }
    }

#if 0
    qDebug() << "_adjustForTolerance";
684
    for (const TransectStyleComplexItem::CoordInfo_t& coordInfo: adjustedPoints) {
685 686 687 688 689 690 691 692 693 694 695
        qDebug() << coordInfo.coordType;
    }
#endif

    transect = adjustedPoints;
}

void TransectStyleComplexItem::_addInterstitialTerrainPoints(QList<CoordInfo_t>& transect, const QList<TerrainPathQuery::PathHeightInfo_t>& transectPathHeightInfo)
{
    QList<CoordInfo_t> adjustedTransect;

696
    double requestedAltitude = _cameraCalc.distanceToSurface()->rawValue().toDouble();
697 698 699 700

    for (int i=0; i<transect.count() - 1; i++) {
        CoordInfo_t fromCoordInfo = transect[i];
        CoordInfo_t toCoordInfo = transect[i+1];
701

702 703 704 705 706 707 708 709
        double azimuth = fromCoordInfo.coord.azimuthTo(toCoordInfo.coord);
        double distance = fromCoordInfo.coord.distanceTo(toCoordInfo.coord);

        const TerrainPathQuery::PathHeightInfo_t& pathHeightInfo = transectPathHeightInfo[i];

        fromCoordInfo.coord.setAltitude(pathHeightInfo.heights.first() + requestedAltitude);
        toCoordInfo.coord.setAltitude(pathHeightInfo.heights.last() + requestedAltitude);

710 711 712 713
        if (i == 0) {
            adjustedTransect.append(fromCoordInfo);
        }

714 715
        int cHeights = pathHeightInfo.heights.count();
        for (int pathHeightIndex=1; pathHeightIndex<cHeights - 1; pathHeightIndex++) {
716
            double interstitialTerrainHeight = pathHeightInfo.heights[pathHeightIndex];
717 718 719 720 721 722 723 724
            double percentTowardsTo = (1.0 / (cHeights - 1)) * pathHeightIndex;

            CoordInfo_t interstitialCoordInfo;
            interstitialCoordInfo.coordType = CoordTypeInteriorTerrainAdded;
            interstitialCoordInfo.coord = fromCoordInfo.coord.atDistanceAndAzimuth(distance * percentTowardsTo, azimuth);
            interstitialCoordInfo.coord.setAltitude(interstitialTerrainHeight + requestedAltitude);

            adjustedTransect.append(interstitialCoordInfo);
725
        }
726 727 728 729

        adjustedTransect.append(toCoordInfo);
    }

730 731 732 733 734
    CoordInfo_t lastCoordInfo = transect.last();
    const TerrainPathQuery::PathHeightInfo_t& pathHeightInfo = transectPathHeightInfo.last();
    lastCoordInfo.coord.setAltitude(pathHeightInfo.heights.last() + requestedAltitude);
    adjustedTransect.append(lastCoordInfo);

735 736
#if 0
    qDebug() << "_addInterstitialTerrainPoints";
737
    for (const TransectStyleComplexItem::CoordInfo_t& coordInfo: adjustedTransect) {
738
        qDebug() << coordInfo.coordType;
739
    }
740
#endif
741

742
    transect = adjustedTransect;
743 744 745 746 747 748 749 750 751
}

void TransectStyleComplexItem::setFollowTerrain(bool followTerrain)
{
    if (followTerrain != _followTerrain) {
        _followTerrain = followTerrain;
        emit followTerrainChanged(followTerrain);
    }
}
752 753 754

int TransectStyleComplexItem::lastSequenceNumber(void) const
{
DonLakeFlyer's avatar
DonLakeFlyer committed
755 756 757 758 759 760
    if (_loadedMissionItems.count()) {
        // We have stored mission items, just use those
        return _sequenceNumber + _loadedMissionItems.count() - 1;
    } else {
        // We have to determine from transects
        int itemCount = 0;
761

762
        for (const QList<CoordInfo_t>& rgCoordInfo: _transects) {
DonLakeFlyer's avatar
DonLakeFlyer committed
763
            itemCount += rgCoordInfo.count() * (hoverAndCaptureEnabled() ? 2 : 1);
DonLakeFlyer's avatar
DonLakeFlyer committed
764
        }
765

DonLakeFlyer's avatar
DonLakeFlyer committed
766

767
        if (!hoverAndCaptureEnabled() && triggerCamera()) {
DonLakeFlyer's avatar
DonLakeFlyer committed
768
            if (_cameraTriggerInTurnAroundFact.rawValue().toBool()) {
769
                // One camera start/stop for beginning/end of entire survey
DonLakeFlyer's avatar
DonLakeFlyer committed
770
                itemCount += 2;
771 772
                // One camera start for each transect
                itemCount += _transects.count();
DonLakeFlyer's avatar
DonLakeFlyer committed
773 774 775 776
            } else {
                // Each transect will have a camera start and stop in it
                itemCount += _transects.count() * 2;
            }
DonLakeFlyer's avatar
DonLakeFlyer committed
777
        }
778

DonLakeFlyer's avatar
DonLakeFlyer committed
779 780
        return _sequenceNumber + itemCount - 1;
    }
781 782
}

783 784 785 786 787 788 789 790 791 792 793 794
bool TransectStyleComplexItem::coordinateHasRelativeAltitude(void) const
{
    return _cameraCalc.distanceToSurfaceRelative();
}

bool TransectStyleComplexItem::exitCoordinateHasRelativeAltitude(void) const
{
    return coordinateHasRelativeAltitude();
}

void TransectStyleComplexItem::_followTerrainChanged(bool followTerrain)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
795
    _cameraCalc.setDistanceToSurfaceRelative(!followTerrain);
796 797 798 799 800
    if (followTerrain) {
        _refly90DegreesFact.setRawValue(false);
        _hoverAndCaptureFact.setRawValue(false);
    }
}