1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2023-05-15
 * Description : geolocation engine based on Marble.
 *               (c) 2007-2022 Marble Team
 *               https://invent.kde.org/education/marble/-/raw/master/data/credits_authors.html
 *
 * SPDX-FileCopyrightText: 2023-2026 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 * ============================================================ */

#include "VectorTileModel.h"

// Qt includes

#include <qmath.h>
#include <QThreadPool>

// Local includes

#include "GeoDataDocument.h"
#include "GeoDataTreeModel.h"
#include "GeoSceneVectorTileDataset.h"
#include "MarbleGlobal.h"
#include "MathHelper.h"
#include "TileLoader.h"
#include "digikam_debug.h"

namespace Marble
{

TileRunner::TileRunner(TileLoader* loader, const GeoSceneVectorTileDataset* tileDataset, const TileId& id)
    : m_loader(loader),
      m_tileDataset(tileDataset),
      m_id(id)
{
}

void TileRunner::run()
{
    GeoDataDocument* const document = m_loader->loadTileVectorData(m_tileDataset, m_id, DownloadBrowse);

    Q_EMIT documentLoaded(m_id, document);
}

VectorTileModel::CacheDocument::CacheDocument(GeoDataDocument* doc, VectorTileModel* vectorTileModel,
                                              const GeoDataLatLonBox& boundingBox)
    : m_document(doc),
      m_vectorTileModel(vectorTileModel),
      m_boundingBox(boundingBox)
{
    // nothing to do
}

VectorTileModel::CacheDocument::~CacheDocument()
{
    m_vectorTileModel->removeTile(m_document);
}

VectorTileModel::VectorTileModel(TileLoader* loader, const GeoSceneVectorTileDataset* layer,
                                 GeoDataTreeModel* treeModel, QThreadPool* threadPool)
    : m_loader(loader),
      m_layer(layer),
      m_treeModel(treeModel),
      m_threadPool(threadPool),
      m_tileLoadLevel(-1),
      m_tileZoomLevel(-1),
      m_deleteDocumentsLater(false)
{
    Q_UNUSED(m_treeModel);

    connect(this, SIGNAL(tileAdded(GeoDataDocument*)),
            treeModel, SLOT(addDocument(GeoDataDocument*)));

    connect(this, SIGNAL(tileRemoved(GeoDataDocument*)),
            treeModel, SLOT(removeDocument(GeoDataDocument*)));

    connect(treeModel, SIGNAL(removed(GeoDataObject*)),
            this, SLOT(cleanupTile(GeoDataObject*)));
}

void VectorTileModel::setViewport(const GeoDataLatLonBox& latLonBox)
{
    bool const smallScreen   = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
    int const nTiles         = smallScreen ? 12 : 20;
    qreal const viewportArea = latLonBox.width() * latLonBox.height();
    qreal const level        = log((nTiles * 2.0 * M_PI * M_PI) / viewportArea) / log(4);
    m_tileZoomLevel          = qFloor(level);
    int tileLoadLevel        = m_tileZoomLevel;

    // Determine available tile levels in the layer and thereby
    // select the tileZoomLevel that is actually used:

    QVector<int> tileLevels  = m_layer->tileLevels();

    if (tileLevels.isEmpty() /* || tileZoomLevel < tileLevels.first() */)
    {
        // if there is no (matching) tile level then show nothing
        // and bail out.

        m_documents.clear();

        return;
    }

    int tileLevel = tileLevels.first();

    for (int i = 1, n = tileLevels.size() ; i < n ; ++i)
    {
        if (tileLevels[i] > tileLoadLevel)
        {
            break;
        }

        tileLevel = tileLevels[i];
    }

    tileLoadLevel = tileLevel;

    // if zoom level has changed, empty vectortile cache

    if (tileLoadLevel != m_tileLoadLevel)
    {
        m_deleteDocumentsLater = (m_tileLoadLevel >= 0);
        m_tileLoadLevel        = tileLoadLevel;
    }

    /** LOGIC FOR DOWNLOADING ALL THE TILES THAT ARE INSIDE THE SCREEN AT THE CURRENT ZOOM LEVEL **/

    // New tiles X and Y for moved screen coordinates
    // More info: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Subtiles         // codespell:ignore
    // More info: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#C.2FC.2B.2B

    const QRect rect = m_layer->tileProjection()->tileIndexes(latLonBox, tileLoadLevel);

    // Download tiles and send them to VectorTileLayer
    // When changing zoom, download everything inside the screen
    // TODO: hardcodes assumption about tiles indexing also ends at dateline
    // TODO: what about crossing things in y direction?

    if (!latLonBox.crossesDateLine())
    {
        queryTiles(tileLoadLevel, rect);
    }
    else     // When only moving screen, just download the new tiles
    {
        // TODO: maxTileX (calculation knowledge) should be a property of tileProjection or m_layer

        const int maxTileX = (1 << tileLoadLevel) * m_layer->levelZeroColumns() - 1;

        queryTiles(tileLoadLevel, QRect(QPoint(0, rect.top()), rect.bottomRight()));
        queryTiles(tileLoadLevel, QRect(rect.topLeft(), QPoint(maxTileX, rect.bottom())));
    }

    removeTilesOutOfView(latLonBox);
}

void VectorTileModel::removeTilesOutOfView(const GeoDataLatLonBox& boundingBox)
{
    GeoDataLatLonBox const extendedViewport = boundingBox.scaled(2.0, 2.0);

    for (auto iter = m_documents.begin() ; iter != m_documents.end() ; )
    {
        bool const isOutOfView = !extendedViewport.intersects(iter.value()->latLonBox());

        if (isOutOfView)
        {
            iter = m_documents.erase(iter);
        }

        else
        {
            ++iter;
        }
    }
}

QString VectorTileModel::name() const
{
    return m_layer->name();
}

const GeoSceneVectorTileDataset* VectorTileModel::layer() const
{
    return m_layer;
}

void VectorTileModel::removeTile(GeoDataDocument* document)
{
    Q_EMIT tileRemoved(document);
}

int VectorTileModel::tileZoomLevel() const
{
    return m_tileZoomLevel;
}

int VectorTileModel::cachedDocuments() const
{
    return m_documents.size();
}

void VectorTileModel::reload()
{
    const auto keys = m_documents.keys();

    for (auto const& tile : keys)
    {
        m_loader->downloadTile(m_layer, tile, DownloadBrowse);
    }
}

void VectorTileModel::updateTile(const TileId& idWithMapThemeHash, GeoDataDocument* document)
{
    TileId const id(0, idWithMapThemeHash.zoomLevel(), idWithMapThemeHash.x(), idWithMapThemeHash.y());
    m_pendingDocuments.removeAll(id);

    if (!document)
    {
        return;
    }

    if (m_tileLoadLevel != id.zoomLevel())
    {
        delete document;
        return;
    }

    document->setName(QString::fromUtf8("%1/%2/%3").arg(id.zoomLevel()).arg(id.x()).arg(id.y()));
    m_garbageQueue << document;

    if (m_documents.contains(id))
    {
        m_documents.remove(id);
    }

    if (m_deleteDocumentsLater)
    {
        m_deleteDocumentsLater = false;
        m_documents.clear();
    }

    const GeoDataLatLonBox boundingBox = m_layer->tileProjection()->geoCoordinates(id);
    m_documents[id]                    = QSharedPointer<CacheDocument>(new CacheDocument(document, this, boundingBox));

    Q_EMIT tileAdded(document);
}

void VectorTileModel::clear()
{
    m_documents.clear();
}

void VectorTileModel::queryTiles(int tileZoomLevel, const QRect& rect)<--- Shadow argument
{
    // Download all the tiles inside the given indexes

    for (int x = rect.left() ; x <= rect.right() ; ++x)
    {
        for (int y = rect.top() ; y <= rect.bottom() ; ++y)
        {
            const TileId tileId = TileId(0, tileZoomLevel, x, y);

            if (!m_documents.contains(tileId) && !m_pendingDocuments.contains(tileId))
            {
                m_pendingDocuments << tileId;
                TileRunner* job = new TileRunner(m_loader, m_layer, tileId);

                connect(job, SIGNAL(documentLoaded(TileId,GeoDataDocument*)),
                        this, SLOT(updateTile(TileId,GeoDataDocument*)));

                m_threadPool->start(job);
            }
        }
    }
}

void VectorTileModel::cleanupTile(GeoDataObject* object)
{
    if (GeoDataDocument* document = geodata_cast<GeoDataDocument>(object))
    {
        if (m_garbageQueue.contains(document))
        {
            m_garbageQueue.removeAll(document);
            delete document;
        }
    }
}

} // namespace Marble

#include "moc_VectorTileModel.cpp"