Coverage Report

Created: 2026-09-26 08:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/ogcapi/gdalogcapidataset.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  GDAL
4
 * Purpose:  OGC API interface
5
 * Author:   Even Rouault, <even.rouault at spatialys.com>
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2020, Even Rouault, <even.rouault at spatialys.com>
9
 *
10
 * SPDX-License-Identifier: MIT
11
 ****************************************************************************/
12
13
#include "cpl_error.h"
14
#include "cpl_json.h"
15
#include "cpl_http.h"
16
#include "gdal_frmts.h"
17
#include "gdal_priv.h"
18
#include "tilematrixset.hpp"
19
#include "gdal_utils.h"
20
#include "ogrsf_frmts.h"
21
#include "ogr_spatialref.h"
22
#include "gdalplugindriverproxy.h"
23
24
#include "parsexsd.h"
25
26
#include <algorithm>
27
#include <memory>
28
#include <vector>
29
30
0
#define MEDIA_TYPE_OAPI_3_0 "application/vnd.oai.openapi+json;version=3.0"
31
#define MEDIA_TYPE_OAPI_3_0_ALT "application/openapi+json;version=3.0"
32
0
#define MEDIA_TYPE_JSON "application/json"
33
0
#define MEDIA_TYPE_GEOJSON "application/geo+json"
34
0
#define MEDIA_TYPE_TEXT_XML "text/xml"
35
0
#define MEDIA_TYPE_APPLICATION_XML "application/xml"
36
0
#define MEDIA_TYPE_JSON_SCHEMA "application/schema+json"
37
38
/************************************************************************/
39
/* ==================================================================== */
40
/*                           OGCAPIDataset                              */
41
/* ==================================================================== */
42
/************************************************************************/
43
44
class OGCAPIDataset final : public GDALDataset
45
{
46
    friend class OGCAPIMapWrapperBand;
47
    friend class OGCAPITilesWrapperBand;
48
    friend class OGCAPITiledLayer;
49
50
    bool m_bMustCleanPersistent = false;
51
    CPLString m_osRootURL{};
52
    CPLString m_osUserPwd{};
53
    CPLString m_osUserQueryParams{};
54
    GDALGeoTransform m_gt{};
55
56
    OGRSpatialReference m_oSRS{};
57
    CPLString m_osTileData{};
58
59
    // Classic OGC API features /items access
60
    std::unique_ptr<GDALDataset> m_poOAPIFDS{};
61
62
    // Map API
63
    std::unique_ptr<GDALDataset> m_poWMSDS{};
64
65
    // Tiles API
66
    std::vector<std::unique_ptr<GDALDataset>> m_apoDatasetsElementary{};
67
    std::vector<std::unique_ptr<GDALDataset>> m_apoDatasetsAssembled{};
68
    std::vector<std::unique_ptr<GDALDataset>> m_apoDatasetsCropped{};
69
70
    std::vector<std::unique_ptr<OGRLayer>> m_apoLayers{};
71
72
    CPLString BuildURL(const std::string &href) const;
73
    void SetRootURLFromURL(const std::string &osURL);
74
    int FigureBands(const std::string &osContentType,
75
                    const CPLString &osImageURL);
76
77
    bool InitFromFile(GDALOpenInfo *poOpenInfo);
78
    bool InitFromURL(GDALOpenInfo *poOpenInfo);
79
    bool ProcessScale(const CPLJSONObject &oScaleDenominator,
80
                      const double dfXMin, const double dfYMin,
81
                      const double dfXMax, const double dfYMax);
82
    bool InitFromCollection(GDALOpenInfo *poOpenInfo, CPLJSONDocument &oDoc);
83
    bool Download(const CPLString &osURL, const char *pszPostContent,
84
                  const char *pszAccept, CPLString &osResult,
85
                  CPLString &osContentType, bool bEmptyContentOK,
86
                  CPLStringList *paosHeaders);
87
88
    bool DownloadJSon(const CPLString &osURL, CPLJSONDocument &oDoc,
89
                      const char *pszPostContent = nullptr,
90
                      const char *pszAccept = MEDIA_TYPE_GEOJSON
91
                      ", " MEDIA_TYPE_JSON,
92
                      CPLStringList *paosHeaders = nullptr);
93
94
    std::unique_ptr<GDALDataset>
95
    OpenTile(const CPLString &osURLPattern, int nMatrix, int nColumn, int nRow,
96
             bool &bEmptyContent, unsigned int nOpenTileFlags = 0,
97
             const CPLString &osPrefix = {},
98
             const char *const *papszOpenOptions = nullptr);
99
100
    bool InitWithMapAPI(GDALOpenInfo *poOpenInfo,
101
                        const CPLJSONObject &oCollection, double dfXMin,
102
                        double dfYMin, double dfXMax, double dfYMax);
103
    bool InitWithTilesAPI(GDALOpenInfo *poOpenInfo, const CPLString &osTilesURL,
104
                          bool bIsMap, double dfXMin, double dfYMin,
105
                          double dfXMax, double dfYMax, bool bBBOXIsInCRS84,
106
                          const CPLJSONObject &oJsonCollection);
107
    bool InitWithCoverageAPI(GDALOpenInfo *poOpenInfo,
108
                             const CPLString &osTilesURL, double dfXMin,
109
                             double dfYMin, double dfXMax, double dfYMax,
110
                             const CPLJSONObject &oJsonCollection);
111
112
  protected:
113
    CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
114
                     int nYSize, void *pData, int nBufXSize, int nBufYSize,
115
                     GDALDataType eBufType, int nBandCount,
116
                     BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
117
                     GSpacing nLineSpace, GSpacing nBandSpace,
118
                     GDALRasterIOExtraArg *psExtraArg) override;
119
120
    int CloseDependentDatasets() override;
121
122
  public:
123
14
    OGCAPIDataset() = default;
124
    ~OGCAPIDataset() override;
125
126
    CPLErr GetGeoTransform(GDALGeoTransform &gt) const override;
127
    const OGRSpatialReference *GetSpatialRef() const override;
128
129
    int GetLayerCount() const override
130
0
    {
131
0
        return m_poOAPIFDS ? m_poOAPIFDS->GetLayerCount()
132
0
                           : static_cast<int>(m_apoLayers.size());
133
0
    }
134
135
    const OGRLayer *GetLayer(int idx) const override
136
0
    {
137
0
        return m_poOAPIFDS                         ? m_poOAPIFDS->GetLayer(idx)
138
0
               : idx >= 0 && idx < GetLayerCount() ? m_apoLayers[idx].get()
139
0
                                                   : nullptr;
140
0
    }
141
142
    static int Identify(GDALOpenInfo *poOpenInfo);
143
    static GDALDataset *Open(GDALOpenInfo *poOpenInfo);
144
};
145
146
/************************************************************************/
147
/* ==================================================================== */
148
/*                      OGCAPIMapWrapperBand                            */
149
/* ==================================================================== */
150
/************************************************************************/
151
152
class OGCAPIMapWrapperBand final : public GDALRasterBand
153
{
154
  public:
155
    OGCAPIMapWrapperBand(OGCAPIDataset *poDS, int nBand);
156
157
    GDALRasterBand *GetOverview(int nLevel) override;
158
    int GetOverviewCount() override;
159
    GDALColorInterp GetColorInterpretation() override;
160
161
  protected:
162
    CPLErr IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage) override;
163
    CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
164
                     GDALDataType, GSpacing, GSpacing,
165
                     GDALRasterIOExtraArg *psExtraArg) override;
166
};
167
168
/************************************************************************/
169
/* ==================================================================== */
170
/*                     OGCAPITilesWrapperBand                           */
171
/* ==================================================================== */
172
/************************************************************************/
173
174
class OGCAPITilesWrapperBand final : public GDALRasterBand
175
{
176
  public:
177
    OGCAPITilesWrapperBand(OGCAPIDataset *poDS, int nBand);
178
179
    GDALRasterBand *GetOverview(int nLevel) override;
180
    int GetOverviewCount() override;
181
    GDALColorInterp GetColorInterpretation() override;
182
183
  protected:
184
    CPLErr IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage) override;
185
    CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
186
                     GDALDataType, GSpacing, GSpacing,
187
                     GDALRasterIOExtraArg *psExtraArg) override;
188
};
189
190
/************************************************************************/
191
/* ==================================================================== */
192
/*                           OGCAPITiledLayer                           */
193
/* ==================================================================== */
194
/************************************************************************/
195
196
class OGCAPITiledLayer;
197
198
class OGCAPITiledLayerFeatureDefn final : public OGRFeatureDefn
199
{
200
    OGCAPITiledLayer *m_poLayer = nullptr;
201
202
    CPL_DISALLOW_COPY_ASSIGN(OGCAPITiledLayerFeatureDefn)
203
204
  public:
205
    OGCAPITiledLayerFeatureDefn(OGCAPITiledLayer *poLayer, const char *pszName)
206
0
        : OGRFeatureDefn(pszName), m_poLayer(poLayer)
207
0
    {
208
0
    }
209
210
    int GetFieldCount() const override;
211
212
    void InvalidateLayer()
213
0
    {
214
0
        m_poLayer = nullptr;
215
0
    }
216
};
217
218
class OGCAPITiledLayer final
219
    : public OGRLayer,
220
      public OGRGetNextFeatureThroughRaw<OGCAPITiledLayer>
221
{
222
    OGCAPIDataset *m_poDS = nullptr;
223
    bool m_bFeatureDefnEstablished = false;
224
    bool m_bEstablishFieldsCalled =
225
        false;  // prevent recursion in EstablishFields()
226
    OGCAPITiledLayerFeatureDefn *m_poFeatureDefn = nullptr;
227
    OGREnvelope m_sEnvelope{};
228
    std::unique_ptr<GDALDataset> m_poUnderlyingDS{};
229
    OGRLayer *m_poUnderlyingLayer = nullptr;
230
    int m_nCurY = 0;
231
    int m_nCurX = 0;
232
233
    CPLString m_osTileURL{};
234
    bool m_bIsMVT = false;
235
236
    const gdal::TileMatrixSet::TileMatrix m_oTileMatrix{};
237
    bool m_bInvertAxis = false;
238
239
    // absolute bounds
240
    int m_nMinX = 0;
241
    int m_nMaxX = 0;
242
    int m_nMinY = 0;
243
    int m_nMaxY = 0;
244
245
    // depends on spatial filter
246
    int m_nCurMinX = 0;
247
    int m_nCurMaxX = 0;
248
    int m_nCurMinY = 0;
249
    int m_nCurMaxY = 0;
250
251
    int GetCoalesceFactorForRow(int nRow) const;
252
    bool IncrementTileIndices();
253
    OGRFeature *GetNextRawFeature();
254
    GDALDataset *OpenTile(int nX, int nY, bool &bEmptyContent);
255
    void FinalizeFeatureDefnWithLayer(OGRLayer *poUnderlyingLayer);
256
    OGRFeature *BuildFeature(std::unique_ptr<OGRFeature> poSrcFeature, int nX,
257
                             int nY);
258
259
    CPL_DISALLOW_COPY_ASSIGN(OGCAPITiledLayer)
260
261
  protected:
262
    friend class OGCAPITiledLayerFeatureDefn;
263
    void EstablishFields();
264
265
  public:
266
    OGCAPITiledLayer(OGCAPIDataset *poDS, bool bInvertAxis,
267
                     const CPLString &osTileURL, bool bIsMVT,
268
                     const gdal::TileMatrixSet::TileMatrix &tileMatrix,
269
                     OGRwkbGeometryType eGeomType);
270
    ~OGCAPITiledLayer() override;
271
272
    void SetExtent(double dfXMin, double dfYMin, double dfXMax, double dfYMax);
273
    void SetFields(const std::vector<std::unique_ptr<OGRFieldDefn>> &apoFields);
274
    void SetMinMaxXY(int minCol, int minRow, int maxCol, int maxRow);
275
276
    void ResetReading() override;
277
278
    const OGRFeatureDefn *GetLayerDefn() const override
279
0
    {
280
0
        return m_poFeatureDefn;
281
0
    }
282
283
    const char *GetName() const override
284
0
    {
285
0
        return m_poFeatureDefn->GetName();
286
0
    }
287
288
    OGRwkbGeometryType GetGeomType() const override
289
0
    {
290
0
        return m_poFeatureDefn->GetGeomType();
291
0
    }
292
    DEFINE_GET_NEXT_FEATURE_THROUGH_RAW(OGCAPITiledLayer)
293
294
    GIntBig GetFeatureCount(int /* bForce */) override
295
0
    {
296
0
        return -1;
297
0
    }
298
299
    OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
300
                      bool bForce) override;
301
302
    OGRErr ISetSpatialFilter(int iGeomField,
303
                             const OGRGeometry *poGeom) override;
304
305
    OGRFeature *GetFeature(GIntBig nFID) override;
306
    bool TestCapability(const char *) const override;
307
};
308
309
/************************************************************************/
310
/*                           GetFieldCount()                            */
311
/************************************************************************/
312
313
int OGCAPITiledLayerFeatureDefn::GetFieldCount() const
314
0
{
315
0
    if (m_poLayer)
316
0
    {
317
0
        m_poLayer->EstablishFields();
318
0
    }
319
0
    return OGRFeatureDefn::GetFieldCount();
320
0
}
321
322
/************************************************************************/
323
/*                           ~OGCAPIDataset()                           */
324
/************************************************************************/
325
326
OGCAPIDataset::~OGCAPIDataset()
327
14
{
328
14
    if (m_bMustCleanPersistent)
329
14
    {
330
14
        char **papszOptions = CSLSetNameValue(nullptr, "CLOSE_PERSISTENT",
331
14
                                              CPLSPrintf("OGCAPI:%p", this));
332
14
        CPLHTTPDestroyResult(CPLHTTPFetch(m_osRootURL, papszOptions));
333
14
        CSLDestroy(papszOptions);
334
14
    }
335
336
14
    OGCAPIDataset::CloseDependentDatasets();
337
14
}
338
339
/************************************************************************/
340
/*                       CloseDependentDatasets()                       */
341
/************************************************************************/
342
343
int OGCAPIDataset::CloseDependentDatasets()
344
14
{
345
14
    if (m_apoDatasetsElementary.empty())
346
14
        return false;
347
348
    // in this order
349
0
    m_apoDatasetsCropped.clear();
350
0
    m_apoDatasetsAssembled.clear();
351
0
    m_apoDatasetsElementary.clear();
352
0
    return true;
353
14
}
354
355
/************************************************************************/
356
/*                          GetGeoTransform()                           */
357
/************************************************************************/
358
359
CPLErr OGCAPIDataset::GetGeoTransform(GDALGeoTransform &gt) const
360
0
{
361
0
    gt = m_gt;
362
0
    return CE_None;
363
0
}
364
365
/************************************************************************/
366
/*                           GetSpatialRef()                            */
367
/************************************************************************/
368
369
const OGRSpatialReference *OGCAPIDataset::GetSpatialRef() const
370
0
{
371
0
    return !m_oSRS.IsEmpty() ? &m_oSRS : nullptr;
372
0
}
373
374
/************************************************************************/
375
/*                          CheckContentType()                          */
376
/************************************************************************/
377
378
// We may ask for "application/openapi+json;version=3.0"
379
// and the server returns "application/openapi+json; charset=utf-8; version=3.0"
380
static bool CheckContentType(const char *pszGotContentType,
381
                             const char *pszExpectedContentType)
382
0
{
383
0
    CPLStringList aosGotTokens(CSLTokenizeString2(pszGotContentType, "; ", 0));
384
0
    CPLStringList aosExpectedTokens(
385
0
        CSLTokenizeString2(pszExpectedContentType, "; ", 0));
386
0
    for (int i = 0; i < aosExpectedTokens.size(); i++)
387
0
    {
388
0
        bool bFound = false;
389
0
        for (int j = 0; j < aosGotTokens.size(); j++)
390
0
        {
391
0
            if (EQUAL(aosExpectedTokens[i], aosGotTokens[j]))
392
0
            {
393
0
                bFound = true;
394
0
                break;
395
0
            }
396
0
        }
397
0
        if (!bFound)
398
0
            return false;
399
0
    }
400
0
    return true;
401
0
}
402
403
/************************************************************************/
404
/*                              Download()                              */
405
/************************************************************************/
406
407
bool OGCAPIDataset::Download(const CPLString &osURL, const char *pszPostContent,
408
                             const char *pszAccept, CPLString &osResult,
409
                             CPLString &osContentType, bool bEmptyContentOK,
410
                             CPLStringList *paosHeaders)
411
14
{
412
14
    char **papszOptions = nullptr;
413
14
    CPLString osHeaders;
414
14
    if (pszAccept)
415
14
    {
416
14
        osHeaders += "Accept: ";
417
14
        osHeaders += pszAccept;
418
14
    }
419
14
    if (pszPostContent)
420
0
    {
421
0
        if (!osHeaders.empty())
422
0
        {
423
0
            osHeaders += "\r\n";
424
0
        }
425
0
        osHeaders += "Content-Type: application/json";
426
0
    }
427
14
    if (!osHeaders.empty())
428
14
    {
429
14
        papszOptions =
430
14
            CSLSetNameValue(papszOptions, "HEADERS", osHeaders.c_str());
431
14
    }
432
14
    if (!m_osUserPwd.empty())
433
0
    {
434
0
        papszOptions =
435
0
            CSLSetNameValue(papszOptions, "USERPWD", m_osUserPwd.c_str());
436
0
    }
437
14
    m_bMustCleanPersistent = true;
438
14
    papszOptions =
439
14
        CSLAddString(papszOptions, CPLSPrintf("PERSISTENT=OGCAPI:%p", this));
440
14
    CPLString osURLWithQueryParameters(osURL);
441
14
    if (!m_osUserQueryParams.empty() &&
442
0
        osURL.find('?' + m_osUserQueryParams) == std::string::npos &&
443
0
        osURL.find('&' + m_osUserQueryParams) == std::string::npos)
444
0
    {
445
0
        if (osURL.find('?') == std::string::npos)
446
0
        {
447
0
            osURLWithQueryParameters += '?';
448
0
        }
449
0
        else
450
0
        {
451
0
            osURLWithQueryParameters += '&';
452
0
        }
453
0
        osURLWithQueryParameters += m_osUserQueryParams;
454
0
    }
455
14
    if (pszPostContent)
456
0
    {
457
0
        papszOptions =
458
0
            CSLSetNameValue(papszOptions, "POSTFIELDS", pszPostContent);
459
0
    }
460
14
    CPLHTTPResult *psResult =
461
14
        CPLHTTPFetch(osURLWithQueryParameters, papszOptions);
462
14
    CSLDestroy(papszOptions);
463
14
    if (!psResult)
464
0
        return false;
465
466
14
    if (paosHeaders)
467
0
    {
468
0
        *paosHeaders = CSLDuplicate(psResult->papszHeaders);
469
0
    }
470
471
14
    if (psResult->pszErrBuf != nullptr)
472
14
    {
473
14
        std::string osErrorMsg(psResult->pszErrBuf);
474
14
        const char *pszData =
475
14
            reinterpret_cast<const char *>(psResult->pabyData);
476
14
        if (pszData)
477
0
        {
478
0
            osErrorMsg += ", ";
479
0
            osErrorMsg.append(pszData, CPLStrnlen(pszData, 1000));
480
0
        }
481
14
        CPLError(CE_Failure, CPLE_AppDefined, "%s", osErrorMsg.c_str());
482
14
        CPLHTTPDestroyResult(psResult);
483
14
        return false;
484
14
    }
485
486
0
    if (psResult->pszContentType)
487
0
        osContentType = psResult->pszContentType;
488
489
0
    if (pszAccept != nullptr)
490
0
    {
491
0
        bool bFoundExpectedContentType = false;
492
0
        if (strstr(pszAccept, "xml") && psResult->pszContentType != nullptr &&
493
0
            (CheckContentType(psResult->pszContentType, MEDIA_TYPE_TEXT_XML) ||
494
0
             CheckContentType(psResult->pszContentType,
495
0
                              MEDIA_TYPE_APPLICATION_XML)))
496
0
        {
497
0
            bFoundExpectedContentType = true;
498
0
        }
499
500
0
        if (strstr(pszAccept, MEDIA_TYPE_JSON_SCHEMA) &&
501
0
            psResult->pszContentType != nullptr &&
502
0
            (CheckContentType(psResult->pszContentType, MEDIA_TYPE_JSON) ||
503
0
             CheckContentType(psResult->pszContentType,
504
0
                              MEDIA_TYPE_JSON_SCHEMA)))
505
0
        {
506
0
            bFoundExpectedContentType = true;
507
0
        }
508
509
0
        for (const char *pszMediaType : {
510
0
                 MEDIA_TYPE_JSON,
511
0
                 MEDIA_TYPE_GEOJSON,
512
0
                 MEDIA_TYPE_OAPI_3_0,
513
0
             })
514
0
        {
515
0
            if (strstr(pszAccept, pszMediaType) &&
516
0
                psResult->pszContentType != nullptr &&
517
0
                CheckContentType(psResult->pszContentType, pszMediaType))
518
0
            {
519
0
                bFoundExpectedContentType = true;
520
0
                break;
521
0
            }
522
0
        }
523
524
0
        if (!bFoundExpectedContentType)
525
0
        {
526
0
            CPLError(CE_Failure, CPLE_AppDefined, "Unexpected Content-Type: %s",
527
0
                     psResult->pszContentType ? psResult->pszContentType
528
0
                                              : "(null)");
529
0
            CPLHTTPDestroyResult(psResult);
530
0
            return false;
531
0
        }
532
0
    }
533
534
0
    if (psResult->pabyData == nullptr)
535
0
    {
536
0
        osResult.clear();
537
0
        if (!bEmptyContentOK)
538
0
        {
539
0
            CPLError(CE_Failure, CPLE_AppDefined,
540
0
                     "Empty content returned by server");
541
0
            CPLHTTPDestroyResult(psResult);
542
0
            return false;
543
0
        }
544
0
    }
545
0
    else
546
0
    {
547
0
        osResult.assign(reinterpret_cast<const char *>(psResult->pabyData),
548
0
                        psResult->nDataLen);
549
#ifdef DEBUG_VERBOSE
550
        CPLDebug("OGCAPI", "%s", osResult.c_str());
551
#endif
552
0
    }
553
0
    CPLHTTPDestroyResult(psResult);
554
0
    return true;
555
0
}
556
557
/************************************************************************/
558
/*                            DownloadJSon()                            */
559
/************************************************************************/
560
561
bool OGCAPIDataset::DownloadJSon(const CPLString &osURL, CPLJSONDocument &oDoc,
562
                                 const char *pszPostContent,
563
                                 const char *pszAccept,
564
                                 CPLStringList *paosHeaders)
565
14
{
566
14
    CPLString osResult;
567
14
    CPLString osContentType;
568
14
    if (!Download(osURL, pszPostContent, pszAccept, osResult, osContentType,
569
14
                  false, paosHeaders))
570
14
        return false;
571
0
    return oDoc.LoadMemory(osResult);
572
14
}
573
574
/************************************************************************/
575
/*                              OpenTile()                              */
576
/************************************************************************/
577
578
std::unique_ptr<GDALDataset>
579
OGCAPIDataset::OpenTile(const CPLString &osURLPattern, int nMatrix, int nColumn,
580
                        int nRow, bool &bEmptyContent,
581
                        unsigned int nOpenTileFlags, const CPLString &osPrefix,
582
                        const char *const *papszOpenTileOptions)
583
0
{
584
0
    CPLString osURL(osURLPattern);
585
0
    osURL.replaceAll("{tileMatrix}", CPLSPrintf("%d", nMatrix));
586
0
    osURL.replaceAll("{tileCol}", CPLSPrintf("%d", nColumn));
587
0
    osURL.replaceAll("{tileRow}", CPLSPrintf("%d", nRow));
588
589
0
    CPLString osContentType;
590
0
    if (!this->Download(osURL, nullptr, nullptr, m_osTileData, osContentType,
591
0
                        true, nullptr))
592
0
    {
593
0
        return nullptr;
594
0
    }
595
596
0
    bEmptyContent = m_osTileData.empty();
597
0
    if (bEmptyContent)
598
0
        return nullptr;
599
600
0
    const CPLString osTempFile(VSIMemGenerateHiddenFilename("ogcapi"));
601
0
    VSIFCloseL(VSIFileFromMemBuffer(osTempFile.c_str(),
602
0
                                    reinterpret_cast<GByte *>(&m_osTileData[0]),
603
0
                                    m_osTileData.size(), false));
604
605
0
    GDALDataset *result = nullptr;
606
607
0
    if (osPrefix.empty())
608
0
        result = GDALDataset::Open(osTempFile.c_str(), nOpenTileFlags, nullptr,
609
0
                                   papszOpenTileOptions);
610
0
    else
611
0
        result =
612
0
            GDALDataset::Open((osPrefix + ":" + osTempFile).c_str(),
613
0
                              nOpenTileFlags, nullptr, papszOpenTileOptions);
614
615
0
    VSIUnlink(osTempFile);
616
617
0
    return std::unique_ptr<GDALDataset>(result);
618
0
}
619
620
/************************************************************************/
621
/*                              Identify()                              */
622
/************************************************************************/
623
624
int OGCAPIDataset::Identify(GDALOpenInfo *poOpenInfo)
625
663k
{
626
663k
    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "OGCAPI:"))
627
28
        return TRUE;
628
663k
    if (poOpenInfo->IsExtensionEqualToCI("moaw"))
629
0
        return TRUE;
630
663k
    if (poOpenInfo->IsSingleAllowedDriver("OGCAPI"))
631
0
    {
632
0
        return TRUE;
633
0
    }
634
663k
    return FALSE;
635
663k
}
636
637
/************************************************************************/
638
/*                              BuildURL()                              */
639
/************************************************************************/
640
641
CPLString OGCAPIDataset::BuildURL(const std::string &href) const
642
0
{
643
0
    if (!href.empty() && href[0] == '/')
644
0
        return m_osRootURL + href;
645
0
    return href;
646
0
}
647
648
/************************************************************************/
649
/*                         SetRootURLFromURL()                          */
650
/************************************************************************/
651
652
void OGCAPIDataset::SetRootURLFromURL(const std::string &osURL)
653
0
{
654
0
    const char *pszStr = osURL.c_str();
655
0
    const char *pszPtr = pszStr;
656
0
    if (STARTS_WITH(pszPtr, "http://"))
657
0
        pszPtr += strlen("http://");
658
0
    else if (STARTS_WITH(pszPtr, "https://"))
659
0
        pszPtr += strlen("https://");
660
0
    pszPtr = strchr(pszPtr, '/');
661
0
    if (pszPtr)
662
0
        m_osRootURL.assign(pszStr, pszPtr - pszStr);
663
0
}
664
665
/************************************************************************/
666
/*                            FigureBands()                             */
667
/************************************************************************/
668
669
int OGCAPIDataset::FigureBands(const std::string &osContentType,
670
                               const CPLString &osImageURL)
671
0
{
672
0
    int result = 0;
673
674
0
    if (osContentType == "image/png")
675
0
    {
676
0
        result = 4;
677
0
    }
678
0
    else if (osContentType == "image/jpeg")
679
0
    {
680
0
        result = 3;
681
0
    }
682
0
    else
683
0
    {
684
        // Since we don't know the format download a tile and find out
685
0
        bool bEmptyContent = false;
686
0
        std::unique_ptr<GDALDataset> dataset =
687
0
            OpenTile(osImageURL, 0, 0, 0, bEmptyContent, GDAL_OF_RASTER);
688
689
        // Return the bands from the image, if we didn't get an image then assume 3.
690
0
        result = dataset ? static_cast<int>(dataset->GetBands().size()) : 3;
691
0
    }
692
693
0
    return result;
694
0
}
695
696
/************************************************************************/
697
/*                            InitFromFile()                            */
698
/************************************************************************/
699
700
bool OGCAPIDataset::InitFromFile(GDALOpenInfo *poOpenInfo)
701
0
{
702
0
    CPLJSONDocument oDoc;
703
0
    if (!oDoc.Load(poOpenInfo->pszFilename))
704
0
        return false;
705
0
    auto oProcess = oDoc.GetRoot()["process"];
706
0
    if (oProcess.GetType() != CPLJSONObject::Type::String)
707
0
    {
708
0
        CPLError(CE_Failure, CPLE_AppDefined,
709
0
                 "Cannot find 'process' key in .moaw file");
710
0
        return false;
711
0
    }
712
713
0
    const CPLString osURLProcess(oProcess.ToString());
714
0
    SetRootURLFromURL(osURLProcess);
715
716
0
    GByte *pabyContent = nullptr;
717
0
    vsi_l_offset nSize = 0;
718
0
    if (!VSIIngestFile(poOpenInfo->fpL, nullptr, &pabyContent, &nSize,
719
0
                       1024 * 1024))
720
0
        return false;
721
0
    CPLString osPostContent(reinterpret_cast<const char *>(pabyContent));
722
0
    CPLFree(pabyContent);
723
0
    if (!DownloadJSon(osURLProcess.c_str(), oDoc, osPostContent.c_str()))
724
0
        return false;
725
726
0
    return InitFromCollection(poOpenInfo, oDoc);
727
0
}
728
729
/************************************************************************/
730
/*                            ProcessScale()                            */
731
/************************************************************************/
732
733
bool OGCAPIDataset::ProcessScale(const CPLJSONObject &oScaleDenominator,
734
                                 const double dfXMin, const double dfYMin,
735
                                 const double dfXMax, const double dfYMax)
736
737
0
{
738
0
    double dfRes = 1e-8;  // arbitrary
739
0
    if (oScaleDenominator.IsValid())
740
0
    {
741
0
        const double dfScaleDenominator = oScaleDenominator.ToDouble();
742
0
        constexpr double HALF_CIRCUMFERENCE = 6378137 * M_PI;
743
0
        dfRes = dfScaleDenominator / ((HALF_CIRCUMFERENCE / 180) / 0.28e-3);
744
0
    }
745
0
    if (dfRes == 0.0)
746
0
        return false;
747
748
0
    double dfXSize = (dfXMax - dfXMin) / dfRes;
749
0
    double dfYSize = (dfYMax - dfYMin) / dfRes;
750
0
    while (dfXSize > INT_MAX || dfYSize > INT_MAX)
751
0
    {
752
0
        dfXSize /= 2;
753
0
        dfYSize /= 2;
754
0
    }
755
756
0
    nRasterXSize = std::max(1, static_cast<int>(0.5 + dfXSize));
757
0
    nRasterYSize = std::max(1, static_cast<int>(0.5 + dfYSize));
758
0
    m_gt.xorig = dfXMin;
759
0
    m_gt.xscale = (dfXMax - dfXMin) / nRasterXSize;
760
0
    m_gt.yorig = dfYMax;
761
0
    m_gt.yscale = -(dfYMax - dfYMin) / nRasterYSize;
762
763
0
    return true;
764
0
}
765
766
/************************************************************************/
767
/*                         InitFromCollection()                         */
768
/************************************************************************/
769
770
bool OGCAPIDataset::InitFromCollection(GDALOpenInfo *poOpenInfo,
771
                                       CPLJSONDocument &oDoc)
772
0
{
773
0
    const CPLJSONObject oRoot = oDoc.GetRoot();
774
0
    auto osTitle = oRoot.GetString("title");
775
0
    if (!osTitle.empty())
776
0
    {
777
0
        SetMetadataItem("TITLE", osTitle.c_str());
778
0
    }
779
780
0
    auto oLinks = oRoot.GetArray("links");
781
0
    if (!oLinks.IsValid())
782
0
    {
783
0
        CPLError(CE_Failure, CPLE_AppDefined, "Missing links");
784
0
        return false;
785
0
    }
786
0
    auto oBboxes = oRoot["extent"]["spatial"]["bbox"].ToArray();
787
0
    if (oBboxes.Size() != 1)
788
0
    {
789
0
        CPLError(CE_Failure, CPLE_AppDefined, "Missing bbox");
790
0
        return false;
791
0
    }
792
0
    auto oBbox = oBboxes[0].ToArray();
793
0
    if (oBbox.Size() != 4)
794
0
    {
795
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid bbox");
796
0
        return false;
797
0
    }
798
0
    const bool bBBOXIsInCRS84 =
799
0
        CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINX") == nullptr;
800
0
    const double dfXMin =
801
0
        CPLAtof(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "MINX",
802
0
                                     CPLSPrintf("%.17g", oBbox[0].ToDouble())));
803
0
    const double dfYMin =
804
0
        CPLAtof(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "MINY",
805
0
                                     CPLSPrintf("%.17g", oBbox[1].ToDouble())));
806
0
    const double dfXMax =
807
0
        CPLAtof(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "MAXX",
808
0
                                     CPLSPrintf("%.17g", oBbox[2].ToDouble())));
809
0
    const double dfYMax =
810
0
        CPLAtof(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "MAXY",
811
0
                                     CPLSPrintf("%.17g", oBbox[3].ToDouble())));
812
813
0
    auto oScaleDenominator = oRoot["scaleDenominator"];
814
815
0
    if (!ProcessScale(oScaleDenominator, dfXMin, dfYMin, dfXMax, dfYMax))
816
0
        return false;
817
818
0
    bool bFoundMap = false;
819
820
0
    CPLString osTilesetsMapURL;
821
0
    bool bTilesetsMapURLJson = false;
822
823
0
    CPLString osTilesetsVectorURL;
824
0
    bool bTilesetsVectorURLJson = false;
825
826
0
    CPLString osCoverageURL;
827
0
    bool bCoverageGeotiff = false;
828
829
0
    CPLString osItemsURL;
830
0
    bool bItemsJson = false;
831
832
0
    CPLString osSelfURL;
833
0
    bool bSelfJson = false;
834
835
0
    for (const auto &oLink : oLinks)
836
0
    {
837
0
        const auto osRel = oLink.GetString("rel");
838
0
        const auto osType = oLink.GetString("type");
839
0
        if ((osRel == "http://www.opengis.net/def/rel/ogc/1.0/map" ||
840
0
             osRel == "[ogc-rel:map]") &&
841
0
            (osType == "image/png" || osType == "image/jpeg"))
842
0
        {
843
0
            bFoundMap = true;
844
0
        }
845
0
        else if (!bTilesetsMapURLJson &&
846
0
                 (osRel ==
847
0
                      "http://www.opengis.net/def/rel/ogc/1.0/tilesets-map" ||
848
0
                  osRel == "[ogc-rel:tilesets-map]"))
849
0
        {
850
0
            if (osType == MEDIA_TYPE_JSON)
851
0
            {
852
0
                bTilesetsMapURLJson = true;
853
0
                osTilesetsMapURL = BuildURL(oLink["href"].ToString());
854
0
            }
855
0
            else if (osType.empty())
856
0
            {
857
0
                osTilesetsMapURL = BuildURL(oLink["href"].ToString());
858
0
            }
859
0
        }
860
0
        else if (!bTilesetsVectorURLJson &&
861
0
                 (osRel == "http://www.opengis.net/def/rel/ogc/1.0/"
862
0
                           "tilesets-vector" ||
863
0
                  osRel == "[ogc-rel:tilesets-vector]"))
864
0
        {
865
0
            if (osType == MEDIA_TYPE_JSON)
866
0
            {
867
0
                bTilesetsVectorURLJson = true;
868
0
                osTilesetsVectorURL = BuildURL(oLink["href"].ToString());
869
0
            }
870
0
            else if (osType.empty())
871
0
            {
872
0
                osTilesetsVectorURL = BuildURL(oLink["href"].ToString());
873
0
            }
874
0
        }
875
0
        else if ((osRel == "http://www.opengis.net/def/rel/ogc/1.0/coverage" ||
876
0
                  osRel == "[ogc-rel:coverage]") &&
877
0
                 (osType == "image/tiff; application=geotiff" ||
878
0
                  osType == "application/x-geotiff"))
879
0
        {
880
0
            if (!bCoverageGeotiff)
881
0
            {
882
0
                osCoverageURL = BuildURL(oLink["href"].ToString());
883
0
                bCoverageGeotiff = true;
884
0
            }
885
0
        }
886
0
        else if ((osRel == "http://www.opengis.net/def/rel/ogc/1.0/coverage" ||
887
0
                  osRel == "[ogc-rel:coverage]") &&
888
0
                 osType.empty())
889
0
        {
890
0
            osCoverageURL = BuildURL(oLink["href"].ToString());
891
0
        }
892
0
        else if (!bItemsJson && osRel == "items")
893
0
        {
894
0
            if (osType == MEDIA_TYPE_GEOJSON || osType == MEDIA_TYPE_JSON)
895
0
            {
896
0
                bItemsJson = true;
897
0
                osItemsURL = BuildURL(oLink["href"].ToString());
898
0
            }
899
0
            else if (osType.empty())
900
0
            {
901
0
                osItemsURL = BuildURL(oLink["href"].ToString());
902
0
            }
903
0
        }
904
0
        else if (!bSelfJson && osRel == "self")
905
0
        {
906
0
            if (osType == "application/json")
907
0
            {
908
0
                bSelfJson = true;
909
0
                osSelfURL = BuildURL(oLink["href"].ToString());
910
0
            }
911
0
            else if (osType.empty())
912
0
            {
913
0
                osSelfURL = BuildURL(oLink["href"].ToString());
914
0
            }
915
0
        }
916
0
    }
917
918
0
    if (!bFoundMap && osTilesetsMapURL.empty() && osTilesetsVectorURL.empty() &&
919
0
        osCoverageURL.empty() && osSelfURL.empty() && osItemsURL.empty())
920
0
    {
921
0
        CPLError(CE_Failure, CPLE_AppDefined,
922
0
                 "Missing map, tilesets, coverage or items relation in links");
923
0
        return false;
924
0
    }
925
926
0
    const char *pszAPI =
927
0
        CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "API", "AUTO");
928
0
    if ((EQUAL(pszAPI, "AUTO") || EQUAL(pszAPI, "COVERAGE")) &&
929
0
        !osCoverageURL.empty())
930
0
    {
931
0
        return InitWithCoverageAPI(poOpenInfo, osCoverageURL, dfXMin, dfYMin,
932
0
                                   dfXMax, dfYMax, oDoc.GetRoot());
933
0
    }
934
0
    else if ((EQUAL(pszAPI, "AUTO") || EQUAL(pszAPI, "TILES")) &&
935
0
             (!osTilesetsMapURL.empty() || !osTilesetsVectorURL.empty()))
936
0
    {
937
0
        bool bRet = false;
938
0
        if (!osTilesetsMapURL.empty())
939
0
            bRet = InitWithTilesAPI(poOpenInfo, osTilesetsMapURL, true, dfXMin,
940
0
                                    dfYMin, dfXMax, dfYMax, bBBOXIsInCRS84,
941
0
                                    oDoc.GetRoot());
942
0
        if (!bRet && !osTilesetsVectorURL.empty())
943
0
            bRet = InitWithTilesAPI(poOpenInfo, osTilesetsVectorURL, false,
944
0
                                    dfXMin, dfYMin, dfXMax, dfYMax,
945
0
                                    bBBOXIsInCRS84, oDoc.GetRoot());
946
0
        return bRet;
947
0
    }
948
0
    else if ((EQUAL(pszAPI, "AUTO") || EQUAL(pszAPI, "MAP")) && bFoundMap)
949
0
    {
950
0
        return InitWithMapAPI(poOpenInfo, oRoot, dfXMin, dfYMin, dfXMax,
951
0
                              dfYMax);
952
0
    }
953
0
    else if ((EQUAL(pszAPI, "AUTO") || EQUAL(pszAPI, "ITEMS")) &&
954
0
             !osSelfURL.empty() && !osItemsURL.empty() &&
955
0
             (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0)
956
0
    {
957
0
        m_poOAPIFDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
958
0
            ("OAPIF_COLLECTION:" + osSelfURL).c_str(), GDAL_OF_VECTOR));
959
0
        if (m_poOAPIFDS)
960
0
            return true;
961
0
    }
962
963
0
    CPLError(CE_Failure, CPLE_AppDefined, "API %s requested, but not available",
964
0
             pszAPI);
965
0
    return false;
966
0
}
967
968
/************************************************************************/
969
/*                            InitFromURL()                             */
970
/************************************************************************/
971
972
bool OGCAPIDataset::InitFromURL(GDALOpenInfo *poOpenInfo)
973
14
{
974
14
    const char *pszInitialURL =
975
14
        STARTS_WITH_CI(poOpenInfo->pszFilename, "OGCAPI:")
976
14
            ? poOpenInfo->pszFilename + strlen("OGCAPI:")
977
14
            : poOpenInfo->pszFilename;
978
14
    CPLJSONDocument oDoc;
979
14
    CPLString osURL(pszInitialURL);
980
14
    if (!DownloadJSon(osURL, oDoc))
981
14
        return false;
982
983
0
    SetRootURLFromURL(osURL);
984
985
0
    auto oCollections = oDoc.GetRoot().GetArray("collections");
986
0
    if (!oCollections.IsValid())
987
0
    {
988
0
        if (!oDoc.GetRoot().GetArray("extent").IsValid())
989
0
        {
990
            // If there is no "collections" or "extent" member, then it is
991
            // perhaps a landing page
992
0
            const auto oLinks = oDoc.GetRoot().GetArray("links");
993
0
            osURL.clear();
994
0
            for (const auto &oLink : oLinks)
995
0
            {
996
0
                if (oLink["rel"].ToString() == "data" &&
997
0
                    oLink["type"].ToString() == MEDIA_TYPE_JSON)
998
0
                {
999
0
                    osURL = BuildURL(oLink["href"].ToString());
1000
0
                    break;
1001
0
                }
1002
0
                else if (oLink["rel"].ToString() == "data" &&
1003
0
                         !oLink.GetObj("type").IsValid())
1004
0
                {
1005
0
                    osURL = BuildURL(oLink["href"].ToString());
1006
0
                }
1007
0
            }
1008
0
            if (!osURL.empty())
1009
0
            {
1010
0
                if (!DownloadJSon(osURL, oDoc))
1011
0
                    return false;
1012
0
                oCollections = oDoc.GetRoot().GetArray("collections");
1013
0
            }
1014
0
        }
1015
1016
0
        if (!oCollections.IsValid())
1017
0
        {
1018
            // This is hopefully a /collections/{id} response
1019
0
            return InitFromCollection(poOpenInfo, oDoc);
1020
0
        }
1021
0
    }
1022
1023
    // This is a /collections response
1024
0
    CPLStringList aosSubdatasets;
1025
0
    for (const auto &oCollection : oCollections)
1026
0
    {
1027
0
        const auto osTitle = oCollection.GetString("title");
1028
0
        const auto osLayerDataType = oCollection.GetString("layerDataType");
1029
        // CPLDebug("OGCAPI", "%s: %s", osTitle.c_str(),
1030
        // osLayerDataType.c_str());
1031
0
        if (!osLayerDataType.empty() &&
1032
0
            (EQUAL(osLayerDataType.c_str(), "Raster") ||
1033
0
             EQUAL(osLayerDataType.c_str(), "Coverage")) &&
1034
0
            (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0)
1035
0
        {
1036
0
            continue;
1037
0
        }
1038
0
        if (!osLayerDataType.empty() &&
1039
0
            EQUAL(osLayerDataType.c_str(), "Vector") &&
1040
0
            (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) == 0)
1041
0
        {
1042
0
            continue;
1043
0
        }
1044
0
        osURL.clear();
1045
0
        const auto oLinks = oCollection.GetArray("links");
1046
0
        for (const auto &oLink : oLinks)
1047
0
        {
1048
0
            if (oLink["rel"].ToString() == "self" &&
1049
0
                oLink["type"].ToString() == "application/json")
1050
0
            {
1051
0
                osURL = BuildURL(oLink["href"].ToString());
1052
0
                break;
1053
0
            }
1054
0
            else if (oLink["rel"].ToString() == "self" &&
1055
0
                     oLink.GetString("type").empty())
1056
0
            {
1057
0
                osURL = BuildURL(oLink["href"].ToString());
1058
0
            }
1059
0
        }
1060
0
        if (osURL.empty())
1061
0
        {
1062
0
            continue;
1063
0
        }
1064
0
        const int nIdx = 1 + aosSubdatasets.size() / 2;
1065
0
        aosSubdatasets.AddNameValue(CPLSPrintf("SUBDATASET_%d_NAME", nIdx),
1066
0
                                    CPLSPrintf("OGCAPI:%s", osURL.c_str()));
1067
0
        aosSubdatasets.AddNameValue(
1068
0
            CPLSPrintf("SUBDATASET_%d_DESC", nIdx),
1069
0
            CPLSPrintf("Collection %s", osTitle.c_str()));
1070
0
    }
1071
0
    SetMetadata(aosSubdatasets.List(), GDAL_MDD_SUBDATASETS);
1072
1073
0
    return true;
1074
0
}
1075
1076
/************************************************************************/
1077
/*                           SelectImageURL()                           */
1078
/************************************************************************/
1079
1080
static const std::pair<std::string, std::string>
1081
SelectImageURL(const char *const *papszOptionOptions,
1082
               std::map<std::string, std::string> &oMapItemUrls)
1083
0
{
1084
    // Map IMAGE_FORMATS to their content types. Would be nice if this was
1085
    // globally defined someplace
1086
0
    const std::map<std::string, std::vector<std::string>>
1087
0
        oFormatContentTypeMap = {
1088
0
            {"AUTO",
1089
0
             {"image/png", "image/jpeg", "image/tiff; application=geotiff"}},
1090
0
            {"PNG_PREFERRED",
1091
0
             {"image/png", "image/jpeg", "image/tiff; application=geotiff"}},
1092
0
            {"JPEG_PREFERRED",
1093
0
             {"image/jpeg", "image/png", "image/tiff; application=geotiff"}},
1094
0
            {"PNG", {"image/png"}},
1095
0
            {"JPEG", {"image/jpeg"}},
1096
0
            {"GEOTIFF", {"image/tiff; application=geotiff"}}};
1097
1098
    // Get the IMAGE_FORMAT
1099
0
    const std::string osFormat =
1100
0
        CSLFetchNameValueDef(papszOptionOptions, "IMAGE_FORMAT", "AUTO");
1101
1102
    // Get a list of content types we will search for in priority order based on IMAGE_FORMAT
1103
0
    auto iterFormat = oFormatContentTypeMap.find(osFormat);
1104
0
    if (iterFormat == oFormatContentTypeMap.end())
1105
0
    {
1106
0
        CPLError(CE_Failure, CPLE_AppDefined,
1107
0
                 "Unknown IMAGE_FORMAT specified: %s", osFormat.c_str());
1108
0
        return std::pair<std::string, CPLString>();
1109
0
    }
1110
0
    std::vector<std::string> oContentTypes = iterFormat->second;
1111
1112
    // For "special" IMAGE_FORMATS we will also accept additional content types
1113
    // specified by the server. Note that this will likely result in having
1114
    // some content types duplicated in the vector but that is fine.
1115
0
    if (osFormat == "AUTO" || osFormat == "PNG_PREFERRED" ||
1116
0
        osFormat == "JPEG_PREFERRED")
1117
0
    {
1118
0
        std::transform(oMapItemUrls.begin(), oMapItemUrls.end(),
1119
0
                       std::back_inserter(oContentTypes),
1120
0
                       [](const auto &pair) -> const std::string &
1121
0
                       { return pair.first; });
1122
0
    }
1123
1124
    // Loop over each content type - return the first one we find
1125
0
    for (auto &oContentType : oContentTypes)
1126
0
    {
1127
0
        auto iterContentType = oMapItemUrls.find(oContentType);
1128
0
        if (iterContentType != oMapItemUrls.end())
1129
0
        {
1130
0
            return *iterContentType;
1131
0
        }
1132
0
    }
1133
1134
0
    if (osFormat != "AUTO")
1135
0
    {
1136
0
        CPLError(CE_Failure, CPLE_AppDefined,
1137
0
                 "Server does not support specified IMAGE_FORMAT: %s",
1138
0
                 osFormat.c_str());
1139
0
    }
1140
0
    return std::pair<std::string, CPLString>();
1141
0
}
1142
1143
/************************************************************************/
1144
/*                       SelectVectorFormatURL()                        */
1145
/************************************************************************/
1146
1147
static const CPLString
1148
SelectVectorFormatURL(const char *const *papszOptionOptions,
1149
                      const CPLString &osMVT_URL,
1150
                      const CPLString &osGEOJSON_URL)
1151
0
{
1152
0
    const char *pszFormat =
1153
0
        CSLFetchNameValueDef(papszOptionOptions, "VECTOR_FORMAT", "AUTO");
1154
0
    if (EQUAL(pszFormat, "AUTO") || EQUAL(pszFormat, "MVT_PREFERRED"))
1155
0
        return !osMVT_URL.empty() ? osMVT_URL : osGEOJSON_URL;
1156
0
    else if (EQUAL(pszFormat, "MVT"))
1157
0
        return osMVT_URL;
1158
0
    else if (EQUAL(pszFormat, "GEOJSON"))
1159
0
        return osGEOJSON_URL;
1160
0
    else if (EQUAL(pszFormat, "GEOJSON_PREFERRED"))
1161
0
        return !osGEOJSON_URL.empty() ? osGEOJSON_URL : osMVT_URL;
1162
0
    return CPLString();
1163
0
}
1164
1165
/************************************************************************/
1166
/*                           InitWithMapAPI()                           */
1167
/************************************************************************/
1168
1169
bool OGCAPIDataset::InitWithMapAPI(GDALOpenInfo *poOpenInfo,
1170
                                   const CPLJSONObject &oRoot, double dfXMin,
1171
                                   double dfYMin, double dfXMax, double dfYMax)
1172
0
{
1173
0
    auto oLinks = oRoot["links"].ToArray();
1174
1175
    // Key - mime type, Value url
1176
0
    std::map<std::string, std::string> oMapItemUrls;
1177
1178
0
    for (const auto &oLink : oLinks)
1179
0
    {
1180
0
        if (oLink["rel"].ToString() ==
1181
0
                "http://www.opengis.net/def/rel/ogc/1.0/map" &&
1182
0
            oLink["type"].IsValid())
1183
0
        {
1184
0
            oMapItemUrls[oLink["type"].ToString()] =
1185
0
                BuildURL(oLink["href"].ToString());
1186
0
        }
1187
0
        else
1188
0
        {
1189
            // For lack of additional information assume we are getting some bytes
1190
0
            oMapItemUrls["application/octet-stream"] =
1191
0
                BuildURL(oLink["href"].ToString());
1192
0
        }
1193
0
    }
1194
1195
0
    const std::pair<std::string, std::string> oContentUrlPair =
1196
0
        SelectImageURL(poOpenInfo->papszOpenOptions, oMapItemUrls);
1197
0
    const std::string osContentType = oContentUrlPair.first;
1198
0
    const std::string osImageURL = oContentUrlPair.second;
1199
1200
0
    if (osImageURL.empty())
1201
0
    {
1202
0
        CPLError(CE_Failure, CPLE_AppDefined,
1203
0
                 "Cannot find link to tileset items");
1204
0
        return false;
1205
0
    }
1206
1207
0
    int l_nBands = FigureBands(osContentType, osImageURL);
1208
0
    int nOverviewCount = 0;
1209
0
    int nLargestDim = std::max(nRasterXSize, nRasterYSize);
1210
0
    while (nLargestDim > 256)
1211
0
    {
1212
0
        nOverviewCount++;
1213
0
        nLargestDim /= 2;
1214
0
    }
1215
1216
0
    m_oSRS.importFromEPSG(4326);
1217
0
    m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1218
1219
0
    const bool bCache = CPLTestBool(
1220
0
        CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CACHE", "YES"));
1221
0
    const int nMaxConnections = atoi(
1222
0
        CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "MAX_CONNECTIONS",
1223
0
                             CPLGetConfigOption("GDAL_MAX_CONNECTIONS", "5")));
1224
0
    CPLString osWMS_XML;
1225
0
    char *pszEscapedURL = CPLEscapeString(osImageURL.c_str(), -1, CPLES_XML);
1226
0
    osWMS_XML.Printf("<GDAL_WMS>"
1227
0
                     "    <Service name=\"OGCAPIMaps\">"
1228
0
                     "        <ServerUrl>%s</ServerUrl>"
1229
0
                     "    </Service>"
1230
0
                     "    <DataWindow>"
1231
0
                     "        <UpperLeftX>%.17g</UpperLeftX>"
1232
0
                     "        <UpperLeftY>%.17g</UpperLeftY>"
1233
0
                     "        <LowerRightX>%.17g</LowerRightX>"
1234
0
                     "        <LowerRightY>%.17g</LowerRightY>"
1235
0
                     "        <SizeX>%d</SizeX>"
1236
0
                     "        <SizeY>%d</SizeY>"
1237
0
                     "    </DataWindow>"
1238
0
                     "    <OverviewCount>%d</OverviewCount>"
1239
0
                     "    <BlockSizeX>256</BlockSizeX>"
1240
0
                     "    <BlockSizeY>256</BlockSizeY>"
1241
0
                     "    <BandsCount>%d</BandsCount>"
1242
0
                     "    <MaxConnections>%d</MaxConnections>"
1243
0
                     "    %s"
1244
0
                     "</GDAL_WMS>",
1245
0
                     pszEscapedURL, dfXMin, dfYMax, dfXMax, dfYMin,
1246
0
                     nRasterXSize, nRasterYSize, nOverviewCount, l_nBands,
1247
0
                     nMaxConnections, bCache ? "<Cache />" : "");
1248
0
    CPLFree(pszEscapedURL);
1249
0
    CPLDebug("OGCAPI", "%s", osWMS_XML.c_str());
1250
0
    m_poWMSDS.reset(
1251
0
        GDALDataset::Open(osWMS_XML, GDAL_OF_RASTER | GDAL_OF_INTERNAL));
1252
0
    if (m_poWMSDS == nullptr)
1253
0
        return false;
1254
1255
0
    for (int i = 1; i <= m_poWMSDS->GetRasterCount(); i++)
1256
0
    {
1257
0
        SetBand(i, new OGCAPIMapWrapperBand(this, i));
1258
0
    }
1259
0
    SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL", GDAL_MDD_IMAGE_STRUCTURE);
1260
1261
0
    return true;
1262
0
}
1263
1264
/************************************************************************/
1265
/*                        InitWithCoverageAPI()                         */
1266
/************************************************************************/
1267
1268
bool OGCAPIDataset::InitWithCoverageAPI(GDALOpenInfo *poOpenInfo,
1269
                                        const CPLString &osCoverageURL,
1270
                                        double dfXMin, double dfYMin,
1271
                                        double dfXMax, double dfYMax,
1272
                                        const CPLJSONObject &oJsonCollection)
1273
0
{
1274
0
    int l_nBands = 1;
1275
0
    GDALDataType eDT = GDT_Float32;
1276
1277
0
    auto oRangeType = oJsonCollection["rangeType"];
1278
0
    if (!oRangeType.IsValid())
1279
0
        oRangeType = oJsonCollection["rangetype"];
1280
1281
0
    auto oDomainSet = oJsonCollection["domainset"];
1282
0
    if (!oDomainSet.IsValid())
1283
0
        oDomainSet = oJsonCollection["domainSet"];
1284
1285
0
    if (!oRangeType.IsValid() || !oDomainSet.IsValid())
1286
0
    {
1287
0
        auto oLinks = oJsonCollection.GetArray("links");
1288
0
        for (const auto &oLink : oLinks)
1289
0
        {
1290
0
            const auto osRel = oLink.GetString("rel");
1291
0
            const auto osType = oLink.GetString("type");
1292
0
            if (osRel == "http://www.opengis.net/def/rel/ogc/1.0/"
1293
0
                         "coverage-domainset" &&
1294
0
                (osType == "application/json" || osType.empty()))
1295
0
            {
1296
0
                CPLString osURL = BuildURL(oLink["href"].ToString());
1297
0
                CPLJSONDocument oDoc;
1298
0
                if (DownloadJSon(osURL.c_str(), oDoc))
1299
0
                {
1300
0
                    oDomainSet = oDoc.GetRoot();
1301
0
                }
1302
0
            }
1303
0
            else if (osRel == "http://www.opengis.net/def/rel/ogc/1.0/"
1304
0
                              "coverage-rangetype" &&
1305
0
                     (osType == "application/json" || osType.empty()))
1306
0
            {
1307
0
                CPLString osURL = BuildURL(oLink["href"].ToString());
1308
0
                CPLJSONDocument oDoc;
1309
0
                if (DownloadJSon(osURL.c_str(), oDoc))
1310
0
                {
1311
0
                    oRangeType = oDoc.GetRoot();
1312
0
                }
1313
0
            }
1314
0
        }
1315
0
    }
1316
1317
0
    if (oRangeType.IsValid())
1318
0
    {
1319
0
        auto oField = oRangeType.GetArray("field");
1320
0
        if (oField.IsValid())
1321
0
        {
1322
0
            l_nBands = oField.Size();
1323
            // Such as in https://maps.gnosis.earth/ogcapi/collections/NaturalEarth:raster:HYP_HR_SR_OB_DR/coverage/rangetype?f=json
1324
            // https://github.com/opengeospatial/coverage-implementation-schema/blob/main/standard/schemas/1.1/json/examples/generalGrid/2D_regular.json
1325
0
            std::string osDataType =
1326
0
                oField[0].GetString("encodingInfo/dataType");
1327
0
            if (osDataType.empty())
1328
0
            {
1329
                // Older way?
1330
0
                osDataType = oField[0].GetString("definition");
1331
0
            }
1332
0
            static const std::map<std::string, GDALDataType> oMapTypes = {
1333
                // https://edc-oapi.dev.hub.eox.at/oapi/collections/S2L2A
1334
0
                {"UINT8", GDT_UInt8},
1335
0
                {"INT16", GDT_Int16},
1336
0
                {"UINT16", GDT_UInt16},
1337
0
                {"INT32", GDT_Int32},
1338
0
                {"UINT32", GDT_UInt32},
1339
0
                {"FLOAT32", GDT_Float32},
1340
0
                {"FLOAT64", GDT_Float64},
1341
                // https://test.cubewerx.com/cubewerx/cubeserv/demo/ogcapi/Daraa/collections/Daraa_DTED/coverage/rangetype?f=json
1342
0
                {"ogcType:unsignedByte", GDT_UInt8},
1343
0
                {"ogcType:signedShort", GDT_Int16},
1344
0
                {"ogcType:unsignedShort", GDT_UInt16},
1345
0
                {"ogcType:signedInt", GDT_Int32},
1346
0
                {"ogcType:unsignedInt", GDT_UInt32},
1347
0
                {"ogcType:float32", GDT_Float32},
1348
0
                {"ogcType:float64", GDT_Float64},
1349
0
                {"ogcType:double", GDT_Float64},
1350
0
            };
1351
            // 08-094r1_SWE_Common_Data_Model_2.0_Submission_Package.pdf page
1352
            // 112
1353
0
            auto oIter = oMapTypes.find(
1354
0
                CPLString(osDataType)
1355
0
                    .replaceAll("http://www.opengis.net/def/dataType/OGC/0/",
1356
0
                                "ogcType:"));
1357
0
            if (oIter != oMapTypes.end())
1358
0
            {
1359
0
                eDT = oIter->second;
1360
0
            }
1361
0
            else
1362
0
            {
1363
0
                CPLDebug("OGCAPI", "Unhandled data type: %s",
1364
0
                         osDataType.c_str());
1365
0
            }
1366
0
        }
1367
0
    }
1368
1369
0
    CPLString osXAxisName;
1370
0
    CPLString osYAxisName;
1371
0
    if (oDomainSet.IsValid())
1372
0
    {
1373
0
        auto oAxisLabels = oDomainSet["generalGrid"]["axisLabels"].ToArray();
1374
0
        if (oAxisLabels.IsValid() && oAxisLabels.Size() >= 2)
1375
0
        {
1376
0
            osXAxisName = oAxisLabels[0].ToString();
1377
0
            osYAxisName = oAxisLabels[1].ToString();
1378
0
        }
1379
1380
0
        auto oAxis = oDomainSet["generalGrid"]["axis"].ToArray();
1381
0
        if (oAxis.IsValid() && oAxis.Size() >= 2)
1382
0
        {
1383
0
            double dfXRes = std::abs(oAxis[0].GetDouble("resolution"));
1384
0
            double dfYRes = std::abs(oAxis[1].GetDouble("resolution"));
1385
1386
0
            dfXMin = oAxis[0].GetDouble("lowerBound");
1387
0
            dfXMax = oAxis[0].GetDouble("upperBound");
1388
0
            dfYMin = oAxis[1].GetDouble("lowerBound");
1389
0
            dfYMax = oAxis[1].GetDouble("upperBound");
1390
1391
0
            if (osXAxisName == "Lat")
1392
0
            {
1393
0
                std::swap(dfXRes, dfYRes);
1394
0
                std::swap(dfXMin, dfYMin);
1395
0
                std::swap(dfXMax, dfYMax);
1396
0
            }
1397
1398
0
            double dfXSize = (dfXMax - dfXMin) / dfXRes;
1399
0
            double dfYSize = (dfYMax - dfYMin) / dfYRes;
1400
0
            while (dfXSize > INT_MAX || dfYSize > INT_MAX)
1401
0
            {
1402
0
                dfXSize /= 2;
1403
0
                dfYSize /= 2;
1404
0
            }
1405
1406
0
            nRasterXSize = std::max(1, static_cast<int>(0.5 + dfXSize));
1407
0
            nRasterYSize = std::max(1, static_cast<int>(0.5 + dfYSize));
1408
0
            m_gt.xorig = dfXMin;
1409
0
            m_gt.xscale = (dfXMax - dfXMin) / nRasterXSize;
1410
0
            m_gt.yorig = dfYMax;
1411
0
            m_gt.yscale = -(dfYMax - dfYMin) / nRasterYSize;
1412
0
        }
1413
1414
0
        OGRSpatialReference oSRS;
1415
0
        std::string srsName(oDomainSet["generalGrid"].GetString("srsName"));
1416
0
        bool bSwap = false;
1417
1418
        // Strip of time component, as found in
1419
        // OGCAPI:https://maps.ecere.com/ogcapi/collections/blueMarble
1420
0
        if (STARTS_WITH(srsName.c_str(),
1421
0
                        "http://www.opengis.net/def/crs-compound?1=") &&
1422
0
            srsName.find("&2=http://www.opengis.net/def/crs/OGC/0/") !=
1423
0
                std::string::npos)
1424
0
        {
1425
0
            srsName = srsName.substr(
1426
0
                strlen("http://www.opengis.net/def/crs-compound?1="));
1427
0
            srsName.resize(srsName.find("&2="));
1428
0
        }
1429
1430
0
        if (oSRS.SetFromUserInput(
1431
0
                srsName.c_str(),
1432
0
                OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) ==
1433
0
            OGRERR_NONE)
1434
0
        {
1435
0
            if (oSRS.EPSGTreatsAsLatLong() ||
1436
0
                oSRS.EPSGTreatsAsNorthingEasting())
1437
0
            {
1438
0
                bSwap = true;
1439
0
            }
1440
0
        }
1441
0
        else if (srsName ==
1442
0
                 "https://ows.rasdaman.org/def/crs/EPSG/0/4326")  // HACK
1443
0
        {
1444
0
            bSwap = true;
1445
0
        }
1446
0
        if (bSwap)
1447
0
        {
1448
0
            std::swap(osXAxisName, osYAxisName);
1449
0
        }
1450
0
    }
1451
1452
0
    int nOverviewCount = 0;
1453
0
    int nLargestDim = std::max(nRasterXSize, nRasterYSize);
1454
0
    while (nLargestDim > 256)
1455
0
    {
1456
0
        nOverviewCount++;
1457
0
        nLargestDim /= 2;
1458
0
    }
1459
1460
0
    m_oSRS.importFromEPSG(4326);
1461
0
    m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1462
1463
0
    CPLString osCoverageURLModified(osCoverageURL);
1464
0
    if (osCoverageURLModified.find('&') == std::string::npos &&
1465
0
        osCoverageURLModified.find('?') == std::string::npos)
1466
0
    {
1467
0
        osCoverageURLModified += '?';
1468
0
    }
1469
0
    else
1470
0
    {
1471
0
        osCoverageURLModified += '&';
1472
0
    }
1473
1474
0
    if (!osXAxisName.empty() && !osYAxisName.empty())
1475
0
    {
1476
0
        osCoverageURLModified +=
1477
0
            CPLSPrintf("subset=%s(${minx}:${maxx}),%s(${miny}:${maxy})&"
1478
0
                       "scaleSize=%s(${width}),%s(${height})",
1479
0
                       osXAxisName.c_str(), osYAxisName.c_str(),
1480
0
                       osXAxisName.c_str(), osYAxisName.c_str());
1481
0
    }
1482
0
    else
1483
0
    {
1484
        // FIXME
1485
0
        osCoverageURLModified += "bbox=${minx},${miny},${maxx},${maxy}&"
1486
0
                                 "scaleSize=Lat(${height}),Long(${width})";
1487
0
    }
1488
1489
0
    const bool bCache = CPLTestBool(
1490
0
        CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CACHE", "YES"));
1491
0
    const int nMaxConnections = atoi(
1492
0
        CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "MAX_CONNECTIONS",
1493
0
                             CPLGetConfigOption("GDAL_MAX_CONNECTIONS", "5")));
1494
0
    CPLString osWMS_XML;
1495
0
    char *pszEscapedURL = CPLEscapeString(osCoverageURLModified, -1, CPLES_XML);
1496
0
    std::string osAccept("<Accept>image/tiff;application=geotiff</Accept>");
1497
0
    osWMS_XML.Printf("<GDAL_WMS>"
1498
0
                     "    <Service name=\"OGCAPICoverage\">"
1499
0
                     "        <ServerUrl>%s</ServerUrl>"
1500
0
                     "    </Service>"
1501
0
                     "    <DataWindow>"
1502
0
                     "        <UpperLeftX>%.17g</UpperLeftX>"
1503
0
                     "        <UpperLeftY>%.17g</UpperLeftY>"
1504
0
                     "        <LowerRightX>%.17g</LowerRightX>"
1505
0
                     "        <LowerRightY>%.17g</LowerRightY>"
1506
0
                     "        <SizeX>%d</SizeX>"
1507
0
                     "        <SizeY>%d</SizeY>"
1508
0
                     "    </DataWindow>"
1509
0
                     "    <OverviewCount>%d</OverviewCount>"
1510
0
                     "    <BlockSizeX>256</BlockSizeX>"
1511
0
                     "    <BlockSizeY>256</BlockSizeY>"
1512
0
                     "    <BandsCount>%d</BandsCount>"
1513
0
                     "    <DataType>%s</DataType>"
1514
0
                     "    <MaxConnections>%d</MaxConnections>"
1515
0
                     "    %s"
1516
0
                     "    %s"
1517
0
                     "</GDAL_WMS>",
1518
0
                     pszEscapedURL, dfXMin, dfYMax, dfXMax, dfYMin,
1519
0
                     nRasterXSize, nRasterYSize, nOverviewCount, l_nBands,
1520
0
                     GDALGetDataTypeName(eDT), nMaxConnections,
1521
0
                     osAccept.c_str(), bCache ? "<Cache />" : "");
1522
0
    CPLFree(pszEscapedURL);
1523
0
    CPLDebug("OGCAPI", "%s", osWMS_XML.c_str());
1524
0
    m_poWMSDS.reset(
1525
0
        GDALDataset::Open(osWMS_XML, GDAL_OF_RASTER | GDAL_OF_INTERNAL));
1526
0
    if (m_poWMSDS == nullptr)
1527
0
        return false;
1528
1529
0
    for (int i = 1; i <= m_poWMSDS->GetRasterCount(); i++)
1530
0
    {
1531
0
        SetBand(i, new OGCAPIMapWrapperBand(this, i));
1532
0
    }
1533
0
    SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL", GDAL_MDD_IMAGE_STRUCTURE);
1534
1535
0
    return true;
1536
0
}
1537
1538
/************************************************************************/
1539
/*                        OGCAPIMapWrapperBand()                        */
1540
/************************************************************************/
1541
1542
OGCAPIMapWrapperBand::OGCAPIMapWrapperBand(OGCAPIDataset *poDSIn, int nBandIn)
1543
0
{
1544
0
    poDS = poDSIn;
1545
0
    nBand = nBandIn;
1546
0
    eDataType = poDSIn->m_poWMSDS->GetRasterBand(nBand)->GetRasterDataType();
1547
0
    poDSIn->m_poWMSDS->GetRasterBand(nBand)->GetBlockSize(&nBlockXSize,
1548
0
                                                          &nBlockYSize);
1549
0
}
1550
1551
/************************************************************************/
1552
/*                             IReadBlock()                             */
1553
/************************************************************************/
1554
1555
CPLErr OGCAPIMapWrapperBand::IReadBlock(int nBlockXOff, int nBlockYOff,
1556
                                        void *pImage)
1557
0
{
1558
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
1559
0
    return poGDS->m_poWMSDS->GetRasterBand(nBand)->ReadBlock(
1560
0
        nBlockXOff, nBlockYOff, pImage);
1561
0
}
1562
1563
/************************************************************************/
1564
/*                             IRasterIO()                              */
1565
/************************************************************************/
1566
1567
CPLErr OGCAPIMapWrapperBand::IRasterIO(
1568
    GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
1569
    void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
1570
    GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg *psExtraArg)
1571
0
{
1572
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
1573
0
    return poGDS->m_poWMSDS->GetRasterBand(nBand)->RasterIO(
1574
0
        eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
1575
0
        eBufType, nPixelSpace, nLineSpace, psExtraArg);
1576
0
}
1577
1578
/************************************************************************/
1579
/*                          GetOverviewCount()                          */
1580
/************************************************************************/
1581
1582
int OGCAPIMapWrapperBand::GetOverviewCount()
1583
0
{
1584
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
1585
0
    return poGDS->m_poWMSDS->GetRasterBand(nBand)->GetOverviewCount();
1586
0
}
1587
1588
/************************************************************************/
1589
/*                            GetOverview()                             */
1590
/************************************************************************/
1591
1592
GDALRasterBand *OGCAPIMapWrapperBand::GetOverview(int nLevel)
1593
0
{
1594
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
1595
0
    return poGDS->m_poWMSDS->GetRasterBand(nBand)->GetOverview(nLevel);
1596
0
}
1597
1598
/************************************************************************/
1599
/*                       GetColorInterpretation()                       */
1600
/************************************************************************/
1601
1602
GDALColorInterp OGCAPIMapWrapperBand::GetColorInterpretation()
1603
0
{
1604
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
1605
    // The WMS driver returns Grey-Alpha for 2 band, RGB(A) for 3 or 4 bands
1606
    // Restrict that behavior to Byte only data.
1607
0
    if (eDataType == GDT_UInt8)
1608
0
        return poGDS->m_poWMSDS->GetRasterBand(nBand)->GetColorInterpretation();
1609
0
    return GCI_Undefined;
1610
0
}
1611
1612
/************************************************************************/
1613
/*                           ParseXMLSchema()                           */
1614
/************************************************************************/
1615
1616
static bool
1617
ParseXMLSchema(const std::string &osURL,
1618
               std::vector<std::unique_ptr<OGRFieldDefn>> &apoFields,
1619
               OGRwkbGeometryType &eGeomType)
1620
0
{
1621
0
    CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1622
1623
0
    std::vector<GMLFeatureClass *> apoClasses;
1624
0
    bool bFullyUnderstood = false;
1625
0
    bool bUseSchemaImports = false;
1626
0
    bool bHaveSchema = GMLParseXSD(osURL.c_str(), bUseSchemaImports, apoClasses,
1627
0
                                   bFullyUnderstood);
1628
0
    if (bHaveSchema && apoClasses.size() == 1)
1629
0
    {
1630
0
        auto poGMLFeatureClass = apoClasses[0];
1631
0
        if (poGMLFeatureClass->GetGeometryPropertyCount() == 1 &&
1632
0
            poGMLFeatureClass->GetGeometryProperty(0)->GetType() != wkbUnknown)
1633
0
        {
1634
0
            eGeomType = static_cast<OGRwkbGeometryType>(
1635
0
                poGMLFeatureClass->GetGeometryProperty(0)->GetType());
1636
0
        }
1637
1638
0
        const int nPropertyCount = poGMLFeatureClass->GetPropertyCount();
1639
0
        for (int iField = 0; iField < nPropertyCount; iField++)
1640
0
        {
1641
0
            const auto poProperty = poGMLFeatureClass->GetProperty(iField);
1642
0
            OGRFieldSubType eSubType = OFSTNone;
1643
0
            const OGRFieldType eFType =
1644
0
                GML_GetOGRFieldType(poProperty->GetType(), eSubType);
1645
1646
0
            const char *pszName = poProperty->GetName();
1647
0
            auto poField = std::make_unique<OGRFieldDefn>(pszName, eFType);
1648
0
            poField->SetSubType(eSubType);
1649
0
            apoFields.emplace_back(std::move(poField));
1650
0
        }
1651
0
        delete poGMLFeatureClass;
1652
0
        return true;
1653
0
    }
1654
1655
0
    for (auto poFeatureClass : apoClasses)
1656
0
        delete poFeatureClass;
1657
1658
0
    return false;
1659
0
}
1660
1661
/************************************************************************/
1662
/*                          InitWithTilesAPI()                          */
1663
/************************************************************************/
1664
1665
bool OGCAPIDataset::InitWithTilesAPI(GDALOpenInfo *poOpenInfo,
1666
                                     const CPLString &osTilesURL, bool bIsMap,
1667
                                     double dfXMin, double dfYMin,
1668
                                     double dfXMax, double dfYMax,
1669
                                     bool bBBOXIsInCRS84,
1670
                                     const CPLJSONObject &oJsonCollection)
1671
0
{
1672
0
    CPLJSONDocument oDoc;
1673
0
    if (!DownloadJSon(osTilesURL.c_str(), oDoc))
1674
0
        return false;
1675
1676
0
    auto oTilesets = oDoc.GetRoot()["tilesets"].ToArray();
1677
0
    if (oTilesets.Size() == 0)
1678
0
    {
1679
0
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot find tilesets");
1680
0
        return false;
1681
0
    }
1682
0
    const char *pszRequiredTileMatrixSet =
1683
0
        CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TILEMATRIXSET");
1684
0
    const char *pszPreferredTileMatrixSet = CSLFetchNameValue(
1685
0
        poOpenInfo->papszOpenOptions, "PREFERRED_TILEMATRIXSET");
1686
0
    CPLString osTilesetURL;
1687
0
    for (const auto &oTileset : oTilesets)
1688
0
    {
1689
0
        const auto oTileMatrixSetURI = oTileset.GetString("tileMatrixSetURI");
1690
0
        const auto oLinks = oTileset.GetArray("links");
1691
0
        if (bIsMap)
1692
0
        {
1693
0
            if (oTileset.GetString("dataType") != "map")
1694
0
                continue;
1695
0
        }
1696
0
        else
1697
0
        {
1698
0
            if (oTileset.GetString("dataType") != "vector")
1699
0
                continue;
1700
0
        }
1701
0
        if (!oLinks.IsValid())
1702
0
        {
1703
0
            CPLDebug("OGCAPI", "Missing links for a tileset");
1704
0
            continue;
1705
0
        }
1706
0
        if (pszRequiredTileMatrixSet != nullptr &&
1707
0
            oTileMatrixSetURI.find(pszRequiredTileMatrixSet) ==
1708
0
                std::string::npos)
1709
0
        {
1710
0
            continue;
1711
0
        }
1712
0
        CPLString osCandidateTilesetURL;
1713
0
        for (const auto &oLink : oLinks)
1714
0
        {
1715
0
            if (oLink["rel"].ToString() == "self")
1716
0
            {
1717
0
                const auto osType = oLink["type"].ToString();
1718
0
                if (osType == MEDIA_TYPE_JSON)
1719
0
                {
1720
0
                    osCandidateTilesetURL = BuildURL(oLink["href"].ToString());
1721
0
                    break;
1722
0
                }
1723
0
                else if (osType.empty())
1724
0
                {
1725
0
                    osCandidateTilesetURL = BuildURL(oLink["href"].ToString());
1726
0
                }
1727
0
            }
1728
0
        }
1729
0
        if (pszRequiredTileMatrixSet != nullptr)
1730
0
        {
1731
0
            osTilesetURL = std::move(osCandidateTilesetURL);
1732
0
        }
1733
0
        else if (pszPreferredTileMatrixSet != nullptr &&
1734
0
                 !osCandidateTilesetURL.empty() &&
1735
0
                 (oTileMatrixSetURI.find(pszPreferredTileMatrixSet) !=
1736
0
                  std::string::npos))
1737
0
        {
1738
0
            osTilesetURL = std::move(osCandidateTilesetURL);
1739
0
        }
1740
0
        else if (oTileMatrixSetURI.find("WorldCRS84Quad") != std::string::npos)
1741
0
        {
1742
0
            osTilesetURL = std::move(osCandidateTilesetURL);
1743
0
        }
1744
0
        else if (osTilesetURL.empty())
1745
0
        {
1746
0
            osTilesetURL = std::move(osCandidateTilesetURL);
1747
0
        }
1748
0
    }
1749
0
    if (osTilesetURL.empty())
1750
0
    {
1751
0
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot find tilematrixset");
1752
0
        return false;
1753
0
    }
1754
1755
    // Download and parse selected tileset definition
1756
0
    if (!DownloadJSon(osTilesetURL.c_str(), oDoc))
1757
0
        return false;
1758
1759
0
    const auto oLinks = oDoc.GetRoot().GetArray("links");
1760
0
    if (!oLinks.IsValid())
1761
0
    {
1762
0
        CPLError(CE_Failure, CPLE_AppDefined, "Missing links for tileset");
1763
0
        return false;
1764
0
    }
1765
1766
    // Key - mime type, Value url
1767
0
    std::map<std::string, std::string> oMapItemUrls;
1768
0
    CPLString osMVT_URL;
1769
0
    CPLString osGEOJSON_URL;
1770
0
    CPLString osTilingSchemeURL;
1771
0
    bool bTilingSchemeURLJson = false;
1772
1773
0
    for (const auto &oLink : oLinks)
1774
0
    {
1775
0
        const auto osRel = oLink.GetString("rel");
1776
0
        const auto osType = oLink.GetString("type");
1777
1778
0
        if (!bTilingSchemeURLJson &&
1779
0
            osRel == "http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme")
1780
0
        {
1781
0
            if (osType == MEDIA_TYPE_JSON)
1782
0
            {
1783
0
                bTilingSchemeURLJson = true;
1784
0
                osTilingSchemeURL = BuildURL(oLink["href"].ToString());
1785
0
            }
1786
0
            else if (osType.empty())
1787
0
            {
1788
0
                osTilingSchemeURL = BuildURL(oLink["href"].ToString());
1789
0
            }
1790
0
        }
1791
0
        else if (bIsMap)
1792
0
        {
1793
0
            if (osRel == "item" && !osType.empty())
1794
0
            {
1795
0
                oMapItemUrls[osType] = BuildURL(oLink["href"].ToString());
1796
0
            }
1797
0
            else if (osRel == "item")
1798
0
            {
1799
                // For lack of additional information assume we are getting some bytes
1800
0
                oMapItemUrls["application/octet-stream"] =
1801
0
                    BuildURL(oLink["href"].ToString());
1802
0
            }
1803
0
        }
1804
0
        else
1805
0
        {
1806
0
            if (osRel == "item" &&
1807
0
                osType == "application/vnd.mapbox-vector-tile")
1808
0
            {
1809
0
                osMVT_URL = BuildURL(oLink["href"].ToString());
1810
0
            }
1811
0
            else if (osRel == "item" && osType == "application/geo+json")
1812
0
            {
1813
0
                osGEOJSON_URL = BuildURL(oLink["href"].ToString());
1814
0
            }
1815
0
        }
1816
0
    }
1817
1818
0
    if (osTilingSchemeURL.empty())
1819
0
    {
1820
0
        CPLError(
1821
0
            CE_Failure, CPLE_AppDefined,
1822
0
            "Cannot find http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme");
1823
0
        return false;
1824
0
    }
1825
1826
    // Parse tile matrix set limits.
1827
0
    const auto oTileMatrixSetLimits =
1828
0
        oDoc.GetRoot().GetArray("tileMatrixSetLimits");
1829
1830
0
    struct Limits
1831
0
    {
1832
0
        int minTileRow;
1833
0
        int maxTileRow;
1834
0
        int minTileCol;
1835
0
        int maxTileCol;
1836
0
    };
1837
1838
0
    std::map<CPLString, Limits> oMapTileMatrixSetLimits;
1839
0
    if (CPLTestBool(
1840
0
            CPLGetConfigOption("GDAL_OGCAPI_TILEMATRIXSET_LIMITS", "YES")))
1841
0
    {
1842
0
        for (const auto &jsonLimit : oTileMatrixSetLimits)
1843
0
        {
1844
0
            const auto osTileMatrix = jsonLimit.GetString("tileMatrix");
1845
0
            if (!osTileMatrix.empty())
1846
0
            {
1847
0
                Limits limits;
1848
0
                limits.minTileRow = jsonLimit.GetInteger("minTileRow");
1849
0
                limits.maxTileRow = jsonLimit.GetInteger("maxTileRow");
1850
0
                limits.minTileCol = jsonLimit.GetInteger("minTileCol");
1851
0
                limits.maxTileCol = jsonLimit.GetInteger("maxTileCol");
1852
0
                if (limits.minTileRow > limits.maxTileRow)
1853
0
                    continue;  // shouldn't happen on valid data
1854
0
                oMapTileMatrixSetLimits[osTileMatrix] = limits;
1855
0
            }
1856
0
        }
1857
0
    }
1858
1859
0
    const std::pair<std::string, std::string> oContentUrlPair =
1860
0
        SelectImageURL(poOpenInfo->papszOpenOptions, oMapItemUrls);
1861
0
    const std::string osContentType = oContentUrlPair.first;
1862
0
    const std::string osRasterURL = oContentUrlPair.second;
1863
1864
0
    const CPLString osVectorURL = SelectVectorFormatURL(
1865
0
        poOpenInfo->papszOpenOptions, osMVT_URL, osGEOJSON_URL);
1866
0
    if (osRasterURL.empty() && osVectorURL.empty())
1867
0
    {
1868
0
        CPLError(CE_Failure, CPLE_AppDefined,
1869
0
                 "Cannot find link to PNG, JPEG, MVT or GeoJSON tiles");
1870
0
        return false;
1871
0
    }
1872
1873
0
    for (const char *pszNeedle : {"{tileMatrix}", "{tileRow}", "{tileCol}"})
1874
0
    {
1875
0
        if (!osRasterURL.empty() &&
1876
0
            osRasterURL.find(pszNeedle) == std::string::npos)
1877
0
        {
1878
0
            CPLError(CE_Failure, CPLE_AppDefined, "%s missing in tile URL %s",
1879
0
                     pszNeedle, osRasterURL.c_str());
1880
0
            return false;
1881
0
        }
1882
0
        if (!osVectorURL.empty() &&
1883
0
            osVectorURL.find(pszNeedle) == std::string::npos)
1884
0
        {
1885
0
            CPLError(CE_Failure, CPLE_AppDefined, "%s missing in tile URL %s",
1886
0
                     pszNeedle, osVectorURL.c_str());
1887
0
            return false;
1888
0
        }
1889
0
    }
1890
1891
    // Download and parse tile matrix set definition
1892
0
    if (!DownloadJSon(osTilingSchemeURL.c_str(), oDoc, nullptr,
1893
0
                      MEDIA_TYPE_JSON))
1894
0
        return false;
1895
1896
0
    auto tms = gdal::TileMatrixSet::parse(oDoc.SaveAsString().c_str());
1897
0
    if (tms == nullptr)
1898
0
        return false;
1899
1900
0
    if (m_oSRS.SetFromUserInput(
1901
0
            tms->crs().c_str(),
1902
0
            OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
1903
0
        OGRERR_NONE)
1904
0
        return false;
1905
0
    const bool bInvertAxis = m_oSRS.EPSGTreatsAsLatLong() != FALSE ||
1906
0
                             m_oSRS.EPSGTreatsAsNorthingEasting() != FALSE;
1907
0
    m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1908
1909
0
    bool bFoundSomething = false;
1910
0
    if (!osVectorURL.empty() && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0)
1911
0
    {
1912
0
        const auto osVectorType = oJsonCollection.GetString("vectorType");
1913
0
        OGRwkbGeometryType eGeomType = wkbUnknown;
1914
0
        if (osVectorType == "Points")
1915
0
            eGeomType = wkbPoint;
1916
0
        else if (osVectorType == "Lines")
1917
0
            eGeomType = wkbMultiLineString;
1918
0
        else if (osVectorType == "Polygons")
1919
0
            eGeomType = wkbMultiPolygon;
1920
1921
0
        CPLString osXMLSchemaURL;
1922
0
        for (const auto &oLink : oJsonCollection.GetArray("links"))
1923
0
        {
1924
0
            if (oLink["rel"].ToString() == "describedBy" &&
1925
0
                oLink["type"].ToString() == "text/xml")
1926
0
            {
1927
0
                osXMLSchemaURL = BuildURL(oLink["href"].ToString());
1928
0
            }
1929
0
        }
1930
1931
0
        std::vector<std::unique_ptr<OGRFieldDefn>> apoFields;
1932
0
        bool bGotSchema = false;
1933
0
        if (!osXMLSchemaURL.empty())
1934
0
        {
1935
0
            bGotSchema = ParseXMLSchema(osXMLSchemaURL, apoFields, eGeomType);
1936
0
        }
1937
1938
0
        for (const auto &tileMatrix : tms->tileMatrixList())
1939
0
        {
1940
0
            const double dfOriX =
1941
0
                bInvertAxis ? tileMatrix.mTopLeftY : tileMatrix.mTopLeftX;
1942
0
            const double dfOriY =
1943
0
                bInvertAxis ? tileMatrix.mTopLeftX : tileMatrix.mTopLeftY;
1944
1945
0
            auto oLimitsIter = oMapTileMatrixSetLimits.find(tileMatrix.mId);
1946
0
            if (!oMapTileMatrixSetLimits.empty() &&
1947
0
                oLimitsIter == oMapTileMatrixSetLimits.end())
1948
0
            {
1949
                // Tile matrix level not in known limits
1950
0
                continue;
1951
0
            }
1952
0
            int minCol = std::max(
1953
0
                0, static_cast<int>((dfXMin - dfOriX) / tileMatrix.mResX /
1954
0
                                    tileMatrix.mTileWidth));
1955
0
            int maxCol =
1956
0
                std::min(tileMatrix.mMatrixWidth - 1,
1957
0
                         static_cast<int>((dfXMax - dfOriX) / tileMatrix.mResX /
1958
0
                                          tileMatrix.mTileWidth));
1959
0
            int minRow = std::max(
1960
0
                0, static_cast<int>((dfOriY - dfYMax) / tileMatrix.mResY /
1961
0
                                    tileMatrix.mTileHeight));
1962
0
            int maxRow =
1963
0
                std::min(tileMatrix.mMatrixHeight - 1,
1964
0
                         static_cast<int>((dfOriY - dfYMin) / tileMatrix.mResY /
1965
0
                                          tileMatrix.mTileHeight));
1966
0
            if (oLimitsIter != oMapTileMatrixSetLimits.end())
1967
0
            {
1968
                // Take into account tileMatrixSetLimits
1969
0
                minCol = std::max(minCol, oLimitsIter->second.minTileCol);
1970
0
                minRow = std::max(minRow, oLimitsIter->second.minTileRow);
1971
0
                maxCol = std::min(maxCol, oLimitsIter->second.maxTileCol);
1972
0
                maxRow = std::min(maxRow, oLimitsIter->second.maxTileRow);
1973
0
                if (minCol > maxCol || minRow > maxRow)
1974
0
                {
1975
0
                    continue;
1976
0
                }
1977
0
            }
1978
0
            auto poLayer = std::make_unique<OGCAPITiledLayer>(
1979
0
                this, bInvertAxis, osVectorURL, osVectorURL == osMVT_URL,
1980
0
                tileMatrix, eGeomType);
1981
0
            poLayer->SetMinMaxXY(minCol, minRow, maxCol, maxRow);
1982
0
            poLayer->SetExtent(dfXMin, dfYMin, dfXMax, dfYMax);
1983
0
            if (bGotSchema)
1984
0
                poLayer->SetFields(apoFields);
1985
0
            m_apoLayers.emplace_back(std::move(poLayer));
1986
0
        }
1987
1988
0
        bFoundSomething = true;
1989
0
    }
1990
1991
0
    if (!osRasterURL.empty() && (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0)
1992
0
    {
1993
0
        if (bBBOXIsInCRS84)
1994
0
        {
1995
            // Reproject the extent if needed
1996
0
            OGRSpatialReference oCRS84;
1997
0
            oCRS84.importFromEPSG(4326);
1998
0
            oCRS84.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1999
0
            auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
2000
0
                OGRCreateCoordinateTransformation(&oCRS84, &m_oSRS));
2001
0
            if (poCT)
2002
0
            {
2003
0
                poCT->TransformBounds(dfXMin, dfYMin, dfXMax, dfYMax, &dfXMin,
2004
0
                                      &dfYMin, &dfXMax, &dfYMax, 21);
2005
0
            }
2006
0
        }
2007
2008
0
        const bool bCache = CPLTestBool(
2009
0
            CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CACHE", "YES"));
2010
0
        const int nMaxConnections = atoi(CSLFetchNameValueDef(
2011
0
            poOpenInfo->papszOpenOptions, "MAX_CONNECTIONS",
2012
0
            CPLGetConfigOption("GDAL_WMS_MAX_CONNECTIONS", "5")));
2013
0
        const char *pszTileMatrix =
2014
0
            CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TILEMATRIX");
2015
2016
0
        int l_nBands = FigureBands(osContentType, osRasterURL);
2017
2018
0
        for (const auto &tileMatrix : tms->tileMatrixList())
2019
0
        {
2020
0
            if (pszTileMatrix && !EQUAL(tileMatrix.mId.c_str(), pszTileMatrix))
2021
0
            {
2022
0
                continue;
2023
0
            }
2024
0
            if (tileMatrix.mTileWidth == 0 ||
2025
0
                tileMatrix.mMatrixWidth > INT_MAX / tileMatrix.mTileWidth ||
2026
0
                tileMatrix.mTileHeight == 0 ||
2027
0
                tileMatrix.mMatrixHeight > INT_MAX / tileMatrix.mTileHeight)
2028
0
            {
2029
                // Too resoluted for GDAL limits
2030
0
                break;
2031
0
            }
2032
0
            auto oLimitsIter = oMapTileMatrixSetLimits.find(tileMatrix.mId);
2033
0
            if (!oMapTileMatrixSetLimits.empty() &&
2034
0
                oLimitsIter == oMapTileMatrixSetLimits.end())
2035
0
            {
2036
                // Tile matrix level not in known limits
2037
0
                continue;
2038
0
            }
2039
2040
0
            if (dfXMax - dfXMin < tileMatrix.mResX ||
2041
0
                dfYMax - dfYMin < tileMatrix.mResY)
2042
0
            {
2043
                // skip levels for which the extent is smaller than the size
2044
                // of one pixel
2045
0
                continue;
2046
0
            }
2047
2048
0
            CPLString osURL(osRasterURL);
2049
0
            osURL.replaceAll("{tileMatrix}", tileMatrix.mId.c_str());
2050
0
            osURL.replaceAll("{tileRow}", "${y}");
2051
0
            osURL.replaceAll("{tileCol}", "${x}");
2052
2053
0
            const double dfOriX =
2054
0
                bInvertAxis ? tileMatrix.mTopLeftY : tileMatrix.mTopLeftX;
2055
0
            const double dfOriY =
2056
0
                bInvertAxis ? tileMatrix.mTopLeftX : tileMatrix.mTopLeftY;
2057
2058
0
            const auto CreateWMS_XML =
2059
0
                [=, &osURL, &tileMatrix](int minRow, int rowCount,
2060
0
                                         int nCoalesce, double &dfStripMinY,
2061
0
                                         double &dfStripMaxY)
2062
0
            {
2063
0
                int minCol = 0;
2064
0
                int maxCol = tileMatrix.mMatrixWidth - 1;
2065
0
                int maxRow = minRow + rowCount - 1;
2066
0
                double dfStripMinX =
2067
0
                    dfOriX + minCol * tileMatrix.mTileWidth * tileMatrix.mResX;
2068
0
                double dfStripMaxX = dfOriX + (maxCol + 1) *
2069
0
                                                  tileMatrix.mTileWidth *
2070
0
                                                  tileMatrix.mResX;
2071
0
                dfStripMaxY =
2072
0
                    dfOriY - minRow * tileMatrix.mTileHeight * tileMatrix.mResY;
2073
0
                dfStripMinY = dfOriY - (maxRow + 1) * tileMatrix.mTileHeight *
2074
0
                                           tileMatrix.mResY;
2075
0
                CPLString osWMS_XML;
2076
0
                char *pszEscapedURL = CPLEscapeString(osURL, -1, CPLES_XML);
2077
0
                osWMS_XML.Printf(
2078
0
                    "<GDAL_WMS>"
2079
0
                    "    <Service name=\"TMS\">"
2080
0
                    "        <ServerUrl>%s</ServerUrl>"
2081
0
                    "        <TileXMultiplier>%d</TileXMultiplier>"
2082
0
                    "    </Service>"
2083
0
                    "    <DataWindow>"
2084
0
                    "        <UpperLeftX>%.17g</UpperLeftX>"
2085
0
                    "        <UpperLeftY>%.17g</UpperLeftY>"
2086
0
                    "        <LowerRightX>%.17g</LowerRightX>"
2087
0
                    "        <LowerRightY>%.17g</LowerRightY>"
2088
0
                    "        <TileLevel>0</TileLevel>"
2089
0
                    "        <TileY>%d</TileY>"
2090
0
                    "        <SizeX>%d</SizeX>"
2091
0
                    "        <SizeY>%d</SizeY>"
2092
0
                    "        <YOrigin>top</YOrigin>"
2093
0
                    "    </DataWindow>"
2094
0
                    "    <BlockSizeX>%d</BlockSizeX>"
2095
0
                    "    <BlockSizeY>%d</BlockSizeY>"
2096
0
                    "    <BandsCount>%d</BandsCount>"
2097
0
                    "    <MaxConnections>%d</MaxConnections>"
2098
0
                    "    %s"
2099
0
                    "</GDAL_WMS>",
2100
0
                    pszEscapedURL, nCoalesce, dfStripMinX, dfStripMaxY,
2101
0
                    dfStripMaxX, dfStripMinY, minRow,
2102
0
                    (maxCol - minCol + 1) / nCoalesce * tileMatrix.mTileWidth,
2103
0
                    rowCount * tileMatrix.mTileHeight, tileMatrix.mTileWidth,
2104
0
                    tileMatrix.mTileHeight, l_nBands, nMaxConnections,
2105
0
                    bCache ? "<Cache />" : "");
2106
0
                CPLFree(pszEscapedURL);
2107
0
                return osWMS_XML;
2108
0
            };
2109
2110
0
            auto vmwl = tileMatrix.mVariableMatrixWidthList;
2111
0
            if (vmwl.empty())
2112
0
            {
2113
0
                double dfIgnored1, dfIgnored2;
2114
0
                CPLString osWMS_XML(CreateWMS_XML(0, tileMatrix.mMatrixHeight,
2115
0
                                                  1, dfIgnored1, dfIgnored2));
2116
0
                if (osWMS_XML.empty())
2117
0
                    continue;
2118
0
                std::unique_ptr<GDALDataset> poDS(GDALDataset::Open(
2119
0
                    osWMS_XML, GDAL_OF_RASTER | GDAL_OF_INTERNAL));
2120
0
                if (!poDS)
2121
0
                    return false;
2122
0
                m_apoDatasetsAssembled.emplace_back(std::move(poDS));
2123
0
            }
2124
0
            else
2125
0
            {
2126
0
                std::sort(vmwl.begin(), vmwl.end(),
2127
0
                          [](const gdal::TileMatrixSet::TileMatrix::
2128
0
                                 VariableMatrixWidth &a,
2129
0
                             const gdal::TileMatrixSet::TileMatrix::
2130
0
                                 VariableMatrixWidth &b)
2131
0
                          { return a.mMinTileRow < b.mMinTileRow; });
2132
0
                std::vector<GDALDatasetH> apoStrippedDS;
2133
                // For each variable matrix width, create a separate WMS dataset
2134
                // with the correspond strip
2135
0
                for (size_t i = 0; i < vmwl.size(); i++)
2136
0
                {
2137
0
                    if (vmwl[i].mCoalesce <= 0 ||
2138
0
                        (tileMatrix.mMatrixWidth % vmwl[i].mCoalesce) != 0)
2139
0
                    {
2140
0
                        CPLError(CE_Failure, CPLE_AppDefined,
2141
0
                                 "Invalid coalesce factor (%d) w.r.t matrix "
2142
0
                                 "width (%d)",
2143
0
                                 vmwl[i].mCoalesce, tileMatrix.mMatrixWidth);
2144
0
                        return false;
2145
0
                    }
2146
0
                    {
2147
0
                        double dfStripMinY = 0;
2148
0
                        double dfStripMaxY = 0;
2149
0
                        CPLString osWMS_XML(CreateWMS_XML(
2150
0
                            vmwl[i].mMinTileRow,
2151
0
                            vmwl[i].mMaxTileRow - vmwl[i].mMinTileRow + 1,
2152
0
                            vmwl[i].mCoalesce, dfStripMinY, dfStripMaxY));
2153
0
                        if (osWMS_XML.empty())
2154
0
                            continue;
2155
0
                        if (dfStripMinY < dfYMax && dfStripMaxY > dfYMin)
2156
0
                        {
2157
0
                            std::unique_ptr<GDALDataset> poDS(GDALDataset::Open(
2158
0
                                osWMS_XML, GDAL_OF_RASTER | GDAL_OF_INTERNAL));
2159
0
                            if (!poDS)
2160
0
                                return false;
2161
0
                            m_apoDatasetsElementary.emplace_back(
2162
0
                                std::move(poDS));
2163
0
                            apoStrippedDS.emplace_back(GDALDataset::ToHandle(
2164
0
                                m_apoDatasetsElementary.back().get()));
2165
0
                        }
2166
0
                    }
2167
2168
                    // Add a strip for non-coalesced tiles
2169
0
                    if (i + 1 < vmwl.size() &&
2170
0
                        vmwl[i].mMaxTileRow + 1 != vmwl[i + 1].mMinTileRow)
2171
0
                    {
2172
0
                        double dfStripMinY = 0;
2173
0
                        double dfStripMaxY = 0;
2174
0
                        CPLString osWMS_XML(CreateWMS_XML(
2175
0
                            vmwl[i].mMaxTileRow + 1,
2176
0
                            vmwl[i + 1].mMinTileRow - vmwl[i].mMaxTileRow - 1,
2177
0
                            1, dfStripMinY, dfStripMaxY));
2178
0
                        if (osWMS_XML.empty())
2179
0
                            continue;
2180
0
                        if (dfStripMinY < dfYMax && dfStripMaxY > dfYMin)
2181
0
                        {
2182
0
                            std::unique_ptr<GDALDataset> poDS(GDALDataset::Open(
2183
0
                                osWMS_XML, GDAL_OF_RASTER | GDAL_OF_INTERNAL));
2184
0
                            if (!poDS)
2185
0
                                return false;
2186
0
                            m_apoDatasetsElementary.emplace_back(
2187
0
                                std::move(poDS));
2188
0
                            apoStrippedDS.emplace_back(GDALDataset::ToHandle(
2189
0
                                m_apoDatasetsElementary.back().get()));
2190
0
                        }
2191
0
                    }
2192
0
                }
2193
2194
0
                if (apoStrippedDS.empty())
2195
0
                    return false;
2196
2197
                // Assemble the strips in a single VRT
2198
0
                CPLStringList argv;
2199
0
                argv.AddString("-resolution");
2200
0
                argv.AddString("highest");
2201
0
                GDALBuildVRTOptions *psOptions =
2202
0
                    GDALBuildVRTOptionsNew(argv.List(), nullptr);
2203
0
                GDALDatasetH hAssembledDS = GDALBuildVRT(
2204
0
                    "", static_cast<int>(apoStrippedDS.size()),
2205
0
                    &apoStrippedDS[0], nullptr, psOptions, nullptr);
2206
0
                GDALBuildVRTOptionsFree(psOptions);
2207
0
                if (hAssembledDS == nullptr)
2208
0
                    return false;
2209
0
                m_apoDatasetsAssembled.emplace_back(
2210
0
                    GDALDataset::FromHandle(hAssembledDS));
2211
0
            }
2212
2213
0
            CPLStringList argv;
2214
0
            argv.AddString("-of");
2215
0
            argv.AddString("VRT");
2216
0
            argv.AddString("-projwin");
2217
0
            argv.AddString(CPLSPrintf("%.17g", dfXMin));
2218
0
            argv.AddString(CPLSPrintf("%.17g", dfYMax));
2219
0
            argv.AddString(CPLSPrintf("%.17g", dfXMax));
2220
0
            argv.AddString(CPLSPrintf("%.17g", dfYMin));
2221
0
            GDALTranslateOptions *psOptions =
2222
0
                GDALTranslateOptionsNew(argv.List(), nullptr);
2223
0
            GDALDatasetH hCroppedDS = GDALTranslate(
2224
0
                "", GDALDataset::ToHandle(m_apoDatasetsAssembled.back().get()),
2225
0
                psOptions, nullptr);
2226
0
            GDALTranslateOptionsFree(psOptions);
2227
0
            if (hCroppedDS == nullptr)
2228
0
                return false;
2229
0
            m_apoDatasetsCropped.emplace_back(
2230
0
                GDALDataset::FromHandle(hCroppedDS));
2231
2232
0
            if (tileMatrix.mResX <= m_gt.xscale)
2233
0
                break;
2234
0
        }
2235
0
        if (!m_apoDatasetsCropped.empty())
2236
0
        {
2237
0
            std::reverse(std::begin(m_apoDatasetsCropped),
2238
0
                         std::end(m_apoDatasetsCropped));
2239
0
            nRasterXSize = m_apoDatasetsCropped[0]->GetRasterXSize();
2240
0
            nRasterYSize = m_apoDatasetsCropped[0]->GetRasterYSize();
2241
0
            m_apoDatasetsCropped[0]->GetGeoTransform(m_gt);
2242
2243
0
            for (int i = 1; i <= m_apoDatasetsCropped[0]->GetRasterCount(); i++)
2244
0
            {
2245
0
                SetBand(i, new OGCAPITilesWrapperBand(this, i));
2246
0
            }
2247
0
            SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL",
2248
0
                            GDAL_MDD_IMAGE_STRUCTURE);
2249
2250
0
            bFoundSomething = true;
2251
0
        }
2252
0
    }
2253
2254
0
    return bFoundSomething;
2255
0
}
2256
2257
/************************************************************************/
2258
/*                       OGCAPITilesWrapperBand()                       */
2259
/************************************************************************/
2260
2261
OGCAPITilesWrapperBand::OGCAPITilesWrapperBand(OGCAPIDataset *poDSIn,
2262
                                               int nBandIn)
2263
0
{
2264
0
    poDS = poDSIn;
2265
0
    nBand = nBandIn;
2266
0
    eDataType = poDSIn->m_apoDatasetsCropped[0]
2267
0
                    ->GetRasterBand(nBand)
2268
0
                    ->GetRasterDataType();
2269
0
    poDSIn->m_apoDatasetsCropped[0]->GetRasterBand(nBand)->GetBlockSize(
2270
0
        &nBlockXSize, &nBlockYSize);
2271
0
}
2272
2273
/************************************************************************/
2274
/*                             IReadBlock()                             */
2275
/************************************************************************/
2276
2277
CPLErr OGCAPITilesWrapperBand::IReadBlock(int nBlockXOff, int nBlockYOff,
2278
                                          void *pImage)
2279
0
{
2280
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
2281
0
    return poGDS->m_apoDatasetsCropped[0]->GetRasterBand(nBand)->ReadBlock(
2282
0
        nBlockXOff, nBlockYOff, pImage);
2283
0
}
2284
2285
/************************************************************************/
2286
/*                             IRasterIO()                              */
2287
/************************************************************************/
2288
2289
CPLErr OGCAPITilesWrapperBand::IRasterIO(
2290
    GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
2291
    void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
2292
    GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg *psExtraArg)
2293
0
{
2294
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
2295
2296
0
    if ((nBufXSize < nXSize || nBufYSize < nYSize) &&
2297
0
        poGDS->m_apoDatasetsCropped.size() > 1 && eRWFlag == GF_Read)
2298
0
    {
2299
0
        int bTried;
2300
0
        CPLErr eErr = TryOverviewRasterIO(
2301
0
            eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2302
0
            eBufType, nPixelSpace, nLineSpace, psExtraArg, &bTried);
2303
0
        if (bTried)
2304
0
            return eErr;
2305
0
    }
2306
2307
0
    return poGDS->m_apoDatasetsCropped[0]->GetRasterBand(nBand)->RasterIO(
2308
0
        eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2309
0
        eBufType, nPixelSpace, nLineSpace, psExtraArg);
2310
0
}
2311
2312
/************************************************************************/
2313
/*                          GetOverviewCount()                          */
2314
/************************************************************************/
2315
2316
int OGCAPITilesWrapperBand::GetOverviewCount()
2317
0
{
2318
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
2319
0
    return static_cast<int>(poGDS->m_apoDatasetsCropped.size() - 1);
2320
0
}
2321
2322
/************************************************************************/
2323
/*                            GetOverview()                             */
2324
/************************************************************************/
2325
2326
GDALRasterBand *OGCAPITilesWrapperBand::GetOverview(int nLevel)
2327
0
{
2328
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
2329
0
    if (nLevel < 0 || nLevel >= GetOverviewCount())
2330
0
        return nullptr;
2331
0
    return poGDS->m_apoDatasetsCropped[nLevel + 1]->GetRasterBand(nBand);
2332
0
}
2333
2334
/************************************************************************/
2335
/*                       GetColorInterpretation()                       */
2336
/************************************************************************/
2337
2338
GDALColorInterp OGCAPITilesWrapperBand::GetColorInterpretation()
2339
0
{
2340
0
    OGCAPIDataset *poGDS = cpl::down_cast<OGCAPIDataset *>(poDS);
2341
0
    return poGDS->m_apoDatasetsCropped[0]
2342
0
        ->GetRasterBand(nBand)
2343
0
        ->GetColorInterpretation();
2344
0
}
2345
2346
/************************************************************************/
2347
/*                             IRasterIO()                              */
2348
/************************************************************************/
2349
2350
CPLErr OGCAPIDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
2351
                                int nXSize, int nYSize, void *pData,
2352
                                int nBufXSize, int nBufYSize,
2353
                                GDALDataType eBufType, int nBandCount,
2354
                                BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
2355
                                GSpacing nLineSpace, GSpacing nBandSpace,
2356
                                GDALRasterIOExtraArg *psExtraArg)
2357
0
{
2358
0
    if (!m_apoDatasetsCropped.empty())
2359
0
    {
2360
        // Tiles API
2361
0
        if ((nBufXSize < nXSize || nBufYSize < nYSize) &&
2362
0
            m_apoDatasetsCropped.size() > 1 && eRWFlag == GF_Read)
2363
0
        {
2364
0
            int bTried;
2365
0
            CPLErr eErr = TryOverviewRasterIO(
2366
0
                eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize,
2367
0
                nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace,
2368
0
                nLineSpace, nBandSpace, psExtraArg, &bTried);
2369
0
            if (bTried)
2370
0
                return eErr;
2371
0
        }
2372
2373
0
        return m_apoDatasetsCropped[0]->RasterIO(
2374
0
            eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
2375
0
            eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
2376
0
            nBandSpace, psExtraArg);
2377
0
    }
2378
0
    else if (m_poWMSDS)
2379
0
    {
2380
        // Maps API
2381
0
        return m_poWMSDS->RasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
2382
0
                                   nBufXSize, nBufYSize, eBufType, nBandCount,
2383
0
                                   panBandMap, nPixelSpace, nLineSpace,
2384
0
                                   nBandSpace, psExtraArg);
2385
0
    }
2386
2387
    // Should not be hit
2388
0
    return GDALDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
2389
0
                                  nBufXSize, nBufYSize, eBufType, nBandCount,
2390
0
                                  panBandMap, nPixelSpace, nLineSpace,
2391
0
                                  nBandSpace, psExtraArg);
2392
0
}
2393
2394
/************************************************************************/
2395
/*                          OGCAPITiledLayer()                          */
2396
/************************************************************************/
2397
2398
OGCAPITiledLayer::OGCAPITiledLayer(
2399
    OGCAPIDataset *poDS, bool bInvertAxis, const CPLString &osTileURL,
2400
    bool bIsMVT, const gdal::TileMatrixSet::TileMatrix &tileMatrix,
2401
    OGRwkbGeometryType eGeomType)
2402
0
    : m_poDS(poDS), m_osTileURL(osTileURL), m_bIsMVT(bIsMVT),
2403
0
      m_oTileMatrix(tileMatrix), m_bInvertAxis(bInvertAxis)
2404
0
{
2405
0
    m_poFeatureDefn = new OGCAPITiledLayerFeatureDefn(
2406
0
        this, ("Zoom level " + tileMatrix.mId).c_str());
2407
0
    SetDescription(m_poFeatureDefn->GetName());
2408
0
    m_poFeatureDefn->SetGeomType(eGeomType);
2409
0
    if (eGeomType != wkbNone)
2410
0
    {
2411
0
        auto poClonedSRS = poDS->m_oSRS.Clone();
2412
0
        m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poClonedSRS);
2413
0
        poClonedSRS->Dereference();
2414
0
    }
2415
0
    m_poFeatureDefn->Reference();
2416
0
    m_osTileURL.replaceAll("{tileMatrix}", tileMatrix.mId.c_str());
2417
0
}
2418
2419
/************************************************************************/
2420
/*                         ~OGCAPITiledLayer()                          */
2421
/************************************************************************/
2422
2423
OGCAPITiledLayer::~OGCAPITiledLayer()
2424
0
{
2425
0
    m_poFeatureDefn->InvalidateLayer();
2426
0
    m_poFeatureDefn->Release();
2427
0
}
2428
2429
/************************************************************************/
2430
/*                      GetCoalesceFactorForRow()                       */
2431
/************************************************************************/
2432
2433
int OGCAPITiledLayer::GetCoalesceFactorForRow(int nRow) const
2434
0
{
2435
0
    int nCoalesce = 1;
2436
0
    for (const auto &vmw : m_oTileMatrix.mVariableMatrixWidthList)
2437
0
    {
2438
0
        if (nRow >= vmw.mMinTileRow && nRow <= vmw.mMaxTileRow)
2439
0
        {
2440
0
            nCoalesce = vmw.mCoalesce;
2441
0
            break;
2442
0
        }
2443
0
    }
2444
0
    return nCoalesce;
2445
0
}
2446
2447
/************************************************************************/
2448
/*                            ResetReading()                            */
2449
/************************************************************************/
2450
2451
void OGCAPITiledLayer::ResetReading()
2452
0
{
2453
0
    if (m_nCurX == m_nCurMinX && m_nCurY == m_nCurMinY && m_poUnderlyingLayer)
2454
0
    {
2455
0
        m_poUnderlyingLayer->ResetReading();
2456
0
    }
2457
0
    else
2458
0
    {
2459
0
        m_nCurX = m_nCurMinX;
2460
0
        m_nCurY = m_nCurMinY;
2461
0
        m_poUnderlyingDS.reset();
2462
0
        m_poUnderlyingLayer = nullptr;
2463
0
    }
2464
0
}
2465
2466
/************************************************************************/
2467
/*                              OpenTile()                              */
2468
/************************************************************************/
2469
2470
GDALDataset *OGCAPITiledLayer::OpenTile(int nX, int nY, bool &bEmptyContent)
2471
0
{
2472
0
    int nCoalesce = GetCoalesceFactorForRow(nY);
2473
0
    if (nCoalesce <= 0)
2474
0
        return nullptr;
2475
0
    nX = (nX / nCoalesce) * nCoalesce;
2476
2477
0
    const char *const *papszOpenOptions = nullptr;
2478
0
    CPLString poPrefix;
2479
0
    CPLStringList aosOpenOptions;
2480
2481
0
    if (m_bIsMVT)
2482
0
    {
2483
0
        const double dfOriX =
2484
0
            m_bInvertAxis ? m_oTileMatrix.mTopLeftY : m_oTileMatrix.mTopLeftX;
2485
0
        const double dfOriY =
2486
0
            m_bInvertAxis ? m_oTileMatrix.mTopLeftX : m_oTileMatrix.mTopLeftY;
2487
0
        aosOpenOptions.SetNameValue(
2488
0
            "@GEOREF_TOPX",
2489
0
            CPLSPrintf("%.17g", dfOriX + nX * m_oTileMatrix.mResX *
2490
0
                                             m_oTileMatrix.mTileWidth));
2491
0
        aosOpenOptions.SetNameValue(
2492
0
            "@GEOREF_TOPY",
2493
0
            CPLSPrintf("%.17g", dfOriY - nY * m_oTileMatrix.mResY *
2494
0
                                             m_oTileMatrix.mTileHeight));
2495
0
        aosOpenOptions.SetNameValue(
2496
0
            "@GEOREF_TILEDIMX",
2497
0
            CPLSPrintf("%.17g", nCoalesce * m_oTileMatrix.mResX *
2498
0
                                    m_oTileMatrix.mTileWidth));
2499
0
        aosOpenOptions.SetNameValue(
2500
0
            "@GEOREF_TILEDIMY",
2501
0
            CPLSPrintf("%.17g",
2502
0
                       m_oTileMatrix.mResY * m_oTileMatrix.mTileWidth));
2503
2504
0
        papszOpenOptions = aosOpenOptions.List();
2505
0
        poPrefix = "MVT";
2506
0
    }
2507
2508
0
    std::unique_ptr<GDALDataset> dataset = m_poDS->OpenTile(
2509
0
        m_osTileURL, stoi(m_oTileMatrix.mId), nX, nY, bEmptyContent,
2510
0
        GDAL_OF_VECTOR, poPrefix, papszOpenOptions);
2511
2512
0
    return dataset.release();
2513
0
}
2514
2515
/************************************************************************/
2516
/*                    FinalizeFeatureDefnWithLayer()                    */
2517
/************************************************************************/
2518
2519
void OGCAPITiledLayer::FinalizeFeatureDefnWithLayer(OGRLayer *poUnderlyingLayer)
2520
0
{
2521
0
    if (!m_bFeatureDefnEstablished)
2522
0
    {
2523
0
        m_bFeatureDefnEstablished = true;
2524
0
        const auto poSrcFieldDefn = poUnderlyingLayer->GetLayerDefn();
2525
0
        const int nFieldCount = poSrcFieldDefn->GetFieldCount();
2526
0
        for (int i = 0; i < nFieldCount; i++)
2527
0
        {
2528
0
            m_poFeatureDefn->AddFieldDefn(poSrcFieldDefn->GetFieldDefn(i));
2529
0
        }
2530
0
    }
2531
0
}
2532
2533
/************************************************************************/
2534
/*                            BuildFeature()                            */
2535
/************************************************************************/
2536
2537
OGRFeature *
2538
OGCAPITiledLayer::BuildFeature(std::unique_ptr<OGRFeature> poSrcFeature, int nX,
2539
                               int nY)
2540
0
{
2541
0
    int nCoalesce = GetCoalesceFactorForRow(nY);
2542
0
    if (nCoalesce <= 0)
2543
0
        return nullptr;
2544
0
    nX = (nX / nCoalesce) * nCoalesce;
2545
2546
0
    OGRFeature *poFeature = new OGRFeature(m_poFeatureDefn);
2547
0
    const GIntBig nFID = nY * m_oTileMatrix.mMatrixWidth + nX +
2548
0
                         poSrcFeature->GetFID() * m_oTileMatrix.mMatrixWidth *
2549
0
                             m_oTileMatrix.mMatrixHeight;
2550
0
    auto poGeom = std::unique_ptr<OGRGeometry>(poSrcFeature->StealGeometry());
2551
0
    if (poGeom && m_poFeatureDefn->GetGeomType() != wkbUnknown)
2552
0
    {
2553
0
        poGeom = OGRGeometryFactory::forceTo(std::move(poGeom),
2554
0
                                             m_poFeatureDefn->GetGeomType());
2555
0
    }
2556
0
    poFeature->SetFrom(poSrcFeature.get(), true);
2557
0
    poFeature->SetFID(nFID);
2558
0
    if (poGeom && m_poFeatureDefn->GetGeomFieldCount() > 0)
2559
0
    {
2560
0
        poGeom->assignSpatialReference(
2561
0
            m_poFeatureDefn->GetGeomFieldDefn(0)->GetSpatialRef());
2562
0
    }
2563
0
    poFeature->SetGeometry(std::move(poGeom));
2564
0
    return poFeature;
2565
0
}
2566
2567
/************************************************************************/
2568
/*                        IncrementTileIndices()                        */
2569
/************************************************************************/
2570
2571
bool OGCAPITiledLayer::IncrementTileIndices()
2572
0
{
2573
2574
0
    const int nCoalesce = GetCoalesceFactorForRow(m_nCurY);
2575
0
    if (nCoalesce <= 0)
2576
0
        return false;
2577
0
    if (m_nCurX / nCoalesce < m_nCurMaxX / nCoalesce)
2578
0
    {
2579
0
        m_nCurX += nCoalesce;
2580
0
    }
2581
0
    else if (m_nCurY < m_nCurMaxY)
2582
0
    {
2583
0
        m_nCurX = m_nCurMinX;
2584
0
        m_nCurY++;
2585
0
    }
2586
0
    else
2587
0
    {
2588
0
        m_nCurY = -1;
2589
0
        return false;
2590
0
    }
2591
0
    return true;
2592
0
}
2593
2594
/************************************************************************/
2595
/*                         GetNextRawFeature()                          */
2596
/************************************************************************/
2597
2598
OGRFeature *OGCAPITiledLayer::GetNextRawFeature()
2599
0
{
2600
0
    while (true)
2601
0
    {
2602
0
        if (m_poUnderlyingLayer == nullptr)
2603
0
        {
2604
0
            if (m_nCurY < 0)
2605
0
            {
2606
0
                return nullptr;
2607
0
            }
2608
0
            bool bEmptyContent = false;
2609
0
            m_poUnderlyingDS.reset(OpenTile(m_nCurX, m_nCurY, bEmptyContent));
2610
0
            if (bEmptyContent)
2611
0
            {
2612
0
                if (!IncrementTileIndices())
2613
0
                    return nullptr;
2614
0
                continue;
2615
0
            }
2616
0
            if (m_poUnderlyingDS == nullptr)
2617
0
            {
2618
0
                return nullptr;
2619
0
            }
2620
0
            m_poUnderlyingLayer = m_poUnderlyingDS->GetLayer(0);
2621
0
            if (m_poUnderlyingLayer == nullptr)
2622
0
            {
2623
0
                return nullptr;
2624
0
            }
2625
0
            FinalizeFeatureDefnWithLayer(m_poUnderlyingLayer);
2626
0
        }
2627
2628
0
        auto poSrcFeature =
2629
0
            std::unique_ptr<OGRFeature>(m_poUnderlyingLayer->GetNextFeature());
2630
0
        if (poSrcFeature != nullptr)
2631
0
        {
2632
0
            return BuildFeature(std::move(poSrcFeature), m_nCurX, m_nCurY);
2633
0
        }
2634
2635
0
        m_poUnderlyingDS.reset();
2636
0
        m_poUnderlyingLayer = nullptr;
2637
2638
0
        if (!IncrementTileIndices())
2639
0
            return nullptr;
2640
0
    }
2641
0
}
2642
2643
/************************************************************************/
2644
/*                             GetFeature()                             */
2645
/************************************************************************/
2646
2647
OGRFeature *OGCAPITiledLayer::GetFeature(GIntBig nFID)
2648
0
{
2649
0
    if (nFID < 0)
2650
0
        return nullptr;
2651
0
    const GIntBig nFIDInTile =
2652
0
        nFID / (m_oTileMatrix.mMatrixWidth * m_oTileMatrix.mMatrixHeight);
2653
0
    const GIntBig nTileID =
2654
0
        nFID % (m_oTileMatrix.mMatrixWidth * m_oTileMatrix.mMatrixHeight);
2655
0
    const int nY = static_cast<int>(nTileID / m_oTileMatrix.mMatrixWidth);
2656
0
    const int nX = static_cast<int>(nTileID % m_oTileMatrix.mMatrixWidth);
2657
0
    bool bEmptyContent = false;
2658
0
    std::unique_ptr<GDALDataset> poUnderlyingDS(
2659
0
        OpenTile(nX, nY, bEmptyContent));
2660
0
    if (poUnderlyingDS == nullptr)
2661
0
        return nullptr;
2662
0
    OGRLayer *poUnderlyingLayer = poUnderlyingDS->GetLayer(0);
2663
0
    if (poUnderlyingLayer == nullptr)
2664
0
        return nullptr;
2665
0
    FinalizeFeatureDefnWithLayer(poUnderlyingLayer);
2666
0
    auto poSrcFeature =
2667
0
        std::unique_ptr<OGRFeature>(poUnderlyingLayer->GetFeature(nFIDInTile));
2668
0
    if (poSrcFeature == nullptr)
2669
0
        return nullptr;
2670
0
    return BuildFeature(std::move(poSrcFeature), nX, nY);
2671
0
}
2672
2673
/************************************************************************/
2674
/*                          EstablishFields()                           */
2675
/************************************************************************/
2676
2677
void OGCAPITiledLayer::EstablishFields()
2678
0
{
2679
0
    if (!m_bFeatureDefnEstablished && !m_bEstablishFieldsCalled)
2680
0
    {
2681
0
        m_bEstablishFieldsCalled = true;
2682
2683
        // Try up to 10 requests in order. We could probably remove that
2684
        // to use just the fallback logic.
2685
0
        for (int i = 0; i < 10; ++i)
2686
0
        {
2687
0
            bool bEmptyContent = false;
2688
0
            m_poUnderlyingDS.reset(OpenTile(m_nCurX, m_nCurY, bEmptyContent));
2689
0
            if (bEmptyContent || !m_poUnderlyingDS)
2690
0
            {
2691
0
                if (!IncrementTileIndices())
2692
0
                    break;
2693
0
                continue;
2694
0
            }
2695
0
            m_poUnderlyingLayer = m_poUnderlyingDS->GetLayer(0);
2696
0
            if (m_poUnderlyingLayer)
2697
0
            {
2698
0
                FinalizeFeatureDefnWithLayer(m_poUnderlyingLayer);
2699
0
                break;
2700
0
            }
2701
0
        }
2702
2703
0
        if (!m_bFeatureDefnEstablished)
2704
0
        {
2705
            // Try to sample at different locations in the extent
2706
0
            for (int j = 0; !m_bFeatureDefnEstablished && j < 3; ++j)
2707
0
            {
2708
0
                m_nCurY = m_nMinY + (2 * j + 1) * (m_nMaxY - m_nMinY) / 6;
2709
0
                for (int i = 0; i < 3; ++i)
2710
0
                {
2711
0
                    m_nCurX = m_nMinX + (2 * i + 1) * (m_nMaxX - m_nMinX) / 6;
2712
0
                    bool bEmptyContent = false;
2713
0
                    m_poUnderlyingDS.reset(
2714
0
                        OpenTile(m_nCurX, m_nCurY, bEmptyContent));
2715
0
                    if (bEmptyContent || !m_poUnderlyingDS)
2716
0
                    {
2717
0
                        continue;
2718
0
                    }
2719
0
                    m_poUnderlyingLayer = m_poUnderlyingDS->GetLayer(0);
2720
0
                    if (m_poUnderlyingLayer)
2721
0
                    {
2722
0
                        FinalizeFeatureDefnWithLayer(m_poUnderlyingLayer);
2723
0
                        break;
2724
0
                    }
2725
0
                }
2726
0
            }
2727
0
        }
2728
2729
0
        if (!m_bFeatureDefnEstablished)
2730
0
        {
2731
0
            CPLDebug("OGCAPI", "Could not establish feature definition. No "
2732
0
                               "valid tile found in sampling done");
2733
0
        }
2734
2735
0
        ResetReading();
2736
0
    }
2737
0
}
2738
2739
/************************************************************************/
2740
/*                             SetExtent()                              */
2741
/************************************************************************/
2742
2743
void OGCAPITiledLayer::SetExtent(double dfXMin, double dfYMin, double dfXMax,
2744
                                 double dfYMax)
2745
0
{
2746
0
    m_sEnvelope.MinX = dfXMin;
2747
0
    m_sEnvelope.MinY = dfYMin;
2748
0
    m_sEnvelope.MaxX = dfXMax;
2749
0
    m_sEnvelope.MaxY = dfYMax;
2750
0
}
2751
2752
/************************************************************************/
2753
/*                             IGetExtent()                             */
2754
/************************************************************************/
2755
2756
OGRErr OGCAPITiledLayer::IGetExtent(int /* iGeomField */, OGREnvelope *psExtent,
2757
                                    bool /* bForce */)
2758
0
{
2759
0
    *psExtent = m_sEnvelope;
2760
0
    return OGRERR_NONE;
2761
0
}
2762
2763
/************************************************************************/
2764
/*                         ISetSpatialFilter()                          */
2765
/************************************************************************/
2766
2767
OGRErr OGCAPITiledLayer::ISetSpatialFilter(int iGeomField,
2768
                                           const OGRGeometry *poGeomIn)
2769
0
{
2770
0
    const OGRErr eErr = OGRLayer::ISetSpatialFilter(iGeomField, poGeomIn);
2771
0
    if (eErr == OGRERR_NONE)
2772
0
    {
2773
0
        OGREnvelope sEnvelope;
2774
0
        if (m_poFilterGeom != nullptr)
2775
0
            sEnvelope = m_sFilterEnvelope;
2776
0
        else
2777
0
            sEnvelope = m_sEnvelope;
2778
2779
0
        const double dfTileDim = m_oTileMatrix.mResX * m_oTileMatrix.mTileWidth;
2780
0
        const double dfOriX =
2781
0
            m_bInvertAxis ? m_oTileMatrix.mTopLeftY : m_oTileMatrix.mTopLeftX;
2782
0
        const double dfOriY =
2783
0
            m_bInvertAxis ? m_oTileMatrix.mTopLeftX : m_oTileMatrix.mTopLeftY;
2784
0
        if (sEnvelope.MinX - dfOriX >= -10 * dfTileDim &&
2785
0
            dfOriY - sEnvelope.MinY >= -10 * dfTileDim &&
2786
0
            sEnvelope.MaxX - dfOriX <= 10 * dfTileDim &&
2787
0
            dfOriY - sEnvelope.MaxY <= 10 * dfTileDim)
2788
0
        {
2789
0
            m_nCurMinX = std::max(
2790
0
                m_nMinX,
2791
0
                static_cast<int>(floor((sEnvelope.MinX - dfOriX) / dfTileDim)));
2792
0
            m_nCurMinY = std::max(
2793
0
                m_nMinY,
2794
0
                static_cast<int>(floor((dfOriY - sEnvelope.MaxY) / dfTileDim)));
2795
0
            m_nCurMaxX = std::min(
2796
0
                m_nMaxX,
2797
0
                static_cast<int>(floor((sEnvelope.MaxX - dfOriX) / dfTileDim)));
2798
0
            m_nCurMaxY = std::min(
2799
0
                m_nMaxY,
2800
0
                static_cast<int>(floor((dfOriY - sEnvelope.MinY) / dfTileDim)));
2801
0
        }
2802
0
        else
2803
0
        {
2804
0
            m_nCurMinX = m_nMinX;
2805
0
            m_nCurMinY = m_nMinY;
2806
0
            m_nCurMaxX = m_nMaxX;
2807
0
            m_nCurMaxY = m_nMaxY;
2808
0
        }
2809
2810
0
        ResetReading();
2811
0
    }
2812
0
    return eErr;
2813
0
}
2814
2815
/************************************************************************/
2816
/*                           TestCapability()                           */
2817
/************************************************************************/
2818
2819
bool OGCAPITiledLayer::TestCapability(const char *pszCap) const
2820
0
{
2821
0
    if (EQUAL(pszCap, OLCRandomRead))
2822
0
        return true;
2823
0
    if (EQUAL(pszCap, OLCFastGetExtent))
2824
0
        return true;
2825
0
    if (EQUAL(pszCap, OLCStringsAsUTF8))
2826
0
        return true;
2827
0
    if (EQUAL(pszCap, OLCFastSpatialFilter))
2828
0
        return true;
2829
0
    return false;
2830
0
}
2831
2832
/************************************************************************/
2833
/*                            SetMinMaxXY()                             */
2834
/************************************************************************/
2835
2836
void OGCAPITiledLayer::SetMinMaxXY(int minCol, int minRow, int maxCol,
2837
                                   int maxRow)
2838
0
{
2839
0
    m_nMinX = minCol;
2840
0
    m_nMinY = minRow;
2841
0
    m_nMaxX = maxCol;
2842
0
    m_nMaxY = maxRow;
2843
0
    m_nCurMinX = m_nMinX;
2844
0
    m_nCurMinY = m_nMinY;
2845
0
    m_nCurMaxX = m_nMaxX;
2846
0
    m_nCurMaxY = m_nMaxY;
2847
0
    ResetReading();
2848
0
}
2849
2850
/************************************************************************/
2851
/*                             SetFields()                              */
2852
/************************************************************************/
2853
2854
void OGCAPITiledLayer::SetFields(
2855
    const std::vector<std::unique_ptr<OGRFieldDefn>> &apoFields)
2856
0
{
2857
0
    m_bFeatureDefnEstablished = true;
2858
0
    for (const auto &poField : apoFields)
2859
0
    {
2860
0
        m_poFeatureDefn->AddFieldDefn(poField.get());
2861
0
    }
2862
0
}
2863
2864
/************************************************************************/
2865
/*                                Open()                                */
2866
/************************************************************************/
2867
2868
GDALDataset *OGCAPIDataset::Open(GDALOpenInfo *poOpenInfo)
2869
14
{
2870
14
    if (!Identify(poOpenInfo))
2871
0
        return nullptr;
2872
14
    auto poDS = std::make_unique<OGCAPIDataset>();
2873
14
    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "OGCAPI:") ||
2874
0
        STARTS_WITH(poOpenInfo->pszFilename, "http://") ||
2875
0
        STARTS_WITH(poOpenInfo->pszFilename, "https://"))
2876
14
    {
2877
14
        if (!poDS->InitFromURL(poOpenInfo))
2878
14
            return nullptr;
2879
14
    }
2880
0
    else
2881
0
    {
2882
0
        if (!poDS->InitFromFile(poOpenInfo))
2883
0
            return nullptr;
2884
0
    }
2885
0
    return poDS.release();
2886
14
}
2887
2888
/************************************************************************/
2889
/*                        GDALRegister_OGCAPI()                         */
2890
/************************************************************************/
2891
2892
void GDALRegister_OGCAPI()
2893
2894
24
{
2895
24
    if (GDALGetDriverByName("OGCAPI") != nullptr)
2896
0
        return;
2897
2898
24
    GDALDriver *poDriver = new GDALDriver();
2899
2900
24
    poDriver->SetDescription("OGCAPI");
2901
24
    poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
2902
24
    poDriver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES");
2903
24
    poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "OGCAPI");
2904
2905
24
    poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
2906
2907
24
    poDriver->SetMetadataItem(
2908
24
        GDAL_DMD_OPENOPTIONLIST,
2909
24
        "<OpenOptionList>"
2910
24
        "  <Option name='API' type='string-select' "
2911
24
        "description='Which API to use to access data' default='AUTO'>"
2912
24
        "       <Value>AUTO</Value>"
2913
24
        "       <Value>MAP</Value>"
2914
24
        "       <Value>TILES</Value>"
2915
24
        "       <Value>COVERAGE</Value>"
2916
24
        "       <Value>ITEMS</Value>"
2917
24
        "  </Option>"
2918
24
        "  <Option name='IMAGE_FORMAT' scope='raster' type='string-select' "
2919
24
        "description='Which format to use for pixel acquisition' "
2920
24
        "default='AUTO'>"
2921
24
        "       <Value>AUTO</Value>"
2922
24
        "       <Value>PNG</Value>"
2923
24
        "       <Value>PNG_PREFERRED</Value>"
2924
24
        "       <Value>JPEG</Value>"
2925
24
        "       <Value>JPEG_PREFERRED</Value>"
2926
24
        "       <Value>GEOTIFF</Value>"
2927
24
        "  </Option>"
2928
24
        "  <Option name='VECTOR_FORMAT' scope='vector' type='string-select' "
2929
24
        "description='Which format to use for vector data acquisition' "
2930
24
        "default='AUTO'>"
2931
24
        "       <Value>AUTO</Value>"
2932
24
        "       <Value>GEOJSON</Value>"
2933
24
        "       <Value>GEOJSON_PREFERRED</Value>"
2934
24
        "       <Value>MVT</Value>"
2935
24
        "       <Value>MVT_PREFERRED</Value>"
2936
24
        "  </Option>"
2937
24
        "  <Option name='TILEMATRIXSET' type='string' "
2938
24
        "description='Identifier of the required tile matrix set'/>"
2939
24
        "  <Option name='PREFERRED_TILEMATRIXSET' type='string' "
2940
24
        "description='dentifier of the preferred tile matrix set' "
2941
24
        "default='WorldCRS84Quad'/>"
2942
24
        "  <Option name='TILEMATRIX' scope='raster' type='string' "
2943
24
        "description='Tile matrix identifier.'/>"
2944
24
        "  <Option name='CACHE' scope='raster' type='boolean' "
2945
24
        "description='Whether to enable block/tile caching' default='YES'/>"
2946
24
        "  <Option name='MAX_CONNECTIONS' scope='raster' type='int' "
2947
24
        "description='Maximum number of connections' default='5'/>"
2948
24
        "  <Option name='MINX' type='float' "
2949
24
        "description='Minimum value (in SRS of TileMatrixSet) of X'/>"
2950
24
        "  <Option name='MINY' type='float' "
2951
24
        "description='Minimum value (in SRS of TileMatrixSet) of Y'/>"
2952
24
        "  <Option name='MAXX' type='float' "
2953
24
        "description='Maximum value (in SRS of TileMatrixSet) of X'/>"
2954
24
        "  <Option name='MAXY' type='float' "
2955
24
        "description='Maximum value (in SRS of TileMatrixSet) of Y'/>"
2956
24
        "</OpenOptionList>");
2957
2958
24
    poDriver->pfnIdentify = OGCAPIDataset::Identify;
2959
24
    poDriver->pfnOpen = OGCAPIDataset::Open;
2960
2961
24
    GetGDALDriverManager()->RegisterDriver(poDriver);
2962
24
}