LCOV - code coverage report
Current view: top level - frmts/ogcapi - gdalogcapidataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 919 1313 70.0 %
Date: 2025-10-27 00:14:23 Functions: 56 70 80.0 %

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

Generated by: LCOV version 1.14