File: gdalalg_clip_common.cpp

package info (click to toggle)
gdal 3.12.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 92,396 kB
  • sloc: cpp: 1,224,305; ansic: 206,456; python: 26,284; java: 6,001; xml: 4,769; sh: 3,869; cs: 2,513; yacc: 1,306; makefile: 214
file content (234 lines) | stat: -rw-r--r-- 8,001 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/******************************************************************************
 *
 * Project:  GDAL
 * Purpose:  Common code for gdalalg_raster_clip and gdalalg_vector_clip
 * Author:   Even Rouault <even dot rouault at spatialys.com>
 *
 ******************************************************************************
 * Copyright (c) 2025, Even Rouault <even dot rouault at spatialys.com>
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "gdalalg_clip_common.h"

#include "ogrsf_frmts.h"

//! @cond Doxygen_Suppress

#ifndef _
#define _(x) (x)
#endif

/************************************************************************/
/*                           ~GDALClipCommon()                          */
/************************************************************************/

GDALClipCommon::~GDALClipCommon() = default;

/************************************************************************/
/*                           LoadGeometry()                             */
/************************************************************************/

std::pair<std::unique_ptr<OGRGeometry>, std::string>
GDALClipCommon::LoadGeometry()
{
    auto poDS = m_likeDataset.GetDatasetRef();
    OGRLayer *poLyr = nullptr;
    if (!m_likeSQL.empty())
        poLyr = poDS->ExecuteSQL(m_likeSQL.c_str(), nullptr, nullptr);
    else if (!m_likeLayer.empty())
        poLyr = poDS->GetLayerByName(m_likeLayer.c_str());
    else
        poLyr = poDS->GetLayer(0);

    if (poLyr == nullptr)
    {
        return {nullptr,
                "Failed to identify source layer from clipping dataset."};
    }

    if (!m_likeWhere.empty())
        poLyr->SetAttributeFilter(m_likeWhere.c_str());

    OGRGeometryCollection oGC;
    oGC.assignSpatialReference(poLyr->GetSpatialRef());

    for (auto &poFeat : poLyr)
    {
        auto poSrcGeom = std::unique_ptr<OGRGeometry>(poFeat->StealGeometry());
        if (poSrcGeom)
        {
            // Only take into account areal geometries.
            if (poSrcGeom->getDimension() == 2)
            {
                if (!poSrcGeom->IsValid())
                {
                    return {
                        nullptr,
                        CPLSPrintf("Geometry of feature " CPL_FRMT_GIB " of %s "
                                   "is invalid. You may be able to correct it "
                                   "with 'gdal vector geom make-valid'.",
                                   poFeat->GetFID(), poDS->GetDescription())};
                }
                else
                {
                    oGC.addGeometry(std::move(poSrcGeom));
                }
            }
            else
            {
                CPLErrorOnce(CE_Warning, CPLE_AppDefined,
                             "Non-polygonal geometry encountered in clipping "
                             "dataset will be ignored.");
            }
        }
    }

    if (!m_likeSQL.empty())
        poDS->ReleaseResultSet(poLyr);

    if (oGC.IsEmpty())
    {
        return {nullptr, "No clipping geometry found"};
    }

    return {std::unique_ptr<OGRGeometry>(oGC.UnaryUnion()), std::string()};
}

/************************************************************************/
/*                           GetClipGeometry()                          */
/************************************************************************/

std::pair<std::unique_ptr<OGRGeometry>, std::string>
GDALClipCommon::GetClipGeometry()
{

    std::unique_ptr<OGRGeometry> poClipGeom;

    if (!m_bbox.empty())
    {
        poClipGeom = std::make_unique<OGRPolygon>(m_bbox[0], m_bbox[1],
                                                  m_bbox[2], m_bbox[3]);

        if (!m_bboxCrs.empty())
        {
            auto poSRS = new OGRSpatialReference();
            poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
            CPL_IGNORE_RET_VAL(poSRS->SetFromUserInput(m_bboxCrs.c_str()));
            poClipGeom->assignSpatialReference(poSRS);
            poSRS->Release();
        }
    }
    else if (!m_geometry.empty())
    {
        {
            CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
            auto [poGeom, eErr] =
                OGRGeometryFactory::createFromWkt(m_geometry.c_str());
            if (eErr == OGRERR_NONE)
            {
                poClipGeom = std::move(poGeom);
            }
            else
            {
                poClipGeom.reset(
                    OGRGeometryFactory::createFromGeoJson(m_geometry.c_str()));
                if (poClipGeom && poClipGeom->getSpatialReference() == nullptr)
                {
                    auto poSRS = new OGRSpatialReference();
                    poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
                    CPL_IGNORE_RET_VAL(poSRS->SetFromUserInput("WGS84"));
                    poClipGeom->assignSpatialReference(poSRS);
                    poSRS->Release();
                }
            }
        }
        if (!poClipGeom)
        {
            return {
                nullptr,
                "Clipping geometry is neither a valid WKT or GeoJSON geometry"};
        }

        if (!m_geometryCrs.empty())
        {
            auto poSRS = new OGRSpatialReference();
            poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
            // Validity of CRS already checked by GDALAlgorithm
            CPL_IGNORE_RET_VAL(poSRS->SetFromUserInput(m_geometryCrs.c_str()));
            poClipGeom->assignSpatialReference(poSRS);
            poSRS->Release();
        }
    }
    else if (auto poLikeDS = m_likeDataset.GetDatasetRef())
    {
        if (poLikeDS->GetLayerCount() > 1 && m_likeLayer.empty() &&
            m_likeSQL.empty())
        {
            return {
                nullptr,
                "Only single layer dataset can be specified with --like when "
                "neither --like-layer or --like-sql have been specified"};
        }
        else if (poLikeDS->GetLayerCount() > 0)
        {
            std::string errMsg;
            std::tie(poClipGeom, errMsg) = LoadGeometry();
            if (!poClipGeom)
                return {nullptr, errMsg};
        }
        else if (poLikeDS->GetRasterCount() > 0)
        {
            GDALGeoTransform gt;
            if (poLikeDS->GetGeoTransform(gt) != CE_None)
            {
                return {
                    nullptr,
                    CPLSPrintf(
                        "Dataset '%s' has no geotransform matrix. Its bounds "
                        "cannot be established.",
                        poLikeDS->GetDescription())};
            }
            auto poLikeSRS = poLikeDS->GetSpatialRef();
            const double dfTLX = gt[0];
            const double dfTLY = gt[3];

            double dfTRX = 0;
            double dfTRY = 0;
            gt.Apply(poLikeDS->GetRasterXSize(), 0, &dfTRX, &dfTRY);

            double dfBLX = 0;
            double dfBLY = 0;
            gt.Apply(0, poLikeDS->GetRasterYSize(), &dfBLX, &dfBLY);

            double dfBRX = 0;
            double dfBRY = 0;
            gt.Apply(poLikeDS->GetRasterXSize(), poLikeDS->GetRasterYSize(),
                     &dfBRX, &dfBRY);

            auto poPoly = std::make_unique<OGRPolygon>();
            auto poLR = std::make_unique<OGRLinearRing>();
            poLR->addPoint(dfTLX, dfTLY);
            poLR->addPoint(dfTRX, dfTRY);
            poLR->addPoint(dfBRX, dfBRY);
            poLR->addPoint(dfBLX, dfBLY);
            poLR->addPoint(dfTLX, dfTLY);
            poPoly->addRingDirectly(poLR.release());
            poPoly->assignSpatialReference(poLikeSRS);
            poClipGeom = std::move(poPoly);
        }
        else
        {
            return {nullptr, "Cannot get extent from clip dataset"};
        }
    }
    else
    {
        return {nullptr, "--bbox, --geometry or --like must be specified"};
    }

    return {std::move(poClipGeom), std::string()};
}

//! @endcond