TerrainTile.cc 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 *
 * (c) 2009-2020 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.
 *
 ****************************************************************************/

Andreas Bircher's avatar
Andreas Bircher committed
10 11
#include "TerrainTile.h"
#include "JsonHelper.h"
12
#include "QGCMapEngine.h"
Andreas Bircher's avatar
Andreas Bircher committed
13 14 15 16

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
17
#include <QDataStream>
Andreas Bircher's avatar
Andreas Bircher committed
18

19
QGC_LOGGING_CATEGORY(TerrainTileLog, "TerrainTileLog");
Andreas Bircher's avatar
Andreas Bircher committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

const char*  TerrainTile::_jsonStatusKey        = "status";
const char*  TerrainTile::_jsonDataKey          = "data";
const char*  TerrainTile::_jsonBoundsKey        = "bounds";
const char*  TerrainTile::_jsonSouthWestKey     = "sw";
const char*  TerrainTile::_jsonNorthEastKey     = "ne";
const char*  TerrainTile::_jsonStatsKey         = "stats";
const char*  TerrainTile::_jsonMaxElevationKey  = "max";
const char*  TerrainTile::_jsonMinElevationKey  = "min";
const char*  TerrainTile::_jsonAvgElevationKey  = "avg";
const char*  TerrainTile::_jsonCarpetKey        = "carpet";

TerrainTile::TerrainTile()
    : _minElevation(-1.0)
    , _maxElevation(-1.0)
    , _avgElevation(-1.0)
36
    , _data(nullptr)
37 38
    , _gridSizeLat(-1)
    , _gridSizeLon(-1)
Andreas Bircher's avatar
Andreas Bircher committed
39 40 41 42 43 44 45
    , _isValid(false)
{

}

TerrainTile::~TerrainTile()
{
46 47 48 49
    if (_data) {
        for (int i = 0; i < _gridSizeLat; i++) {
            delete _data[i];
        }
Andreas Bircher's avatar
Andreas Bircher committed
50
        delete _data;
51
        _data = nullptr;
52
    }
Andreas Bircher's avatar
Andreas Bircher committed
53 54
}

55
TerrainTile::TerrainTile(QByteArray byteArray)
Andreas Bircher's avatar
Andreas Bircher committed
56 57 58
    : _minElevation(-1.0)
    , _maxElevation(-1.0)
    , _avgElevation(-1.0)
59
    , _data(nullptr)
60 61
    , _gridSizeLat(-1)
    , _gridSizeLon(-1)
Andreas Bircher's avatar
Andreas Bircher committed
62 63
    , _isValid(false)
{
64 65
    int cTileHeaderBytes = static_cast<int>(sizeof(TileInfo_t));
    int cTileBytesAvailable = byteArray.size();
66

67 68
    if (cTileBytesAvailable < cTileHeaderBytes) {
        qWarning() << "Terrain tile binary data too small for TileInfo_s header";
69 70 71
        return;
    }

72 73 74 75 76 77 78 79 80 81
    const TileInfo_t* tileInfo = reinterpret_cast<const TileInfo_t*>(byteArray.constData());
    _southWest.setLatitude(tileInfo->swLat);
    _southWest.setLongitude(tileInfo->swLon);
    _northEast.setLatitude(tileInfo->neLat);
    _northEast.setLongitude(tileInfo->neLon);
    _minElevation = tileInfo->minElevation;
    _maxElevation = tileInfo->maxElevation;
    _avgElevation = tileInfo->avgElevation;
    _gridSizeLat = tileInfo->gridSizeLat;
    _gridSizeLon = tileInfo->gridSizeLon;
82

83 84 85 86 87 88
    qCDebug(TerrainTileLog) << "Loading terrain tile: " << _southWest << " - " << _northEast;
    qCDebug(TerrainTileLog) << "min:max:avg:sizeLat:sizeLon" << _minElevation << _maxElevation << _avgElevation << _gridSizeLat << _gridSizeLon;

    int cTileDataBytes = static_cast<int>(sizeof(int16_t)) * _gridSizeLat * _gridSizeLon;
    if (cTileBytesAvailable < cTileHeaderBytes + cTileDataBytes) {
        qWarning() << "Terrain tile binary data too small for tile data";
89 90
        return;
    }
91

92 93 94 95
    _data = new int16_t*[_gridSizeLat];
    for (int k = 0; k < _gridSizeLat; k++) {
        _data[k] = new int16_t[_gridSizeLon];
    }
96

97 98
    int valueIndex = 0;
    const int16_t* pTileData = reinterpret_cast<const int16_t*>(&reinterpret_cast<const uint8_t*>(byteArray.constData())[cTileHeaderBytes]);
99 100
    for (int i = 0; i < _gridSizeLat; i++) {
        for (int j = 0; j < _gridSizeLon; j++) {
101
            _data[i][j] = pTileData[valueIndex++];
102 103 104 105
        }
    }

    _isValid = true;
106 107

    return;
108 109 110 111 112 113
}


bool TerrainTile::isIn(const QGeoCoordinate& coordinate) const
{
    if (!_isValid) {
114
        qCWarning(TerrainTileLog) << "isIn requested, but tile not valid";
115 116 117 118 119 120 121 122
        return false;
    }
    bool ret = coordinate.latitude() >= _southWest.latitude() && coordinate.longitude() >= _southWest.longitude() &&
            coordinate.latitude() <= _northEast.latitude() && coordinate.longitude() <= _northEast.longitude();
    qCDebug(TerrainTileLog) << "Checking isIn: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
    return ret;
}

123
double TerrainTile::elevation(const QGeoCoordinate& coordinate) const
124 125 126 127 128 129
{
    if (_isValid) {
        qCDebug(TerrainTileLog) << "elevation: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast;
        // Get the index at resolution of 1 arc second
        int indexLat = _latToDataIndex(coordinate.latitude());
        int indexLon = _lonToDataIndex(coordinate.longitude());
130 131
        if (indexLat == -1 || indexLon == -1) {
            qCWarning(TerrainTileLog) << "Internal error indexLat:indexLon == -1" << indexLat << indexLon;
132
            return qQNaN();
133
        }
134
        qCDebug(TerrainTileLog) << "indexLat:indexLon" << indexLat << indexLon << "elevation" << _data[indexLat][indexLon];
135
        return static_cast<double>(_data[indexLat][indexLon]);
136
    } else {
137
        qCWarning(TerrainTileLog) << "Asking for elevation, but no valid data.";
138
        return qQNaN();
139 140 141 142 143 144 145 146
    }
}

QGeoCoordinate TerrainTile::centerCoordinate(void) const
{
    return _southWest.atDistanceAndAzimuth(_southWest.distanceTo(_northEast) / 2.0, _southWest.azimuthTo(_northEast));
}

147
QByteArray TerrainTile::serialize(QByteArray input)
148
{
149 150 151 152 153 154 155
    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(input, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        QByteArray emptyArray;
        return emptyArray;
    }

Andreas Bircher's avatar
Andreas Bircher committed
156
    if (!document.isObject()) {
Andreas Bircher's avatar
Andreas Bircher committed
157
        qCDebug(TerrainTileLog) << "Terrain tile json doc is no object";
158 159
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
160
    }
Andreas Bircher's avatar
Andreas Bircher committed
161
    QJsonObject rootObject = document.object();
Andreas Bircher's avatar
Andreas Bircher committed
162 163 164 165

    QString errorString;
    QList<JsonHelper::KeyValidateInfo> rootVersionKeyInfoList = {
        { _jsonStatusKey, QJsonValue::String, true },
166
        { _jsonDataKey,   QJsonValue::Object, true },
Andreas Bircher's avatar
Andreas Bircher committed
167 168 169
    };
    if (!JsonHelper::validateKeys(rootObject, rootVersionKeyInfoList, errorString)) {
        qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
170 171
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
172 173 174 175
    }

    if (rootObject[_jsonStatusKey].toString() != "success") {
        qCDebug(TerrainTileLog) << "Invalid terrain tile.";
176 177
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
178 179 180 181
    }
    const QJsonObject& dataObject = rootObject[_jsonDataKey].toObject();
    QList<JsonHelper::KeyValidateInfo> dataVersionKeyInfoList = {
        { _jsonBoundsKey, QJsonValue::Object, true },
182
        { _jsonStatsKey,  QJsonValue::Object, true },
Andreas Bircher's avatar
Andreas Bircher committed
183 184 185 186
        { _jsonCarpetKey, QJsonValue::Array, true },
    };
    if (!JsonHelper::validateKeys(dataObject, dataVersionKeyInfoList, errorString)) {
        qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
187 188
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
189 190 191 192 193 194 195 196 197 198
    }

    // Bounds
    const QJsonObject& boundsObject = dataObject[_jsonBoundsKey].toObject();
    QList<JsonHelper::KeyValidateInfo> boundsVersionKeyInfoList = {
        { _jsonSouthWestKey, QJsonValue::Array, true },
        { _jsonNorthEastKey, QJsonValue::Array, true },
    };
    if (!JsonHelper::validateKeys(boundsObject, boundsVersionKeyInfoList, errorString)) {
        qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
199 200
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
201 202 203 204 205
    }
    const QJsonArray& swArray = boundsObject[_jsonSouthWestKey].toArray();
    const QJsonArray& neArray = boundsObject[_jsonNorthEastKey].toArray();
    if (swArray.count() < 2 || neArray.count() < 2 ) {
        qCDebug(TerrainTileLog) << "Incomplete bounding location";
206 207
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
208 209 210
    }

    // Stats
211
    const QJsonObject& statsObject = dataObject[_jsonStatsKey].toObject();
Andreas Bircher's avatar
Andreas Bircher committed
212 213
    QList<JsonHelper::KeyValidateInfo> statsVersionKeyInfoList = {
        { _jsonMinElevationKey, QJsonValue::Double, true },
214
        { _jsonMaxElevationKey, QJsonValue::Double, true },
Andreas Bircher's avatar
Andreas Bircher committed
215 216 217 218
        { _jsonAvgElevationKey, QJsonValue::Double, true },
    };
    if (!JsonHelper::validateKeys(statsObject, statsVersionKeyInfoList, errorString)) {
        qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
219 220
        QByteArray emptyArray;
        return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
221 222 223 224
    }

    // Carpet
    const QJsonArray& carpetArray = dataObject[_jsonCarpetKey].toArray();
225
    int gridSizeLat = carpetArray.count();
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    int gridSizeLon = carpetArray[0].toArray().count();
    qCDebug(TerrainTileLog) << "Received tile has size in latitude direction: " << gridSizeLat;
    qCDebug(TerrainTileLog) << "Received tile has size in longitued direction: " << gridSizeLon;

    TileInfo_t tileInfo;

    tileInfo.swLat = swArray[0].toDouble();
    tileInfo.swLon = swArray[1].toDouble();
    tileInfo.neLat = neArray[0].toDouble();
    tileInfo.neLon = neArray[1].toDouble();
    tileInfo.minElevation = static_cast<int16_t>(statsObject[_jsonMinElevationKey].toInt());
    tileInfo.maxElevation = static_cast<int16_t>(statsObject[_jsonMaxElevationKey].toInt());
    tileInfo.avgElevation = statsObject[_jsonAvgElevationKey].toDouble();
    tileInfo.gridSizeLat = static_cast<int16_t>(gridSizeLat);
    tileInfo.gridSizeLon = static_cast<int16_t>(gridSizeLon);

    int cTileHeaderBytes = static_cast<int>(sizeof(TileInfo_t));
    int cTileDataBytes = static_cast<int>(sizeof(int16_t)) * gridSizeLat * gridSizeLon;

    QByteArray byteArray(cTileHeaderBytes + cTileDataBytes, 0);

    TileInfo_t* pTileInfo = reinterpret_cast<TileInfo_t*>(byteArray.data());
    int16_t*    pTileData = reinterpret_cast<int16_t*>(&reinterpret_cast<uint8_t*>(byteArray.data())[cTileHeaderBytes]);

    *pTileInfo = tileInfo;

    int valueIndex = 0;
253
    for (int i = 0; i < gridSizeLat; i++) {
Andreas Bircher's avatar
Andreas Bircher committed
254
        const QJsonArray& row = carpetArray[i].toArray();
255 256 257 258
        if (row.count() < gridSizeLon) {
            qCDebug(TerrainTileLog) << "Expected row array of " << gridSizeLon << ", instead got " << row.count();
            QByteArray emptyArray;
            return emptyArray;
Andreas Bircher's avatar
Andreas Bircher committed
259
        }
260
        for (int j = 0; j < gridSizeLon; j++) {
261
            pTileData[valueIndex++] = static_cast<int16_t>(row[j].toDouble());
Andreas Bircher's avatar
Andreas Bircher committed
262 263 264
        }
    }

265
    return byteArray;
Andreas Bircher's avatar
Andreas Bircher committed
266 267
}

268 269 270 271 272 273

int TerrainTile::_latToDataIndex(double latitude) const
{
    if (isValid() && _southWest.isValid() && _northEast.isValid()) {
        return qRound((latitude - _southWest.latitude()) / (_northEast.latitude() - _southWest.latitude()) * (_gridSizeLat - 1));
    } else {
274
        qCWarning(TerrainTileLog) << "TerrainTile::_latToDataIndex internal error" << isValid() << _southWest.isValid() << _northEast.isValid();
275 276 277 278 279 280 281 282 283
        return -1;
    }
}

int TerrainTile::_lonToDataIndex(double longitude) const
{
    if (isValid() && _southWest.isValid() && _northEast.isValid()) {
        return qRound((longitude - _southWest.longitude()) / (_northEast.longitude() - _southWest.longitude()) * (_gridSizeLon - 1));
    } else {
284
        qCWarning(TerrainTileLog) << "TerrainTile::_lonToDataIndex internal error" << isValid() << _southWest.isValid() << _northEast.isValid();
285 286 287
        return -1;
    }
}