Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: High Performance Image Reprojector
4 : * Purpose: Test program for high performance warper API.
5 : * Author: Frank Warmerdam <warmerdam@pobox.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2002, i3 - information integration and imaging
9 : * Fort Collins, CO
10 : * Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys.com>
11 : * Copyright (c) 2015, Faza Mahamood
12 : *
13 : * SPDX-License-Identifier: MIT
14 : ****************************************************************************/
15 :
16 : #include "cpl_port.h"
17 : #include "gdal_utils.h"
18 : #include "gdal_utils_priv.h"
19 : #include "gdalargumentparser.h"
20 :
21 : #include <cctype>
22 : #include <cmath>
23 : #include <cstdio>
24 : #include <cstdlib>
25 : #include <cstring>
26 :
27 : #include <algorithm>
28 : #include <array>
29 : #include <limits>
30 : #include <set>
31 : #include <utility>
32 : #include <vector>
33 :
34 : // Suppress deprecation warning for GDALOpenVerticalShiftGrid and
35 : // GDALApplyVerticalShiftGrid
36 : #ifndef CPL_WARN_DEPRECATED_GDALOpenVerticalShiftGrid
37 : #define CPL_WARN_DEPRECATED_GDALOpenVerticalShiftGrid(x)
38 : #define CPL_WARN_DEPRECATED_GDALApplyVerticalShiftGrid(x)
39 : #endif
40 :
41 : #include "commonutils.h"
42 : #include "cpl_conv.h"
43 : #include "cpl_error.h"
44 : #include "cpl_progress.h"
45 : #include "cpl_string.h"
46 : #include "gdal.h"
47 : #include "gdal_alg.h"
48 : #include "gdal_alg_priv.h"
49 : #include "gdal_priv.h"
50 : #include "gdalwarper.h"
51 : #include "ogr_api.h"
52 : #include "ogr_core.h"
53 : #include "ogr_geometry.h"
54 : #include "ogr_spatialref.h"
55 : #include "ogr_srs_api.h"
56 : #include "ogr_proj_p.h"
57 : #include "ogrct_priv.h"
58 : #include "ogrsf_frmts.h"
59 : #include "vrtdataset.h"
60 : #include "../frmts/gtiff/cogdriver.h"
61 :
62 : #if PROJ_VERSION_MAJOR > 6 || PROJ_VERSION_MINOR >= 3
63 : #define USE_PROJ_BASED_VERTICAL_SHIFT_METHOD
64 : #endif
65 :
66 : /************************************************************************/
67 : /* GDALWarpAppOptions */
68 : /************************************************************************/
69 :
70 : /** Options for use with GDALWarp(). GDALWarpAppOptions* must be allocated and
71 : * freed with GDALWarpAppOptionsNew() and GDALWarpAppOptionsFree() respectively.
72 : */
73 : struct GDALWarpAppOptions
74 : {
75 : /*! Raw program arguments */
76 : CPLStringList aosArgs{};
77 :
78 : /*! set georeferenced extents of output file to be created (in target SRS by
79 : default, or in the SRS specified with pszTE_SRS) */
80 : double dfMinX = 0;
81 : double dfMinY = 0;
82 : double dfMaxX = 0;
83 : double dfMaxY = 0;
84 :
85 : /*! the SRS in which to interpret the coordinates given in
86 : GDALWarpAppOptions::dfMinX, GDALWarpAppOptions::dfMinY,
87 : GDALWarpAppOptions::dfMaxX and GDALWarpAppOptions::dfMaxY. The SRS may be
88 : any of the usual GDAL/OGR forms, complete WKT, PROJ.4, EPSG:n or a file
89 : containing the WKT. It is a convenience e.g. when knowing the output
90 : coordinates in a geodetic long/lat SRS, but still wanting a result in a
91 : projected coordinate system. */
92 : std::string osTE_SRS{};
93 :
94 : /*! set output file resolution (in target georeferenced units) */
95 : double dfXRes = 0;
96 : double dfYRes = 0;
97 :
98 : /*! whether target pixels should have dfXRes == dfYRes */
99 : bool bSquarePixels = false;
100 :
101 : /*! align the coordinates of the extent of the output file to the values of
102 : the GDALWarpAppOptions::dfXRes and GDALWarpAppOptions::dfYRes, such that
103 : the aligned extent includes the minimum extent. */
104 : bool bTargetAlignedPixels = false;
105 :
106 : /*! set output file size in pixels and lines. If
107 : GDALWarpAppOptions::nForcePixels or GDALWarpAppOptions::nForceLines is
108 : set to 0, the other dimension will be guessed from the computed
109 : resolution. Note that GDALWarpAppOptions::nForcePixels and
110 : GDALWarpAppOptions::nForceLines cannot be used with
111 : GDALWarpAppOptions::dfXRes and GDALWarpAppOptions::dfYRes. */
112 : int nForcePixels = 0;
113 : int nForceLines = 0;
114 :
115 : /*! allow or suppress progress monitor and other non-error output */
116 : bool bQuiet = true;
117 :
118 : /*! the progress function to use */
119 : GDALProgressFunc pfnProgress = GDALDummyProgress;
120 :
121 : /*! pointer to the progress data variable */
122 : void *pProgressData = nullptr;
123 :
124 : /*! creates an output alpha band to identify nodata (unset/transparent)
125 : pixels when set to true */
126 : bool bEnableDstAlpha = false;
127 :
128 : /*! forces the last band of an input file to be considered as alpha band. */
129 : bool bEnableSrcAlpha = false;
130 :
131 : /*! Prevent a source alpha band from being considered as such */
132 : bool bDisableSrcAlpha = false;
133 :
134 : /*! output format. Use the short format name. */
135 : std::string osFormat{};
136 :
137 : bool bCreateOutput = false;
138 :
139 : /*! list of warp options. ("NAME1=VALUE1","NAME2=VALUE2",...). The
140 : GDALWarpOptions::aosWarpOptions docs show all options. */
141 : CPLStringList aosWarpOptions{};
142 :
143 : double dfErrorThreshold = -1;
144 :
145 : /*! the amount of memory (in megabytes) that the warp API is allowed
146 : to use for caching. */
147 : double dfWarpMemoryLimit = 0;
148 :
149 : /*! list of create options for the output format driver. See format
150 : specific documentation for legal creation options for each format. */
151 : CPLStringList aosCreateOptions{};
152 :
153 : /*! the data type of the output bands */
154 : GDALDataType eOutputType = GDT_Unknown;
155 :
156 : /*! working pixel data type. The data type of pixels in the source
157 : image and destination image buffers. */
158 : GDALDataType eWorkingType = GDT_Unknown;
159 :
160 : /*! the resampling method. Available methods are: near, bilinear,
161 : cubic, cubicspline, lanczos, average, mode, max, min, med,
162 : q1, q3, sum */
163 : GDALResampleAlg eResampleAlg = GRA_NearestNeighbour;
164 :
165 : /*! whether -r was specified */
166 : bool bResampleAlgSpecifiedByUser = false;
167 :
168 : /*! nodata masking values for input bands (different values can be supplied
169 : for each band). ("value1 value2 ..."). Masked values will not be used
170 : in interpolation. Use a value of "None" to ignore intrinsic nodata
171 : settings on the source dataset. */
172 : std::string osSrcNodata{};
173 :
174 : /*! nodata values for output bands (different values can be supplied for
175 : each band). ("value1 value2 ..."). New files will be initialized to
176 : this value and if possible the nodata value will be recorded in the
177 : output file. Use a value of "None" to ensure that nodata is not defined.
178 : If this argument is not used then nodata values will be copied from
179 : the source dataset. */
180 : std::string osDstNodata{};
181 :
182 : /*! use multithreaded warping implementation. Multiple threads will be used
183 : to process chunks of image and perform input/output operation
184 : simultaneously. */
185 : bool bMulti = false;
186 :
187 : /*! list of transformer options suitable to pass to
188 : GDALCreateGenImgProjTransformer2().
189 : ("NAME1=VALUE1","NAME2=VALUE2",...) */
190 : CPLStringList aosTransformerOptions{};
191 :
192 : /*! enable use of a blend cutline from a vector dataset name or a WKT
193 : * geometry
194 : */
195 : std::string osCutlineDSNameOrWKT{};
196 :
197 : /*! cutline SRS */
198 : std::string osCutlineSRS{};
199 :
200 : /*! the named layer to be selected from the cutline datasource */
201 : std::string osCLayer{};
202 :
203 : /*! restrict desired cutline features based on attribute query */
204 : std::string osCWHERE{};
205 :
206 : /*! SQL query to select the cutline features instead of from a layer
207 : with osCLayer */
208 : std::string osCSQL{};
209 :
210 : /*! crop the extent of the target dataset to the extent of the cutline */
211 : bool bCropToCutline = false;
212 :
213 : /*! copy dataset and band metadata will be copied from the first source
214 : dataset. Items that differ between source datasets will be set "*" (see
215 : GDALWarpAppOptions::pszMDConflictValue) */
216 : bool bCopyMetadata = true;
217 :
218 : /*! copy band information from the first source dataset */
219 : bool bCopyBandInfo = true;
220 :
221 : /*! value to set metadata items that conflict between source datasets
222 : (default is "*"). Use "" to remove conflicting items. */
223 : std::string osMDConflictValue = "*";
224 :
225 : /*! set the color interpretation of the bands of the target dataset from the
226 : * source dataset */
227 : bool bSetColorInterpretation = false;
228 :
229 : /*! overview level of source files to be used */
230 : int nOvLevel = OVR_LEVEL_AUTO;
231 :
232 : /*! Whether to enable vertical shift adjustment */
233 : bool bVShift = false;
234 :
235 : /*! Whether to disable vertical shift adjustment */
236 : bool bNoVShift = false;
237 :
238 : /*! Source bands */
239 : std::vector<int> anSrcBands{};
240 :
241 : /*! Destination bands */
242 : std::vector<int> anDstBands{};
243 :
244 : /*! Used when using a temporary TIFF file while warping */
245 : bool bDeleteOutputFileOnceCreated = false;
246 : };
247 :
248 : static CPLErr
249 : LoadCutline(const std::string &osCutlineDSNameOrWKT, const std::string &osSRS,
250 : const std::string &oszCLayer, const std::string &osCWHERE,
251 : const std::string &osCSQL, OGRGeometryH *phCutlineRet);
252 : static CPLErr TransformCutlineToSource(GDALDataset *poSrcDS,
253 : OGRGeometry *poCutline,
254 : char ***ppapszWarpOptions,
255 : CSLConstList papszTO);
256 :
257 : static GDALDatasetH GDALWarpCreateOutput(
258 : int nSrcCount, GDALDatasetH *pahSrcDS, const char *pszFilename,
259 : const char *pszFormat, char **papszTO, CSLConstList papszCreateOptions,
260 : GDALDataType eDT, GDALTransformerArgUniquePtr &hTransformArg,
261 : bool bSetColorInterpretation, GDALWarpAppOptions *psOptions,
262 : bool bUpdateTransformerWithDestGT);
263 :
264 : static void RemoveConflictingMetadata(GDALMajorObjectH hObj,
265 : CSLConstList papszMetadata,
266 : const char *pszValueConflict);
267 :
268 3 : static double GetAverageSegmentLength(const OGRGeometry *poGeom)
269 : {
270 3 : if (!poGeom)
271 0 : return 0;
272 3 : switch (wkbFlatten(poGeom->getGeometryType()))
273 : {
274 1 : case wkbLineString:
275 : {
276 1 : const auto *poLS = poGeom->toLineString();
277 1 : double dfSum = 0;
278 1 : const int nPoints = poLS->getNumPoints();
279 1 : if (nPoints == 0)
280 0 : return 0;
281 5 : for (int i = 0; i < nPoints - 1; i++)
282 : {
283 4 : double dfX1 = poLS->getX(i);
284 4 : double dfY1 = poLS->getY(i);
285 4 : double dfX2 = poLS->getX(i + 1);
286 4 : double dfY2 = poLS->getY(i + 1);
287 4 : double dfDX = dfX2 - dfX1;
288 4 : double dfDY = dfY2 - dfY1;
289 4 : dfSum += sqrt(dfDX * dfDX + dfDY * dfDY);
290 : }
291 1 : return dfSum / nPoints;
292 : }
293 :
294 1 : case wkbPolygon:
295 : {
296 1 : if (poGeom->IsEmpty())
297 0 : return 0;
298 1 : double dfSum = 0;
299 2 : for (const auto *poLS : poGeom->toPolygon())
300 : {
301 1 : dfSum += GetAverageSegmentLength(poLS);
302 : }
303 1 : return dfSum / (1 + poGeom->toPolygon()->getNumInteriorRings());
304 : }
305 :
306 1 : case wkbMultiPolygon:
307 : case wkbMultiLineString:
308 : case wkbGeometryCollection:
309 : {
310 1 : if (poGeom->IsEmpty())
311 0 : return 0;
312 1 : double dfSum = 0;
313 2 : for (const auto *poSubGeom : poGeom->toGeometryCollection())
314 : {
315 1 : dfSum += GetAverageSegmentLength(poSubGeom);
316 : }
317 1 : return dfSum / poGeom->toGeometryCollection()->getNumGeometries();
318 : }
319 :
320 0 : default:
321 0 : return 0;
322 : }
323 : }
324 :
325 : /************************************************************************/
326 : /* FetchSrcMethod() */
327 : /************************************************************************/
328 :
329 2620 : static const char *FetchSrcMethod(CSLConstList papszTO,
330 : const char *pszDefault = nullptr)
331 : {
332 2620 : const char *pszMethod = CSLFetchNameValue(papszTO, "SRC_METHOD");
333 2620 : if (!pszMethod)
334 2546 : pszMethod = CSLFetchNameValueDef(papszTO, "METHOD", pszDefault);
335 2620 : return pszMethod;
336 : }
337 :
338 1021 : static const char *FetchSrcMethod(const CPLStringList &aosTO,
339 : const char *pszDefault = nullptr)
340 : {
341 1021 : const char *pszMethod = aosTO.FetchNameValue("SRC_METHOD");
342 1021 : if (!pszMethod)
343 988 : pszMethod = aosTO.FetchNameValueDef("METHOD", pszDefault);
344 1021 : return pszMethod;
345 : }
346 :
347 : /************************************************************************/
348 : /* GetSrcDSProjection() */
349 : /* */
350 : /* Takes into account SRC_SRS transformer option in priority, and then */
351 : /* dataset characteristics as well as the METHOD transformer */
352 : /* option to determine the source SRS. */
353 : /************************************************************************/
354 :
355 1096 : static CPLString GetSrcDSProjection(GDALDatasetH hDS, CSLConstList papszTO)
356 : {
357 1096 : const char *pszProjection = CSLFetchNameValue(papszTO, "SRC_SRS");
358 1096 : if (pszProjection != nullptr || hDS == nullptr)
359 : {
360 76 : return pszProjection ? pszProjection : "";
361 : }
362 :
363 1020 : const char *pszMethod = FetchSrcMethod(papszTO);
364 1020 : char **papszMD = nullptr;
365 1020 : const OGRSpatialReferenceH hSRS = GDALGetSpatialRef(hDS);
366 : const char *pszGeolocationDataset =
367 1020 : CSLFetchNameValueDef(papszTO, "SRC_GEOLOC_ARRAY",
368 : CSLFetchNameValue(papszTO, "GEOLOC_ARRAY"));
369 1020 : if (pszGeolocationDataset != nullptr &&
370 0 : (pszMethod == nullptr || EQUAL(pszMethod, "GEOLOC_ARRAY")))
371 : {
372 : auto aosMD =
373 1 : GDALCreateGeolocationMetadata(hDS, pszGeolocationDataset, true);
374 1 : pszProjection = aosMD.FetchNameValue("SRS");
375 1 : if (pszProjection)
376 1 : return pszProjection; // return in this scope so that aosMD is
377 : // still valid
378 : }
379 1019 : else if (hSRS && (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")))
380 : {
381 831 : char *pszWKT = nullptr;
382 : {
383 1662 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
384 831 : if (OSRExportToWkt(hSRS, &pszWKT) != OGRERR_NONE)
385 : {
386 0 : CPLFree(pszWKT);
387 0 : pszWKT = nullptr;
388 0 : const char *const apszOptions[] = {"FORMAT=WKT2", nullptr};
389 0 : OSRExportToWktEx(hSRS, &pszWKT, apszOptions);
390 : }
391 : }
392 1662 : CPLString osWKT = pszWKT ? pszWKT : "";
393 831 : CPLFree(pszWKT);
394 831 : return osWKT;
395 : }
396 188 : else if (GDALGetGCPProjection(hDS) != nullptr &&
397 188 : strlen(GDALGetGCPProjection(hDS)) > 0 &&
398 380 : GDALGetGCPCount(hDS) > 1 &&
399 4 : (pszMethod == nullptr || STARTS_WITH_CI(pszMethod, "GCP_")))
400 : {
401 26 : pszProjection = GDALGetGCPProjection(hDS);
402 : }
403 165 : else if (GDALGetMetadata(hDS, "RPC") != nullptr &&
404 3 : (pszMethod == nullptr || EQUAL(pszMethod, "RPC")))
405 : {
406 14 : pszProjection = SRS_WKT_WGS84_LAT_LONG;
407 : }
408 157 : else if ((papszMD = GDALGetMetadata(hDS, "GEOLOCATION")) != nullptr &&
409 9 : (pszMethod == nullptr || EQUAL(pszMethod, "GEOLOC_ARRAY")))
410 : {
411 16 : pszProjection = CSLFetchNameValue(papszMD, "SRS");
412 : }
413 188 : return pszProjection ? pszProjection : "";
414 : }
415 :
416 : /************************************************************************/
417 : /* CreateCTCutlineToSrc() */
418 : /************************************************************************/
419 :
420 52 : static std::unique_ptr<OGRCoordinateTransformation> CreateCTCutlineToSrc(
421 : const OGRSpatialReference *poRasterSRS, const OGRSpatialReference *poDstSRS,
422 : const OGRSpatialReference *poCutlineSRS, CSLConstList papszTO)
423 : {
424 52 : const OGRSpatialReference *poCutlineOrTargetSRS =
425 52 : poCutlineSRS ? poCutlineSRS : poDstSRS;
426 52 : std::unique_ptr<OGRCoordinateTransformation> poCTCutlineToSrc;
427 100 : if (poCutlineOrTargetSRS && poRasterSRS &&
428 48 : !poCutlineOrTargetSRS->IsSame(poRasterSRS))
429 : {
430 16 : OGRCoordinateTransformationOptions oOptions;
431 : // If the cutline SRS is the same as the target SRS and there is
432 : // an explicit -ct between the source SRS and the target SRS, then
433 : // use it in the reverse way to transform from the cutline SRS to
434 : // the source SRS.
435 8 : if (poDstSRS && poCutlineOrTargetSRS->IsSame(poDstSRS))
436 : {
437 : const char *pszCT =
438 2 : CSLFetchNameValue(papszTO, "COORDINATE_OPERATION");
439 2 : if (pszCT)
440 : {
441 1 : oOptions.SetCoordinateOperation(pszCT, /* bInverse = */ true);
442 : }
443 : }
444 8 : poCTCutlineToSrc.reset(OGRCreateCoordinateTransformation(
445 : poCutlineOrTargetSRS, poRasterSRS, oOptions));
446 : }
447 52 : return poCTCutlineToSrc;
448 : }
449 :
450 : /************************************************************************/
451 : /* CropToCutline() */
452 : /************************************************************************/
453 :
454 18 : static CPLErr CropToCutline(const OGRGeometry *poCutline, CSLConstList papszTO,
455 : CSLConstList papszWarpOptions, int nSrcCount,
456 : GDALDatasetH *pahSrcDS, double &dfMinX,
457 : double &dfMinY, double &dfMaxX, double &dfMaxY,
458 : const GDALWarpAppOptions *psOptions)
459 : {
460 : // We could possibly directly reproject from cutline SRS to target SRS,
461 : // but when applying the cutline, it is reprojected to source raster image
462 : // space using the source SRS. To be consistent, we reproject
463 : // the cutline from cutline SRS to source SRS and then from source SRS to
464 : // target SRS.
465 18 : const OGRSpatialReference *poCutlineSRS = poCutline->getSpatialReference();
466 18 : const char *pszThisTargetSRS = CSLFetchNameValue(papszTO, "DST_SRS");
467 18 : std::unique_ptr<OGRSpatialReference> poSrcSRS;
468 18 : std::unique_ptr<OGRSpatialReference> poDstSRS;
469 :
470 : const CPLString osThisSourceSRS =
471 36 : GetSrcDSProjection(nSrcCount > 0 ? pahSrcDS[0] : nullptr, papszTO);
472 18 : if (!osThisSourceSRS.empty())
473 : {
474 14 : poSrcSRS = std::make_unique<OGRSpatialReference>();
475 14 : poSrcSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
476 14 : if (poSrcSRS->SetFromUserInput(osThisSourceSRS) != OGRERR_NONE)
477 : {
478 1 : CPLError(CE_Failure, CPLE_AppDefined,
479 : "Cannot compute bounding box of cutline.");
480 1 : return CE_Failure;
481 : }
482 : }
483 4 : else if (!pszThisTargetSRS && !poCutlineSRS)
484 : {
485 1 : OGREnvelope sEnvelope;
486 1 : poCutline->getEnvelope(&sEnvelope);
487 :
488 1 : dfMinX = sEnvelope.MinX;
489 1 : dfMinY = sEnvelope.MinY;
490 1 : dfMaxX = sEnvelope.MaxX;
491 1 : dfMaxY = sEnvelope.MaxY;
492 :
493 1 : return CE_None;
494 : }
495 : else
496 : {
497 3 : CPLError(CE_Failure, CPLE_AppDefined,
498 : "Cannot compute bounding box of cutline. Cannot find "
499 : "source SRS");
500 3 : return CE_Failure;
501 : }
502 :
503 13 : if (pszThisTargetSRS)
504 : {
505 3 : poDstSRS = std::make_unique<OGRSpatialReference>();
506 3 : poDstSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
507 3 : if (poDstSRS->SetFromUserInput(pszThisTargetSRS) != OGRERR_NONE)
508 : {
509 1 : CPLError(CE_Failure, CPLE_AppDefined,
510 : "Cannot compute bounding box of cutline.");
511 1 : return CE_Failure;
512 : }
513 : }
514 : else
515 : {
516 10 : poDstSRS.reset(poSrcSRS->Clone());
517 : }
518 :
519 24 : auto poCutlineGeom = std::unique_ptr<OGRGeometry>(poCutline->clone());
520 12 : auto poCTCutlineToSrc = CreateCTCutlineToSrc(poSrcSRS.get(), poDstSRS.get(),
521 24 : poCutlineSRS, papszTO);
522 :
523 12 : std::unique_ptr<OGRCoordinateTransformation> poCTSrcToDst;
524 12 : if (!poSrcSRS->IsSame(poDstSRS.get()))
525 : {
526 1 : poCTSrcToDst.reset(
527 1 : OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get()));
528 : }
529 :
530 : // Reproject cutline to target SRS, by doing intermediate vertex
531 : // densification in source SRS.
532 12 : if (poCTSrcToDst || poCTCutlineToSrc)
533 : {
534 2 : OGREnvelope sLastEnvelope, sCurEnvelope;
535 0 : std::unique_ptr<OGRGeometry> poTransformedGeom;
536 : auto poGeomInSrcSRS =
537 2 : std::unique_ptr<OGRGeometry>(poCutlineGeom->clone());
538 2 : if (poCTCutlineToSrc)
539 : {
540 4 : poGeomInSrcSRS.reset(OGRGeometryFactory::transformWithOptions(
541 2 : poGeomInSrcSRS.get(), poCTCutlineToSrc.get(), nullptr));
542 2 : if (!poGeomInSrcSRS)
543 0 : return CE_Failure;
544 : }
545 :
546 : // Do not use a smaller epsilon, otherwise it could cause useless
547 : // segmentization (https://github.com/OSGeo/gdal/issues/4826)
548 2 : constexpr double epsilon = 1e-10;
549 3 : for (int nIter = 0; nIter < 10; nIter++)
550 : {
551 3 : poTransformedGeom.reset(poGeomInSrcSRS->clone());
552 3 : if (poCTSrcToDst)
553 : {
554 4 : poTransformedGeom.reset(
555 : OGRGeometryFactory::transformWithOptions(
556 2 : poTransformedGeom.get(), poCTSrcToDst.get(), nullptr));
557 2 : if (!poTransformedGeom)
558 0 : return CE_Failure;
559 : }
560 3 : poTransformedGeom->getEnvelope(&sCurEnvelope);
561 3 : if (nIter > 0 || !poCTSrcToDst)
562 : {
563 2 : if (std::abs(sCurEnvelope.MinX - sLastEnvelope.MinX) <=
564 2 : epsilon *
565 2 : std::abs(sCurEnvelope.MinX + sLastEnvelope.MinX) &&
566 2 : std::abs(sCurEnvelope.MinY - sLastEnvelope.MinY) <=
567 2 : epsilon *
568 2 : std::abs(sCurEnvelope.MinY + sLastEnvelope.MinY) &&
569 2 : std::abs(sCurEnvelope.MaxX - sLastEnvelope.MaxX) <=
570 2 : epsilon *
571 6 : std::abs(sCurEnvelope.MaxX + sLastEnvelope.MaxX) &&
572 2 : std::abs(sCurEnvelope.MaxY - sLastEnvelope.MaxY) <=
573 2 : epsilon *
574 2 : std::abs(sCurEnvelope.MaxY + sLastEnvelope.MaxY))
575 : {
576 2 : break;
577 : }
578 : }
579 : double dfAverageSegmentLength =
580 1 : GetAverageSegmentLength(poGeomInSrcSRS.get());
581 1 : poGeomInSrcSRS->segmentize(dfAverageSegmentLength / 4);
582 :
583 1 : sLastEnvelope = sCurEnvelope;
584 : }
585 :
586 2 : poCutlineGeom = std::move(poTransformedGeom);
587 : }
588 :
589 12 : OGREnvelope sEnvelope;
590 12 : poCutlineGeom->getEnvelope(&sEnvelope);
591 :
592 12 : dfMinX = sEnvelope.MinX;
593 12 : dfMinY = sEnvelope.MinY;
594 12 : dfMaxX = sEnvelope.MaxX;
595 12 : dfMaxY = sEnvelope.MaxY;
596 22 : if (!poCTSrcToDst && nSrcCount > 0 && psOptions->dfXRes == 0.0 &&
597 10 : psOptions->dfYRes == 0.0)
598 : {
599 : // No raster reprojection: stick on exact pixel boundaries of the source
600 : // to preserve resolution and avoid resampling
601 : double adfGT[6];
602 10 : if (GDALGetGeoTransform(pahSrcDS[0], adfGT) == CE_None)
603 : {
604 : // We allow for a relative error in coordinates up to 0.1% of the
605 : // pixel size for rounding purposes.
606 10 : constexpr double REL_EPS_PIXEL = 1e-3;
607 10 : if (CPLFetchBool(papszWarpOptions, "CUTLINE_ALL_TOUCHED", false))
608 : {
609 : // All touched ? Then make the extent a bit larger than the
610 : // cutline envelope
611 3 : dfMinX = adfGT[0] +
612 3 : floor((dfMinX - adfGT[0]) / adfGT[1] + REL_EPS_PIXEL) *
613 3 : adfGT[1];
614 3 : dfMinY = adfGT[3] +
615 3 : ceil((dfMinY - adfGT[3]) / adfGT[5] - REL_EPS_PIXEL) *
616 3 : adfGT[5];
617 3 : dfMaxX = adfGT[0] +
618 3 : ceil((dfMaxX - adfGT[0]) / adfGT[1] - REL_EPS_PIXEL) *
619 3 : adfGT[1];
620 3 : dfMaxY = adfGT[3] +
621 3 : floor((dfMaxY - adfGT[3]) / adfGT[5] + REL_EPS_PIXEL) *
622 3 : adfGT[5];
623 : }
624 : else
625 : {
626 : // Otherwise, make it a bit smaller
627 7 : dfMinX = adfGT[0] +
628 7 : ceil((dfMinX - adfGT[0]) / adfGT[1] - REL_EPS_PIXEL) *
629 7 : adfGT[1];
630 7 : dfMinY = adfGT[3] +
631 7 : floor((dfMinY - adfGT[3]) / adfGT[5] + REL_EPS_PIXEL) *
632 7 : adfGT[5];
633 7 : dfMaxX = adfGT[0] +
634 7 : floor((dfMaxX - adfGT[0]) / adfGT[1] + REL_EPS_PIXEL) *
635 7 : adfGT[1];
636 7 : dfMaxY = adfGT[3] +
637 7 : ceil((dfMaxY - adfGT[3]) / adfGT[5] - REL_EPS_PIXEL) *
638 7 : adfGT[5];
639 : }
640 : }
641 : }
642 :
643 12 : return CE_None;
644 : }
645 :
646 : #ifdef USE_PROJ_BASED_VERTICAL_SHIFT_METHOD
647 :
648 1986 : static bool MustApplyVerticalShift(GDALDatasetH hWrkSrcDS,
649 : const GDALWarpAppOptions *psOptions,
650 : OGRSpatialReference &oSRSSrc,
651 : OGRSpatialReference &oSRSDst,
652 : bool &bSrcHasVertAxis, bool &bDstHasVertAxis)
653 : {
654 1986 : bool bApplyVShift = psOptions->bVShift;
655 :
656 : // Check if we must do vertical shift grid transform
657 : const char *pszSrcWKT =
658 1986 : psOptions->aosTransformerOptions.FetchNameValue("SRC_SRS");
659 1986 : if (pszSrcWKT)
660 88 : oSRSSrc.SetFromUserInput(pszSrcWKT);
661 : else
662 : {
663 1898 : auto hSRS = GDALGetSpatialRef(hWrkSrcDS);
664 1898 : if (hSRS)
665 1440 : oSRSSrc = *(OGRSpatialReference::FromHandle(hSRS));
666 : else
667 458 : return false;
668 : }
669 :
670 : const char *pszDstWKT =
671 1528 : psOptions->aosTransformerOptions.FetchNameValue("DST_SRS");
672 1528 : if (pszDstWKT)
673 395 : oSRSDst.SetFromUserInput(pszDstWKT);
674 : else
675 1133 : return false;
676 :
677 395 : if (oSRSSrc.IsSame(&oSRSDst))
678 10 : return false;
679 :
680 742 : bSrcHasVertAxis = oSRSSrc.IsCompound() ||
681 357 : ((oSRSSrc.IsProjected() || oSRSSrc.IsGeographic()) &&
682 357 : oSRSSrc.GetAxesCount() == 3);
683 :
684 748 : bDstHasVertAxis = oSRSDst.IsCompound() ||
685 363 : ((oSRSDst.IsProjected() || oSRSDst.IsGeographic()) &&
686 362 : oSRSDst.GetAxesCount() == 3);
687 :
688 653 : if ((GDALGetRasterCount(hWrkSrcDS) == 1 || psOptions->bVShift) &&
689 268 : (bSrcHasVertAxis || bDstHasVertAxis))
690 : {
691 38 : bApplyVShift = true;
692 : }
693 385 : return bApplyVShift;
694 : }
695 :
696 : /************************************************************************/
697 : /* ApplyVerticalShift() */
698 : /************************************************************************/
699 :
700 988 : static bool ApplyVerticalShift(GDALDatasetH hWrkSrcDS,
701 : const GDALWarpAppOptions *psOptions,
702 : GDALWarpOptions *psWO)
703 : {
704 988 : if (psOptions->bVShift)
705 : {
706 0 : psWO->papszWarpOptions = CSLSetNameValue(psWO->papszWarpOptions,
707 : "APPLY_VERTICAL_SHIFT", "YES");
708 : }
709 :
710 1976 : OGRSpatialReference oSRSSrc;
711 988 : OGRSpatialReference oSRSDst;
712 988 : bool bSrcHasVertAxis = false;
713 988 : bool bDstHasVertAxis = false;
714 : bool bApplyVShift =
715 988 : MustApplyVerticalShift(hWrkSrcDS, psOptions, oSRSSrc, oSRSDst,
716 : bSrcHasVertAxis, bDstHasVertAxis);
717 :
718 1787 : if ((GDALGetRasterCount(hWrkSrcDS) == 1 || psOptions->bVShift) &&
719 799 : (bSrcHasVertAxis || bDstHasVertAxis))
720 : {
721 19 : bApplyVShift = true;
722 19 : psWO->papszWarpOptions = CSLSetNameValue(psWO->papszWarpOptions,
723 : "APPLY_VERTICAL_SHIFT", "YES");
724 :
725 19 : if (CSLFetchNameValue(psWO->papszWarpOptions,
726 19 : "MULT_FACTOR_VERTICAL_SHIFT") == nullptr)
727 : {
728 : // Select how to go from input dataset units to meters
729 19 : double dfToMeterSrc = 1.0;
730 : const char *pszUnit =
731 19 : GDALGetRasterUnitType(GDALGetRasterBand(hWrkSrcDS, 1));
732 :
733 19 : double dfToMeterSrcAxis = 1.0;
734 19 : if (bSrcHasVertAxis)
735 : {
736 15 : oSRSSrc.GetAxis(nullptr, 2, nullptr, &dfToMeterSrcAxis);
737 : }
738 :
739 19 : if (pszUnit && (EQUAL(pszUnit, "m") || EQUAL(pszUnit, "meter") ||
740 18 : EQUAL(pszUnit, "metre")))
741 : {
742 : }
743 18 : else if (pszUnit &&
744 18 : (EQUAL(pszUnit, "ft") || EQUAL(pszUnit, "foot")))
745 : {
746 1 : dfToMeterSrc = CPLAtof(SRS_UL_FOOT_CONV);
747 : }
748 17 : else if (pszUnit && (EQUAL(pszUnit, "US survey foot")))
749 : {
750 1 : dfToMeterSrc = CPLAtof(SRS_UL_US_FOOT_CONV);
751 : }
752 16 : else if (pszUnit && !EQUAL(pszUnit, ""))
753 : {
754 1 : if (bSrcHasVertAxis)
755 : {
756 1 : dfToMeterSrc = dfToMeterSrcAxis;
757 : }
758 : else
759 : {
760 0 : CPLError(CE_Warning, CPLE_AppDefined,
761 : "Unknown units=%s. Assuming metre.", pszUnit);
762 : }
763 : }
764 : else
765 : {
766 15 : if (bSrcHasVertAxis)
767 11 : oSRSSrc.GetAxis(nullptr, 2, nullptr, &dfToMeterSrc);
768 : }
769 :
770 19 : double dfToMeterDst = 1.0;
771 19 : if (bDstHasVertAxis)
772 19 : oSRSDst.GetAxis(nullptr, 2, nullptr, &dfToMeterDst);
773 :
774 19 : if (dfToMeterSrc > 0 && dfToMeterDst > 0)
775 : {
776 19 : const double dfMultFactorVerticalShift =
777 19 : dfToMeterSrc / dfToMeterDst;
778 19 : CPLDebug("WARP", "Applying MULT_FACTOR_VERTICAL_SHIFT=%.18g",
779 : dfMultFactorVerticalShift);
780 19 : psWO->papszWarpOptions = CSLSetNameValue(
781 : psWO->papszWarpOptions, "MULT_FACTOR_VERTICAL_SHIFT",
782 : CPLSPrintf("%.18g", dfMultFactorVerticalShift));
783 :
784 19 : const double dfMultFactorVerticalShiftPipeline =
785 19 : dfToMeterSrcAxis / dfToMeterDst;
786 19 : CPLDebug("WARP",
787 : "Applying MULT_FACTOR_VERTICAL_SHIFT_PIPELINE=%.18g",
788 : dfMultFactorVerticalShiftPipeline);
789 19 : psWO->papszWarpOptions = CSLSetNameValue(
790 : psWO->papszWarpOptions,
791 : "MULT_FACTOR_VERTICAL_SHIFT_PIPELINE",
792 : CPLSPrintf("%.18g", dfMultFactorVerticalShiftPipeline));
793 : }
794 : }
795 : }
796 :
797 1976 : return bApplyVShift;
798 : }
799 :
800 : #else
801 :
802 : /************************************************************************/
803 : /* ApplyVerticalShiftGrid() */
804 : /************************************************************************/
805 :
806 : static GDALDatasetH ApplyVerticalShiftGrid(GDALDatasetH hWrkSrcDS,
807 : const GDALWarpAppOptions *psOptions,
808 : GDALDatasetH hVRTDS,
809 : bool &bErrorOccurredOut)
810 : {
811 : bErrorOccurredOut = false;
812 : // Check if we must do vertical shift grid transform
813 : OGRSpatialReference oSRSSrc;
814 : OGRSpatialReference oSRSDst;
815 : const char *pszSrcWKT =
816 : psOptions->aosTransformerOptions.FetchNameValue("SRC_SRS");
817 : if (pszSrcWKT)
818 : oSRSSrc.SetFromUserInput(pszSrcWKT);
819 : else
820 : {
821 : auto hSRS = GDALGetSpatialRef(hWrkSrcDS);
822 : if (hSRS)
823 : oSRSSrc = *(OGRSpatialReference::FromHandle(hSRS));
824 : }
825 :
826 : const char *pszDstWKT =
827 : psOptions->aosTransformerOptions.FetchNameValue("DST_SRS");
828 : if (pszDstWKT)
829 : oSRSDst.SetFromUserInput(pszDstWKT);
830 :
831 : double adfGT[6] = {};
832 : if (GDALGetRasterCount(hWrkSrcDS) == 1 &&
833 : GDALGetGeoTransform(hWrkSrcDS, adfGT) == CE_None &&
834 : !oSRSSrc.IsEmpty() && !oSRSDst.IsEmpty())
835 : {
836 : if ((oSRSSrc.IsCompound() ||
837 : (oSRSSrc.IsGeographic() && oSRSSrc.GetAxesCount() == 3)) ||
838 : (oSRSDst.IsCompound() ||
839 : (oSRSDst.IsGeographic() && oSRSDst.GetAxesCount() == 3)))
840 : {
841 : const char *pszSrcProj4Geoids =
842 : oSRSSrc.GetExtension("VERT_DATUM", "PROJ4_GRIDS");
843 : const char *pszDstProj4Geoids =
844 : oSRSDst.GetExtension("VERT_DATUM", "PROJ4_GRIDS");
845 :
846 : if (oSRSSrc.IsCompound() && pszSrcProj4Geoids == nullptr)
847 : {
848 : CPLDebug("GDALWARP", "Source SRS is a compound CRS but lacks "
849 : "+geoidgrids");
850 : }
851 :
852 : if (oSRSDst.IsCompound() && pszDstProj4Geoids == nullptr)
853 : {
854 : CPLDebug("GDALWARP", "Target SRS is a compound CRS but lacks "
855 : "+geoidgrids");
856 : }
857 :
858 : if (pszSrcProj4Geoids != nullptr && pszDstProj4Geoids != nullptr &&
859 : EQUAL(pszSrcProj4Geoids, pszDstProj4Geoids))
860 : {
861 : pszSrcProj4Geoids = nullptr;
862 : pszDstProj4Geoids = nullptr;
863 : }
864 :
865 : // Select how to go from input dataset units to meters
866 : const char *pszUnit =
867 : GDALGetRasterUnitType(GDALGetRasterBand(hWrkSrcDS, 1));
868 : double dfToMeterSrc = 1.0;
869 : if (pszUnit && (EQUAL(pszUnit, "m") || EQUAL(pszUnit, "meter") ||
870 : EQUAL(pszUnit, "metre")))
871 : {
872 : }
873 : else if (pszUnit &&
874 : (EQUAL(pszUnit, "ft") || EQUAL(pszUnit, "foot")))
875 : {
876 : dfToMeterSrc = CPLAtof(SRS_UL_FOOT_CONV);
877 : }
878 : else if (pszUnit && (EQUAL(pszUnit, "US survey foot")))
879 : {
880 : dfToMeterSrc = CPLAtof(SRS_UL_US_FOOT_CONV);
881 : }
882 : else
883 : {
884 : if (pszUnit && !EQUAL(pszUnit, ""))
885 : {
886 : CPLError(CE_Warning, CPLE_AppDefined, "Unknown units=%s",
887 : pszUnit);
888 : }
889 : if (oSRSSrc.IsCompound())
890 : {
891 : dfToMeterSrc = oSRSSrc.GetTargetLinearUnits("VERT_CS");
892 : }
893 : else if (oSRSSrc.IsProjected())
894 : {
895 : dfToMeterSrc = oSRSSrc.GetLinearUnits();
896 : }
897 : }
898 :
899 : double dfToMeterDst = 1.0;
900 : if (oSRSDst.IsCompound())
901 : {
902 : dfToMeterDst = oSRSDst.GetTargetLinearUnits("VERT_CS");
903 : }
904 : else if (oSRSDst.IsProjected())
905 : {
906 : dfToMeterDst = oSRSDst.GetLinearUnits();
907 : }
908 :
909 : char **papszOptions = nullptr;
910 : if (psOptions->eOutputType != GDT_Unknown)
911 : {
912 : papszOptions = CSLSetNameValue(
913 : papszOptions, "DATATYPE",
914 : GDALGetDataTypeName(psOptions->eOutputType));
915 : }
916 : papszOptions =
917 : CSLSetNameValue(papszOptions, "ERROR_ON_MISSING_VERT_SHIFT",
918 : psOptions->aosTransformerOptions.FetchNameValue(
919 : "ERROR_ON_MISSING_VERT_SHIFT"));
920 : papszOptions = CSLSetNameValue(papszOptions, "SRC_SRS", pszSrcWKT);
921 :
922 : if (pszSrcProj4Geoids != nullptr)
923 : {
924 : int bError = FALSE;
925 : GDALDatasetH hGridDataset =
926 : GDALOpenVerticalShiftGrid(pszSrcProj4Geoids, &bError);
927 : if (bError && hGridDataset == nullptr)
928 : {
929 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s.",
930 : pszSrcProj4Geoids);
931 : bErrorOccurredOut = true;
932 : CSLDestroy(papszOptions);
933 : return hWrkSrcDS;
934 : }
935 : else if (hGridDataset != nullptr)
936 : {
937 : // Transform from source vertical datum to WGS84
938 : GDALDatasetH hTmpDS = GDALApplyVerticalShiftGrid(
939 : hWrkSrcDS, hGridDataset, FALSE, dfToMeterSrc, 1.0,
940 : papszOptions);
941 : GDALReleaseDataset(hGridDataset);
942 : if (hTmpDS == nullptr)
943 : {
944 : bErrorOccurredOut = true;
945 : CSLDestroy(papszOptions);
946 : return hWrkSrcDS;
947 : }
948 : else
949 : {
950 : if (hVRTDS)
951 : {
952 : CPLError(
953 : CE_Failure, CPLE_NotSupported,
954 : "Warping to VRT with vertical transformation "
955 : "not supported with PROJ < 6.3");
956 : bErrorOccurredOut = true;
957 : CSLDestroy(papszOptions);
958 : return hWrkSrcDS;
959 : }
960 :
961 : CPLDebug("GDALWARP",
962 : "Adjusting source dataset "
963 : "with source vertical datum using %s",
964 : pszSrcProj4Geoids);
965 : GDALReleaseDataset(hWrkSrcDS);
966 : hWrkSrcDS = hTmpDS;
967 : dfToMeterSrc = 1.0;
968 : }
969 : }
970 : }
971 :
972 : if (pszDstProj4Geoids != nullptr)
973 : {
974 : int bError = FALSE;
975 : GDALDatasetH hGridDataset =
976 : GDALOpenVerticalShiftGrid(pszDstProj4Geoids, &bError);
977 : if (bError && hGridDataset == nullptr)
978 : {
979 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s.",
980 : pszDstProj4Geoids);
981 : bErrorOccurredOut = true;
982 : CSLDestroy(papszOptions);
983 : return hWrkSrcDS;
984 : }
985 : else if (hGridDataset != nullptr)
986 : {
987 : // Transform from WGS84 to target vertical datum
988 : GDALDatasetH hTmpDS = GDALApplyVerticalShiftGrid(
989 : hWrkSrcDS, hGridDataset, TRUE, dfToMeterSrc,
990 : dfToMeterDst, papszOptions);
991 : GDALReleaseDataset(hGridDataset);
992 : if (hTmpDS == nullptr)
993 : {
994 : bErrorOccurredOut = true;
995 : CSLDestroy(papszOptions);
996 : return hWrkSrcDS;
997 : }
998 : else
999 : {
1000 : if (hVRTDS)
1001 : {
1002 : CPLError(
1003 : CE_Failure, CPLE_NotSupported,
1004 : "Warping to VRT with vertical transformation "
1005 : "not supported with PROJ < 6.3");
1006 : bErrorOccurredOut = true;
1007 : CSLDestroy(papszOptions);
1008 : return hWrkSrcDS;
1009 : }
1010 :
1011 : CPLDebug("GDALWARP",
1012 : "Adjusting source dataset "
1013 : "with target vertical datum using %s",
1014 : pszDstProj4Geoids);
1015 : GDALReleaseDataset(hWrkSrcDS);
1016 : hWrkSrcDS = hTmpDS;
1017 : }
1018 : }
1019 : }
1020 :
1021 : CSLDestroy(papszOptions);
1022 : }
1023 : }
1024 : return hWrkSrcDS;
1025 : }
1026 :
1027 : #endif
1028 :
1029 : /************************************************************************/
1030 : /* CanUseBuildVRT() */
1031 : /************************************************************************/
1032 :
1033 5 : static bool CanUseBuildVRT(int nSrcCount, GDALDatasetH *pahSrcDS)
1034 : {
1035 :
1036 5 : bool bCanUseBuildVRT = true;
1037 10 : std::vector<std::array<double, 4>> aoExtents;
1038 5 : bool bSrcHasAlpha = false;
1039 5 : int nPrevBandCount = 0;
1040 5 : OGRSpatialReference oSRSPrev;
1041 5 : double dfLastResX = 0;
1042 5 : double dfLastResY = 0;
1043 14 : for (int i = 0; i < nSrcCount; i++)
1044 : {
1045 : double adfGT[6];
1046 9 : auto hSrcDS = pahSrcDS[i];
1047 9 : if (EQUAL(GDALGetDescription(hSrcDS), ""))
1048 : {
1049 0 : bCanUseBuildVRT = false;
1050 0 : break;
1051 : }
1052 18 : if (GDALGetGeoTransform(hSrcDS, adfGT) != CE_None || adfGT[2] != 0 ||
1053 18 : adfGT[4] != 0 || adfGT[5] > 0)
1054 : {
1055 0 : bCanUseBuildVRT = false;
1056 0 : break;
1057 : }
1058 9 : const double dfMinX = adfGT[0];
1059 9 : const double dfMinY = adfGT[3] + GDALGetRasterYSize(hSrcDS) * adfGT[5];
1060 9 : const double dfMaxX = adfGT[0] + GDALGetRasterXSize(hSrcDS) * adfGT[1];
1061 9 : const double dfMaxY = adfGT[3];
1062 9 : const int nBands = GDALGetRasterCount(hSrcDS);
1063 9 : if (nBands > 1 && GDALGetRasterColorInterpretation(GDALGetRasterBand(
1064 : hSrcDS, nBands)) == GCI_AlphaBand)
1065 : {
1066 4 : bSrcHasAlpha = true;
1067 : }
1068 : aoExtents.emplace_back(
1069 9 : std::array<double, 4>{{dfMinX, dfMinY, dfMaxX, dfMaxY}});
1070 9 : const auto poSRS = GDALDataset::FromHandle(hSrcDS)->GetSpatialRef();
1071 9 : if (i == 0)
1072 : {
1073 5 : nPrevBandCount = nBands;
1074 5 : if (poSRS)
1075 5 : oSRSPrev = *poSRS;
1076 5 : dfLastResX = adfGT[1];
1077 5 : dfLastResY = adfGT[5];
1078 : }
1079 : else
1080 : {
1081 4 : if (nPrevBandCount != nBands)
1082 : {
1083 0 : bCanUseBuildVRT = false;
1084 0 : break;
1085 : }
1086 4 : if (poSRS == nullptr && !oSRSPrev.IsEmpty())
1087 : {
1088 0 : bCanUseBuildVRT = false;
1089 0 : break;
1090 : }
1091 8 : if (poSRS != nullptr &&
1092 4 : (oSRSPrev.IsEmpty() || !poSRS->IsSame(&oSRSPrev)))
1093 : {
1094 0 : bCanUseBuildVRT = false;
1095 0 : break;
1096 : }
1097 4 : if (dfLastResX != adfGT[1] || dfLastResY != adfGT[5])
1098 : {
1099 0 : bCanUseBuildVRT = false;
1100 0 : break;
1101 : }
1102 : }
1103 : }
1104 5 : if (bSrcHasAlpha && bCanUseBuildVRT)
1105 : {
1106 : // Quadratic performance loop. If that happens to be an issue,
1107 : // we might need to build a quad tree
1108 2 : for (size_t i = 0; i < aoExtents.size(); i++)
1109 : {
1110 2 : const double dfMinX = aoExtents[i][0];
1111 2 : const double dfMinY = aoExtents[i][1];
1112 2 : const double dfMaxX = aoExtents[i][2];
1113 2 : const double dfMaxY = aoExtents[i][3];
1114 2 : for (size_t j = i + 1; j < aoExtents.size(); j++)
1115 : {
1116 2 : const double dfOtherMinX = aoExtents[j][0];
1117 2 : const double dfOtherMinY = aoExtents[j][1];
1118 2 : const double dfOtherMaxX = aoExtents[j][2];
1119 2 : const double dfOtherMaxY = aoExtents[j][3];
1120 2 : if (dfMinX < dfOtherMaxX && dfOtherMinX < dfMaxX &&
1121 2 : dfMinY < dfOtherMaxY && dfOtherMinY < dfMaxY)
1122 : {
1123 2 : bCanUseBuildVRT = false;
1124 2 : break;
1125 : }
1126 : }
1127 2 : if (!bCanUseBuildVRT)
1128 2 : break;
1129 : }
1130 : }
1131 10 : return bCanUseBuildVRT;
1132 : }
1133 :
1134 : #ifdef HAVE_TIFF
1135 :
1136 : /************************************************************************/
1137 : /* DealWithCOGOptions() */
1138 : /************************************************************************/
1139 :
1140 8 : static bool DealWithCOGOptions(CPLStringList &aosCreateOptions, int nSrcCount,
1141 : GDALDatasetH *pahSrcDS,
1142 : GDALWarpAppOptions *psOptions,
1143 : GDALTransformerArgUniquePtr &hUniqueTransformArg)
1144 : {
1145 8 : const auto SetDstSRS = [psOptions](const std::string &osTargetSRS)
1146 : {
1147 : const char *pszExistingDstSRS =
1148 5 : psOptions->aosTransformerOptions.FetchNameValue("DST_SRS");
1149 5 : if (pszExistingDstSRS)
1150 : {
1151 2 : OGRSpatialReference oSRS1;
1152 2 : oSRS1.SetFromUserInput(pszExistingDstSRS);
1153 2 : OGRSpatialReference oSRS2;
1154 2 : oSRS2.SetFromUserInput(osTargetSRS.c_str());
1155 2 : if (!oSRS1.IsSame(&oSRS2))
1156 : {
1157 2 : CPLError(CE_Failure, CPLE_AppDefined,
1158 : "Target SRS implied by COG creation options is not "
1159 : "the same as the one specified by -t_srs");
1160 2 : return false;
1161 : }
1162 : }
1163 : psOptions->aosTransformerOptions.SetNameValue("DST_SRS",
1164 3 : osTargetSRS.c_str());
1165 3 : return true;
1166 8 : };
1167 :
1168 16 : CPLString osTargetSRS;
1169 8 : if (COGGetTargetSRS(aosCreateOptions.List(), osTargetSRS))
1170 : {
1171 5 : if (!SetDstSRS(osTargetSRS))
1172 2 : return false;
1173 : }
1174 :
1175 6 : if (!(psOptions->dfMinX == 0 && psOptions->dfMinY == 0 &&
1176 5 : psOptions->dfMaxX == 0 && psOptions->dfMaxY == 0 &&
1177 5 : psOptions->dfXRes == 0 && psOptions->dfYRes == 0 &&
1178 5 : psOptions->nForcePixels == 0 && psOptions->nForceLines == 0))
1179 : {
1180 2 : if (!psOptions->bResampleAlgSpecifiedByUser && nSrcCount > 0)
1181 : {
1182 : try
1183 : {
1184 1 : GDALGetWarpResampleAlg(
1185 2 : COGGetResampling(GDALDataset::FromHandle(pahSrcDS[0]),
1186 1 : aosCreateOptions.List())
1187 : .c_str(),
1188 1 : psOptions->eResampleAlg);
1189 : }
1190 0 : catch (const std::invalid_argument &)
1191 : {
1192 : // Cannot happen actually. Coverity Scan false positive...
1193 0 : CPLAssert(false);
1194 : }
1195 : }
1196 2 : return true;
1197 : }
1198 :
1199 8 : GDALWarpAppOptions oClonedOptions(*psOptions);
1200 4 : oClonedOptions.bQuiet = true;
1201 : const CPLString osTmpFilename(
1202 8 : VSIMemGenerateHiddenFilename("gdalwarp_tmp.tif"));
1203 8 : CPLStringList aosTmpGTiffCreateOptions;
1204 4 : aosTmpGTiffCreateOptions.SetNameValue("SPARSE_OK", "YES");
1205 4 : aosTmpGTiffCreateOptions.SetNameValue("TILED", "YES");
1206 4 : aosTmpGTiffCreateOptions.SetNameValue("BLOCKXSIZE", "4096");
1207 4 : aosTmpGTiffCreateOptions.SetNameValue("BLOCKYSIZE", "4096");
1208 4 : auto hTmpDS = GDALWarpCreateOutput(
1209 : nSrcCount, pahSrcDS, osTmpFilename, "GTiff",
1210 : oClonedOptions.aosTransformerOptions.List(),
1211 4 : aosTmpGTiffCreateOptions.List(), oClonedOptions.eOutputType,
1212 : hUniqueTransformArg, false, &oClonedOptions,
1213 : /* bUpdateTransformerWithDestGT = */ false);
1214 4 : if (hTmpDS == nullptr)
1215 : {
1216 0 : return false;
1217 : }
1218 :
1219 4 : CPLString osResampling;
1220 4 : int nXSize = 0;
1221 4 : int nYSize = 0;
1222 4 : double dfMinX = 0;
1223 4 : double dfMinY = 0;
1224 4 : double dfMaxX = 0;
1225 4 : double dfMaxY = 0;
1226 4 : bool bRet = true;
1227 4 : if (COGGetWarpingCharacteristics(GDALDataset::FromHandle(hTmpDS),
1228 4 : aosCreateOptions.List(), osResampling,
1229 : osTargetSRS, nXSize, nYSize, dfMinX,
1230 : dfMinY, dfMaxX, dfMaxY))
1231 : {
1232 2 : if (!psOptions->bResampleAlgSpecifiedByUser)
1233 : {
1234 : try
1235 : {
1236 2 : GDALGetWarpResampleAlg(osResampling, psOptions->eResampleAlg);
1237 : }
1238 0 : catch (const std::invalid_argument &)
1239 : {
1240 : // Cannot happen actually. Coverity Scan false positive...
1241 0 : CPLAssert(false);
1242 : }
1243 : }
1244 :
1245 2 : psOptions->dfMinX = dfMinX;
1246 2 : psOptions->dfMinY = dfMinY;
1247 2 : psOptions->dfMaxX = dfMaxX;
1248 2 : psOptions->dfMaxY = dfMaxY;
1249 2 : psOptions->nForcePixels = nXSize;
1250 2 : psOptions->nForceLines = nYSize;
1251 2 : COGRemoveWarpingOptions(aosCreateOptions);
1252 : }
1253 4 : GDALClose(hTmpDS);
1254 4 : VSIUnlink(osTmpFilename);
1255 4 : return bRet;
1256 : }
1257 :
1258 : #endif
1259 :
1260 : /************************************************************************/
1261 : /* GDALWarpIndirect() */
1262 : /************************************************************************/
1263 :
1264 : static GDALDatasetH
1265 : GDALWarpDirect(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
1266 : GDALDatasetH *pahSrcDS,
1267 : GDALTransformerArgUniquePtr hUniqueTransformArg,
1268 : GDALWarpAppOptions *psOptions, int *pbUsageError);
1269 :
1270 1028 : static int CPL_STDCALL myScaledProgress(double dfProgress, const char *,
1271 : void *pProgressData)
1272 : {
1273 1028 : return GDALScaledProgress(dfProgress, nullptr, pProgressData);
1274 : }
1275 :
1276 14 : static GDALDatasetH GDALWarpIndirect(const char *pszDest, GDALDriverH hDriver,
1277 : int nSrcCount, GDALDatasetH *pahSrcDS,
1278 : GDALWarpAppOptions *psOptions,
1279 : int *pbUsageError)
1280 : {
1281 28 : CPLStringList aosCreateOptions(psOptions->aosCreateOptions);
1282 14 : psOptions->aosCreateOptions.Clear();
1283 :
1284 : // Do not use a warped VRT input for COG output, because that would cause
1285 : // warping to be done both during overview computation and creation of
1286 : // full resolution image. Better materialize a temporary GTiff a bit later
1287 : // in that method.
1288 14 : if (nSrcCount == 1 && !EQUAL(psOptions->osFormat.c_str(), "COG"))
1289 : {
1290 3 : psOptions->osFormat = "VRT";
1291 3 : auto pfnProgress = psOptions->pfnProgress;
1292 3 : psOptions->pfnProgress = GDALDummyProgress;
1293 3 : auto pProgressData = psOptions->pProgressData;
1294 3 : psOptions->pProgressData = nullptr;
1295 :
1296 3 : auto hTmpDS = GDALWarpDirect("", nullptr, nSrcCount, pahSrcDS, nullptr,
1297 : psOptions, pbUsageError);
1298 3 : if (hTmpDS)
1299 : {
1300 3 : auto hRet = GDALCreateCopy(hDriver, pszDest, hTmpDS, FALSE,
1301 3 : aosCreateOptions.List(), pfnProgress,
1302 : pProgressData);
1303 3 : GDALClose(hTmpDS);
1304 3 : return hRet;
1305 : }
1306 0 : return nullptr;
1307 : }
1308 :
1309 : // Detect a pure mosaicing situation where a BuildVRT approach is
1310 : // sufficient.
1311 11 : GDALDatasetH hTmpDS = nullptr;
1312 11 : if (psOptions->aosTransformerOptions.empty() &&
1313 5 : psOptions->eOutputType == GDT_Unknown && psOptions->dfMinX == 0 &&
1314 5 : psOptions->dfMinY == 0 && psOptions->dfMaxX == 0 &&
1315 5 : psOptions->dfMaxY == 0 && psOptions->dfXRes == 0 &&
1316 5 : psOptions->dfYRes == 0 && psOptions->nForcePixels == 0 &&
1317 10 : psOptions->nForceLines == 0 &&
1318 21 : psOptions->osCutlineDSNameOrWKT.empty() &&
1319 5 : CanUseBuildVRT(nSrcCount, pahSrcDS))
1320 : {
1321 6 : CPLStringList aosArgv;
1322 3 : const int nBands = GDALGetRasterCount(pahSrcDS[0]);
1323 0 : if ((nBands == 1 ||
1324 0 : (nBands > 1 && GDALGetRasterColorInterpretation(GDALGetRasterBand(
1325 6 : pahSrcDS[0], nBands)) != GCI_AlphaBand)) &&
1326 3 : (psOptions->bEnableDstAlpha
1327 : #ifdef HAVE_TIFF
1328 3 : || (EQUAL(psOptions->osFormat.c_str(), "COG") &&
1329 3 : COGHasWarpingOptions(aosCreateOptions.List()) &&
1330 2 : CPLTestBool(
1331 : aosCreateOptions.FetchNameValueDef("ADD_ALPHA", "YES")))
1332 : #endif
1333 : ))
1334 : {
1335 2 : aosArgv.AddString("-addalpha");
1336 : }
1337 : auto psBuildVRTOptions =
1338 3 : GDALBuildVRTOptionsNew(aosArgv.List(), nullptr);
1339 3 : hTmpDS = GDALBuildVRT("", nSrcCount, pahSrcDS, nullptr,
1340 : psBuildVRTOptions, nullptr);
1341 3 : GDALBuildVRTOptionsFree(psBuildVRTOptions);
1342 : }
1343 11 : auto pfnProgress = psOptions->pfnProgress;
1344 11 : auto pProgressData = psOptions->pProgressData;
1345 22 : CPLString osTmpFilename;
1346 11 : double dfStartPctCreateCopy = 0.0;
1347 11 : if (hTmpDS == nullptr)
1348 : {
1349 0 : GDALTransformerArgUniquePtr hUniqueTransformArg;
1350 : #ifdef HAVE_TIFF
1351 : // Special processing for COG output. As some of its options do
1352 : // on-the-fly reprojection, take them into account now, and remove them
1353 : // from the COG creation stage.
1354 16 : if (EQUAL(psOptions->osFormat.c_str(), "COG") &&
1355 8 : !DealWithCOGOptions(aosCreateOptions, nSrcCount, pahSrcDS,
1356 : psOptions, hUniqueTransformArg))
1357 : {
1358 2 : return nullptr;
1359 : }
1360 : #endif
1361 :
1362 : // Materialize a temporary GeoTIFF with the result of the warp
1363 6 : psOptions->osFormat = "GTiff";
1364 6 : psOptions->aosCreateOptions.AddString("SPARSE_OK=YES");
1365 6 : psOptions->aosCreateOptions.AddString("COMPRESS=LZW");
1366 6 : psOptions->aosCreateOptions.AddString("TILED=YES");
1367 6 : psOptions->aosCreateOptions.AddString("BIGTIFF=YES");
1368 6 : psOptions->pfnProgress = myScaledProgress;
1369 6 : dfStartPctCreateCopy = 2. / 3;
1370 6 : psOptions->pProgressData = GDALCreateScaledProgress(
1371 : 0, dfStartPctCreateCopy, pfnProgress, pProgressData);
1372 6 : psOptions->bDeleteOutputFileOnceCreated = true;
1373 6 : osTmpFilename = CPLGenerateTempFilenameSafe(CPLGetFilename(pszDest));
1374 6 : hTmpDS = GDALWarpDirect(osTmpFilename, nullptr, nSrcCount, pahSrcDS,
1375 6 : std::move(hUniqueTransformArg), psOptions,
1376 : pbUsageError);
1377 6 : GDALDestroyScaledProgress(psOptions->pProgressData);
1378 6 : psOptions->pfnProgress = nullptr;
1379 6 : psOptions->pProgressData = nullptr;
1380 : }
1381 9 : if (hTmpDS)
1382 : {
1383 9 : auto pScaledProgressData = GDALCreateScaledProgress(
1384 : dfStartPctCreateCopy, 1.0, pfnProgress, pProgressData);
1385 9 : auto hRet = GDALCreateCopy(hDriver, pszDest, hTmpDS, FALSE,
1386 9 : aosCreateOptions.List(), myScaledProgress,
1387 : pScaledProgressData);
1388 9 : GDALDestroyScaledProgress(pScaledProgressData);
1389 9 : GDALClose(hTmpDS);
1390 : VSIStatBufL sStat;
1391 15 : if (!osTmpFilename.empty() &&
1392 6 : VSIStatL(osTmpFilename.c_str(), &sStat) == 0)
1393 : {
1394 6 : GDALDeleteDataset(GDALGetDriverByName("GTiff"), osTmpFilename);
1395 : }
1396 9 : return hRet;
1397 : }
1398 0 : return nullptr;
1399 : }
1400 :
1401 : /************************************************************************/
1402 : /* GDALWarp() */
1403 : /************************************************************************/
1404 :
1405 : /**
1406 : * Image reprojection and warping function.
1407 : *
1408 : * This is the equivalent of the <a href="/programs/gdalwarp.html">gdalwarp</a>
1409 : * utility.
1410 : *
1411 : * GDALWarpAppOptions* must be allocated and freed with GDALWarpAppOptionsNew()
1412 : * and GDALWarpAppOptionsFree() respectively.
1413 : * pszDest and hDstDS cannot be used at the same time.
1414 : *
1415 : * @param pszDest the destination dataset path or NULL.
1416 : * @param hDstDS the destination dataset or NULL.
1417 : * @param nSrcCount the number of input datasets.
1418 : * @param pahSrcDS the list of input datasets. For practical purposes, the type
1419 : * of this argument should be considered as "const GDALDatasetH* const*", that
1420 : * is neither the array nor its values are mutated by this function.
1421 : * @param psOptionsIn the options struct returned by GDALWarpAppOptionsNew() or
1422 : * NULL.
1423 : * @param pbUsageError pointer to a integer output variable to store if any
1424 : * usage error has occurred, or NULL.
1425 : * @return the output dataset (new dataset that must be closed using
1426 : * GDALClose(), or hDstDS if not NULL) or NULL in case of error. If the output
1427 : * format is a VRT dataset, then the returned VRT dataset has a reference to
1428 : * pahSrcDS[0]. Hence pahSrcDS[0] should be closed after the returned dataset
1429 : * if using GDALClose().
1430 : * A safer alternative is to use GDALReleaseDataset() instead of using
1431 : * GDALClose(), in which case you can close datasets in any order.
1432 : *
1433 : * @since GDAL 2.1
1434 : */
1435 :
1436 1010 : GDALDatasetH GDALWarp(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
1437 : GDALDatasetH *pahSrcDS,
1438 : const GDALWarpAppOptions *psOptionsIn, int *pbUsageError)
1439 : {
1440 1010 : CPLErrorReset();
1441 :
1442 2043 : for (int i = 0; i < nSrcCount; i++)
1443 : {
1444 1033 : if (!pahSrcDS[i])
1445 0 : return nullptr;
1446 : }
1447 :
1448 2020 : GDALWarpAppOptions oOptionsTmp;
1449 1010 : if (psOptionsIn)
1450 1008 : oOptionsTmp = *psOptionsIn;
1451 1010 : GDALWarpAppOptions *psOptions = &oOptionsTmp;
1452 :
1453 1010 : if (hDstDS == nullptr)
1454 : {
1455 911 : if (psOptions->osFormat.empty())
1456 : {
1457 406 : psOptions->osFormat = GetOutputDriverForRaster(pszDest);
1458 406 : if (psOptions->osFormat.empty())
1459 : {
1460 0 : return nullptr;
1461 : }
1462 : }
1463 :
1464 911 : auto hDriver = GDALGetDriverByName(psOptions->osFormat.c_str());
1465 1822 : if (hDriver != nullptr &&
1466 911 : (EQUAL(psOptions->osFormat.c_str(), "COG") ||
1467 900 : (GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) ==
1468 3 : nullptr &&
1469 3 : GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATECOPY, nullptr) !=
1470 : nullptr)))
1471 : {
1472 14 : auto ret = GDALWarpIndirect(pszDest, hDriver, nSrcCount, pahSrcDS,
1473 : psOptions, pbUsageError);
1474 14 : return ret;
1475 : }
1476 : }
1477 :
1478 996 : auto ret = GDALWarpDirect(pszDest, hDstDS, nSrcCount, pahSrcDS, nullptr,
1479 : psOptions, pbUsageError);
1480 :
1481 996 : return ret;
1482 : }
1483 :
1484 : /************************************************************************/
1485 : /* UseTEAndTSAndTRConsistently() */
1486 : /************************************************************************/
1487 :
1488 910 : static bool UseTEAndTSAndTRConsistently(const GDALWarpAppOptions *psOptions)
1489 : {
1490 : // We normally don't allow -te, -ts and -tr together, unless they are all
1491 : // consistent. The interest of this is to use the -tr values to produce
1492 : // exact pixel size, rather than inferring it from -te and -ts
1493 :
1494 : // Constant and logic to be kept in sync with cogdriver.cpp
1495 910 : constexpr double RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP = 1e-8;
1496 194 : return psOptions->nForcePixels != 0 && psOptions->nForceLines != 0 &&
1497 189 : psOptions->dfXRes != 0 && psOptions->dfYRes != 0 &&
1498 50 : !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
1499 0 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0) &&
1500 50 : fabs((psOptions->dfMaxX - psOptions->dfMinX) / psOptions->dfXRes -
1501 50 : psOptions->nForcePixels) <=
1502 1104 : RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP &&
1503 50 : fabs((psOptions->dfMaxY - psOptions->dfMinY) / psOptions->dfYRes -
1504 50 : psOptions->nForceLines) <=
1505 910 : RELATIVE_ERROR_RES_SHARED_BY_COG_AND_GDALWARP;
1506 : }
1507 :
1508 : /************************************************************************/
1509 : /* CheckOptions() */
1510 : /************************************************************************/
1511 :
1512 1005 : static bool CheckOptions(const char *pszDest, GDALDatasetH hDstDS,
1513 : int nSrcCount, GDALDatasetH *pahSrcDS,
1514 : GDALWarpAppOptions *psOptions, bool &bVRT,
1515 : int *pbUsageError)
1516 : {
1517 :
1518 1005 : if (hDstDS)
1519 : {
1520 99 : if (psOptions->bCreateOutput == true)
1521 : {
1522 0 : CPLError(CE_Warning, CPLE_AppDefined,
1523 : "All options related to creation ignored in update mode");
1524 0 : psOptions->bCreateOutput = false;
1525 : }
1526 : }
1527 :
1528 2208 : if ((psOptions->osFormat.empty() &&
1529 2010 : EQUAL(CPLGetExtensionSafe(pszDest).c_str(), "VRT")) ||
1530 1005 : (EQUAL(psOptions->osFormat.c_str(), "VRT")))
1531 : {
1532 112 : if (hDstDS != nullptr)
1533 : {
1534 0 : CPLError(CE_Warning, CPLE_NotSupported,
1535 : "VRT output not compatible with existing dataset.");
1536 0 : return false;
1537 : }
1538 :
1539 112 : bVRT = true;
1540 :
1541 112 : if (nSrcCount > 1)
1542 : {
1543 0 : CPLError(CE_Warning, CPLE_AppDefined,
1544 : "gdalwarp -of VRT just takes into account "
1545 : "the first source dataset.\nIf all source datasets "
1546 : "are in the same projection, try making a mosaic of\n"
1547 : "them with gdalbuildvrt, and use the resulting "
1548 : "VRT file as the input of\ngdalwarp -of VRT.");
1549 : }
1550 : }
1551 :
1552 : /* -------------------------------------------------------------------- */
1553 : /* Check that incompatible options are not used */
1554 : /* -------------------------------------------------------------------- */
1555 :
1556 836 : if ((psOptions->nForcePixels != 0 || psOptions->nForceLines != 0) &&
1557 1866 : (psOptions->dfXRes != 0 && psOptions->dfYRes != 0) &&
1558 25 : !UseTEAndTSAndTRConsistently(psOptions))
1559 : {
1560 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1561 : "-tr and -ts options cannot be used at the same time.");
1562 0 : if (pbUsageError)
1563 0 : *pbUsageError = TRUE;
1564 0 : return false;
1565 : }
1566 :
1567 1005 : if (psOptions->bTargetAlignedPixels && psOptions->dfXRes == 0 &&
1568 1 : psOptions->dfYRes == 0)
1569 : {
1570 1 : CPLError(CE_Failure, CPLE_IllegalArg,
1571 : "-tap option cannot be used without using -tr.");
1572 1 : if (pbUsageError)
1573 1 : *pbUsageError = TRUE;
1574 1 : return false;
1575 : }
1576 :
1577 1004 : if (!psOptions->bQuiet &&
1578 81 : !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
1579 64 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0))
1580 : {
1581 17 : if (psOptions->dfMinX >= psOptions->dfMaxX)
1582 0 : CPLError(CE_Warning, CPLE_AppDefined,
1583 : "-te values have minx >= maxx. This will result in a "
1584 : "horizontally flipped image.");
1585 17 : if (psOptions->dfMinY >= psOptions->dfMaxY)
1586 0 : CPLError(CE_Warning, CPLE_AppDefined,
1587 : "-te values have miny >= maxy. This will result in a "
1588 : "vertically flipped image.");
1589 : }
1590 :
1591 1004 : if (psOptions->dfErrorThreshold < 0)
1592 : {
1593 : // By default, use approximate transformer unless RPC_DEM is specified
1594 991 : if (psOptions->aosTransformerOptions.FetchNameValue("RPC_DEM") !=
1595 : nullptr)
1596 4 : psOptions->dfErrorThreshold = 0.0;
1597 : else
1598 987 : psOptions->dfErrorThreshold = 0.125;
1599 : }
1600 :
1601 : /* -------------------------------------------------------------------- */
1602 : /* -te_srs option */
1603 : /* -------------------------------------------------------------------- */
1604 1004 : if (!psOptions->osTE_SRS.empty())
1605 : {
1606 5 : if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
1607 0 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
1608 : {
1609 0 : CPLError(CE_Warning, CPLE_AppDefined,
1610 : "-te_srs ignored since -te is not specified.");
1611 : }
1612 : else
1613 : {
1614 5 : OGRSpatialReference oSRSIn;
1615 5 : oSRSIn.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1616 5 : oSRSIn.SetFromUserInput(psOptions->osTE_SRS.c_str());
1617 5 : OGRSpatialReference oSRSDS;
1618 5 : oSRSDS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1619 5 : bool bOK = false;
1620 5 : if (psOptions->aosTransformerOptions.FetchNameValue("DST_SRS") !=
1621 : nullptr)
1622 : {
1623 2 : oSRSDS.SetFromUserInput(
1624 : psOptions->aosTransformerOptions.FetchNameValue("DST_SRS"));
1625 2 : bOK = true;
1626 : }
1627 3 : else if (psOptions->aosTransformerOptions.FetchNameValue(
1628 3 : "SRC_SRS") != nullptr)
1629 : {
1630 0 : oSRSDS.SetFromUserInput(
1631 : psOptions->aosTransformerOptions.FetchNameValue("SRC_SRS"));
1632 0 : bOK = true;
1633 : }
1634 3 : else if (nSrcCount)
1635 : {
1636 : const auto poSrcSRS =
1637 3 : GDALDataset::FromHandle(pahSrcDS[0])->GetSpatialRef();
1638 3 : if (poSrcSRS)
1639 : {
1640 3 : oSRSDS = *poSrcSRS;
1641 3 : bOK = true;
1642 : }
1643 : }
1644 5 : if (!bOK)
1645 : {
1646 0 : CPLError(CE_Failure, CPLE_AppDefined,
1647 : "-te_srs ignored since none of -t_srs, -s_srs is "
1648 : "specified or the input dataset has no projection.");
1649 0 : return false;
1650 : }
1651 5 : if (!oSRSIn.IsSame(&oSRSDS))
1652 : {
1653 5 : double dfWestLongitudeDeg = 0.0;
1654 5 : double dfSouthLatitudeDeg = 0.0;
1655 5 : double dfEastLongitudeDeg = 0.0;
1656 5 : double dfNorthLatitudeDeg = 0.0;
1657 :
1658 5 : OGRCoordinateTransformationOptions options;
1659 5 : if (GDALComputeAreaOfInterest(
1660 : &oSRSIn, psOptions->dfMinX, psOptions->dfMinY,
1661 : psOptions->dfMaxX, psOptions->dfMaxY,
1662 : dfWestLongitudeDeg, dfSouthLatitudeDeg,
1663 : dfEastLongitudeDeg, dfNorthLatitudeDeg))
1664 : {
1665 5 : options.SetAreaOfInterest(
1666 : dfWestLongitudeDeg, dfSouthLatitudeDeg,
1667 : dfEastLongitudeDeg, dfNorthLatitudeDeg);
1668 : }
1669 : auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
1670 : OGRCreateCoordinateTransformation(&oSRSIn, &oSRSDS,
1671 5 : options));
1672 5 : constexpr int DENSIFY_PTS = 21;
1673 10 : if (!(poCT && poCT->TransformBounds(
1674 : psOptions->dfMinX, psOptions->dfMinY,
1675 : psOptions->dfMaxX, psOptions->dfMaxY,
1676 : &(psOptions->dfMinX), &(psOptions->dfMinY),
1677 : &(psOptions->dfMaxX), &(psOptions->dfMaxY),
1678 10 : DENSIFY_PTS)))
1679 : {
1680 0 : CPLError(CE_Failure, CPLE_AppDefined,
1681 : "-te_srs ignored since coordinate transformation "
1682 : "failed.");
1683 0 : return false;
1684 : }
1685 : }
1686 : }
1687 : }
1688 1004 : return true;
1689 : }
1690 :
1691 : /************************************************************************/
1692 : /* ProcessCutlineOptions() */
1693 : /************************************************************************/
1694 :
1695 1004 : static bool ProcessCutlineOptions(int nSrcCount, GDALDatasetH *pahSrcDS,
1696 : GDALWarpAppOptions *psOptions,
1697 : std::unique_ptr<OGRGeometry> &poCutline)
1698 : {
1699 1004 : if (!psOptions->osCutlineDSNameOrWKT.empty())
1700 : {
1701 : CPLErr eError;
1702 52 : OGRGeometryH hCutline = nullptr;
1703 104 : eError = LoadCutline(psOptions->osCutlineDSNameOrWKT,
1704 52 : psOptions->osCutlineSRS, psOptions->osCLayer,
1705 52 : psOptions->osCWHERE, psOptions->osCSQL, &hCutline);
1706 52 : poCutline.reset(OGRGeometry::FromHandle(hCutline));
1707 52 : if (eError == CE_Failure)
1708 : {
1709 6 : return false;
1710 : }
1711 : }
1712 :
1713 998 : if (psOptions->bCropToCutline && poCutline)
1714 : {
1715 : CPLErr eError;
1716 18 : eError = CropToCutline(poCutline.get(),
1717 18 : psOptions->aosTransformerOptions.List(),
1718 18 : psOptions->aosWarpOptions.List(), nSrcCount,
1719 18 : pahSrcDS, psOptions->dfMinX, psOptions->dfMinY,
1720 18 : psOptions->dfMaxX, psOptions->dfMaxY, psOptions);
1721 18 : if (eError == CE_Failure)
1722 : {
1723 5 : return false;
1724 : }
1725 : }
1726 :
1727 : const char *pszWarpThreads =
1728 993 : psOptions->aosWarpOptions.FetchNameValue("NUM_THREADS");
1729 993 : if (pszWarpThreads != nullptr)
1730 : {
1731 : /* Used by TPS transformer to parallelize direct and inverse matrix
1732 : * computation */
1733 : psOptions->aosTransformerOptions.SetNameValue("NUM_THREADS",
1734 19 : pszWarpThreads);
1735 : }
1736 :
1737 993 : return true;
1738 : }
1739 :
1740 : /************************************************************************/
1741 : /* CreateOutput() */
1742 : /************************************************************************/
1743 :
1744 : static GDALDatasetH
1745 894 : CreateOutput(const char *pszDest, int nSrcCount, GDALDatasetH *pahSrcDS,
1746 : GDALWarpAppOptions *psOptions, const bool bInitDestSetByUser,
1747 : GDALTransformerArgUniquePtr &hUniqueTransformArg)
1748 : {
1749 894 : if (nSrcCount == 1 && !psOptions->bDisableSrcAlpha)
1750 : {
1751 1726 : if (GDALGetRasterCount(pahSrcDS[0]) > 0 &&
1752 863 : GDALGetRasterColorInterpretation(GDALGetRasterBand(
1753 : pahSrcDS[0], GDALGetRasterCount(pahSrcDS[0]))) == GCI_AlphaBand)
1754 : {
1755 22 : psOptions->bEnableSrcAlpha = true;
1756 22 : psOptions->bEnableDstAlpha = true;
1757 22 : if (!psOptions->bQuiet)
1758 0 : printf("Using band %d of source image as alpha.\n",
1759 : GDALGetRasterCount(pahSrcDS[0]));
1760 : }
1761 : }
1762 :
1763 894 : auto hDstDS = GDALWarpCreateOutput(
1764 : nSrcCount, pahSrcDS, pszDest, psOptions->osFormat.c_str(),
1765 : psOptions->aosTransformerOptions.List(),
1766 894 : psOptions->aosCreateOptions.List(), psOptions->eOutputType,
1767 894 : hUniqueTransformArg, psOptions->bSetColorInterpretation, psOptions,
1768 : /* bUpdateTransformerWithDestGT = */ true);
1769 894 : if (hDstDS == nullptr)
1770 : {
1771 19 : return nullptr;
1772 : }
1773 875 : psOptions->bCreateOutput = true;
1774 :
1775 875 : if (!bInitDestSetByUser)
1776 : {
1777 855 : if (psOptions->osDstNodata.empty())
1778 : {
1779 807 : psOptions->aosWarpOptions.SetNameValue("INIT_DEST", "0");
1780 : }
1781 : else
1782 : {
1783 48 : psOptions->aosWarpOptions.SetNameValue("INIT_DEST", "NO_DATA");
1784 : }
1785 : }
1786 :
1787 875 : return hDstDS;
1788 : }
1789 :
1790 : /************************************************************************/
1791 : /* EditISIS3ForMetadataChanges() */
1792 : /************************************************************************/
1793 :
1794 : static std::string
1795 2 : EditISIS3ForMetadataChanges(const char *pszJSON,
1796 : const GDALWarpAppOptions *psOptions)
1797 : {
1798 4 : CPLJSONDocument oJSONDocument;
1799 2 : if (!oJSONDocument.LoadMemory(pszJSON))
1800 : {
1801 0 : return std::string();
1802 : }
1803 :
1804 4 : auto oRoot = oJSONDocument.GetRoot();
1805 2 : if (!oRoot.IsValid())
1806 : {
1807 0 : return std::string();
1808 : }
1809 :
1810 6 : auto oGDALHistory = oRoot.GetObj("GDALHistory");
1811 2 : if (!oGDALHistory.IsValid())
1812 : {
1813 2 : oGDALHistory = CPLJSONObject();
1814 2 : oRoot.Add("GDALHistory", oGDALHistory);
1815 : }
1816 2 : oGDALHistory["_type"] = "object";
1817 :
1818 2 : char szFullFilename[2048] = {0};
1819 2 : if (!CPLGetExecPath(szFullFilename, sizeof(szFullFilename) - 1))
1820 0 : strcpy(szFullFilename, "unknown_program");
1821 4 : const CPLString osProgram(CPLGetBasenameSafe(szFullFilename));
1822 4 : const CPLString osPath(CPLGetPathSafe(szFullFilename));
1823 :
1824 2 : oGDALHistory["GdalVersion"] = GDALVersionInfo("RELEASE_NAME");
1825 2 : oGDALHistory["Program"] = osProgram;
1826 2 : if (osPath != ".")
1827 2 : oGDALHistory["ProgramPath"] = osPath;
1828 :
1829 4 : std::string osArgs;
1830 6 : for (const char *pszArg : psOptions->aosArgs)
1831 : {
1832 4 : if (!osArgs.empty())
1833 2 : osArgs += ' ';
1834 4 : osArgs += pszArg;
1835 : }
1836 2 : oGDALHistory["ProgramArguments"] = osArgs;
1837 :
1838 2 : oGDALHistory.Add(
1839 : "Comment",
1840 : "Part of that metadata might be invalid due to a reprojection "
1841 : "operation having been performed by GDAL tools");
1842 :
1843 2 : return oRoot.Format(CPLJSONObject::PrettyFormat::Pretty);
1844 : }
1845 :
1846 : /************************************************************************/
1847 : /* ProcessMetadata() */
1848 : /************************************************************************/
1849 :
1850 995 : static void ProcessMetadata(int iSrc, GDALDatasetH hSrcDS, GDALDatasetH hDstDS,
1851 : const GDALWarpAppOptions *psOptions,
1852 : const bool bEnableDstAlpha)
1853 : {
1854 995 : if (psOptions->bCopyMetadata)
1855 : {
1856 995 : const char *pszSrcInfo = nullptr;
1857 995 : GDALRasterBandH hSrcBand = nullptr;
1858 995 : GDALRasterBandH hDstBand = nullptr;
1859 :
1860 : /* copy metadata from first dataset */
1861 995 : if (iSrc == 0)
1862 : {
1863 971 : CPLDebug(
1864 : "WARP",
1865 : "Copying metadata from first source to destination dataset");
1866 : /* copy dataset-level metadata */
1867 971 : char **papszMetadata = GDALGetMetadata(hSrcDS, nullptr);
1868 :
1869 971 : char **papszMetadataNew = nullptr;
1870 2378 : for (int i = 0;
1871 2378 : papszMetadata != nullptr && papszMetadata[i] != nullptr; i++)
1872 : {
1873 : // Do not preserve NODATA_VALUES when the output includes an
1874 : // alpha band
1875 1407 : if (bEnableDstAlpha &&
1876 70 : STARTS_WITH_CI(papszMetadata[i], "NODATA_VALUES="))
1877 : {
1878 1 : continue;
1879 : }
1880 : // Do not preserve the CACHE_PATH from the WMS driver
1881 1406 : if (STARTS_WITH_CI(papszMetadata[i], "CACHE_PATH="))
1882 : {
1883 0 : continue;
1884 : }
1885 :
1886 : papszMetadataNew =
1887 1406 : CSLAddString(papszMetadataNew, papszMetadata[i]);
1888 : }
1889 :
1890 971 : if (CSLCount(papszMetadataNew) > 0)
1891 : {
1892 683 : if (GDALSetMetadata(hDstDS, papszMetadataNew, nullptr) !=
1893 : CE_None)
1894 0 : CPLError(CE_Warning, CPLE_AppDefined,
1895 : "error copying metadata to destination dataset.");
1896 : }
1897 :
1898 971 : CSLDestroy(papszMetadataNew);
1899 :
1900 : /* ISIS3 -> ISIS3 special case */
1901 971 : if (EQUAL(psOptions->osFormat.c_str(), "ISIS3") ||
1902 970 : EQUAL(psOptions->osFormat.c_str(), "PDS4") ||
1903 2472 : EQUAL(psOptions->osFormat.c_str(), "GTIFF") ||
1904 531 : EQUAL(psOptions->osFormat.c_str(), "COG"))
1905 : {
1906 440 : char **papszMD_ISIS3 = GDALGetMetadata(hSrcDS, "json:ISIS3");
1907 440 : if (papszMD_ISIS3 != nullptr && papszMD_ISIS3[0])
1908 : {
1909 4 : std::string osJSON = papszMD_ISIS3[0];
1910 : osJSON =
1911 2 : EditISIS3ForMetadataChanges(osJSON.c_str(), psOptions);
1912 2 : if (!osJSON.empty())
1913 : {
1914 2 : char *apszMD[] = {osJSON.data(), nullptr};
1915 2 : GDALSetMetadata(hDstDS, apszMD, "json:ISIS3");
1916 : }
1917 : }
1918 : }
1919 531 : else if (EQUAL(psOptions->osFormat.c_str(), "PDS4"))
1920 : {
1921 0 : char **papszMD_PDS4 = GDALGetMetadata(hSrcDS, "xml:PDS4");
1922 0 : if (papszMD_PDS4 != nullptr)
1923 0 : GDALSetMetadata(hDstDS, papszMD_PDS4, "xml:PDS4");
1924 : }
1925 531 : else if (EQUAL(psOptions->osFormat.c_str(), "VICAR"))
1926 : {
1927 0 : char **papszMD_VICAR = GDALGetMetadata(hSrcDS, "json:VICAR");
1928 0 : if (papszMD_VICAR != nullptr)
1929 0 : GDALSetMetadata(hDstDS, papszMD_VICAR, "json:VICAR");
1930 : }
1931 :
1932 : /* copy band-level metadata and other info */
1933 971 : if (GDALGetRasterCount(hSrcDS) == GDALGetRasterCount(hDstDS))
1934 : {
1935 2096 : for (int iBand = 0; iBand < GDALGetRasterCount(hSrcDS); iBand++)
1936 : {
1937 1183 : hSrcBand = GDALGetRasterBand(hSrcDS, iBand + 1);
1938 1183 : hDstBand = GDALGetRasterBand(hDstDS, iBand + 1);
1939 : /* copy metadata, except stats (#5319) */
1940 1183 : papszMetadata = GDALGetMetadata(hSrcBand, nullptr);
1941 1183 : if (CSLCount(papszMetadata) > 0)
1942 : {
1943 : // GDALSetMetadata( hDstBand, papszMetadata, NULL );
1944 18 : papszMetadataNew = nullptr;
1945 94 : for (int i = 0; papszMetadata != nullptr &&
1946 94 : papszMetadata[i] != nullptr;
1947 : i++)
1948 : {
1949 76 : if (!STARTS_WITH(papszMetadata[i], "STATISTICS_"))
1950 61 : papszMetadataNew = CSLAddString(
1951 61 : papszMetadataNew, papszMetadata[i]);
1952 : }
1953 18 : GDALSetMetadata(hDstBand, papszMetadataNew, nullptr);
1954 18 : CSLDestroy(papszMetadataNew);
1955 : }
1956 : /* copy other info (Description, Unit Type) - what else? */
1957 1183 : if (psOptions->bCopyBandInfo)
1958 : {
1959 1183 : pszSrcInfo = GDALGetDescription(hSrcBand);
1960 1183 : if (pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0)
1961 3 : GDALSetDescription(hDstBand, pszSrcInfo);
1962 1183 : pszSrcInfo = GDALGetRasterUnitType(hSrcBand);
1963 1183 : if (pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0)
1964 36 : GDALSetRasterUnitType(hDstBand, pszSrcInfo);
1965 : }
1966 : }
1967 : }
1968 : }
1969 : /* remove metadata that conflicts between datasets */
1970 : else
1971 : {
1972 24 : CPLDebug("WARP",
1973 : "Removing conflicting metadata from destination dataset "
1974 : "(source #%d)",
1975 : iSrc);
1976 : /* remove conflicting dataset-level metadata */
1977 24 : RemoveConflictingMetadata(hDstDS, GDALGetMetadata(hSrcDS, nullptr),
1978 : psOptions->osMDConflictValue.c_str());
1979 :
1980 : /* remove conflicting copy band-level metadata and other info */
1981 24 : if (GDALGetRasterCount(hSrcDS) == GDALGetRasterCount(hDstDS))
1982 : {
1983 44 : for (int iBand = 0; iBand < GDALGetRasterCount(hSrcDS); iBand++)
1984 : {
1985 23 : hSrcBand = GDALGetRasterBand(hSrcDS, iBand + 1);
1986 23 : hDstBand = GDALGetRasterBand(hDstDS, iBand + 1);
1987 : /* remove conflicting metadata */
1988 23 : RemoveConflictingMetadata(
1989 23 : hDstBand, GDALGetMetadata(hSrcBand, nullptr),
1990 : psOptions->osMDConflictValue.c_str());
1991 : /* remove conflicting info */
1992 23 : if (psOptions->bCopyBandInfo)
1993 : {
1994 23 : pszSrcInfo = GDALGetDescription(hSrcBand);
1995 23 : const char *pszDstInfo = GDALGetDescription(hDstBand);
1996 23 : if (!(pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0 &&
1997 0 : pszDstInfo != nullptr && strlen(pszDstInfo) > 0 &&
1998 0 : EQUAL(pszSrcInfo, pszDstInfo)))
1999 23 : GDALSetDescription(hDstBand, "");
2000 23 : pszSrcInfo = GDALGetRasterUnitType(hSrcBand);
2001 23 : pszDstInfo = GDALGetRasterUnitType(hDstBand);
2002 23 : if (!(pszSrcInfo != nullptr && strlen(pszSrcInfo) > 0 &&
2003 0 : pszDstInfo != nullptr && strlen(pszDstInfo) > 0 &&
2004 0 : EQUAL(pszSrcInfo, pszDstInfo)))
2005 23 : GDALSetRasterUnitType(hDstBand, "");
2006 : }
2007 : }
2008 : }
2009 : }
2010 : }
2011 995 : }
2012 :
2013 : /************************************************************************/
2014 : /* SetupNoData() */
2015 : /************************************************************************/
2016 :
2017 992 : static CPLErr SetupNoData(const char *pszDest, int iSrc, GDALDatasetH hSrcDS,
2018 : GDALDatasetH hWrkSrcDS, GDALDatasetH hDstDS,
2019 : GDALWarpOptions *psWO, GDALWarpAppOptions *psOptions,
2020 : const bool bEnableDstAlpha,
2021 : const bool bInitDestSetByUser)
2022 : {
2023 1022 : if (!psOptions->osSrcNodata.empty() &&
2024 30 : !EQUAL(psOptions->osSrcNodata.c_str(), "none"))
2025 : {
2026 : CPLStringList aosTokens(
2027 26 : CSLTokenizeString(psOptions->osSrcNodata.c_str()));
2028 26 : const int nTokenCount = aosTokens.Count();
2029 :
2030 26 : psWO->padfSrcNoDataReal =
2031 26 : static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));
2032 26 : psWO->padfSrcNoDataImag = nullptr;
2033 :
2034 63 : for (int i = 0; i < psWO->nBandCount; i++)
2035 : {
2036 38 : if (i < nTokenCount)
2037 : {
2038 : double dfNoDataReal;
2039 : double dfNoDataImag;
2040 :
2041 28 : if (CPLStringToComplex(aosTokens[i], &dfNoDataReal,
2042 28 : &dfNoDataImag) != CE_None)
2043 : {
2044 1 : CPLError(CE_Failure, CPLE_AppDefined,
2045 : "Error parsing srcnodata for band %d", i + 1);
2046 1 : return CE_Failure;
2047 : }
2048 :
2049 54 : psWO->padfSrcNoDataReal[i] =
2050 27 : GDALAdjustNoDataCloseToFloatMax(dfNoDataReal);
2051 :
2052 27 : if (strchr(aosTokens[i], 'i') != nullptr)
2053 : {
2054 1 : if (psWO->padfSrcNoDataImag == nullptr)
2055 : {
2056 1 : psWO->padfSrcNoDataImag = static_cast<double *>(
2057 1 : CPLCalloc(psWO->nBandCount, sizeof(double)));
2058 : }
2059 2 : psWO->padfSrcNoDataImag[i] =
2060 1 : GDALAdjustNoDataCloseToFloatMax(dfNoDataImag);
2061 : }
2062 : }
2063 : else
2064 : {
2065 10 : psWO->padfSrcNoDataReal[i] = psWO->padfSrcNoDataReal[i - 1];
2066 10 : if (psWO->padfSrcNoDataImag != nullptr)
2067 : {
2068 0 : psWO->padfSrcNoDataImag[i] = psWO->padfSrcNoDataImag[i - 1];
2069 : }
2070 : }
2071 : }
2072 :
2073 31 : if (psWO->nBandCount > 1 &&
2074 6 : CSLFetchNameValue(psWO->papszWarpOptions, "UNIFIED_SRC_NODATA") ==
2075 : nullptr)
2076 : {
2077 6 : CPLDebug("WARP", "Set UNIFIED_SRC_NODATA=YES");
2078 6 : psWO->papszWarpOptions = CSLSetNameValue(
2079 : psWO->papszWarpOptions, "UNIFIED_SRC_NODATA", "YES");
2080 : }
2081 : }
2082 :
2083 : /* -------------------------------------------------------------------- */
2084 : /* If -srcnodata was not specified, but the data has nodata */
2085 : /* values, use them. */
2086 : /* -------------------------------------------------------------------- */
2087 991 : if (psOptions->osSrcNodata.empty())
2088 : {
2089 962 : int bHaveNodata = FALSE;
2090 962 : double dfReal = 0.0;
2091 :
2092 2136 : for (int i = 0; !bHaveNodata && i < psWO->nBandCount; i++)
2093 : {
2094 : GDALRasterBandH hBand =
2095 1174 : GDALGetRasterBand(hWrkSrcDS, psWO->panSrcBands[i]);
2096 1174 : dfReal = GDALGetRasterNoDataValue(hBand, &bHaveNodata);
2097 : }
2098 :
2099 962 : if (bHaveNodata)
2100 : {
2101 82 : if (!psOptions->bQuiet)
2102 : {
2103 10 : if (std::isnan(dfReal))
2104 0 : printf("Using internal nodata values (e.g. nan) for image "
2105 : "%s.\n",
2106 : GDALGetDescription(hSrcDS));
2107 : else
2108 10 : printf("Using internal nodata values (e.g. %g) for image "
2109 : "%s.\n",
2110 : dfReal, GDALGetDescription(hSrcDS));
2111 : }
2112 82 : psWO->padfSrcNoDataReal = static_cast<double *>(
2113 82 : CPLMalloc(psWO->nBandCount * sizeof(double)));
2114 :
2115 201 : for (int i = 0; i < psWO->nBandCount; i++)
2116 : {
2117 : GDALRasterBandH hBand =
2118 119 : GDALGetRasterBand(hWrkSrcDS, psWO->panSrcBands[i]);
2119 :
2120 119 : dfReal = GDALGetRasterNoDataValue(hBand, &bHaveNodata);
2121 :
2122 119 : if (bHaveNodata)
2123 : {
2124 119 : psWO->padfSrcNoDataReal[i] = dfReal;
2125 : }
2126 : else
2127 : {
2128 0 : psWO->padfSrcNoDataReal[i] = -123456.789;
2129 : }
2130 : }
2131 : }
2132 : }
2133 :
2134 : /* -------------------------------------------------------------------- */
2135 : /* If the output dataset was created, and we have a destination */
2136 : /* nodata value, go through marking the bands with the information.*/
2137 : /* -------------------------------------------------------------------- */
2138 1051 : if (!psOptions->osDstNodata.empty() &&
2139 60 : !EQUAL(psOptions->osDstNodata.c_str(), "none"))
2140 : {
2141 : CPLStringList aosTokens(
2142 60 : CSLTokenizeString(psOptions->osDstNodata.c_str()));
2143 60 : const int nTokenCount = aosTokens.Count();
2144 60 : bool bDstNoDataNone = true;
2145 :
2146 60 : psWO->padfDstNoDataReal =
2147 60 : static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));
2148 60 : psWO->padfDstNoDataImag =
2149 60 : static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));
2150 :
2151 122 : for (int i = 0; i < psWO->nBandCount; i++)
2152 : {
2153 63 : psWO->padfDstNoDataReal[i] = -1.1e20;
2154 63 : psWO->padfDstNoDataImag[i] = 0.0;
2155 :
2156 63 : if (i < nTokenCount)
2157 : {
2158 61 : if (aosTokens[i] != nullptr && EQUAL(aosTokens[i], "none"))
2159 : {
2160 0 : CPLDebug("WARP", "dstnodata of band %d not set", i);
2161 0 : bDstNoDataNone = true;
2162 0 : continue;
2163 : }
2164 61 : else if (aosTokens[i] ==
2165 : nullptr) // this should not happen, but just in case
2166 : {
2167 0 : CPLError(CE_Failure, CPLE_AppDefined,
2168 : "Error parsing dstnodata arg #%d", i);
2169 0 : bDstNoDataNone = true;
2170 0 : continue;
2171 : }
2172 :
2173 61 : if (CPLStringToComplex(aosTokens[i],
2174 61 : psWO->padfDstNoDataReal + i,
2175 122 : psWO->padfDstNoDataImag + i) != CE_None)
2176 : {
2177 :
2178 1 : CPLError(CE_Failure, CPLE_AppDefined,
2179 : "Error parsing dstnodata for band %d", i + 1);
2180 1 : return CE_Failure;
2181 : }
2182 :
2183 120 : psWO->padfDstNoDataReal[i] =
2184 60 : GDALAdjustNoDataCloseToFloatMax(psWO->padfDstNoDataReal[i]);
2185 120 : psWO->padfDstNoDataImag[i] =
2186 60 : GDALAdjustNoDataCloseToFloatMax(psWO->padfDstNoDataImag[i]);
2187 60 : bDstNoDataNone = false;
2188 60 : CPLDebug("WARP", "dstnodata of band %d set to %f", i,
2189 60 : psWO->padfDstNoDataReal[i]);
2190 : }
2191 : else
2192 : {
2193 2 : if (!bDstNoDataNone)
2194 : {
2195 2 : psWO->padfDstNoDataReal[i] = psWO->padfDstNoDataReal[i - 1];
2196 2 : psWO->padfDstNoDataImag[i] = psWO->padfDstNoDataImag[i - 1];
2197 2 : CPLDebug("WARP",
2198 : "dstnodata of band %d set from previous band", i);
2199 : }
2200 : else
2201 : {
2202 0 : CPLDebug("WARP", "dstnodata value of band %d not set", i);
2203 0 : continue;
2204 : }
2205 : }
2206 :
2207 : GDALRasterBandH hBand =
2208 62 : GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
2209 62 : int bClamped = FALSE;
2210 62 : int bRounded = FALSE;
2211 62 : psWO->padfDstNoDataReal[i] = GDALAdjustValueToDataType(
2212 62 : GDALGetRasterDataType(hBand), psWO->padfDstNoDataReal[i],
2213 : &bClamped, &bRounded);
2214 :
2215 62 : if (bClamped)
2216 : {
2217 0 : CPLError(
2218 : CE_Warning, CPLE_AppDefined,
2219 : "for band %d, destination nodata value has been clamped "
2220 : "to %.0f, the original value being out of range.",
2221 0 : psWO->panDstBands[i], psWO->padfDstNoDataReal[i]);
2222 : }
2223 62 : else if (bRounded)
2224 : {
2225 0 : CPLError(
2226 : CE_Warning, CPLE_AppDefined,
2227 : "for band %d, destination nodata value has been rounded "
2228 : "to %.0f, %s being an integer datatype.",
2229 0 : psWO->panDstBands[i], psWO->padfDstNoDataReal[i],
2230 : GDALGetDataTypeName(GDALGetRasterDataType(hBand)));
2231 : }
2232 :
2233 62 : if (psOptions->bCreateOutput && iSrc == 0)
2234 : {
2235 58 : GDALSetRasterNoDataValue(
2236 58 : GDALGetRasterBand(hDstDS, psWO->panDstBands[i]),
2237 58 : psWO->padfDstNoDataReal[i]);
2238 : }
2239 : }
2240 : }
2241 :
2242 : /* check if the output dataset has already nodata */
2243 990 : if (psOptions->osDstNodata.empty())
2244 : {
2245 931 : int bHaveNodataAll = TRUE;
2246 2128 : for (int i = 0; i < psWO->nBandCount; i++)
2247 : {
2248 : GDALRasterBandH hBand =
2249 1197 : GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
2250 1197 : int bHaveNodata = FALSE;
2251 1197 : GDALGetRasterNoDataValue(hBand, &bHaveNodata);
2252 1197 : bHaveNodataAll &= bHaveNodata;
2253 : }
2254 931 : if (bHaveNodataAll)
2255 : {
2256 6 : psWO->padfDstNoDataReal = static_cast<double *>(
2257 6 : CPLMalloc(psWO->nBandCount * sizeof(double)));
2258 13 : for (int i = 0; i < psWO->nBandCount; i++)
2259 : {
2260 : GDALRasterBandH hBand =
2261 7 : GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
2262 7 : int bHaveNodata = FALSE;
2263 14 : psWO->padfDstNoDataReal[i] =
2264 7 : GDALGetRasterNoDataValue(hBand, &bHaveNodata);
2265 7 : CPLDebug("WARP", "band=%d dstNoData=%f", i,
2266 7 : psWO->padfDstNoDataReal[i]);
2267 : }
2268 : }
2269 : }
2270 :
2271 : // If creating a new file that has default nodata value,
2272 : // try to override the default output nodata values with the source ones.
2273 1921 : if (psOptions->osDstNodata.empty() && psWO->padfSrcNoDataReal != nullptr &&
2274 87 : psWO->padfDstNoDataReal != nullptr && psOptions->bCreateOutput &&
2275 1921 : iSrc == 0 && !bEnableDstAlpha)
2276 : {
2277 5 : for (int i = 0; i < psWO->nBandCount; i++)
2278 : {
2279 : GDALRasterBandH hBand =
2280 3 : GDALGetRasterBand(hDstDS, psWO->panDstBands[i]);
2281 3 : int bHaveNodata = FALSE;
2282 3 : CPLPushErrorHandler(CPLQuietErrorHandler);
2283 : bool bRedefinedOK =
2284 3 : (GDALSetRasterNoDataValue(hBand, psWO->padfSrcNoDataReal[i]) ==
2285 3 : CE_None &&
2286 3 : GDALGetRasterNoDataValue(hBand, &bHaveNodata) ==
2287 9 : psWO->padfSrcNoDataReal[i] &&
2288 3 : bHaveNodata);
2289 3 : CPLPopErrorHandler();
2290 3 : if (bRedefinedOK)
2291 : {
2292 3 : if (i == 0 && !psOptions->bQuiet)
2293 0 : printf("Copying nodata values from source %s "
2294 : "to destination %s.\n",
2295 : GDALGetDescription(hSrcDS), pszDest);
2296 3 : psWO->padfDstNoDataReal[i] = psWO->padfSrcNoDataReal[i];
2297 :
2298 3 : if (i == 0 && !bInitDestSetByUser)
2299 : {
2300 : /* As we didn't know at the beginning if there was source
2301 : * nodata */
2302 : /* we have initialized INIT_DEST=0. Override this with
2303 : * NO_DATA now */
2304 2 : psWO->papszWarpOptions = CSLSetNameValue(
2305 : psWO->papszWarpOptions, "INIT_DEST", "NO_DATA");
2306 : }
2307 : }
2308 : else
2309 : {
2310 0 : break;
2311 : }
2312 : }
2313 : }
2314 :
2315 : /* else try to fill dstNoData from source bands, unless -dstalpha is
2316 : * specified */
2317 988 : else if (psOptions->osDstNodata.empty() &&
2318 929 : psWO->padfSrcNoDataReal != nullptr &&
2319 1917 : psWO->padfDstNoDataReal == nullptr && !bEnableDstAlpha)
2320 : {
2321 70 : psWO->padfDstNoDataReal =
2322 70 : static_cast<double *>(CPLMalloc(psWO->nBandCount * sizeof(double)));
2323 :
2324 70 : if (psWO->padfSrcNoDataImag != nullptr)
2325 : {
2326 1 : psWO->padfDstNoDataImag = static_cast<double *>(
2327 1 : CPLMalloc(psWO->nBandCount * sizeof(double)));
2328 : }
2329 :
2330 70 : if (!psOptions->bQuiet)
2331 3 : printf("Copying nodata values from source %s to destination %s.\n",
2332 : GDALGetDescription(hSrcDS), pszDest);
2333 :
2334 159 : for (int i = 0; i < psWO->nBandCount; i++)
2335 : {
2336 89 : psWO->padfDstNoDataReal[i] = psWO->padfSrcNoDataReal[i];
2337 89 : if (psWO->padfSrcNoDataImag != nullptr)
2338 : {
2339 1 : psWO->padfDstNoDataImag[i] = psWO->padfSrcNoDataImag[i];
2340 : }
2341 89 : CPLDebug("WARP", "srcNoData=%f dstNoData=%f",
2342 89 : psWO->padfSrcNoDataReal[i], psWO->padfDstNoDataReal[i]);
2343 :
2344 89 : if (psOptions->bCreateOutput && iSrc == 0)
2345 : {
2346 89 : CPLDebug("WARP",
2347 : "calling GDALSetRasterNoDataValue() for band#%d", i);
2348 89 : GDALSetRasterNoDataValue(
2349 89 : GDALGetRasterBand(hDstDS, psWO->panDstBands[i]),
2350 89 : psWO->padfDstNoDataReal[i]);
2351 : }
2352 : }
2353 :
2354 70 : if (psOptions->bCreateOutput && !bInitDestSetByUser && iSrc == 0)
2355 : {
2356 : /* As we didn't know at the beginning if there was source nodata */
2357 : /* we have initialized INIT_DEST=0. Override this with NO_DATA now
2358 : */
2359 67 : psWO->papszWarpOptions =
2360 67 : CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "NO_DATA");
2361 : }
2362 : }
2363 :
2364 990 : return CE_None;
2365 : }
2366 :
2367 : /************************************************************************/
2368 : /* SetupSkipNoSource() */
2369 : /************************************************************************/
2370 :
2371 990 : static void SetupSkipNoSource(int iSrc, GDALDatasetH hDstDS,
2372 : GDALWarpOptions *psWO,
2373 : GDALWarpAppOptions *psOptions)
2374 : {
2375 893 : if (psOptions->bCreateOutput && iSrc == 0 &&
2376 871 : CSLFetchNameValue(psWO->papszWarpOptions, "SKIP_NOSOURCE") == nullptr &&
2377 866 : CSLFetchNameValue(psWO->papszWarpOptions, "STREAMABLE_OUTPUT") ==
2378 1883 : nullptr &&
2379 : // This white list of drivers could potentially be extended.
2380 865 : (EQUAL(psOptions->osFormat.c_str(), "MEM") ||
2381 548 : EQUAL(psOptions->osFormat.c_str(), "GTiff") ||
2382 115 : EQUAL(psOptions->osFormat.c_str(), "GPKG")))
2383 : {
2384 : // We can enable the optimization only if the user didn't specify
2385 : // a INIT_DEST value that would contradict the destination nodata.
2386 :
2387 750 : bool bOKRegardingInitDest = false;
2388 : const char *pszInitDest =
2389 750 : CSLFetchNameValue(psWO->papszWarpOptions, "INIT_DEST");
2390 750 : if (pszInitDest == nullptr || EQUAL(pszInitDest, "NO_DATA"))
2391 : {
2392 93 : bOKRegardingInitDest = true;
2393 :
2394 : // The MEM driver will return non-initialized blocks at 0
2395 : // so make sure that the nodata value is 0.
2396 93 : if (EQUAL(psOptions->osFormat.c_str(), "MEM"))
2397 : {
2398 106 : for (int i = 0; i < GDALGetRasterCount(hDstDS); i++)
2399 : {
2400 74 : int bHasNoData = false;
2401 74 : double dfDstNoDataVal = GDALGetRasterNoDataValue(
2402 : GDALGetRasterBand(hDstDS, i + 1), &bHasNoData);
2403 74 : if (bHasNoData && dfDstNoDataVal != 0.0)
2404 : {
2405 38 : bOKRegardingInitDest = false;
2406 38 : break;
2407 : }
2408 : }
2409 93 : }
2410 : }
2411 : else
2412 : {
2413 657 : char **papszTokensInitDest = CSLTokenizeString(pszInitDest);
2414 657 : const int nTokenCountInitDest = CSLCount(papszTokensInitDest);
2415 657 : if (nTokenCountInitDest == 1 ||
2416 0 : nTokenCountInitDest == GDALGetRasterCount(hDstDS))
2417 : {
2418 657 : bOKRegardingInitDest = true;
2419 1530 : for (int i = 0; i < GDALGetRasterCount(hDstDS); i++)
2420 : {
2421 881 : double dfInitVal = GDALAdjustNoDataCloseToFloatMax(
2422 881 : CPLAtofM(papszTokensInitDest[std::min(
2423 881 : i, nTokenCountInitDest - 1)]));
2424 881 : int bHasNoData = false;
2425 881 : double dfDstNoDataVal = GDALGetRasterNoDataValue(
2426 : GDALGetRasterBand(hDstDS, i + 1), &bHasNoData);
2427 881 : if (!((bHasNoData && dfInitVal == dfDstNoDataVal) ||
2428 879 : (!bHasNoData && dfInitVal == 0.0)))
2429 : {
2430 7 : bOKRegardingInitDest = false;
2431 8 : break;
2432 : }
2433 874 : if (EQUAL(psOptions->osFormat.c_str(), "MEM") &&
2434 874 : bHasNoData && dfDstNoDataVal != 0.0)
2435 : {
2436 1 : bOKRegardingInitDest = false;
2437 1 : break;
2438 : }
2439 : }
2440 : }
2441 657 : CSLDestroy(papszTokensInitDest);
2442 : }
2443 :
2444 750 : if (bOKRegardingInitDest)
2445 : {
2446 704 : CPLDebug("GDALWARP", "Defining SKIP_NOSOURCE=YES");
2447 704 : psWO->papszWarpOptions =
2448 704 : CSLSetNameValue(psWO->papszWarpOptions, "SKIP_NOSOURCE", "YES");
2449 : }
2450 : }
2451 990 : }
2452 :
2453 : /************************************************************************/
2454 : /* AdjustOutputExtentForRPC() */
2455 : /************************************************************************/
2456 :
2457 : /** Returns false if there's no intersection between source extent defined
2458 : * by RPC and target extent.
2459 : */
2460 990 : static bool AdjustOutputExtentForRPC(GDALDatasetH hSrcDS, GDALDatasetH hDstDS,
2461 : GDALTransformerFunc pfnTransformer,
2462 : void *hTransformArg, GDALWarpOptions *psWO,
2463 : GDALWarpAppOptions *psOptions,
2464 : int &nWarpDstXOff, int &nWarpDstYOff,
2465 : int &nWarpDstXSize, int &nWarpDstYSize)
2466 : {
2467 990 : if (CPLTestBool(CSLFetchNameValueDef(psWO->papszWarpOptions,
2468 826 : "SKIP_NOSOURCE", "NO")) &&
2469 826 : GDALGetMetadata(hSrcDS, "RPC") != nullptr &&
2470 1828 : EQUAL(FetchSrcMethod(psOptions->aosTransformerOptions, "RPC"), "RPC") &&
2471 12 : CPLTestBool(
2472 : CPLGetConfigOption("RESTRICT_OUTPUT_DATASET_UPDATE", "YES")))
2473 : {
2474 : double adfSuggestedGeoTransform[6];
2475 : double adfExtent[4];
2476 : int nPixels, nLines;
2477 10 : if (GDALSuggestedWarpOutput2(hSrcDS, pfnTransformer, hTransformArg,
2478 : adfSuggestedGeoTransform, &nPixels,
2479 10 : &nLines, adfExtent, 0) == CE_None)
2480 : {
2481 6 : const double dfMinX = adfExtent[0];
2482 6 : const double dfMinY = adfExtent[1];
2483 6 : const double dfMaxX = adfExtent[2];
2484 6 : const double dfMaxY = adfExtent[3];
2485 6 : const double dfThreshold = static_cast<double>(INT_MAX) / 2;
2486 6 : if (std::fabs(dfMinX) < dfThreshold &&
2487 6 : std::fabs(dfMinY) < dfThreshold &&
2488 6 : std::fabs(dfMaxX) < dfThreshold &&
2489 6 : std::fabs(dfMaxY) < dfThreshold)
2490 : {
2491 6 : const int nPadding = 5;
2492 6 : nWarpDstXOff =
2493 6 : std::max(nWarpDstXOff,
2494 6 : static_cast<int>(std::floor(dfMinX)) - nPadding);
2495 6 : nWarpDstYOff =
2496 6 : std::max(nWarpDstYOff,
2497 6 : static_cast<int>(std::floor(dfMinY)) - nPadding);
2498 12 : nWarpDstXSize = std::min(nWarpDstXSize - nWarpDstXOff,
2499 6 : static_cast<int>(std::ceil(dfMaxX)) +
2500 6 : nPadding - nWarpDstXOff);
2501 12 : nWarpDstYSize = std::min(nWarpDstYSize - nWarpDstYOff,
2502 6 : static_cast<int>(std::ceil(dfMaxY)) +
2503 6 : nPadding - nWarpDstYOff);
2504 6 : if (nWarpDstXSize <= 0 || nWarpDstYSize <= 0)
2505 : {
2506 1 : CPLDebug("WARP",
2507 : "No intersection between source extent defined "
2508 : "by RPC and target extent");
2509 1 : return false;
2510 : }
2511 2 : if (nWarpDstXOff != 0 || nWarpDstYOff != 0 ||
2512 9 : nWarpDstXSize != GDALGetRasterXSize(hDstDS) ||
2513 2 : nWarpDstYSize != GDALGetRasterYSize(hDstDS))
2514 : {
2515 3 : CPLDebug("WARP",
2516 : "Restricting warping to output dataset window "
2517 : "%d,%d,%dx%d",
2518 : nWarpDstXOff, nWarpDstYOff, nWarpDstXSize,
2519 : nWarpDstYSize);
2520 : }
2521 : }
2522 : }
2523 : }
2524 989 : return true;
2525 : }
2526 :
2527 : /************************************************************************/
2528 : /* GDALWarpDirect() */
2529 : /************************************************************************/
2530 :
2531 : static GDALDatasetH
2532 1005 : GDALWarpDirect(const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
2533 : GDALDatasetH *pahSrcDS,
2534 : GDALTransformerArgUniquePtr hUniqueTransformArg,
2535 : GDALWarpAppOptions *psOptions, int *pbUsageError)
2536 : {
2537 1005 : CPLErrorReset();
2538 1005 : if (pszDest == nullptr && hDstDS == nullptr)
2539 : {
2540 0 : CPLError(CE_Failure, CPLE_AppDefined,
2541 : "pszDest == NULL && hDstDS == NULL");
2542 :
2543 0 : if (pbUsageError)
2544 0 : *pbUsageError = TRUE;
2545 0 : return nullptr;
2546 : }
2547 1005 : if (pszDest == nullptr)
2548 96 : pszDest = GDALGetDescription(hDstDS);
2549 :
2550 : #ifdef DEBUG
2551 1005 : GDALDataset *poDstDS = GDALDataset::FromHandle(hDstDS);
2552 : const int nExpectedRefCountAtEnd =
2553 1005 : (poDstDS != nullptr) ? poDstDS->GetRefCount() : 1;
2554 : (void)nExpectedRefCountAtEnd;
2555 : #endif
2556 1005 : const bool bDropDstDSRef = (hDstDS != nullptr);
2557 1005 : if (hDstDS != nullptr)
2558 99 : GDALReferenceDataset(hDstDS);
2559 :
2560 : #if defined(USE_PROJ_BASED_VERTICAL_SHIFT_METHOD)
2561 1005 : if (psOptions->bNoVShift)
2562 : {
2563 1 : psOptions->aosTransformerOptions.SetNameValue("@STRIP_VERT_CS", "YES");
2564 : }
2565 1004 : else if (nSrcCount)
2566 : {
2567 998 : bool bSrcHasVertAxis = false;
2568 998 : bool bDstHasVertAxis = false;
2569 1996 : OGRSpatialReference oSRSSrc;
2570 1996 : OGRSpatialReference oSRSDst;
2571 :
2572 998 : if (MustApplyVerticalShift(pahSrcDS[0], psOptions, oSRSSrc, oSRSDst,
2573 : bSrcHasVertAxis, bDstHasVertAxis))
2574 : {
2575 : psOptions->aosTransformerOptions.SetNameValue("PROMOTE_TO_3D",
2576 19 : "YES");
2577 : }
2578 : }
2579 : #else
2580 : psOptions->aosTransformerOptions.SetNameValue("@STRIP_VERT_CS", "YES");
2581 : #endif
2582 :
2583 1005 : bool bVRT = false;
2584 1005 : if (!CheckOptions(pszDest, hDstDS, nSrcCount, pahSrcDS, psOptions, bVRT,
2585 : pbUsageError))
2586 : {
2587 1 : return nullptr;
2588 : }
2589 :
2590 : /* -------------------------------------------------------------------- */
2591 : /* If we have a cutline datasource read it and attach it in the */
2592 : /* warp options. */
2593 : /* -------------------------------------------------------------------- */
2594 1004 : std::unique_ptr<OGRGeometry> poCutline;
2595 1004 : if (!ProcessCutlineOptions(nSrcCount, pahSrcDS, psOptions, poCutline))
2596 : {
2597 11 : return nullptr;
2598 : }
2599 :
2600 : /* -------------------------------------------------------------------- */
2601 : /* If the target dataset does not exist, we need to create it. */
2602 : /* -------------------------------------------------------------------- */
2603 : const bool bInitDestSetByUser =
2604 993 : (psOptions->aosWarpOptions.FetchNameValue("INIT_DEST") != nullptr);
2605 :
2606 993 : const bool bFigureoutCorrespondingWindow =
2607 1887 : (hDstDS != nullptr) ||
2608 894 : (((psOptions->nForcePixels != 0 && psOptions->nForceLines != 0) ||
2609 730 : (psOptions->dfXRes != 0 && psOptions->dfYRes != 0)) &&
2610 213 : !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
2611 131 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0));
2612 :
2613 993 : const char *pszMethod = FetchSrcMethod(psOptions->aosTransformerOptions);
2614 34 : if (pszMethod && EQUAL(pszMethod, "GCP_TPS") &&
2615 1032 : psOptions->dfErrorThreshold > 0 &&
2616 5 : !psOptions->aosTransformerOptions.FetchNameValue(
2617 : "SRC_APPROX_ERROR_IN_PIXEL"))
2618 : {
2619 : psOptions->aosTransformerOptions.SetNameValue(
2620 : "SRC_APPROX_ERROR_IN_PIXEL",
2621 5 : CPLSPrintf("%g", psOptions->dfErrorThreshold));
2622 : }
2623 :
2624 993 : if (hDstDS == nullptr)
2625 : {
2626 894 : hDstDS = CreateOutput(pszDest, nSrcCount, pahSrcDS, psOptions,
2627 : bInitDestSetByUser, hUniqueTransformArg);
2628 894 : if (!hDstDS)
2629 : {
2630 19 : return nullptr;
2631 : }
2632 : #ifdef DEBUG
2633 : // Do not remove this if the #ifdef DEBUG before is still there !
2634 875 : poDstDS = GDALDataset::FromHandle(hDstDS);
2635 875 : CPL_IGNORE_RET_VAL(poDstDS);
2636 : #endif
2637 : }
2638 : else
2639 : {
2640 99 : if (psOptions->aosWarpOptions.FetchNameValue("SKIP_NOSOURCE") ==
2641 : nullptr)
2642 : {
2643 98 : CPLDebug("GDALWARP", "Defining SKIP_NOSOURCE=YES");
2644 98 : psOptions->aosWarpOptions.SetNameValue("SKIP_NOSOURCE", "YES");
2645 : }
2646 : }
2647 :
2648 : /* -------------------------------------------------------------------- */
2649 : /* Detect if output has alpha channel. */
2650 : /* -------------------------------------------------------------------- */
2651 974 : bool bEnableDstAlpha = psOptions->bEnableDstAlpha;
2652 909 : if (!bEnableDstAlpha && GDALGetRasterCount(hDstDS) &&
2653 908 : GDALGetRasterColorInterpretation(GDALGetRasterBand(
2654 1883 : hDstDS, GDALGetRasterCount(hDstDS))) == GCI_AlphaBand &&
2655 40 : !psOptions->bDisableSrcAlpha)
2656 : {
2657 39 : if (!psOptions->bQuiet)
2658 1 : printf("Using band %d of destination image as alpha.\n",
2659 : GDALGetRasterCount(hDstDS));
2660 :
2661 39 : bEnableDstAlpha = true;
2662 : }
2663 :
2664 : /* -------------------------------------------------------------------- */
2665 : /* Create global progress function. */
2666 : /* -------------------------------------------------------------------- */
2667 : struct Progress
2668 : {
2669 : GDALProgressFunc pfnExternalProgress;
2670 : void *pExternalProgressData;
2671 : int iSrc;
2672 : int nSrcCount;
2673 : GDALDatasetH *pahSrcDS;
2674 :
2675 18699 : int Do(double dfComplete)
2676 : {
2677 37398 : CPLString osMsg;
2678 : osMsg.Printf("Processing %s [%d/%d]",
2679 18699 : CPLGetFilename(GDALGetDescription(pahSrcDS[iSrc])),
2680 18699 : iSrc + 1, nSrcCount);
2681 18699 : return pfnExternalProgress((iSrc + dfComplete) / nSrcCount,
2682 37398 : osMsg.c_str(), pExternalProgressData);
2683 : }
2684 :
2685 17603 : static int CPL_STDCALL ProgressFunc(double dfComplete, const char *,
2686 : void *pThis)
2687 : {
2688 17603 : return static_cast<Progress *>(pThis)->Do(dfComplete);
2689 : }
2690 : };
2691 :
2692 : Progress oProgress;
2693 974 : oProgress.pfnExternalProgress = psOptions->pfnProgress;
2694 974 : oProgress.pExternalProgressData = psOptions->pProgressData;
2695 974 : oProgress.nSrcCount = nSrcCount;
2696 974 : oProgress.pahSrcDS = pahSrcDS;
2697 :
2698 : /* -------------------------------------------------------------------- */
2699 : /* Loop over all source files, processing each in turn. */
2700 : /* -------------------------------------------------------------------- */
2701 974 : bool bHasGotErr = false;
2702 1855 : for (int iSrc = 0; iSrc < nSrcCount; iSrc++)
2703 : {
2704 : GDALDatasetH hSrcDS;
2705 :
2706 : /* --------------------------------------------------------------------
2707 : */
2708 : /* Open this file. */
2709 : /* --------------------------------------------------------------------
2710 : */
2711 996 : hSrcDS = pahSrcDS[iSrc];
2712 996 : oProgress.iSrc = iSrc;
2713 :
2714 : /* --------------------------------------------------------------------
2715 : */
2716 : /* Check that there's at least one raster band */
2717 : /* --------------------------------------------------------------------
2718 : */
2719 996 : if (GDALGetRasterCount(hSrcDS) == 0)
2720 : {
2721 1 : CPLError(CE_Failure, CPLE_AppDefined,
2722 : "Input file %s has no raster bands.",
2723 : GDALGetDescription(hSrcDS));
2724 1 : GDALReleaseDataset(hDstDS);
2725 115 : return nullptr;
2726 : }
2727 :
2728 : /* --------------------------------------------------------------------
2729 : */
2730 : /* Do we have a source alpha band? */
2731 : /* --------------------------------------------------------------------
2732 : */
2733 995 : bool bEnableSrcAlpha = psOptions->bEnableSrcAlpha;
2734 995 : if (GDALGetRasterColorInterpretation(GDALGetRasterBand(
2735 62 : hSrcDS, GDALGetRasterCount(hSrcDS))) == GCI_AlphaBand &&
2736 995 : !bEnableSrcAlpha && !psOptions->bDisableSrcAlpha)
2737 : {
2738 37 : bEnableSrcAlpha = true;
2739 37 : if (!psOptions->bQuiet)
2740 0 : printf("Using band %d of source image as alpha.\n",
2741 : GDALGetRasterCount(hSrcDS));
2742 : }
2743 :
2744 : /* --------------------------------------------------------------------
2745 : */
2746 : /* Get the metadata of the first source DS and copy it to the */
2747 : /* destination DS. Copy Band-level metadata and other info, only */
2748 : /* if source and destination band count are equal. Any values that
2749 : */
2750 : /* conflict between source datasets are set to pszMDConflictValue.
2751 : */
2752 : /* --------------------------------------------------------------------
2753 : */
2754 995 : ProcessMetadata(iSrc, hSrcDS, hDstDS, psOptions, bEnableDstAlpha);
2755 :
2756 : /* --------------------------------------------------------------------
2757 : */
2758 : /* Warns if the file has a color table and something more */
2759 : /* complicated than nearest neighbour resampling is asked */
2760 : /* --------------------------------------------------------------------
2761 : */
2762 :
2763 2461 : if (psOptions->eResampleAlg != GRA_NearestNeighbour &&
2764 1425 : psOptions->eResampleAlg != GRA_Mode &&
2765 430 : GDALGetRasterColorTable(GDALGetRasterBand(hSrcDS, 1)) != nullptr)
2766 : {
2767 0 : if (!psOptions->bQuiet)
2768 0 : CPLError(
2769 : CE_Warning, CPLE_AppDefined,
2770 : "Input file %s has a color table, which will likely lead "
2771 : "to "
2772 : "bad results when using a resampling method other than "
2773 : "nearest neighbour or mode. Converting the dataset prior "
2774 : "to 24/32 bit "
2775 : "is advised.",
2776 : GDALGetDescription(hSrcDS));
2777 : }
2778 :
2779 : // For RPC warping add a few extra source pixels by default
2780 : // (probably mostly needed in the RPC DEM case)
2781 998 : if (iSrc == 0 && (GDALGetMetadata(hSrcDS, "RPC") != nullptr &&
2782 3 : (pszMethod == nullptr || EQUAL(pszMethod, "RPC"))))
2783 : {
2784 13 : if (!psOptions->aosWarpOptions.FetchNameValue("SOURCE_EXTRA"))
2785 : {
2786 13 : CPLDebug(
2787 : "WARP",
2788 : "Set SOURCE_EXTRA=5 warping options due to RPC warping");
2789 13 : psOptions->aosWarpOptions.SetNameValue("SOURCE_EXTRA", "5");
2790 : }
2791 :
2792 13 : if (!psOptions->aosWarpOptions.FetchNameValue("SAMPLE_STEPS") &&
2793 26 : !psOptions->aosWarpOptions.FetchNameValue("SAMPLE_GRID") &&
2794 13 : psOptions->aosTransformerOptions.FetchNameValue("RPC_DEM"))
2795 : {
2796 10 : CPLDebug("WARP", "Set SAMPLE_STEPS=ALL warping options due to "
2797 : "RPC DEM warping");
2798 10 : psOptions->aosWarpOptions.SetNameValue("SAMPLE_STEPS", "ALL");
2799 : }
2800 : }
2801 : // Also do the same for GCP TPS warping, e.g. to solve use case of
2802 : // https://github.com/OSGeo/gdal/issues/12736
2803 1940 : else if (iSrc == 0 &&
2804 958 : (GDALGetGCPCount(hSrcDS) > 0 &&
2805 5 : (pszMethod == nullptr || EQUAL(pszMethod, "TPS"))))
2806 : {
2807 20 : if (!psOptions->aosWarpOptions.FetchNameValue("SOURCE_EXTRA"))
2808 : {
2809 20 : CPLDebug(
2810 : "WARP",
2811 : "Set SOURCE_EXTRA=5 warping options due to TPS warping");
2812 : }
2813 : }
2814 :
2815 995 : if (iSrc > 0)
2816 : psOptions->aosWarpOptions.SetNameValue("RESET_DEST_PIXELS",
2817 24 : nullptr);
2818 :
2819 : /* --------------------------------------------------------------------
2820 : */
2821 : /* Create a transformation object from the source to */
2822 : /* destination coordinate system. */
2823 : /* --------------------------------------------------------------------
2824 : */
2825 0 : GDALTransformerArgUniquePtr hTransformArg;
2826 995 : if (hUniqueTransformArg)
2827 853 : hTransformArg = std::move(hUniqueTransformArg);
2828 : else
2829 : {
2830 142 : hTransformArg.reset(GDALCreateGenImgProjTransformer2(
2831 142 : hSrcDS, hDstDS, psOptions->aosTransformerOptions.List()));
2832 142 : if (hTransformArg == nullptr)
2833 : {
2834 0 : GDALReleaseDataset(hDstDS);
2835 0 : return nullptr;
2836 : }
2837 : }
2838 :
2839 995 : GDALTransformerFunc pfnTransformer = GDALGenImgProjTransform;
2840 :
2841 : // Check if transformation is inversible
2842 : {
2843 995 : double dfX = GDALGetRasterXSize(hDstDS) / 2.0;
2844 995 : double dfY = GDALGetRasterYSize(hDstDS) / 2.0;
2845 995 : double dfZ = 0;
2846 995 : int bSuccess = false;
2847 995 : const auto nErrorCounterBefore = CPLGetErrorCounter();
2848 995 : pfnTransformer(hTransformArg.get(), TRUE, 1, &dfX, &dfY, &dfZ,
2849 : &bSuccess);
2850 995 : if (!bSuccess && CPLGetErrorCounter() > nErrorCounterBefore &&
2851 0 : strstr(CPLGetLastErrorMsg(), "No inverse operation"))
2852 : {
2853 0 : GDALReleaseDataset(hDstDS);
2854 0 : return nullptr;
2855 : }
2856 : }
2857 :
2858 : /* --------------------------------------------------------------------
2859 : */
2860 : /* Determine if we must work with the full-resolution source */
2861 : /* dataset, or one of its overview level. */
2862 : /* --------------------------------------------------------------------
2863 : */
2864 995 : GDALDataset *poSrcDS = static_cast<GDALDataset *>(hSrcDS);
2865 995 : GDALDataset *poSrcOvrDS = nullptr;
2866 995 : int nOvCount = poSrcDS->GetRasterBand(1)->GetOverviewCount();
2867 995 : if (psOptions->nOvLevel <= OVR_LEVEL_AUTO && nOvCount > 0)
2868 : {
2869 21 : double dfTargetRatio = 0;
2870 21 : double dfTargetRatioX = 0;
2871 21 : double dfTargetRatioY = 0;
2872 :
2873 21 : if (bFigureoutCorrespondingWindow)
2874 : {
2875 : // If the user has explicitly set the target bounds and
2876 : // resolution, or we're updating an existing file, then figure
2877 : // out which source window corresponds to the target raster.
2878 4 : constexpr int nPointsOneDim = 10;
2879 4 : constexpr int nPoints = nPointsOneDim * nPointsOneDim;
2880 8 : std::vector<double> adfX(nPoints);
2881 8 : std::vector<double> adfY(nPoints);
2882 8 : std::vector<double> adfZ(nPoints);
2883 4 : const int nDstXSize = GDALGetRasterXSize(hDstDS);
2884 4 : const int nDstYSize = GDALGetRasterYSize(hDstDS);
2885 4 : int iPoint = 0;
2886 44 : for (int iX = 0; iX < nPointsOneDim; ++iX)
2887 : {
2888 440 : for (int iY = 0; iY < nPointsOneDim; ++iY)
2889 : {
2890 400 : adfX[iPoint] = nDstXSize * static_cast<double>(iX) /
2891 : (nPointsOneDim - 1);
2892 400 : adfY[iPoint] = nDstYSize * static_cast<double>(iY) /
2893 : (nPointsOneDim - 1);
2894 400 : iPoint++;
2895 : }
2896 : }
2897 4 : std::vector<int> abSuccess(nPoints);
2898 4 : pfnTransformer(hTransformArg.get(), TRUE, nPoints, &adfX[0],
2899 4 : &adfY[0], &adfZ[0], &abSuccess[0]);
2900 :
2901 4 : double dfMinSrcX = std::numeric_limits<double>::infinity();
2902 4 : double dfMaxSrcX = -std::numeric_limits<double>::infinity();
2903 4 : double dfMinSrcY = std::numeric_limits<double>::infinity();
2904 4 : double dfMaxSrcY = -std::numeric_limits<double>::infinity();
2905 404 : for (int i = 0; i < nPoints; i++)
2906 : {
2907 400 : if (abSuccess[i])
2908 : {
2909 400 : dfMinSrcX = std::min(dfMinSrcX, adfX[i]);
2910 400 : dfMaxSrcX = std::max(dfMaxSrcX, adfX[i]);
2911 400 : dfMinSrcY = std::min(dfMinSrcY, adfY[i]);
2912 400 : dfMaxSrcY = std::max(dfMaxSrcY, adfY[i]);
2913 : }
2914 : }
2915 4 : if (dfMaxSrcX > dfMinSrcX)
2916 : {
2917 4 : dfTargetRatioX =
2918 4 : (dfMaxSrcX - dfMinSrcX) / GDALGetRasterXSize(hDstDS);
2919 : }
2920 4 : if (dfMaxSrcY > dfMinSrcY)
2921 : {
2922 4 : dfTargetRatioY =
2923 4 : (dfMaxSrcY - dfMinSrcY) / GDALGetRasterYSize(hDstDS);
2924 : }
2925 : // take the minimum of these ratios #7019
2926 4 : dfTargetRatio = std::min(dfTargetRatioX, dfTargetRatioY);
2927 : }
2928 : else
2929 : {
2930 : /* Compute what the "natural" output resolution (in pixels)
2931 : * would be for this */
2932 : /* input dataset */
2933 : double adfSuggestedGeoTransform[6];
2934 : int nPixels, nLines;
2935 17 : if (GDALSuggestedWarpOutput(
2936 : hSrcDS, pfnTransformer, hTransformArg.get(),
2937 17 : adfSuggestedGeoTransform, &nPixels, &nLines) == CE_None)
2938 : {
2939 17 : dfTargetRatio = 1.0 / adfSuggestedGeoTransform[1];
2940 : }
2941 : }
2942 :
2943 21 : if (dfTargetRatio > 1.0)
2944 : {
2945 : // Note: keep this logic for overview selection in sync between
2946 : // gdalwarp_lib.cpp and rasterio.cpp
2947 15 : const char *pszOversampligThreshold = CPLGetConfigOption(
2948 : "GDALWARP_OVERSAMPLING_THRESHOLD", nullptr);
2949 : const double dfOversamplingThreshold =
2950 15 : pszOversampligThreshold ? CPLAtof(pszOversampligThreshold)
2951 15 : : 1.0;
2952 :
2953 15 : int iBestOvr = -1;
2954 15 : double dfBestRatio = 0;
2955 35 : for (int iOvr = -1; iOvr < nOvCount; iOvr++)
2956 : {
2957 : const double dfOvrRatio =
2958 : iOvr < 0
2959 31 : ? 1.0
2960 16 : : static_cast<double>(poSrcDS->GetRasterXSize()) /
2961 16 : poSrcDS->GetRasterBand(1)
2962 16 : ->GetOverview(iOvr)
2963 16 : ->GetXSize();
2964 :
2965 : // Is it nearly the requested factor and better (lower) than
2966 : // the current best factor?
2967 : // Use an epsilon because of numerical instability.
2968 31 : constexpr double EPSILON = 1e-1;
2969 35 : if (dfOvrRatio >=
2970 31 : dfTargetRatio * dfOversamplingThreshold + EPSILON ||
2971 : dfOvrRatio <= dfBestRatio)
2972 : {
2973 4 : continue;
2974 : }
2975 :
2976 27 : iBestOvr = iOvr;
2977 27 : dfBestRatio = dfOvrRatio;
2978 27 : if (std::abs(dfTargetRatio - dfOvrRatio) < EPSILON)
2979 : {
2980 11 : break;
2981 : }
2982 : }
2983 15 : const int iOvr =
2984 15 : iBestOvr + (psOptions->nOvLevel - OVR_LEVEL_AUTO);
2985 15 : if (iOvr >= 0)
2986 : {
2987 9 : CPLDebug("WARP", "Selecting overview level %d for %s", iOvr,
2988 : GDALGetDescription(hSrcDS));
2989 : poSrcOvrDS =
2990 9 : GDALCreateOverviewDataset(poSrcDS, iOvr,
2991 : /* bThisLevelOnly = */ false);
2992 : }
2993 21 : }
2994 : }
2995 974 : else if (psOptions->nOvLevel >= 0)
2996 : {
2997 6 : poSrcOvrDS = GDALCreateOverviewDataset(poSrcDS, psOptions->nOvLevel,
2998 : /* bThisLevelOnly = */ true);
2999 6 : if (poSrcOvrDS == nullptr)
3000 : {
3001 1 : if (!psOptions->bQuiet)
3002 : {
3003 1 : CPLError(CE_Warning, CPLE_AppDefined,
3004 : "cannot get overview level %d for "
3005 : "dataset %s. Defaulting to level %d",
3006 : psOptions->nOvLevel, GDALGetDescription(hSrcDS),
3007 : nOvCount - 1);
3008 : }
3009 1 : if (nOvCount > 0)
3010 : poSrcOvrDS =
3011 1 : GDALCreateOverviewDataset(poSrcDS, nOvCount - 1,
3012 : /* bThisLevelOnly = */ false);
3013 : }
3014 : else
3015 : {
3016 5 : CPLDebug("WARP", "Selecting overview level %d for %s",
3017 : psOptions->nOvLevel, GDALGetDescription(hSrcDS));
3018 : }
3019 : }
3020 :
3021 995 : if (poSrcOvrDS == nullptr)
3022 980 : GDALReferenceDataset(hSrcDS);
3023 :
3024 995 : GDALDatasetH hWrkSrcDS =
3025 995 : poSrcOvrDS ? static_cast<GDALDatasetH>(poSrcOvrDS) : hSrcDS;
3026 :
3027 : #if !defined(USE_PROJ_BASED_VERTICAL_SHIFT_METHOD)
3028 : if (!psOptions->bNoVShift)
3029 : {
3030 : bool bErrorOccurred = false;
3031 : hWrkSrcDS = ApplyVerticalShiftGrid(
3032 : hWrkSrcDS, psOptions, bVRT ? hDstDS : nullptr, bErrorOccurred);
3033 : if (bErrorOccurred)
3034 : {
3035 : GDALReleaseDataset(hWrkSrcDS);
3036 : GDALReleaseDataset(hDstDS);
3037 : return nullptr;
3038 : }
3039 : }
3040 : #endif
3041 :
3042 : /* --------------------------------------------------------------------
3043 : */
3044 : /* Clear temporary INIT_DEST settings after the first image. */
3045 : /* --------------------------------------------------------------------
3046 : */
3047 995 : if (psOptions->bCreateOutput && iSrc == 1)
3048 22 : psOptions->aosWarpOptions.SetNameValue("INIT_DEST", nullptr);
3049 :
3050 : /* --------------------------------------------------------------------
3051 : */
3052 : /* Define SKIP_NOSOURCE after the first image (since
3053 : * initialization*/
3054 : /* has already be done). */
3055 : /* --------------------------------------------------------------------
3056 : */
3057 995 : if (iSrc == 1 && psOptions->aosWarpOptions.FetchNameValue(
3058 : "SKIP_NOSOURCE") == nullptr)
3059 : {
3060 22 : CPLDebug("GDALWARP", "Defining SKIP_NOSOURCE=YES");
3061 22 : psOptions->aosWarpOptions.SetNameValue("SKIP_NOSOURCE", "YES");
3062 : }
3063 :
3064 : /* --------------------------------------------------------------------
3065 : */
3066 : /* Setup warp options. */
3067 : /* --------------------------------------------------------------------
3068 : */
3069 : std::unique_ptr<GDALWarpOptions, decltype(&GDALDestroyWarpOptions)>
3070 995 : psWO(GDALCreateWarpOptions(), GDALDestroyWarpOptions);
3071 :
3072 995 : psWO->papszWarpOptions = CSLDuplicate(psOptions->aosWarpOptions.List());
3073 995 : psWO->eWorkingDataType = psOptions->eWorkingType;
3074 :
3075 995 : psWO->eResampleAlg = psOptions->eResampleAlg;
3076 :
3077 995 : psWO->hSrcDS = hWrkSrcDS;
3078 995 : psWO->hDstDS = hDstDS;
3079 :
3080 995 : if (!bVRT)
3081 : {
3082 887 : if (psOptions->pfnProgress == GDALDummyProgress)
3083 : {
3084 769 : psWO->pfnProgress = GDALDummyProgress;
3085 769 : psWO->pProgressArg = nullptr;
3086 : }
3087 : else
3088 : {
3089 118 : psWO->pfnProgress = Progress::ProgressFunc;
3090 118 : psWO->pProgressArg = &oProgress;
3091 : }
3092 : }
3093 :
3094 995 : if (psOptions->dfWarpMemoryLimit != 0.0)
3095 35 : psWO->dfWarpMemoryLimit = psOptions->dfWarpMemoryLimit;
3096 :
3097 : /* --------------------------------------------------------------------
3098 : */
3099 : /* Setup band mapping. */
3100 : /* --------------------------------------------------------------------
3101 : */
3102 995 : if (psOptions->anSrcBands.empty())
3103 : {
3104 977 : if (bEnableSrcAlpha)
3105 56 : psWO->nBandCount = GDALGetRasterCount(hWrkSrcDS) - 1;
3106 : else
3107 921 : psWO->nBandCount = GDALGetRasterCount(hWrkSrcDS);
3108 : }
3109 : else
3110 : {
3111 18 : psWO->nBandCount = static_cast<int>(psOptions->anSrcBands.size());
3112 : }
3113 :
3114 : const int nNeededDstBands =
3115 995 : psWO->nBandCount + (bEnableDstAlpha ? 1 : 0);
3116 995 : if (nNeededDstBands > GDALGetRasterCount(hDstDS))
3117 : {
3118 1 : CPLError(CE_Failure, CPLE_AppDefined,
3119 : "Destination dataset has %d bands, but at least %d "
3120 : "are needed",
3121 : GDALGetRasterCount(hDstDS), nNeededDstBands);
3122 1 : GDALReleaseDataset(hWrkSrcDS);
3123 1 : GDALReleaseDataset(hDstDS);
3124 1 : return nullptr;
3125 : }
3126 :
3127 1988 : psWO->panSrcBands =
3128 994 : static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
3129 1988 : psWO->panDstBands =
3130 994 : static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
3131 994 : if (psOptions->anSrcBands.empty())
3132 : {
3133 2210 : for (int i = 0; i < psWO->nBandCount; i++)
3134 : {
3135 1234 : psWO->panSrcBands[i] = i + 1;
3136 1234 : psWO->panDstBands[i] = i + 1;
3137 : }
3138 : }
3139 : else
3140 : {
3141 45 : for (int i = 0; i < psWO->nBandCount; i++)
3142 : {
3143 58 : if (psOptions->anSrcBands[i] <= 0 ||
3144 29 : psOptions->anSrcBands[i] > GDALGetRasterCount(hSrcDS))
3145 : {
3146 1 : CPLError(CE_Failure, CPLE_AppDefined,
3147 : "-srcband[%d] = %d is invalid", i,
3148 1 : psOptions->anSrcBands[i]);
3149 1 : GDALReleaseDataset(hWrkSrcDS);
3150 1 : GDALReleaseDataset(hDstDS);
3151 1 : return nullptr;
3152 : }
3153 56 : if (psOptions->anDstBands[i] <= 0 ||
3154 28 : psOptions->anDstBands[i] > GDALGetRasterCount(hDstDS))
3155 : {
3156 1 : CPLError(CE_Failure, CPLE_AppDefined,
3157 : "-dstband[%d] = %d is invalid", i,
3158 1 : psOptions->anDstBands[i]);
3159 1 : GDALReleaseDataset(hWrkSrcDS);
3160 1 : GDALReleaseDataset(hDstDS);
3161 1 : return nullptr;
3162 : }
3163 27 : psWO->panSrcBands[i] = psOptions->anSrcBands[i];
3164 27 : psWO->panDstBands[i] = psOptions->anDstBands[i];
3165 : }
3166 : }
3167 :
3168 : /* --------------------------------------------------------------------
3169 : */
3170 : /* Setup alpha bands used if any. */
3171 : /* --------------------------------------------------------------------
3172 : */
3173 992 : if (bEnableSrcAlpha)
3174 59 : psWO->nSrcAlphaBand = GDALGetRasterCount(hWrkSrcDS);
3175 :
3176 992 : if (bEnableDstAlpha)
3177 : {
3178 109 : if (psOptions->anSrcBands.empty())
3179 105 : psWO->nDstAlphaBand = GDALGetRasterCount(hDstDS);
3180 : else
3181 4 : psWO->nDstAlphaBand =
3182 4 : static_cast<int>(psOptions->anDstBands.size()) + 1;
3183 : }
3184 :
3185 : /* ------------------------------------------------------------------ */
3186 : /* Setup NODATA options. */
3187 : /* ------------------------------------------------------------------ */
3188 992 : if (SetupNoData(pszDest, iSrc, hSrcDS, hWrkSrcDS, hDstDS, psWO.get(),
3189 : psOptions, bEnableDstAlpha,
3190 992 : bInitDestSetByUser) != CE_None)
3191 : {
3192 2 : GDALReleaseDataset(hWrkSrcDS);
3193 2 : GDALReleaseDataset(hDstDS);
3194 2 : return nullptr;
3195 : }
3196 :
3197 990 : oProgress.Do(0);
3198 :
3199 : /* --------------------------------------------------------------------
3200 : */
3201 : /* For the first source image of a newly created dataset, decide */
3202 : /* if we can safely enable SKIP_NOSOURCE optimization. */
3203 : /* --------------------------------------------------------------------
3204 : */
3205 990 : SetupSkipNoSource(iSrc, hDstDS, psWO.get(), psOptions);
3206 :
3207 : /* --------------------------------------------------------------------
3208 : */
3209 : /* In some cases, RPC evaluation can find valid input pixel for */
3210 : /* output pixels that are outside the footprint of the source */
3211 : /* dataset, so limit the area we update in the target dataset from
3212 : */
3213 : /* the suggested warp output (only in cases where
3214 : * SKIP_NOSOURCE=YES) */
3215 : /* --------------------------------------------------------------------
3216 : */
3217 990 : int nWarpDstXOff = 0;
3218 990 : int nWarpDstYOff = 0;
3219 990 : int nWarpDstXSize = GDALGetRasterXSize(hDstDS);
3220 990 : int nWarpDstYSize = GDALGetRasterYSize(hDstDS);
3221 :
3222 990 : if (!AdjustOutputExtentForRPC(hSrcDS, hDstDS, pfnTransformer,
3223 : hTransformArg.get(), psWO.get(),
3224 : psOptions, nWarpDstXOff, nWarpDstYOff,
3225 : nWarpDstXSize, nWarpDstYSize))
3226 : {
3227 1 : GDALReleaseDataset(hWrkSrcDS);
3228 1 : continue;
3229 : }
3230 :
3231 : /* We need to recreate the transform when operating on an overview */
3232 989 : if (poSrcOvrDS != nullptr)
3233 : {
3234 15 : hTransformArg.reset(GDALCreateGenImgProjTransformer2(
3235 15 : hWrkSrcDS, hDstDS, psOptions->aosTransformerOptions.List()));
3236 : }
3237 :
3238 989 : bool bUseApproxTransformer = psOptions->dfErrorThreshold != 0.0;
3239 : #ifdef USE_PROJ_BASED_VERTICAL_SHIFT_METHOD
3240 989 : if (!psOptions->bNoVShift)
3241 : {
3242 : // Can modify psWO->papszWarpOptions
3243 988 : if (ApplyVerticalShift(hWrkSrcDS, psOptions, psWO.get()))
3244 : {
3245 19 : bUseApproxTransformer = false;
3246 : }
3247 : }
3248 : #endif
3249 :
3250 : /* --------------------------------------------------------------------
3251 : */
3252 : /* Warp the transformer with a linear approximator unless the */
3253 : /* acceptable error is zero. */
3254 : /* --------------------------------------------------------------------
3255 : */
3256 989 : if (bUseApproxTransformer)
3257 : {
3258 956 : hTransformArg.reset(GDALCreateApproxTransformer(
3259 : GDALGenImgProjTransform, hTransformArg.release(),
3260 : psOptions->dfErrorThreshold));
3261 956 : pfnTransformer = GDALApproxTransform;
3262 956 : GDALApproxTransformerOwnsSubtransformer(hTransformArg.get(), TRUE);
3263 : }
3264 :
3265 : /* --------------------------------------------------------------------
3266 : */
3267 : /* If we have a cutline, transform it into the source */
3268 : /* pixel/line coordinate system and insert into warp options. */
3269 : /* --------------------------------------------------------------------
3270 : */
3271 989 : if (poCutline)
3272 : {
3273 : CPLErr eError;
3274 40 : eError = TransformCutlineToSource(
3275 : GDALDataset::FromHandle(hWrkSrcDS), poCutline.get(),
3276 40 : &(psWO->papszWarpOptions),
3277 40 : psOptions->aosTransformerOptions.List());
3278 40 : if (eError == CE_Failure)
3279 : {
3280 1 : GDALReleaseDataset(hWrkSrcDS);
3281 1 : GDALReleaseDataset(hDstDS);
3282 1 : return nullptr;
3283 : }
3284 : }
3285 :
3286 : /* --------------------------------------------------------------------
3287 : */
3288 : /* If we are producing VRT output, then just initialize it with */
3289 : /* the warp options and write out now rather than proceeding */
3290 : /* with the operations. */
3291 : /* --------------------------------------------------------------------
3292 : */
3293 988 : if (bVRT)
3294 : {
3295 108 : GDALSetMetadataItem(hDstDS, "SrcOvrLevel",
3296 : CPLSPrintf("%d", psOptions->nOvLevel), nullptr);
3297 :
3298 : // In case of success, hDstDS has become the owner of hTransformArg
3299 : // so we need to release it
3300 108 : psWO->pfnTransformer = pfnTransformer;
3301 108 : psWO->pTransformerArg = hTransformArg.release();
3302 108 : CPLErr eErr = GDALInitializeWarpedVRT(hDstDS, psWO.get());
3303 108 : if (eErr != CE_None)
3304 : {
3305 : // In case of error, reacquire psWO->pTransformerArg
3306 1 : hTransformArg.reset(psWO->pTransformerArg);
3307 : }
3308 108 : GDALReleaseDataset(hWrkSrcDS);
3309 108 : if (eErr != CE_None)
3310 : {
3311 1 : GDALReleaseDataset(hDstDS);
3312 1 : return nullptr;
3313 : }
3314 :
3315 107 : if (!EQUAL(pszDest, ""))
3316 : {
3317 : const bool bWasFailureBefore =
3318 20 : (CPLGetLastErrorType() == CE_Failure);
3319 20 : GDALFlushCache(hDstDS);
3320 20 : if (!bWasFailureBefore && CPLGetLastErrorType() == CE_Failure)
3321 : {
3322 1 : GDALReleaseDataset(hDstDS);
3323 1 : hDstDS = nullptr;
3324 : }
3325 : }
3326 :
3327 107 : if (hDstDS)
3328 106 : oProgress.Do(1);
3329 :
3330 107 : return hDstDS;
3331 : }
3332 :
3333 : /* --------------------------------------------------------------------
3334 : */
3335 : /* Initialize and execute the warp. */
3336 : /* --------------------------------------------------------------------
3337 : */
3338 1760 : GDALWarpOperation oWO;
3339 :
3340 1760 : if (oWO.Initialize(psWO.get(), pfnTransformer,
3341 1760 : std::move(hTransformArg)) == CE_None)
3342 : {
3343 : CPLErr eErr;
3344 877 : if (psOptions->bMulti)
3345 6 : eErr = oWO.ChunkAndWarpMulti(nWarpDstXOff, nWarpDstYOff,
3346 : nWarpDstXSize, nWarpDstYSize);
3347 : else
3348 871 : eErr = oWO.ChunkAndWarpImage(nWarpDstXOff, nWarpDstYOff,
3349 : nWarpDstXSize, nWarpDstYSize);
3350 877 : if (eErr != CE_None)
3351 5 : bHasGotErr = true;
3352 : }
3353 : else
3354 : {
3355 3 : bHasGotErr = true;
3356 : }
3357 :
3358 : /* --------------------------------------------------------------------
3359 : */
3360 : /* Cleanup */
3361 : /* --------------------------------------------------------------------
3362 : */
3363 880 : GDALReleaseDataset(hWrkSrcDS);
3364 : }
3365 :
3366 : /* -------------------------------------------------------------------- */
3367 : /* Final Cleanup. */
3368 : /* -------------------------------------------------------------------- */
3369 859 : const bool bWasFailureBefore = (CPLGetLastErrorType() == CE_Failure);
3370 859 : GDALFlushCache(hDstDS);
3371 859 : if (!bWasFailureBefore && CPLGetLastErrorType() == CE_Failure)
3372 : {
3373 1 : bHasGotErr = true;
3374 : }
3375 :
3376 859 : if (bHasGotErr || bDropDstDSRef)
3377 106 : GDALReleaseDataset(hDstDS);
3378 :
3379 : #ifdef DEBUG
3380 859 : if (!bHasGotErr || bDropDstDSRef)
3381 : {
3382 850 : CPLAssert(poDstDS->GetRefCount() == nExpectedRefCountAtEnd);
3383 : }
3384 : #endif
3385 :
3386 859 : return bHasGotErr ? nullptr : hDstDS;
3387 : }
3388 :
3389 : /************************************************************************/
3390 : /* ValidateCutline() */
3391 : /* Same as OGR_G_IsValid() except that it processes polygon per polygon*/
3392 : /* without paying attention to MultiPolygon specific validity rules. */
3393 : /************************************************************************/
3394 :
3395 216 : static bool ValidateCutline(const OGRGeometry *poGeom, bool bVerbose)
3396 : {
3397 216 : const OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
3398 216 : if (eType == wkbMultiPolygon)
3399 : {
3400 151 : for (const auto *poSubGeom : *(poGeom->toMultiPolygon()))
3401 : {
3402 81 : if (!ValidateCutline(poSubGeom, bVerbose))
3403 5 : return false;
3404 : }
3405 : }
3406 141 : else if (eType == wkbPolygon)
3407 : {
3408 140 : if (OGRGeometryFactory::haveGEOS() && !poGeom->IsValid())
3409 : {
3410 6 : if (!bVerbose)
3411 6 : return false;
3412 :
3413 2 : char *pszWKT = nullptr;
3414 2 : poGeom->exportToWkt(&pszWKT);
3415 2 : CPLDebug("GDALWARP", "WKT = \"%s\"", pszWKT ? pszWKT : "(null)");
3416 : const char *pszFile =
3417 2 : CPLGetConfigOption("GDALWARP_DUMP_WKT_TO_FILE", nullptr);
3418 2 : if (pszFile && pszWKT)
3419 : {
3420 : FILE *f =
3421 0 : EQUAL(pszFile, "stderr") ? stderr : fopen(pszFile, "wb");
3422 0 : if (f)
3423 : {
3424 0 : fprintf(f, "id,WKT\n");
3425 0 : fprintf(f, "1,\"%s\"\n", pszWKT);
3426 0 : if (!EQUAL(pszFile, "stderr"))
3427 0 : fclose(f);
3428 : }
3429 : }
3430 2 : CPLFree(pszWKT);
3431 :
3432 2 : if (CPLTestBool(
3433 : CPLGetConfigOption("GDALWARP_IGNORE_BAD_CUTLINE", "NO")))
3434 0 : CPLError(CE_Warning, CPLE_AppDefined,
3435 : "Cutline polygon is invalid.");
3436 : else
3437 : {
3438 2 : CPLError(CE_Failure, CPLE_AppDefined,
3439 : "Cutline polygon is invalid.");
3440 2 : return false;
3441 : }
3442 : }
3443 : }
3444 : else
3445 : {
3446 1 : if (bVerbose)
3447 : {
3448 1 : CPLError(CE_Failure, CPLE_AppDefined,
3449 : "Cutline not of polygon type.");
3450 : }
3451 1 : return false;
3452 : }
3453 :
3454 204 : return true;
3455 : }
3456 :
3457 : /************************************************************************/
3458 : /* LoadCutline() */
3459 : /* */
3460 : /* Load blend cutline from OGR datasource. */
3461 : /************************************************************************/
3462 :
3463 52 : static CPLErr LoadCutline(const std::string &osCutlineDSNameOrWKT,
3464 : const std::string &osSRS, const std::string &osCLayer,
3465 : const std::string &osCWHERE,
3466 : const std::string &osCSQL, OGRGeometryH *phCutlineRet)
3467 :
3468 : {
3469 52 : if (STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "POLYGON(") ||
3470 52 : STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "POLYGON (") ||
3471 148 : STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "MULTIPOLYGON(") ||
3472 44 : STARTS_WITH_CI(osCutlineDSNameOrWKT.c_str(), "MULTIPOLYGON ("))
3473 : {
3474 8 : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSRS;
3475 8 : if (!osSRS.empty())
3476 : {
3477 2 : poSRS.reset(new OGRSpatialReference());
3478 2 : poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
3479 2 : poSRS->SetFromUserInput(osSRS.c_str());
3480 : }
3481 :
3482 8 : auto [poGeom, _] = OGRGeometryFactory::createFromWkt(
3483 8 : osCutlineDSNameOrWKT.c_str(), poSRS.get());
3484 8 : *phCutlineRet = OGRGeometry::ToHandle(poGeom.release());
3485 8 : return *phCutlineRet ? CE_None : CE_Failure;
3486 : }
3487 :
3488 : /* -------------------------------------------------------------------- */
3489 : /* Open source vector dataset. */
3490 : /* -------------------------------------------------------------------- */
3491 : auto poDS = std::unique_ptr<GDALDataset>(
3492 88 : GDALDataset::Open(osCutlineDSNameOrWKT.c_str(), GDAL_OF_VECTOR));
3493 44 : if (poDS == nullptr)
3494 : {
3495 1 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s.",
3496 : osCutlineDSNameOrWKT.c_str());
3497 1 : return CE_Failure;
3498 : }
3499 :
3500 : /* -------------------------------------------------------------------- */
3501 : /* Get the source layer */
3502 : /* -------------------------------------------------------------------- */
3503 43 : OGRLayer *poLayer = nullptr;
3504 :
3505 43 : if (!osCSQL.empty())
3506 2 : poLayer = poDS->ExecuteSQL(osCSQL.c_str(), nullptr, nullptr);
3507 41 : else if (!osCLayer.empty())
3508 15 : poLayer = poDS->GetLayerByName(osCLayer.c_str());
3509 : else
3510 26 : poLayer = poDS->GetLayer(0);
3511 :
3512 43 : if (poLayer == nullptr)
3513 : {
3514 1 : CPLError(CE_Failure, CPLE_AppDefined,
3515 : "Failed to identify source layer from datasource.");
3516 1 : return CE_Failure;
3517 : }
3518 :
3519 : /* -------------------------------------------------------------------- */
3520 : /* Apply WHERE clause if there is one. */
3521 : /* -------------------------------------------------------------------- */
3522 42 : if (!osCWHERE.empty())
3523 1 : poLayer->SetAttributeFilter(osCWHERE.c_str());
3524 :
3525 : /* -------------------------------------------------------------------- */
3526 : /* Collect the geometries from this layer, and build list of */
3527 : /* burn values. */
3528 : /* -------------------------------------------------------------------- */
3529 84 : auto poMultiPolygon = std::make_unique<OGRMultiPolygon>();
3530 :
3531 81 : for (auto &&poFeature : poLayer)
3532 : {
3533 42 : auto poGeom = std::unique_ptr<OGRGeometry>(poFeature->StealGeometry());
3534 42 : if (poGeom == nullptr)
3535 : {
3536 1 : CPLError(CE_Failure, CPLE_AppDefined,
3537 : "Cutline feature without a geometry.");
3538 1 : goto error;
3539 : }
3540 :
3541 41 : if (!ValidateCutline(poGeom.get(), true))
3542 : {
3543 2 : goto error;
3544 : }
3545 :
3546 39 : OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
3547 :
3548 39 : if (eType == wkbPolygon)
3549 36 : poMultiPolygon->addGeometry(std::move(poGeom));
3550 3 : else if (eType == wkbMultiPolygon)
3551 : {
3552 7 : for (const auto *poSubGeom : poGeom->toMultiPolygon())
3553 : {
3554 4 : poMultiPolygon->addGeometry(poSubGeom);
3555 : }
3556 : }
3557 : }
3558 :
3559 39 : if (poMultiPolygon->IsEmpty())
3560 : {
3561 1 : CPLError(CE_Failure, CPLE_AppDefined,
3562 : "Did not get any cutline features.");
3563 1 : goto error;
3564 : }
3565 :
3566 : /* -------------------------------------------------------------------- */
3567 : /* Ensure the coordinate system gets set on the geometry. */
3568 : /* -------------------------------------------------------------------- */
3569 38 : if (!osSRS.empty())
3570 : {
3571 : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSRS(
3572 2 : new OGRSpatialReference());
3573 1 : poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
3574 1 : poSRS->SetFromUserInput(osSRS.c_str());
3575 1 : poMultiPolygon->assignSpatialReference(poSRS.get());
3576 : }
3577 : else
3578 : {
3579 37 : poMultiPolygon->assignSpatialReference(poLayer->GetSpatialRef());
3580 : }
3581 :
3582 38 : *phCutlineRet = OGRGeometry::ToHandle(poMultiPolygon.release());
3583 :
3584 : /* -------------------------------------------------------------------- */
3585 : /* Cleanup */
3586 : /* -------------------------------------------------------------------- */
3587 38 : if (!osCSQL.empty())
3588 1 : poDS->ReleaseResultSet(poLayer);
3589 :
3590 38 : return CE_None;
3591 :
3592 4 : error:
3593 4 : if (!osCSQL.empty())
3594 1 : poDS->ReleaseResultSet(poLayer);
3595 :
3596 4 : return CE_Failure;
3597 : }
3598 :
3599 : /************************************************************************/
3600 : /* GDALWarpCreateOutput() */
3601 : /* */
3602 : /* Create the output file based on various command line options, */
3603 : /* and the input file. */
3604 : /* If there's just one source file, then hUniqueTransformArg will */
3605 : /* be set in order them to be reused by main function. This saves */
3606 : /* transform recomputation, which can be expensive in the -tps case*/
3607 : /************************************************************************/
3608 :
3609 898 : static GDALDatasetH GDALWarpCreateOutput(
3610 : int nSrcCount, GDALDatasetH *pahSrcDS, const char *pszFilename,
3611 : const char *pszFormat, char **papszTO, CSLConstList papszCreateOptions,
3612 : GDALDataType eDT, GDALTransformerArgUniquePtr &hUniqueTransformArg,
3613 : bool bSetColorInterpretation, GDALWarpAppOptions *psOptions,
3614 : bool bUpdateTransformerWithDestGT)
3615 :
3616 : {
3617 : GDALDriverH hDriver;
3618 : GDALDatasetH hDstDS;
3619 898 : GDALRasterAttributeTableH hRAT = nullptr;
3620 898 : double dfWrkMinX = 0, dfWrkMaxX = 0, dfWrkMinY = 0, dfWrkMaxY = 0;
3621 898 : double dfWrkResX = 0, dfWrkResY = 0;
3622 898 : int nDstBandCount = 0;
3623 1796 : std::vector<GDALColorInterp> apeColorInterpretations;
3624 898 : bool bVRT = false;
3625 :
3626 898 : if (EQUAL(pszFormat, "VRT"))
3627 112 : bVRT = true;
3628 :
3629 : // Special case for geographic to Mercator (typically EPSG:4326 to EPSG:3857)
3630 : // where latitudes close to 90 go to infinity
3631 : // We clamp latitudes between ~ -85 and ~ 85 degrees.
3632 898 : const char *pszDstSRS = CSLFetchNameValue(papszTO, "DST_SRS");
3633 898 : if (nSrcCount == 1 && pszDstSRS && psOptions->dfMinX == 0.0 &&
3634 117 : psOptions->dfMinY == 0.0 && psOptions->dfMaxX == 0.0 &&
3635 117 : psOptions->dfMaxY == 0.0)
3636 : {
3637 117 : auto hSrcDS = pahSrcDS[0];
3638 234 : const auto osSrcSRS = GetSrcDSProjection(pahSrcDS[0], papszTO);
3639 234 : OGRSpatialReference oSrcSRS;
3640 117 : oSrcSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
3641 117 : oSrcSRS.SetFromUserInput(osSrcSRS.c_str());
3642 234 : OGRSpatialReference oDstSRS;
3643 117 : oDstSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
3644 117 : oDstSRS.SetFromUserInput(pszDstSRS);
3645 117 : const char *pszProjection = oDstSRS.GetAttrValue("PROJECTION");
3646 117 : const char *pszMethod = FetchSrcMethod(papszTO);
3647 117 : double adfSrcGT[6] = {0};
3648 : // This MAX_LAT values is equivalent to the semi_major_axis * PI
3649 : // easting/northing value only for EPSG:3857, but it is also quite
3650 : // reasonable for other Mercator projections
3651 117 : constexpr double MAX_LAT = 85.0511287798066;
3652 117 : constexpr double EPS = 1e-3;
3653 5 : const auto GetMinLon = [&adfSrcGT]() { return adfSrcGT[0]; };
3654 5 : const auto GetMaxLon = [&adfSrcGT, hSrcDS]()
3655 5 : { return adfSrcGT[0] + adfSrcGT[1] * GDALGetRasterXSize(hSrcDS); };
3656 5 : const auto GetMinLat = [&adfSrcGT, hSrcDS]()
3657 5 : { return adfSrcGT[3] + adfSrcGT[5] * GDALGetRasterYSize(hSrcDS); };
3658 6 : const auto GetMaxLat = [&adfSrcGT]() { return adfSrcGT[3]; };
3659 154 : if (oSrcSRS.IsGeographic() && !oSrcSRS.IsDerivedGeographic() &&
3660 33 : pszProjection && EQUAL(pszProjection, SRS_PT_MERCATOR_1SP) &&
3661 3 : oDstSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0) == 0 &&
3662 0 : (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")) &&
3663 3 : CSLFetchNameValue(papszTO, "COORDINATE_OPERATION") == nullptr &&
3664 3 : CSLFetchNameValue(papszTO, "SRC_METHOD") == nullptr &&
3665 3 : CSLFetchNameValue(papszTO, "DST_METHOD") == nullptr &&
3666 3 : GDALGetGeoTransform(hSrcDS, adfSrcGT) == CE_None &&
3667 6 : adfSrcGT[2] == 0 && adfSrcGT[4] == 0 && adfSrcGT[5] < 0 &&
3668 9 : GetMinLon() >= -180 - EPS && GetMaxLon() <= 180 + EPS &&
3669 6 : ((GetMaxLat() > MAX_LAT && GetMinLat() < MAX_LAT) ||
3670 2 : (GetMaxLat() > -MAX_LAT && GetMinLat() < -MAX_LAT)) &&
3671 156 : GDALGetMetadata(hSrcDS, "GEOLOC_ARRAY") == nullptr &&
3672 2 : GDALGetMetadata(hSrcDS, "RPC") == nullptr)
3673 : {
3674 : auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
3675 4 : OGRCreateCoordinateTransformation(&oSrcSRS, &oDstSRS));
3676 2 : if (poCT)
3677 : {
3678 2 : double xLL = std::max(GetMinLon(), -180.0);
3679 2 : double yLL = std::max(GetMinLat(), -MAX_LAT);
3680 2 : double xUR = std::min(GetMaxLon(), 180.0);
3681 2 : double yUR = std::min(GetMaxLat(), MAX_LAT);
3682 4 : if (poCT->Transform(1, &xLL, &yLL) &&
3683 2 : poCT->Transform(1, &xUR, &yUR))
3684 : {
3685 2 : psOptions->dfMinX = xLL;
3686 2 : psOptions->dfMinY = yLL;
3687 2 : psOptions->dfMaxX = xUR;
3688 2 : psOptions->dfMaxY = yUR;
3689 2 : CPLError(CE_Warning, CPLE_AppDefined,
3690 : "Clamping output bounds to (%f,%f) -> (%f, %f)",
3691 : psOptions->dfMinX, psOptions->dfMinY,
3692 : psOptions->dfMaxX, psOptions->dfMaxY);
3693 : }
3694 : }
3695 : }
3696 : }
3697 :
3698 : /* If (-ts and -te) or (-tr and -te) are specified, we don't need to compute
3699 : * the suggested output extent */
3700 898 : const bool bNeedsSuggestedWarpOutput =
3701 1796 : !(((psOptions->nForcePixels != 0 && psOptions->nForceLines != 0) ||
3702 734 : (psOptions->dfXRes != 0 && psOptions->dfYRes != 0)) &&
3703 213 : !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
3704 131 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0));
3705 :
3706 : // If -te is specified, not not -tr and -ts
3707 898 : const bool bKnownTargetExtentButNotResolution =
3708 729 : !(psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
3709 724 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0) &&
3710 176 : psOptions->nForcePixels == 0 && psOptions->nForceLines == 0 &&
3711 1796 : psOptions->dfXRes == 0 && psOptions->dfYRes == 0;
3712 :
3713 : /* -------------------------------------------------------------------- */
3714 : /* Find the output driver. */
3715 : /* -------------------------------------------------------------------- */
3716 898 : hDriver = GDALGetDriverByName(pszFormat);
3717 1796 : if (hDriver == nullptr ||
3718 898 : (GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) == nullptr &&
3719 0 : GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATECOPY, nullptr) ==
3720 : nullptr))
3721 : {
3722 : auto poMissingDriver =
3723 0 : GetGDALDriverManager()->GetHiddenDriverByName(pszFormat);
3724 0 : if (poMissingDriver)
3725 : {
3726 : const std::string msg =
3727 0 : GDALGetMessageAboutMissingPluginDriver(poMissingDriver);
3728 0 : printf("Output driver `%s' not found but is known. However plugin "
3729 : "%s\n",
3730 : pszFormat, msg.c_str());
3731 0 : return nullptr;
3732 : }
3733 :
3734 0 : printf("Output driver `%s' not recognised or does not support\n",
3735 : pszFormat);
3736 0 : printf("direct output file creation or CreateCopy. "
3737 : "The following format drivers are eligible for warp output:\n");
3738 :
3739 0 : for (int iDr = 0; iDr < GDALGetDriverCount(); iDr++)
3740 : {
3741 0 : hDriver = GDALGetDriver(iDr);
3742 :
3743 0 : if (GDALGetMetadataItem(hDriver, GDAL_DCAP_RASTER, nullptr) !=
3744 0 : nullptr &&
3745 0 : (GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) !=
3746 0 : nullptr ||
3747 0 : GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATECOPY, nullptr) !=
3748 : nullptr))
3749 : {
3750 0 : printf(" %s: %s\n", GDALGetDriverShortName(hDriver),
3751 : GDALGetDriverLongName(hDriver));
3752 : }
3753 : }
3754 0 : printf("\n");
3755 0 : return nullptr;
3756 : }
3757 :
3758 : /* -------------------------------------------------------------------- */
3759 : /* For virtual output files, we have to set a special subclass */
3760 : /* of dataset to create. */
3761 : /* -------------------------------------------------------------------- */
3762 1796 : CPLStringList aosCreateOptions(CSLDuplicate(papszCreateOptions));
3763 898 : if (bVRT)
3764 112 : aosCreateOptions.SetNameValue("SUBCLASS", "VRTWarpedDataset");
3765 :
3766 : /* -------------------------------------------------------------------- */
3767 : /* Loop over all input files to collect extents. */
3768 : /* -------------------------------------------------------------------- */
3769 1796 : CPLString osThisTargetSRS;
3770 : {
3771 898 : const char *pszThisTargetSRS = CSLFetchNameValue(papszTO, "DST_SRS");
3772 898 : if (pszThisTargetSRS != nullptr)
3773 209 : osThisTargetSRS = pszThisTargetSRS;
3774 : }
3775 :
3776 1796 : CPLStringList aoTOList(papszTO, FALSE);
3777 :
3778 898 : double dfResFromSourceAndTargetExtent =
3779 : std::numeric_limits<double>::infinity();
3780 :
3781 : /* -------------------------------------------------------------------- */
3782 : /* Establish list of files of output dataset if it already exists. */
3783 : /* -------------------------------------------------------------------- */
3784 1796 : std::set<std::string> oSetExistingDestFiles;
3785 : {
3786 898 : CPLPushErrorHandler(CPLQuietErrorHandler);
3787 898 : const char *const apszAllowedDrivers[] = {pszFormat, nullptr};
3788 : auto poExistingOutputDS = std::unique_ptr<GDALDataset>(
3789 1796 : GDALDataset::Open(pszFilename, GDAL_OF_RASTER, apszAllowedDrivers));
3790 898 : if (poExistingOutputDS)
3791 : {
3792 74 : for (const char *pszFilenameInList :
3793 70 : CPLStringList(poExistingOutputDS->GetFileList()))
3794 : {
3795 : oSetExistingDestFiles.insert(
3796 37 : CPLString(pszFilenameInList).replaceAll('\\', '/'));
3797 : }
3798 : }
3799 898 : CPLPopErrorHandler();
3800 : }
3801 1796 : std::set<std::string> oSetExistingDestFilesFoundInSource;
3802 898 : std::unique_ptr<GDALColorTable> poCT;
3803 :
3804 1810 : for (int iSrc = 0; iSrc < nSrcCount; iSrc++)
3805 : {
3806 : /* --------------------------------------------------------------------
3807 : */
3808 : /* Check that there's at least one raster band */
3809 : /* --------------------------------------------------------------------
3810 : */
3811 922 : GDALDatasetH hSrcDS = pahSrcDS[iSrc];
3812 922 : if (GDALGetRasterCount(hSrcDS) == 0)
3813 : {
3814 1 : CPLError(CE_Failure, CPLE_AppDefined,
3815 : "Input file %s has no raster bands.",
3816 : GDALGetDescription(hSrcDS));
3817 10 : return nullptr;
3818 : }
3819 :
3820 : // Examine desired overview level and retrieve the corresponding dataset
3821 : // if it exists.
3822 0 : std::unique_ptr<GDALDataset> oDstDSOverview;
3823 921 : if (psOptions->nOvLevel >= 0)
3824 : {
3825 5 : oDstDSOverview.reset(GDALCreateOverviewDataset(
3826 : GDALDataset::FromHandle(hSrcDS), psOptions->nOvLevel,
3827 : /* bThisLevelOnly = */ true));
3828 5 : if (oDstDSOverview)
3829 4 : hSrcDS = oDstDSOverview.get();
3830 : }
3831 :
3832 : /* --------------------------------------------------------------------
3833 : */
3834 : /* Check if the source dataset shares some files with the dest
3835 : * one.*/
3836 : /* --------------------------------------------------------------------
3837 : */
3838 921 : if (!oSetExistingDestFiles.empty())
3839 : {
3840 : // We need to reopen in a temporary dataset for the particular
3841 : // case of overwritten a .tif.ovr file from a .tif
3842 : // If we probe the file list of the .tif, it will then open the
3843 : // .tif.ovr !
3844 36 : auto poSrcDS = GDALDataset::FromHandle(hSrcDS);
3845 36 : const char *const apszAllowedDrivers[] = {
3846 36 : poSrcDS->GetDriver() ? poSrcDS->GetDriver()->GetDescription()
3847 : : nullptr,
3848 36 : nullptr};
3849 : auto poSrcDSTmp = std::unique_ptr<GDALDataset>(GDALDataset::Open(
3850 72 : poSrcDS->GetDescription(), GDAL_OF_RASTER, apszAllowedDrivers));
3851 36 : if (poSrcDSTmp)
3852 : {
3853 38 : for (const char *pszFilenameInList :
3854 74 : CPLStringList(poSrcDSTmp->GetFileList()))
3855 : {
3856 : std::string osFilename =
3857 76 : CPLString(pszFilenameInList).replaceAll('\\', '/');
3858 38 : if (oSetExistingDestFiles.find(osFilename) !=
3859 76 : oSetExistingDestFiles.end())
3860 : {
3861 : oSetExistingDestFilesFoundInSource.insert(
3862 5 : std::move(osFilename));
3863 : }
3864 : }
3865 : }
3866 : }
3867 :
3868 921 : if (eDT == GDT_Unknown)
3869 860 : eDT = GDALGetRasterDataType(GDALGetRasterBand(hSrcDS, 1));
3870 :
3871 : /* --------------------------------------------------------------------
3872 : */
3873 : /* If we are processing the first file, and it has a raster */
3874 : /* attribute table, then we will copy it to the destination file.
3875 : */
3876 : /* --------------------------------------------------------------------
3877 : */
3878 921 : if (iSrc == 0)
3879 : {
3880 895 : hRAT = GDALGetDefaultRAT(GDALGetRasterBand(hSrcDS, 1));
3881 895 : if (hRAT != nullptr)
3882 : {
3883 0 : if (psOptions->eResampleAlg != GRA_NearestNeighbour &&
3884 0 : psOptions->eResampleAlg != GRA_Mode &&
3885 0 : GDALRATGetTableType(hRAT) == GRTT_THEMATIC)
3886 : {
3887 0 : if (!psOptions->bQuiet)
3888 : {
3889 0 : CPLError(CE_Warning, CPLE_AppDefined,
3890 : "Warning: Input file %s has a thematic RAT, "
3891 : "which will likely lead "
3892 : "to bad results when using a resampling "
3893 : "method other than nearest neighbour "
3894 : "or mode so we are discarding it.\n",
3895 : GDALGetDescription(hSrcDS));
3896 : }
3897 0 : hRAT = nullptr;
3898 : }
3899 : else
3900 : {
3901 0 : if (!psOptions->bQuiet)
3902 0 : printf("Copying raster attribute table from %s to new "
3903 : "file.\n",
3904 : GDALGetDescription(hSrcDS));
3905 : }
3906 : }
3907 : }
3908 :
3909 : /* --------------------------------------------------------------------
3910 : */
3911 : /* If we are processing the first file, and it has a color */
3912 : /* table, then we will copy it to the destination file. */
3913 : /* --------------------------------------------------------------------
3914 : */
3915 921 : if (iSrc == 0)
3916 : {
3917 895 : auto hCT = GDALGetRasterColorTable(GDALGetRasterBand(hSrcDS, 1));
3918 895 : if (hCT != nullptr)
3919 : {
3920 5 : poCT.reset(
3921 : GDALColorTable::FromHandle(GDALCloneColorTable(hCT)));
3922 5 : if (!psOptions->bQuiet)
3923 0 : printf("Copying color table from %s to new file.\n",
3924 : GDALGetDescription(hSrcDS));
3925 : }
3926 :
3927 895 : if (psOptions->anDstBands.empty())
3928 : {
3929 878 : nDstBandCount = GDALGetRasterCount(hSrcDS);
3930 2014 : for (int iBand = 0; iBand < nDstBandCount; iBand++)
3931 : {
3932 1136 : if (psOptions->anDstBands.empty())
3933 : {
3934 : GDALColorInterp eInterp =
3935 1136 : GDALGetRasterColorInterpretation(
3936 1136 : GDALGetRasterBand(hSrcDS, iBand + 1));
3937 1136 : apeColorInterpretations.push_back(eInterp);
3938 : }
3939 : }
3940 :
3941 : // Do we want to generate an alpha band in the output file?
3942 878 : if (psOptions->bEnableSrcAlpha)
3943 19 : nDstBandCount--;
3944 :
3945 878 : if (psOptions->bEnableDstAlpha)
3946 61 : nDstBandCount++;
3947 : }
3948 : else
3949 : {
3950 45 : for (int nSrcBand : psOptions->anSrcBands)
3951 : {
3952 28 : auto hBand = GDALGetRasterBand(hSrcDS, nSrcBand);
3953 : GDALColorInterp eInterp =
3954 28 : hBand ? GDALGetRasterColorInterpretation(hBand)
3955 28 : : GCI_Undefined;
3956 28 : apeColorInterpretations.push_back(eInterp);
3957 : }
3958 17 : nDstBandCount = static_cast<int>(psOptions->anDstBands.size());
3959 17 : if (psOptions->bEnableDstAlpha)
3960 : {
3961 4 : nDstBandCount++;
3962 4 : apeColorInterpretations.push_back(GCI_AlphaBand);
3963 : }
3964 13 : else if (GDALGetRasterCount(hSrcDS) &&
3965 13 : GDALGetRasterColorInterpretation(GDALGetRasterBand(
3966 : hSrcDS, GDALGetRasterCount(hSrcDS))) ==
3967 26 : GCI_AlphaBand &&
3968 1 : !psOptions->bDisableSrcAlpha)
3969 : {
3970 0 : nDstBandCount++;
3971 0 : apeColorInterpretations.push_back(GCI_AlphaBand);
3972 : }
3973 : }
3974 : }
3975 :
3976 : /* --------------------------------------------------------------------
3977 : */
3978 : /* If we are processing the first file, get the source srs from */
3979 : /* dataset, if not set already. */
3980 : /* --------------------------------------------------------------------
3981 : */
3982 921 : const auto osThisSourceSRS = GetSrcDSProjection(hSrcDS, papszTO);
3983 921 : if (iSrc == 0 && osThisTargetSRS.empty())
3984 : {
3985 686 : if (!osThisSourceSRS.empty())
3986 : {
3987 565 : osThisTargetSRS = osThisSourceSRS;
3988 565 : aoTOList.SetNameValue("DST_SRS", osThisSourceSRS);
3989 : }
3990 : }
3991 :
3992 : /* --------------------------------------------------------------------
3993 : */
3994 : /* Create a transformation object from the source to */
3995 : /* destination coordinate system. */
3996 : /* --------------------------------------------------------------------
3997 : */
3998 0 : GDALTransformerArgUniquePtr hTransformArg;
3999 921 : if (hUniqueTransformArg)
4000 2 : hTransformArg = std::move(hUniqueTransformArg);
4001 : else
4002 : {
4003 919 : hTransformArg.reset(GDALCreateGenImgProjTransformer2(
4004 919 : hSrcDS, nullptr, aoTOList.List()));
4005 919 : if (hTransformArg == nullptr)
4006 : {
4007 9 : return nullptr;
4008 : }
4009 : }
4010 :
4011 : GDALTransformerInfo *psInfo =
4012 912 : static_cast<GDALTransformerInfo *>(hTransformArg.get());
4013 :
4014 : /* --------------------------------------------------------------------
4015 : */
4016 : /* Get approximate output resolution */
4017 : /* --------------------------------------------------------------------
4018 : */
4019 :
4020 912 : if (bKnownTargetExtentButNotResolution)
4021 : {
4022 : // Sample points along a grid in target CRS
4023 99 : constexpr int nPointsX = 10;
4024 99 : constexpr int nPointsY = 10;
4025 99 : constexpr int nPoints = 3 * nPointsX * nPointsY;
4026 198 : std::vector<double> padfX;
4027 198 : std::vector<double> padfY;
4028 198 : std::vector<double> padfZ(nPoints);
4029 198 : std::vector<int> pabSuccess(nPoints);
4030 : const double dfEps =
4031 198 : std::min(psOptions->dfMaxX - psOptions->dfMinX,
4032 99 : std::abs(psOptions->dfMaxY - psOptions->dfMinY)) /
4033 99 : 1000;
4034 1089 : for (int iY = 0; iY < nPointsY; iY++)
4035 : {
4036 10890 : for (int iX = 0; iX < nPointsX; iX++)
4037 : {
4038 9900 : const double dfX =
4039 9900 : psOptions->dfMinX +
4040 9900 : static_cast<double>(iX) *
4041 9900 : (psOptions->dfMaxX - psOptions->dfMinX) /
4042 : (nPointsX - 1);
4043 9900 : const double dfY =
4044 9900 : psOptions->dfMinY +
4045 9900 : static_cast<double>(iY) *
4046 9900 : (psOptions->dfMaxY - psOptions->dfMinY) /
4047 : (nPointsY - 1);
4048 :
4049 : // Reproject each destination sample point and its
4050 : // neighbours at (x+1,y) and (x,y+1), so as to get the local
4051 : // scale.
4052 9900 : padfX.push_back(dfX);
4053 9900 : padfY.push_back(dfY);
4054 :
4055 18810 : padfX.push_back((iX == nPointsX - 1) ? dfX - dfEps
4056 8910 : : dfX + dfEps);
4057 9900 : padfY.push_back(dfY);
4058 :
4059 9900 : padfX.push_back(dfX);
4060 18810 : padfY.push_back((iY == nPointsY - 1) ? dfY - dfEps
4061 8910 : : dfY + dfEps);
4062 : }
4063 : }
4064 :
4065 99 : bool transformedToSrcCRS{false};
4066 :
4067 : GDALGenImgProjTransformInfo *psTransformInfo{
4068 : static_cast<GDALGenImgProjTransformInfo *>(
4069 99 : hTransformArg.get())};
4070 :
4071 : // If a transformer is available, use an extent that covers the
4072 : // target extent instead of the real source image extent, but also
4073 : // check for target extent compatibility with source CRS extent
4074 99 : if (psTransformInfo && psTransformInfo->pReprojectArg &&
4075 79 : psTransformInfo->sSrcParams.pTransformer == nullptr)
4076 : {
4077 79 : const GDALReprojectionTransformInfo *psRTI =
4078 : static_cast<const GDALReprojectionTransformInfo *>(
4079 : psTransformInfo->pReprojectArg);
4080 79 : if (psRTI && psRTI->poReverseTransform)
4081 : {
4082 :
4083 : // Compute new geotransform from transformed target extent
4084 : double adfGeoTransform[6];
4085 79 : if (GDALGetGeoTransform(hSrcDS, adfGeoTransform) ==
4086 79 : CE_None &&
4087 79 : adfGeoTransform[2] == 0 && adfGeoTransform[4] == 0)
4088 : {
4089 :
4090 : // Transform target extent to source CRS
4091 79 : double dfMinX = psOptions->dfMinX;
4092 79 : double dfMinY = psOptions->dfMinY;
4093 :
4094 : // Need this to check if the target extent is compatible with the source extent
4095 79 : double dfMaxX = psOptions->dfMaxX;
4096 79 : double dfMaxY = psOptions->dfMaxY;
4097 :
4098 : // Clone of psRTI->poReverseTransform with CHECK_WITH_INVERT_PROJ set to TRUE
4099 : // to detect out of source CRS bounds destination extent and fall back to original
4100 : // algorithm if needed
4101 : CPLConfigOptionSetter oSetter("CHECK_WITH_INVERT_PROJ",
4102 158 : "TRUE", false);
4103 158 : OGRCoordinateTransformationOptions options;
4104 : auto poReverseTransform =
4105 : std::unique_ptr<OGRCoordinateTransformation>(
4106 : OGRCreateCoordinateTransformation(
4107 79 : psRTI->poReverseTransform->GetSourceCS(),
4108 79 : psRTI->poReverseTransform->GetTargetCS(),
4109 158 : options));
4110 :
4111 79 : if (poReverseTransform)
4112 : {
4113 :
4114 158 : poReverseTransform->Transform(
4115 79 : 1, &dfMinX, &dfMinY, nullptr, &pabSuccess[0]);
4116 :
4117 79 : if (pabSuccess[0])
4118 : {
4119 75 : adfGeoTransform[0] = dfMinX;
4120 75 : adfGeoTransform[3] = dfMinY;
4121 :
4122 150 : poReverseTransform->Transform(1, &dfMaxX,
4123 : &dfMaxY, nullptr,
4124 75 : &pabSuccess[0]);
4125 :
4126 75 : if (pabSuccess[0])
4127 : {
4128 :
4129 : // Reproject to source image CRS
4130 74 : psRTI->poReverseTransform->Transform(
4131 74 : nPoints, &padfX[0], &padfY[0],
4132 74 : &padfZ[0], &pabSuccess[0]);
4133 :
4134 : // Transform back to source image coordinate space using geotransform
4135 22274 : for (size_t i = 0; i < padfX.size(); i++)
4136 : {
4137 44400 : padfX[i] =
4138 22200 : (padfX[i] - adfGeoTransform[0]) /
4139 22200 : adfGeoTransform[1];
4140 22200 : padfY[i] = std::abs(
4141 22200 : (padfY[i] - adfGeoTransform[3]) /
4142 22200 : adfGeoTransform[5]);
4143 : }
4144 :
4145 74 : transformedToSrcCRS = true;
4146 : }
4147 : }
4148 : }
4149 : }
4150 : }
4151 : }
4152 :
4153 99 : if (!transformedToSrcCRS)
4154 : {
4155 : // Transform to source image coordinate space
4156 25 : psInfo->pfnTransform(hTransformArg.get(), TRUE, nPoints,
4157 25 : &padfX[0], &padfY[0], &padfZ[0],
4158 25 : &pabSuccess[0]);
4159 : }
4160 :
4161 : // Compute the resolution at sampling points
4162 198 : std::vector<std::pair<double, double>> aoResPairs;
4163 :
4164 18062 : const auto Distance = [](double x, double y)
4165 18062 : { return sqrt(x * x + y * y); };
4166 :
4167 99 : const int nSrcXSize = GDALGetRasterXSize(hSrcDS);
4168 99 : const int nSrcYSize = GDALGetRasterYSize(hSrcDS);
4169 :
4170 9999 : for (int i = 0; i < nPoints; i += 3)
4171 : {
4172 19800 : if (pabSuccess[i] && pabSuccess[i + 1] && pabSuccess[i + 2] &&
4173 21925 : padfX[i] >= 0 && padfY[i] >= 0 &&
4174 2125 : (transformedToSrcCRS ||
4175 2125 : (padfX[i] <= nSrcXSize && padfY[i] <= nSrcYSize)))
4176 : {
4177 : const double dfRes1 =
4178 18062 : std::abs(dfEps) / Distance(padfX[i + 1] - padfX[i],
4179 9031 : padfY[i + 1] - padfY[i]);
4180 : const double dfRes2 =
4181 18062 : std::abs(dfEps) / Distance(padfX[i + 2] - padfX[i],
4182 9031 : padfY[i + 2] - padfY[i]);
4183 9031 : if (std::isfinite(dfRes1) && std::isfinite(dfRes2))
4184 : {
4185 9011 : aoResPairs.push_back(
4186 18022 : std::pair<double, double>(dfRes1, dfRes2));
4187 : }
4188 : }
4189 : }
4190 :
4191 : // Find the minimum resolution that is at least 10 times greater
4192 : // than the median, to remove outliers.
4193 : // Start first by doing that on dfRes1, then dfRes2 and then their
4194 : // average.
4195 99 : std::sort(aoResPairs.begin(), aoResPairs.end(),
4196 46972 : [](const std::pair<double, double> &oPair1,
4197 : const std::pair<double, double> &oPair2)
4198 46972 : { return oPair1.first < oPair2.first; });
4199 :
4200 99 : if (!aoResPairs.empty())
4201 : {
4202 198 : std::vector<std::pair<double, double>> aoResPairsNew;
4203 : const double dfMedian1 =
4204 99 : aoResPairs[aoResPairs.size() / 2].first;
4205 9110 : for (const auto &oPair : aoResPairs)
4206 : {
4207 9011 : if (oPair.first > dfMedian1 / 10)
4208 : {
4209 8981 : aoResPairsNew.push_back(oPair);
4210 : }
4211 : }
4212 :
4213 99 : aoResPairs = std::move(aoResPairsNew);
4214 99 : std::sort(aoResPairs.begin(), aoResPairs.end(),
4215 50150 : [](const std::pair<double, double> &oPair1,
4216 : const std::pair<double, double> &oPair2)
4217 50150 : { return oPair1.second < oPair2.second; });
4218 99 : if (!aoResPairs.empty())
4219 : {
4220 198 : std::vector<double> adfRes;
4221 : const double dfMedian2 =
4222 99 : aoResPairs[aoResPairs.size() / 2].second;
4223 9080 : for (const auto &oPair : aoResPairs)
4224 : {
4225 8981 : if (oPair.second > dfMedian2 / 10)
4226 : {
4227 8971 : adfRes.push_back((oPair.first + oPair.second) / 2);
4228 : }
4229 : }
4230 :
4231 99 : std::sort(adfRes.begin(), adfRes.end());
4232 99 : if (!adfRes.empty())
4233 : {
4234 99 : const double dfMedian = adfRes[adfRes.size() / 2];
4235 99 : for (const double dfRes : adfRes)
4236 : {
4237 99 : if (dfRes > dfMedian / 10)
4238 : {
4239 99 : dfResFromSourceAndTargetExtent = std::min(
4240 99 : dfResFromSourceAndTargetExtent, dfRes);
4241 99 : break;
4242 : }
4243 : }
4244 : }
4245 : }
4246 : }
4247 : }
4248 :
4249 : /* --------------------------------------------------------------------
4250 : */
4251 : /* Get approximate output definition. */
4252 : /* --------------------------------------------------------------------
4253 : */
4254 : double adfThisGeoTransform[6];
4255 : double adfExtent[4];
4256 912 : if (bNeedsSuggestedWarpOutput)
4257 : {
4258 : int nThisPixels, nThisLines;
4259 :
4260 : // For sum, round-up dimension, to be sure that the output extent
4261 : // includes all source pixels, to have the sum preserving property.
4262 1656 : int nOptions = (psOptions->eResampleAlg == GRA_Sum)
4263 828 : ? GDAL_SWO_ROUND_UP_SIZE
4264 : : 0;
4265 828 : if (psOptions->bSquarePixels)
4266 : {
4267 1 : nOptions |= GDAL_SWO_FORCE_SQUARE_PIXEL;
4268 : }
4269 :
4270 828 : if (GDALSuggestedWarpOutput2(
4271 : hSrcDS, psInfo->pfnTransform, hTransformArg.get(),
4272 : adfThisGeoTransform, &nThisPixels, &nThisLines, adfExtent,
4273 828 : nOptions) != CE_None)
4274 : {
4275 0 : return nullptr;
4276 : }
4277 :
4278 828 : if (CPLGetConfigOption("CHECK_WITH_INVERT_PROJ", nullptr) ==
4279 : nullptr)
4280 : {
4281 828 : double MinX = adfExtent[0];
4282 828 : double MaxX = adfExtent[2];
4283 828 : double MaxY = adfExtent[3];
4284 828 : double MinY = adfExtent[1];
4285 828 : int bSuccess = TRUE;
4286 :
4287 : // +/-180 deg in longitude do not roundtrip sometimes
4288 828 : if (MinX == -180)
4289 35 : MinX += 1e-6;
4290 828 : if (MaxX == 180)
4291 34 : MaxX -= 1e-6;
4292 :
4293 : // +/-90 deg in latitude do not roundtrip sometimes
4294 828 : if (MinY == -90)
4295 24 : MinY += 1e-6;
4296 828 : if (MaxY == 90)
4297 38 : MaxY -= 1e-6;
4298 :
4299 : /* Check that the edges of the target image are in the validity
4300 : * area */
4301 : /* of the target projection */
4302 828 : const int N_STEPS = 20;
4303 17691 : for (int i = 0; i <= N_STEPS && bSuccess; i++)
4304 : {
4305 370550 : for (int j = 0; j <= N_STEPS && bSuccess; j++)
4306 : {
4307 353687 : const double dfRatioI = i * 1.0 / N_STEPS;
4308 353687 : const double dfRatioJ = j * 1.0 / N_STEPS;
4309 353687 : const double expected_x =
4310 353687 : (1 - dfRatioI) * MinX + dfRatioI * MaxX;
4311 353687 : const double expected_y =
4312 353687 : (1 - dfRatioJ) * MinY + dfRatioJ * MaxY;
4313 353687 : double x = expected_x;
4314 353687 : double y = expected_y;
4315 353687 : double z = 0;
4316 : /* Target SRS coordinates to source image pixel
4317 : * coordinates */
4318 353687 : if (!psInfo->pfnTransform(hTransformArg.get(), TRUE, 1,
4319 707358 : &x, &y, &z, &bSuccess) ||
4320 353671 : !bSuccess)
4321 16 : bSuccess = FALSE;
4322 : /* Source image pixel coordinates to target SRS
4323 : * coordinates */
4324 353687 : if (!psInfo->pfnTransform(hTransformArg.get(), FALSE, 1,
4325 707356 : &x, &y, &z, &bSuccess) ||
4326 353669 : !bSuccess)
4327 18 : bSuccess = FALSE;
4328 353687 : if (fabs(x - expected_x) >
4329 353687 : (MaxX - MinX) / nThisPixels ||
4330 353660 : fabs(y - expected_y) > (MaxY - MinY) / nThisLines)
4331 27 : bSuccess = FALSE;
4332 : }
4333 : }
4334 :
4335 : /* If not, retry with CHECK_WITH_INVERT_PROJ=TRUE that forces
4336 : * ogrct.cpp */
4337 : /* to check the consistency of each requested projection result
4338 : * with the */
4339 : /* invert projection */
4340 828 : if (!bSuccess)
4341 : {
4342 27 : CPLSetThreadLocalConfigOption("CHECK_WITH_INVERT_PROJ",
4343 : "TRUE");
4344 27 : CPLDebug("WARP", "Recompute out extent with "
4345 : "CHECK_WITH_INVERT_PROJ=TRUE");
4346 :
4347 27 : const CPLErr eErr = GDALSuggestedWarpOutput2(
4348 : hSrcDS, psInfo->pfnTransform, hTransformArg.get(),
4349 : adfThisGeoTransform, &nThisPixels, &nThisLines,
4350 : adfExtent, 0);
4351 27 : CPLSetThreadLocalConfigOption("CHECK_WITH_INVERT_PROJ",
4352 : nullptr);
4353 27 : if (eErr != CE_None)
4354 : {
4355 0 : return nullptr;
4356 : }
4357 : }
4358 : }
4359 : }
4360 :
4361 : // If no reprojection or geometry change is involved, and that the
4362 : // source image is north-up, preserve source resolution instead of
4363 : // forcing square pixels.
4364 912 : const char *pszMethod = FetchSrcMethod(papszTO);
4365 : double adfThisGeoTransformTmp[6];
4366 911 : if (!psOptions->bSquarePixels && bNeedsSuggestedWarpOutput &&
4367 827 : psOptions->dfXRes == 0 && psOptions->dfYRes == 0 &&
4368 801 : psOptions->nForcePixels == 0 && psOptions->nForceLines == 0 &&
4369 27 : (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")) &&
4370 661 : CSLFetchNameValue(papszTO, "COORDINATE_OPERATION") == nullptr &&
4371 657 : CSLFetchNameValue(papszTO, "SRC_METHOD") == nullptr &&
4372 657 : CSLFetchNameValue(papszTO, "DST_METHOD") == nullptr &&
4373 654 : GDALGetGeoTransform(hSrcDS, adfThisGeoTransformTmp) == CE_None &&
4374 635 : adfThisGeoTransformTmp[2] == 0 && adfThisGeoTransformTmp[4] == 0 &&
4375 635 : adfThisGeoTransformTmp[5] < 0 &&
4376 2429 : GDALGetMetadata(hSrcDS, "GEOLOC_ARRAY") == nullptr &&
4377 606 : GDALGetMetadata(hSrcDS, "RPC") == nullptr)
4378 : {
4379 606 : bool bIsSameHorizontal = osThisSourceSRS == osThisTargetSRS;
4380 606 : if (!bIsSameHorizontal)
4381 : {
4382 266 : OGRSpatialReference oSrcSRS;
4383 266 : OGRSpatialReference oDstSRS;
4384 266 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
4385 : // DemoteTo2D requires PROJ >= 6.3
4386 133 : if (oSrcSRS.SetFromUserInput(osThisSourceSRS.c_str()) ==
4387 133 : OGRERR_NONE &&
4388 133 : oDstSRS.SetFromUserInput(osThisTargetSRS.c_str()) ==
4389 133 : OGRERR_NONE &&
4390 133 : (oSrcSRS.GetAxesCount() == 3 ||
4391 116 : oDstSRS.GetAxesCount() == 3) &&
4392 287 : oSrcSRS.DemoteTo2D(nullptr) == OGRERR_NONE &&
4393 21 : oDstSRS.DemoteTo2D(nullptr) == OGRERR_NONE)
4394 : {
4395 21 : bIsSameHorizontal = oSrcSRS.IsSame(&oDstSRS);
4396 : }
4397 : }
4398 606 : if (bIsSameHorizontal)
4399 : {
4400 479 : memcpy(adfThisGeoTransform, adfThisGeoTransformTmp,
4401 : 6 * sizeof(double));
4402 479 : adfExtent[0] = adfThisGeoTransform[0];
4403 479 : adfExtent[1] =
4404 958 : adfThisGeoTransform[3] +
4405 479 : GDALGetRasterYSize(hSrcDS) * adfThisGeoTransform[5];
4406 479 : adfExtent[2] =
4407 958 : adfThisGeoTransform[0] +
4408 479 : GDALGetRasterXSize(hSrcDS) * adfThisGeoTransform[1];
4409 479 : adfExtent[3] = adfThisGeoTransform[3];
4410 479 : dfResFromSourceAndTargetExtent =
4411 479 : std::numeric_limits<double>::infinity();
4412 : }
4413 : }
4414 :
4415 912 : if (bNeedsSuggestedWarpOutput)
4416 : {
4417 : /* --------------------------------------------------------------------
4418 : */
4419 : /* Expand the working bounds to include this region, ensure the
4420 : */
4421 : /* working resolution is no more than this resolution. */
4422 : /* --------------------------------------------------------------------
4423 : */
4424 828 : if (dfWrkMaxX == 0.0 && dfWrkMinX == 0.0)
4425 : {
4426 804 : dfWrkMinX = adfExtent[0];
4427 804 : dfWrkMaxX = adfExtent[2];
4428 804 : dfWrkMaxY = adfExtent[3];
4429 804 : dfWrkMinY = adfExtent[1];
4430 804 : dfWrkResX = adfThisGeoTransform[1];
4431 804 : dfWrkResY = std::abs(adfThisGeoTransform[5]);
4432 : }
4433 : else
4434 : {
4435 24 : dfWrkMinX = std::min(dfWrkMinX, adfExtent[0]);
4436 24 : dfWrkMaxX = std::max(dfWrkMaxX, adfExtent[2]);
4437 24 : dfWrkMaxY = std::max(dfWrkMaxY, adfExtent[3]);
4438 24 : dfWrkMinY = std::min(dfWrkMinY, adfExtent[1]);
4439 24 : dfWrkResX = std::min(dfWrkResX, adfThisGeoTransform[1]);
4440 24 : dfWrkResY =
4441 24 : std::min(dfWrkResY, std::abs(adfThisGeoTransform[5]));
4442 : }
4443 : }
4444 :
4445 912 : if (nSrcCount == 1)
4446 : {
4447 860 : hUniqueTransformArg = std::move(hTransformArg);
4448 : }
4449 : }
4450 :
4451 : // If the source file(s) and the dest one share some files in common,
4452 : // only remove the files that are *not* in common
4453 888 : if (!oSetExistingDestFilesFoundInSource.empty())
4454 : {
4455 14 : for (const std::string &osFilename : oSetExistingDestFiles)
4456 : {
4457 9 : if (oSetExistingDestFilesFoundInSource.find(osFilename) ==
4458 18 : oSetExistingDestFilesFoundInSource.end())
4459 : {
4460 4 : VSIUnlink(osFilename.c_str());
4461 : }
4462 : }
4463 : }
4464 :
4465 888 : if (std::isfinite(dfResFromSourceAndTargetExtent))
4466 : {
4467 41 : dfWrkResX = dfResFromSourceAndTargetExtent;
4468 41 : dfWrkResY = dfResFromSourceAndTargetExtent;
4469 : }
4470 :
4471 : /* -------------------------------------------------------------------- */
4472 : /* Did we have any usable sources? */
4473 : /* -------------------------------------------------------------------- */
4474 888 : if (nDstBandCount == 0)
4475 : {
4476 3 : CPLError(CE_Failure, CPLE_AppDefined, "No usable source images.");
4477 3 : return nullptr;
4478 : }
4479 :
4480 : /* -------------------------------------------------------------------- */
4481 : /* Turn the suggested region into a geotransform and suggested */
4482 : /* number of pixels and lines. */
4483 : /* -------------------------------------------------------------------- */
4484 885 : double adfDstGeoTransform[6] = {0, 0, 0, 0, 0, 0};
4485 885 : int nPixels = 0;
4486 885 : int nLines = 0;
4487 :
4488 169 : const auto ComputePixelsFromResAndExtent = [psOptions]()
4489 : {
4490 338 : return std::max(1.0,
4491 338 : std::round((psOptions->dfMaxX - psOptions->dfMinX) /
4492 169 : psOptions->dfXRes));
4493 885 : };
4494 :
4495 171 : const auto ComputeLinesFromResAndExtent = [psOptions]()
4496 : {
4497 : return std::max(
4498 342 : 1.0, std::round(std::fabs(psOptions->dfMaxY - psOptions->dfMinY) /
4499 171 : psOptions->dfYRes));
4500 885 : };
4501 :
4502 885 : if (bNeedsSuggestedWarpOutput)
4503 : {
4504 802 : adfDstGeoTransform[0] = dfWrkMinX;
4505 802 : adfDstGeoTransform[1] = dfWrkResX;
4506 802 : adfDstGeoTransform[2] = 0.0;
4507 802 : adfDstGeoTransform[3] = dfWrkMaxY;
4508 802 : adfDstGeoTransform[4] = 0.0;
4509 802 : adfDstGeoTransform[5] = -1 * dfWrkResY;
4510 :
4511 802 : const double dfPixels = (dfWrkMaxX - dfWrkMinX) / dfWrkResX;
4512 802 : const double dfLines = (dfWrkMaxY - dfWrkMinY) / dfWrkResY;
4513 : // guaranteed by GDALSuggestedWarpOutput2() behavior
4514 802 : CPLAssert(std::round(dfPixels) <= INT_MAX);
4515 802 : CPLAssert(std::round(dfLines) <= INT_MAX);
4516 802 : nPixels =
4517 802 : static_cast<int>(std::min<double>(std::round(dfPixels), INT_MAX));
4518 802 : nLines =
4519 802 : static_cast<int>(std::min<double>(std::round(dfLines), INT_MAX));
4520 : }
4521 :
4522 : /* -------------------------------------------------------------------- */
4523 : /* Did the user override some parameters? */
4524 : /* -------------------------------------------------------------------- */
4525 885 : if (UseTEAndTSAndTRConsistently(psOptions))
4526 : {
4527 25 : adfDstGeoTransform[0] = psOptions->dfMinX;
4528 25 : adfDstGeoTransform[3] = psOptions->dfMaxY;
4529 25 : adfDstGeoTransform[1] = psOptions->dfXRes;
4530 25 : adfDstGeoTransform[5] = -psOptions->dfYRes;
4531 :
4532 25 : nPixels = psOptions->nForcePixels;
4533 25 : nLines = psOptions->nForceLines;
4534 : }
4535 860 : else if (psOptions->dfXRes != 0.0 && psOptions->dfYRes != 0.0)
4536 : {
4537 49 : bool bDetectBlankBorders = false;
4538 :
4539 49 : if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
4540 27 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
4541 : {
4542 26 : bDetectBlankBorders = bNeedsSuggestedWarpOutput;
4543 :
4544 26 : psOptions->dfMinX = adfDstGeoTransform[0];
4545 26 : psOptions->dfMaxX =
4546 26 : adfDstGeoTransform[0] + adfDstGeoTransform[1] * nPixels;
4547 26 : psOptions->dfMaxY = adfDstGeoTransform[3];
4548 26 : psOptions->dfMinY =
4549 26 : adfDstGeoTransform[3] + adfDstGeoTransform[5] * nLines;
4550 : }
4551 :
4552 94 : if (psOptions->bTargetAlignedPixels ||
4553 45 : (psOptions->bCropToCutline &&
4554 1 : psOptions->aosWarpOptions.FetchBool("CUTLINE_ALL_TOUCHED", false)))
4555 : {
4556 4 : if ((psOptions->bTargetAlignedPixels &&
4557 10 : bNeedsSuggestedWarpOutput) ||
4558 2 : (psOptions->bCropToCutline &&
4559 1 : psOptions->aosWarpOptions.FetchBool("CUTLINE_ALL_TOUCHED",
4560 : false)))
4561 : {
4562 4 : bDetectBlankBorders = true;
4563 : }
4564 5 : constexpr double EPS = 1e-8;
4565 5 : psOptions->dfMinX =
4566 5 : floor(psOptions->dfMinX / psOptions->dfXRes + EPS) *
4567 5 : psOptions->dfXRes;
4568 5 : psOptions->dfMaxX =
4569 5 : ceil(psOptions->dfMaxX / psOptions->dfXRes - EPS) *
4570 5 : psOptions->dfXRes;
4571 5 : psOptions->dfMinY =
4572 5 : floor(psOptions->dfMinY / psOptions->dfYRes + EPS) *
4573 5 : psOptions->dfYRes;
4574 5 : psOptions->dfMaxY =
4575 5 : ceil(psOptions->dfMaxY / psOptions->dfYRes - EPS) *
4576 5 : psOptions->dfYRes;
4577 : }
4578 :
4579 74 : const auto UpdateGeoTransformandAndPixelLines = [&]()
4580 : {
4581 74 : const double dfPixels = ComputePixelsFromResAndExtent();
4582 74 : const double dfLines = ComputeLinesFromResAndExtent();
4583 74 : if (dfPixels > INT_MAX || dfLines > INT_MAX)
4584 : {
4585 2 : CPLError(CE_Failure, CPLE_AppDefined,
4586 : "Too large output raster size: %f x %f", dfPixels,
4587 : dfLines);
4588 2 : return false;
4589 : }
4590 :
4591 72 : nPixels = static_cast<int>(dfPixels);
4592 72 : nLines = static_cast<int>(dfLines);
4593 216 : adfDstGeoTransform[0] = psOptions->dfMinX;
4594 72 : adfDstGeoTransform[3] = psOptions->dfMaxY;
4595 72 : adfDstGeoTransform[1] = psOptions->dfXRes;
4596 144 : adfDstGeoTransform[5] = (psOptions->dfMaxY > psOptions->dfMinY)
4597 72 : ? -psOptions->dfYRes
4598 2 : : psOptions->dfYRes;
4599 72 : return true;
4600 49 : };
4601 :
4602 76 : if (bDetectBlankBorders && nSrcCount == 1 && hUniqueTransformArg &&
4603 : // to avoid too large memory allocations
4604 27 : std::max(nPixels, nLines) < 100 * 1000 * 1000)
4605 : {
4606 : // Try to detect if the edge of the raster would be blank
4607 : // Cf https://github.com/OSGeo/gdal/issues/7905
4608 28 : while (nPixels > 1 || nLines > 1)
4609 : {
4610 25 : if (!UpdateGeoTransformandAndPixelLines())
4611 0 : return nullptr;
4612 :
4613 25 : GDALSetGenImgProjTransformerDstGeoTransform(
4614 : hUniqueTransformArg.get(), adfDstGeoTransform);
4615 :
4616 25 : std::vector<double> adfX(std::max(nPixels, nLines));
4617 25 : std::vector<double> adfY(adfX.size());
4618 25 : std::vector<double> adfZ(adfX.size());
4619 25 : std::vector<int> abSuccess(adfX.size());
4620 :
4621 : const auto DetectBlankBorder =
4622 100 : [&](int nValues,
4623 : std::function<bool(double, double)> funcIsOK)
4624 : {
4625 100 : if (nValues > 3)
4626 : {
4627 : // First try with just a subsample of 3 points
4628 44 : double adf3X[3] = {adfX[0], adfX[nValues / 2],
4629 44 : adfX[nValues - 1]};
4630 44 : double adf3Y[3] = {adfY[0], adfY[nValues / 2],
4631 44 : adfY[nValues - 1]};
4632 44 : double adf3Z[3] = {0};
4633 44 : if (GDALGenImgProjTransform(
4634 44 : hUniqueTransformArg.get(), TRUE, 3, &adf3X[0],
4635 88 : &adf3Y[0], &adf3Z[0], &abSuccess[0]))
4636 : {
4637 53 : for (int i = 0; i < 3; ++i)
4638 : {
4639 100 : if (abSuccess[i] &&
4640 50 : funcIsOK(adf3X[i], adf3Y[i]))
4641 : {
4642 41 : return false;
4643 : }
4644 : }
4645 : }
4646 : }
4647 :
4648 : // Do on full border to confirm
4649 59 : if (GDALGenImgProjTransform(hUniqueTransformArg.get(), TRUE,
4650 59 : nValues, &adfX[0], &adfY[0],
4651 118 : &adfZ[0], &abSuccess[0]))
4652 : {
4653 125 : for (int i = 0; i < nValues; ++i)
4654 : {
4655 122 : if (abSuccess[i] && funcIsOK(adfX[i], adfY[i]))
4656 : {
4657 56 : return false;
4658 : }
4659 : }
4660 : }
4661 :
4662 3 : return true;
4663 25 : };
4664 :
4665 9784 : for (int i = 0; i < nPixels; ++i)
4666 : {
4667 9759 : adfX[i] = i + 0.5;
4668 9759 : adfY[i] = 0.5;
4669 9759 : adfZ[i] = 0;
4670 : }
4671 25 : const bool bTopBlankLine = DetectBlankBorder(
4672 40 : nPixels, [](double, double y) { return y >= 0; });
4673 :
4674 9784 : for (int i = 0; i < nPixels; ++i)
4675 : {
4676 9759 : adfX[i] = i + 0.5;
4677 9759 : adfY[i] = nLines - 0.5;
4678 9759 : adfZ[i] = 0;
4679 : }
4680 25 : const int nSrcLines = GDALGetRasterYSize(pahSrcDS[0]);
4681 : const bool bBottomBlankLine =
4682 25 : DetectBlankBorder(nPixels, [nSrcLines](double, double y)
4683 25 : { return y <= nSrcLines; });
4684 :
4685 4909 : for (int i = 0; i < nLines; ++i)
4686 : {
4687 4884 : adfX[i] = 0.5;
4688 4884 : adfY[i] = i + 0.5;
4689 4884 : adfZ[i] = 0;
4690 : }
4691 25 : const bool bLeftBlankCol = DetectBlankBorder(
4692 55 : nLines, [](double x, double) { return x >= 0; });
4693 :
4694 4909 : for (int i = 0; i < nLines; ++i)
4695 : {
4696 4884 : adfX[i] = nPixels - 0.5;
4697 4884 : adfY[i] = i + 0.5;
4698 4884 : adfZ[i] = 0;
4699 : }
4700 25 : const int nSrcCols = GDALGetRasterXSize(pahSrcDS[0]);
4701 : const bool bRightBlankCol =
4702 25 : DetectBlankBorder(nLines, [nSrcCols](double x, double)
4703 52 : { return x <= nSrcCols; });
4704 :
4705 25 : if (!bTopBlankLine && !bBottomBlankLine && !bLeftBlankCol &&
4706 23 : !bRightBlankCol)
4707 23 : break;
4708 :
4709 2 : if (bTopBlankLine)
4710 : {
4711 1 : if (psOptions->dfMaxY - psOptions->dfMinY <=
4712 1 : 2 * psOptions->dfYRes)
4713 0 : break;
4714 1 : psOptions->dfMaxY -= psOptions->dfYRes;
4715 : }
4716 2 : if (bBottomBlankLine)
4717 : {
4718 0 : if (psOptions->dfMaxY - psOptions->dfMinY <=
4719 0 : 2 * psOptions->dfYRes)
4720 0 : break;
4721 0 : psOptions->dfMinY += psOptions->dfYRes;
4722 : }
4723 2 : if (bLeftBlankCol)
4724 : {
4725 1 : if (psOptions->dfMaxX - psOptions->dfMinX <=
4726 1 : 2 * psOptions->dfXRes)
4727 0 : break;
4728 1 : psOptions->dfMinX += psOptions->dfXRes;
4729 : }
4730 2 : if (bRightBlankCol)
4731 : {
4732 1 : if (psOptions->dfMaxX - psOptions->dfMinX <=
4733 1 : 2 * psOptions->dfXRes)
4734 0 : break;
4735 1 : psOptions->dfMaxX -= psOptions->dfXRes;
4736 : }
4737 : }
4738 : }
4739 :
4740 49 : if (!UpdateGeoTransformandAndPixelLines())
4741 49 : return nullptr;
4742 : }
4743 :
4744 811 : else if (psOptions->nForcePixels != 0 && psOptions->nForceLines != 0)
4745 : {
4746 139 : if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
4747 104 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
4748 : {
4749 104 : psOptions->dfMinX = dfWrkMinX;
4750 104 : psOptions->dfMaxX = dfWrkMaxX;
4751 104 : psOptions->dfMaxY = dfWrkMaxY;
4752 104 : psOptions->dfMinY = dfWrkMinY;
4753 : }
4754 :
4755 139 : psOptions->dfXRes =
4756 139 : (psOptions->dfMaxX - psOptions->dfMinX) / psOptions->nForcePixels;
4757 139 : psOptions->dfYRes =
4758 139 : (psOptions->dfMaxY - psOptions->dfMinY) / psOptions->nForceLines;
4759 :
4760 139 : adfDstGeoTransform[0] = psOptions->dfMinX;
4761 139 : adfDstGeoTransform[3] = psOptions->dfMaxY;
4762 139 : adfDstGeoTransform[1] = psOptions->dfXRes;
4763 139 : adfDstGeoTransform[5] = -psOptions->dfYRes;
4764 :
4765 139 : nPixels = psOptions->nForcePixels;
4766 139 : nLines = psOptions->nForceLines;
4767 : }
4768 :
4769 672 : else if (psOptions->nForcePixels != 0)
4770 : {
4771 5 : if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
4772 4 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
4773 : {
4774 4 : psOptions->dfMinX = dfWrkMinX;
4775 4 : psOptions->dfMaxX = dfWrkMaxX;
4776 4 : psOptions->dfMaxY = dfWrkMaxY;
4777 4 : psOptions->dfMinY = dfWrkMinY;
4778 : }
4779 :
4780 5 : psOptions->dfXRes =
4781 5 : (psOptions->dfMaxX - psOptions->dfMinX) / psOptions->nForcePixels;
4782 5 : psOptions->dfYRes = psOptions->dfXRes;
4783 :
4784 5 : adfDstGeoTransform[0] = psOptions->dfMinX;
4785 5 : adfDstGeoTransform[3] = psOptions->dfMaxY;
4786 5 : adfDstGeoTransform[1] = psOptions->dfXRes;
4787 10 : adfDstGeoTransform[5] = (psOptions->dfMaxY > psOptions->dfMinY)
4788 5 : ? -psOptions->dfYRes
4789 0 : : psOptions->dfYRes;
4790 :
4791 5 : nPixels = psOptions->nForcePixels;
4792 5 : const double dfLines = ComputeLinesFromResAndExtent();
4793 5 : if (dfLines > INT_MAX)
4794 : {
4795 1 : CPLError(CE_Failure, CPLE_AppDefined,
4796 : "Too large output raster size: %d x %f", nPixels, dfLines);
4797 1 : return nullptr;
4798 : }
4799 4 : nLines = static_cast<int>(dfLines);
4800 : }
4801 :
4802 667 : else if (psOptions->nForceLines != 0)
4803 : {
4804 3 : if (psOptions->dfMinX == 0.0 && psOptions->dfMinY == 0.0 &&
4805 3 : psOptions->dfMaxX == 0.0 && psOptions->dfMaxY == 0.0)
4806 : {
4807 3 : psOptions->dfMinX = dfWrkMinX;
4808 3 : psOptions->dfMaxX = dfWrkMaxX;
4809 3 : psOptions->dfMaxY = dfWrkMaxY;
4810 3 : psOptions->dfMinY = dfWrkMinY;
4811 : }
4812 :
4813 3 : psOptions->dfYRes =
4814 3 : (psOptions->dfMaxY - psOptions->dfMinY) / psOptions->nForceLines;
4815 3 : psOptions->dfXRes = std::fabs(psOptions->dfYRes);
4816 :
4817 3 : adfDstGeoTransform[0] = psOptions->dfMinX;
4818 3 : adfDstGeoTransform[3] = psOptions->dfMaxY;
4819 3 : adfDstGeoTransform[1] = psOptions->dfXRes;
4820 3 : adfDstGeoTransform[5] = -psOptions->dfYRes;
4821 :
4822 3 : const double dfPixels = ComputePixelsFromResAndExtent();
4823 3 : nLines = psOptions->nForceLines;
4824 3 : if (dfPixels > INT_MAX)
4825 : {
4826 1 : CPLError(CE_Failure, CPLE_AppDefined,
4827 : "Too large output raster size: %f x %d", dfPixels, nLines);
4828 1 : return nullptr;
4829 : }
4830 2 : nPixels = static_cast<int>(dfPixels);
4831 : }
4832 :
4833 664 : else if (psOptions->dfMinX != 0.0 || psOptions->dfMinY != 0.0 ||
4834 573 : psOptions->dfMaxX != 0.0 || psOptions->dfMaxY != 0.0)
4835 : {
4836 92 : psOptions->dfXRes = adfDstGeoTransform[1];
4837 92 : psOptions->dfYRes = fabs(adfDstGeoTransform[5]);
4838 :
4839 92 : const double dfPixels = ComputePixelsFromResAndExtent();
4840 92 : const double dfLines = ComputeLinesFromResAndExtent();
4841 92 : if (dfPixels > INT_MAX || dfLines > INT_MAX)
4842 : {
4843 1 : CPLError(CE_Failure, CPLE_AppDefined,
4844 : "Too large output raster size: %f x %f", dfPixels,
4845 : dfLines);
4846 1 : return nullptr;
4847 : }
4848 :
4849 91 : nPixels = static_cast<int>(dfPixels);
4850 91 : nLines = static_cast<int>(dfLines);
4851 :
4852 91 : psOptions->dfXRes = (psOptions->dfMaxX - psOptions->dfMinX) / nPixels;
4853 91 : psOptions->dfYRes = (psOptions->dfMaxY - psOptions->dfMinY) / nLines;
4854 :
4855 91 : adfDstGeoTransform[0] = psOptions->dfMinX;
4856 91 : adfDstGeoTransform[3] = psOptions->dfMaxY;
4857 91 : adfDstGeoTransform[1] = psOptions->dfXRes;
4858 91 : adfDstGeoTransform[5] = -psOptions->dfYRes;
4859 : }
4860 :
4861 880 : if (EQUAL(pszFormat, "GTiff"))
4862 : {
4863 :
4864 : /* --------------------------------------------------------------------
4865 : */
4866 : /* Automatically set PHOTOMETRIC=RGB for GTiff when appropriate */
4867 : /* --------------------------------------------------------------------
4868 : */
4869 444 : if (apeColorInterpretations.size() >= 3 &&
4870 34 : apeColorInterpretations[0] == GCI_RedBand &&
4871 34 : apeColorInterpretations[1] == GCI_GreenBand &&
4872 512 : apeColorInterpretations[2] == GCI_BlueBand &&
4873 34 : aosCreateOptions.FetchNameValue("PHOTOMETRIC") == nullptr)
4874 : {
4875 34 : aosCreateOptions.SetNameValue("PHOTOMETRIC", "RGB");
4876 :
4877 : // Preserve potential ALPHA=PREMULTIPLIED from source alpha band
4878 68 : if (aosCreateOptions.FetchNameValue("ALPHA") == nullptr &&
4879 34 : apeColorInterpretations.size() == 4 &&
4880 73 : apeColorInterpretations[3] == GCI_AlphaBand &&
4881 5 : GDALGetRasterCount(pahSrcDS[0]) == 4)
4882 : {
4883 : const char *pszAlpha =
4884 5 : GDALGetMetadataItem(GDALGetRasterBand(pahSrcDS[0], 4),
4885 : "ALPHA", "IMAGE_STRUCTURE");
4886 5 : if (pszAlpha)
4887 : {
4888 1 : aosCreateOptions.SetNameValue("ALPHA", pszAlpha);
4889 : }
4890 : }
4891 : }
4892 :
4893 : /* The GTiff driver now supports writing band color interpretation */
4894 : /* in the TIFF_GDAL_METADATA tag */
4895 444 : bSetColorInterpretation = true;
4896 : }
4897 :
4898 : /* -------------------------------------------------------------------- */
4899 : /* Create the output file. */
4900 : /* -------------------------------------------------------------------- */
4901 880 : if (!psOptions->bQuiet)
4902 78 : printf("Creating output file that is %dP x %dL.\n", nPixels, nLines);
4903 :
4904 880 : hDstDS = GDALCreate(hDriver, pszFilename, nPixels, nLines, nDstBandCount,
4905 880 : eDT, aosCreateOptions.List());
4906 :
4907 880 : if (hDstDS == nullptr)
4908 : {
4909 1 : return nullptr;
4910 : }
4911 :
4912 879 : if (psOptions->bDeleteOutputFileOnceCreated)
4913 : {
4914 12 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
4915 6 : GDALDeleteDataset(hDriver, pszFilename);
4916 : }
4917 :
4918 : /* -------------------------------------------------------------------- */
4919 : /* Write out the projection definition. */
4920 : /* -------------------------------------------------------------------- */
4921 879 : const char *pszDstMethod = CSLFetchNameValue(papszTO, "DST_METHOD");
4922 879 : if (pszDstMethod == nullptr || !EQUAL(pszDstMethod, "NO_GEOTRANSFORM"))
4923 : {
4924 877 : OGRSpatialReference oTargetSRS;
4925 877 : oTargetSRS.SetFromUserInput(osThisTargetSRS);
4926 877 : oTargetSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
4927 :
4928 877 : if (oTargetSRS.IsDynamic())
4929 : {
4930 571 : double dfCoordEpoch = CPLAtof(CSLFetchNameValueDef(
4931 : papszTO, "DST_COORDINATE_EPOCH",
4932 : CSLFetchNameValueDef(papszTO, "COORDINATE_EPOCH", "0")));
4933 571 : if (dfCoordEpoch == 0)
4934 : {
4935 : const OGRSpatialReferenceH hSrcSRS =
4936 571 : GDALGetSpatialRef(pahSrcDS[0]);
4937 571 : const char *pszMethod = FetchSrcMethod(papszTO);
4938 571 : if (hSrcSRS &&
4939 3 : (pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")))
4940 : {
4941 532 : dfCoordEpoch = OSRGetCoordinateEpoch(hSrcSRS);
4942 : }
4943 : }
4944 571 : if (dfCoordEpoch > 0)
4945 1 : oTargetSRS.SetCoordinateEpoch(dfCoordEpoch);
4946 : }
4947 :
4948 877 : if (GDALSetSpatialRef(hDstDS, OGRSpatialReference::ToHandle(
4949 1754 : &oTargetSRS)) == CE_Failure ||
4950 877 : GDALSetGeoTransform(hDstDS, adfDstGeoTransform) == CE_Failure)
4951 : {
4952 0 : GDALClose(hDstDS);
4953 0 : return nullptr;
4954 877 : }
4955 : }
4956 : else
4957 : {
4958 2 : adfDstGeoTransform[3] += adfDstGeoTransform[5] * nLines;
4959 2 : adfDstGeoTransform[5] = fabs(adfDstGeoTransform[5]);
4960 : }
4961 :
4962 879 : if (hUniqueTransformArg && bUpdateTransformerWithDestGT)
4963 : {
4964 853 : GDALSetGenImgProjTransformerDstGeoTransform(hUniqueTransformArg.get(),
4965 : adfDstGeoTransform);
4966 :
4967 853 : void *pTransformerArg = hUniqueTransformArg.get();
4968 853 : if (GDALIsTransformer(pTransformerArg,
4969 : GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
4970 : {
4971 : // Detect if there is a change of coordinate operation in the area of
4972 : // interest. The underlying proj_trans_get_last_used_operation() is
4973 : // quite costly due to using proj_clone() internally, so only do that
4974 : // on a restricted set of points.
4975 853 : GDALGenImgProjTransformInfo *psTransformInfo{
4976 : static_cast<GDALGenImgProjTransformInfo *>(pTransformerArg)};
4977 853 : GDALTransformerInfo *psInfo = &psTransformInfo->sTI;
4978 :
4979 853 : void *pReprojectArg = psTransformInfo->pReprojectArg;
4980 853 : if (GDALIsTransformer(pReprojectArg,
4981 : GDAL_APPROX_TRANSFORMER_CLASS_NAME))
4982 : {
4983 1 : const auto *pApproxInfo =
4984 : static_cast<const GDALApproxTransformInfo *>(pReprojectArg);
4985 1 : pReprojectArg = pApproxInfo->pBaseCBData;
4986 : }
4987 :
4988 853 : if (GDALIsTransformer(pReprojectArg,
4989 : GDAL_REPROJECTION_TRANSFORMER_CLASS_NAME))
4990 : {
4991 544 : const GDALReprojectionTransformInfo *psRTI =
4992 : static_cast<const GDALReprojectionTransformInfo *>(
4993 : pReprojectArg);
4994 544 : if (psRTI->poReverseTransform)
4995 : {
4996 1088 : std::vector<double> adfX, adfY, adfZ;
4997 1088 : std::vector<int> abSuccess;
4998 :
4999 544 : GDALDatasetH hSrcDS = pahSrcDS[0];
5000 :
5001 : // Sample points on a N x N grid in the source raster
5002 544 : constexpr int N = 10;
5003 544 : const int nSrcXSize = GDALGetRasterXSize(hSrcDS);
5004 544 : const int nSrcYSize = GDALGetRasterYSize(hSrcDS);
5005 6528 : for (int j = 0; j <= N; ++j)
5006 : {
5007 71808 : for (int i = 0; i <= N; ++i)
5008 : {
5009 65824 : adfX.push_back(static_cast<double>(i) / N *
5010 : nSrcXSize);
5011 65824 : adfY.push_back(static_cast<double>(j) / N *
5012 : nSrcYSize);
5013 65824 : adfZ.push_back(0);
5014 65824 : abSuccess.push_back(0);
5015 : }
5016 : }
5017 :
5018 : {
5019 1088 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
5020 :
5021 : // Transform from source raster coordinates to target raster
5022 : // coordinates
5023 544 : psInfo->pfnTransform(hUniqueTransformArg.get(), FALSE,
5024 544 : static_cast<int>(adfX.size()),
5025 544 : &adfX[0], &adfY[0], &adfZ[0],
5026 544 : &abSuccess[0]);
5027 :
5028 544 : const int nDstXSize = nPixels;
5029 544 : const int nDstYSize = nLines;
5030 :
5031 : // Clamp target raster coordinates
5032 66368 : for (size_t i = 0; i < adfX.size(); ++i)
5033 : {
5034 65824 : if (adfX[i] < 0)
5035 1042 : adfX[i] = 0;
5036 65824 : if (adfX[i] > nDstXSize)
5037 3146 : adfX[i] = nDstXSize;
5038 65824 : if (adfY[i] < 0)
5039 1177 : adfY[i] = 0;
5040 65824 : if (adfY[i] > nDstYSize)
5041 3527 : adfY[i] = nDstYSize;
5042 : }
5043 :
5044 : // Start recording if different coordinate operations are
5045 : // going to be used
5046 544 : OGRProjCTDifferentOperationsStart(
5047 544 : psRTI->poReverseTransform);
5048 :
5049 : // Transform back to source raster coordinates.
5050 544 : psInfo->pfnTransform(hUniqueTransformArg.get(), TRUE,
5051 544 : static_cast<int>(adfX.size()),
5052 544 : &adfX[0], &adfY[0], &adfZ[0],
5053 544 : &abSuccess[0]);
5054 : }
5055 :
5056 544 : if (OGRProjCTDifferentOperationsUsed(
5057 544 : psRTI->poReverseTransform))
5058 : {
5059 0 : CPLError(
5060 : CE_Warning, CPLE_AppDefined,
5061 : "Several coordinate operations are going to be "
5062 : "used. Artifacts may appear. You may consider "
5063 : "using the -to ALLOW_BALLPARK=NO and/or "
5064 : "-to ONLY_BEST=YES transform options, or specify "
5065 : "a particular coordinate operation with -ct");
5066 : }
5067 :
5068 : // Stop recording
5069 544 : OGRProjCTDifferentOperationsStop(psRTI->poReverseTransform);
5070 : }
5071 : }
5072 : }
5073 : }
5074 :
5075 : /* -------------------------------------------------------------------- */
5076 : /* Try to set color interpretation of source bands to target */
5077 : /* dataset. */
5078 : /* FIXME? We should likely do that for other drivers than VRT & */
5079 : /* GTiff but it might create spurious .aux.xml files (at least */
5080 : /* with HFA, and netCDF) */
5081 : /* -------------------------------------------------------------------- */
5082 879 : if (bVRT || bSetColorInterpretation)
5083 : {
5084 552 : int nBandsToCopy = static_cast<int>(apeColorInterpretations.size());
5085 552 : if (psOptions->bEnableSrcAlpha)
5086 13 : nBandsToCopy--;
5087 1236 : for (int iBand = 0; iBand < nBandsToCopy; iBand++)
5088 : {
5089 684 : GDALSetRasterColorInterpretation(
5090 : GDALGetRasterBand(hDstDS, iBand + 1),
5091 684 : apeColorInterpretations[iBand]);
5092 : }
5093 : }
5094 :
5095 : /* -------------------------------------------------------------------- */
5096 : /* Try to set color interpretation of output file alpha band. */
5097 : /* -------------------------------------------------------------------- */
5098 879 : if (psOptions->bEnableDstAlpha)
5099 : {
5100 65 : GDALSetRasterColorInterpretation(
5101 : GDALGetRasterBand(hDstDS, nDstBandCount), GCI_AlphaBand);
5102 : }
5103 :
5104 : /* -------------------------------------------------------------------- */
5105 : /* Copy the raster attribute table, if required. */
5106 : /* -------------------------------------------------------------------- */
5107 879 : if (hRAT != nullptr)
5108 : {
5109 0 : GDALSetDefaultRAT(GDALGetRasterBand(hDstDS, 1), hRAT);
5110 : }
5111 :
5112 : /* -------------------------------------------------------------------- */
5113 : /* Copy the color table, if required. */
5114 : /* -------------------------------------------------------------------- */
5115 879 : if (poCT)
5116 : {
5117 2 : GDALSetRasterColorTable(GDALGetRasterBand(hDstDS, 1),
5118 : GDALColorTable::ToHandle(poCT.get()));
5119 : }
5120 :
5121 : /* -------------------------------------------------------------------- */
5122 : /* Copy scale/offset if found on source */
5123 : /* -------------------------------------------------------------------- */
5124 879 : if (nSrcCount == 1)
5125 : {
5126 855 : GDALDataset *poSrcDS = GDALDataset::FromHandle(pahSrcDS[0]);
5127 855 : GDALDataset *poDstDS = GDALDataset::FromHandle(hDstDS);
5128 :
5129 855 : int nBandsToCopy = nDstBandCount;
5130 855 : if (psOptions->bEnableDstAlpha)
5131 62 : nBandsToCopy--;
5132 855 : nBandsToCopy = std::min(nBandsToCopy, poSrcDS->GetRasterCount());
5133 :
5134 1948 : for (int i = 0; i < nBandsToCopy; i++)
5135 : {
5136 1119 : auto poSrcBand = poSrcDS->GetRasterBand(
5137 1093 : psOptions->anSrcBands.empty() ? i + 1
5138 26 : : psOptions->anSrcBands[i]);
5139 1119 : auto poDstBand = poDstDS->GetRasterBand(
5140 1093 : psOptions->anDstBands.empty() ? i + 1
5141 26 : : psOptions->anDstBands[i]);
5142 1093 : if (poSrcBand && poDstBand)
5143 : {
5144 1091 : int bHasScale = FALSE;
5145 1091 : const double dfScale = poSrcBand->GetScale(&bHasScale);
5146 1091 : if (bHasScale)
5147 29 : poDstBand->SetScale(dfScale);
5148 :
5149 1091 : int bHasOffset = FALSE;
5150 1091 : const double dfOffset = poSrcBand->GetOffset(&bHasOffset);
5151 1091 : if (bHasOffset)
5152 29 : poDstBand->SetOffset(dfOffset);
5153 : }
5154 : }
5155 : }
5156 :
5157 879 : return hDstDS;
5158 : }
5159 :
5160 : /************************************************************************/
5161 : /* GeoTransform_Transformer() */
5162 : /* */
5163 : /* Convert points from georef coordinates to pixel/line based */
5164 : /* on a geotransform. */
5165 : /************************************************************************/
5166 :
5167 : class CutlineTransformer : public OGRCoordinateTransformation
5168 : {
5169 : CPL_DISALLOW_COPY_ASSIGN(CutlineTransformer)
5170 :
5171 : public:
5172 : void *hSrcImageTransformer = nullptr;
5173 :
5174 40 : explicit CutlineTransformer(void *hTransformArg)
5175 40 : : hSrcImageTransformer(hTransformArg)
5176 : {
5177 40 : }
5178 :
5179 0 : const OGRSpatialReference *GetSourceCS() const override
5180 : {
5181 0 : return nullptr;
5182 : }
5183 :
5184 161 : const OGRSpatialReference *GetTargetCS() const override
5185 : {
5186 161 : return nullptr;
5187 : }
5188 :
5189 : ~CutlineTransformer() override;
5190 :
5191 60 : virtual int Transform(size_t nCount, double *x, double *y, double *z,
5192 : double * /* t */, int *pabSuccess) override
5193 : {
5194 60 : CPLAssert(nCount <=
5195 : static_cast<size_t>(std::numeric_limits<int>::max()));
5196 60 : return GDALGenImgProjTransform(hSrcImageTransformer, TRUE,
5197 : static_cast<int>(nCount), x, y, z,
5198 60 : pabSuccess);
5199 : }
5200 :
5201 0 : OGRCoordinateTransformation *Clone() const override
5202 : {
5203 : return new CutlineTransformer(
5204 0 : GDALCloneTransformer(hSrcImageTransformer));
5205 : }
5206 :
5207 0 : OGRCoordinateTransformation *GetInverse() const override
5208 : {
5209 0 : return nullptr;
5210 : }
5211 : };
5212 :
5213 40 : CutlineTransformer::~CutlineTransformer()
5214 : {
5215 40 : GDALDestroyTransformer(hSrcImageTransformer);
5216 40 : }
5217 :
5218 276 : static double GetMaximumSegmentLength(OGRGeometry *poGeom)
5219 : {
5220 276 : switch (wkbFlatten(poGeom->getGeometryType()))
5221 : {
5222 102 : case wkbLineString:
5223 : {
5224 102 : OGRLineString *poLS = static_cast<OGRLineString *>(poGeom);
5225 102 : double dfMaxSquaredLength = 0.0;
5226 13245 : for (int i = 0; i < poLS->getNumPoints() - 1; i++)
5227 : {
5228 13143 : double dfDeltaX = poLS->getX(i + 1) - poLS->getX(i);
5229 13143 : double dfDeltaY = poLS->getY(i + 1) - poLS->getY(i);
5230 13143 : double dfSquaredLength =
5231 13143 : dfDeltaX * dfDeltaX + dfDeltaY * dfDeltaY;
5232 13143 : dfMaxSquaredLength =
5233 13143 : std::max(dfMaxSquaredLength, dfSquaredLength);
5234 : }
5235 102 : return sqrt(dfMaxSquaredLength);
5236 : }
5237 :
5238 100 : case wkbPolygon:
5239 : {
5240 100 : OGRPolygon *poPoly = static_cast<OGRPolygon *>(poGeom);
5241 : double dfMaxLength =
5242 100 : GetMaximumSegmentLength(poPoly->getExteriorRing());
5243 102 : for (int i = 0; i < poPoly->getNumInteriorRings(); i++)
5244 : {
5245 2 : dfMaxLength = std::max(
5246 : dfMaxLength,
5247 2 : GetMaximumSegmentLength(poPoly->getInteriorRing(i)));
5248 : }
5249 100 : return dfMaxLength;
5250 : }
5251 :
5252 74 : case wkbMultiPolygon:
5253 : {
5254 74 : OGRMultiPolygon *poMP = static_cast<OGRMultiPolygon *>(poGeom);
5255 74 : double dfMaxLength = 0.0;
5256 152 : for (int i = 0; i < poMP->getNumGeometries(); i++)
5257 : {
5258 78 : dfMaxLength =
5259 78 : std::max(dfMaxLength,
5260 78 : GetMaximumSegmentLength(poMP->getGeometryRef(i)));
5261 : }
5262 74 : return dfMaxLength;
5263 : }
5264 :
5265 0 : default:
5266 0 : CPLAssert(false);
5267 : return 0.0;
5268 : }
5269 : }
5270 :
5271 : /************************************************************************/
5272 : /* RemoveZeroWidthSlivers() */
5273 : /* */
5274 : /* Such slivers can cause issues after reprojection. */
5275 : /************************************************************************/
5276 :
5277 118 : static void RemoveZeroWidthSlivers(OGRGeometry *poGeom)
5278 : {
5279 118 : const OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
5280 118 : if (eType == wkbMultiPolygon)
5281 : {
5282 32 : auto poMP = poGeom->toMultiPolygon();
5283 32 : int nNumGeometries = poMP->getNumGeometries();
5284 66 : for (int i = 0; i < nNumGeometries; /* incremented in loop */)
5285 : {
5286 34 : auto poPoly = poMP->getGeometryRef(i);
5287 34 : RemoveZeroWidthSlivers(poPoly);
5288 34 : if (poPoly->IsEmpty())
5289 : {
5290 1 : CPLDebug("WARP",
5291 : "RemoveZeroWidthSlivers: removing empty polygon");
5292 1 : poMP->removeGeometry(i, /* bDelete = */ true);
5293 1 : --nNumGeometries;
5294 : }
5295 : else
5296 : {
5297 33 : ++i;
5298 : }
5299 : }
5300 : }
5301 86 : else if (eType == wkbPolygon)
5302 : {
5303 42 : auto poPoly = poGeom->toPolygon();
5304 42 : if (auto poExteriorRing = poPoly->getExteriorRing())
5305 : {
5306 42 : RemoveZeroWidthSlivers(poExteriorRing);
5307 42 : if (poExteriorRing->getNumPoints() < 4)
5308 : {
5309 1 : poPoly->empty();
5310 1 : return;
5311 : }
5312 : }
5313 41 : int nNumInteriorRings = poPoly->getNumInteriorRings();
5314 43 : for (int i = 0; i < nNumInteriorRings; /* incremented in loop */)
5315 : {
5316 2 : auto poRing = poPoly->getInteriorRing(i);
5317 2 : RemoveZeroWidthSlivers(poRing);
5318 2 : if (poRing->getNumPoints() < 4)
5319 : {
5320 1 : CPLDebug(
5321 : "WARP",
5322 : "RemoveZeroWidthSlivers: removing empty interior ring");
5323 1 : constexpr int OFFSET_EXTERIOR_RING = 1;
5324 1 : poPoly->removeRing(i + OFFSET_EXTERIOR_RING,
5325 : /* bDelete = */ true);
5326 1 : --nNumInteriorRings;
5327 : }
5328 : else
5329 : {
5330 1 : ++i;
5331 : }
5332 : }
5333 : }
5334 44 : else if (eType == wkbLineString)
5335 : {
5336 44 : OGRLineString *poLS = poGeom->toLineString();
5337 44 : int numPoints = poLS->getNumPoints();
5338 210 : for (int i = 1; i < numPoints - 1;)
5339 : {
5340 166 : const double x1 = poLS->getX(i - 1);
5341 166 : const double y1 = poLS->getY(i - 1);
5342 166 : const double x2 = poLS->getX(i);
5343 166 : const double y2 = poLS->getY(i);
5344 166 : const double x3 = poLS->getX(i + 1);
5345 166 : const double y3 = poLS->getY(i + 1);
5346 166 : const double dx1 = x2 - x1;
5347 166 : const double dy1 = y2 - y1;
5348 166 : const double dx2 = x3 - x2;
5349 166 : const double dy2 = y3 - y2;
5350 166 : const double scalar_product = dx1 * dx2 + dy1 * dy2;
5351 166 : const double square_scalar_product =
5352 : scalar_product * scalar_product;
5353 166 : const double square_norm1 = dx1 * dx1 + dy1 * dy1;
5354 166 : const double square_norm2 = dx2 * dx2 + dy2 * dy2;
5355 166 : const double square_norm1_mult_norm2 = square_norm1 * square_norm2;
5356 166 : if (scalar_product < 0 &&
5357 25 : fabs(square_scalar_product - square_norm1_mult_norm2) <=
5358 25 : 1e-15 * square_norm1_mult_norm2)
5359 : {
5360 5 : CPLDebug("WARP",
5361 : "RemoveZeroWidthSlivers: removing point %.10g %.10g",
5362 : x2, y2);
5363 5 : poLS->removePoint(i);
5364 5 : numPoints--;
5365 : }
5366 : else
5367 : {
5368 161 : ++i;
5369 : }
5370 : }
5371 : }
5372 : }
5373 :
5374 : /************************************************************************/
5375 : /* TransformCutlineToSource() */
5376 : /* */
5377 : /* Transform cutline from its SRS to source pixel/line coordinates.*/
5378 : /************************************************************************/
5379 40 : static CPLErr TransformCutlineToSource(GDALDataset *poSrcDS,
5380 : OGRGeometry *poCutline,
5381 : char ***ppapszWarpOptions,
5382 : CSLConstList papszTO_In)
5383 :
5384 : {
5385 40 : RemoveZeroWidthSlivers(poCutline);
5386 :
5387 80 : auto poMultiPolygon = std::unique_ptr<OGRGeometry>(poCutline->clone());
5388 :
5389 : /* -------------------------------------------------------------------- */
5390 : /* Checkout that if there's a cutline SRS, there's also a raster */
5391 : /* one. */
5392 : /* -------------------------------------------------------------------- */
5393 40 : std::unique_ptr<OGRSpatialReference> poRasterSRS;
5394 : const CPLString osProjection =
5395 80 : GetSrcDSProjection(GDALDataset::ToHandle(poSrcDS), papszTO_In);
5396 40 : if (!osProjection.empty())
5397 : {
5398 36 : poRasterSRS = std::make_unique<OGRSpatialReference>();
5399 36 : poRasterSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
5400 36 : if (poRasterSRS->SetFromUserInput(osProjection) != OGRERR_NONE)
5401 : {
5402 0 : poRasterSRS.reset();
5403 : }
5404 : }
5405 :
5406 40 : std::unique_ptr<OGRSpatialReference> poDstSRS;
5407 40 : const char *pszThisTargetSRS = CSLFetchNameValue(papszTO_In, "DST_SRS");
5408 40 : if (pszThisTargetSRS)
5409 : {
5410 8 : poDstSRS = std::make_unique<OGRSpatialReference>();
5411 8 : poDstSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
5412 8 : if (poDstSRS->SetFromUserInput(pszThisTargetSRS) != OGRERR_NONE)
5413 : {
5414 0 : return CE_Failure;
5415 : }
5416 : }
5417 32 : else if (poRasterSRS)
5418 : {
5419 28 : poDstSRS.reset(poRasterSRS->Clone());
5420 : }
5421 :
5422 : /* -------------------------------------------------------------------- */
5423 : /* Extract the cutline SRS. */
5424 : /* -------------------------------------------------------------------- */
5425 : const OGRSpatialReference *poCutlineSRS =
5426 40 : poMultiPolygon->getSpatialReference();
5427 :
5428 : /* -------------------------------------------------------------------- */
5429 : /* Detect if there's no transform at all involved, in which case */
5430 : /* we can avoid densification. */
5431 : /* -------------------------------------------------------------------- */
5432 40 : bool bMayNeedDensify = true;
5433 76 : if (poRasterSRS && poCutlineSRS && poRasterSRS->IsSame(poCutlineSRS) &&
5434 26 : poSrcDS->GetGCPCount() == 0 && !poSrcDS->GetMetadata("RPC") &&
5435 22 : !poSrcDS->GetMetadata("GEOLOCATION") &&
5436 98 : !CSLFetchNameValue(papszTO_In, "GEOLOC_ARRAY") &&
5437 22 : !CSLFetchNameValue(papszTO_In, "SRC_GEOLOC_ARRAY"))
5438 : {
5439 44 : CPLStringList aosTOTmp(papszTO_In);
5440 22 : aosTOTmp.SetNameValue("SRC_SRS", nullptr);
5441 22 : aosTOTmp.SetNameValue("DST_SRS", nullptr);
5442 22 : if (aosTOTmp.size() == 0)
5443 : {
5444 22 : bMayNeedDensify = false;
5445 : }
5446 : }
5447 :
5448 : /* -------------------------------------------------------------------- */
5449 : /* Compare source raster SRS and cutline SRS */
5450 : /* -------------------------------------------------------------------- */
5451 40 : if (poRasterSRS && poCutlineSRS)
5452 : {
5453 : /* OK, we will reproject */
5454 : }
5455 8 : else if (poRasterSRS && !poCutlineSRS)
5456 : {
5457 4 : CPLError(
5458 : CE_Warning, CPLE_AppDefined,
5459 : "the source raster dataset has a SRS, but the cutline features\n"
5460 : "not. We assume that the cutline coordinates are expressed in the "
5461 : "destination SRS.\n"
5462 : "If not, cutline results may be incorrect.");
5463 : }
5464 4 : else if (!poRasterSRS && poCutlineSRS)
5465 : {
5466 0 : CPLError(CE_Warning, CPLE_AppDefined,
5467 : "the input vector layer has a SRS, but the source raster "
5468 : "dataset does not.\n"
5469 : "Cutline results may be incorrect.");
5470 : }
5471 :
5472 : auto poCTCutlineToSrc = CreateCTCutlineToSrc(
5473 80 : poRasterSRS.get(), poDstSRS.get(), poCutlineSRS, papszTO_In);
5474 :
5475 80 : CPLStringList aosTO(papszTO_In);
5476 :
5477 40 : if (pszThisTargetSRS && !osProjection.empty())
5478 : {
5479 : // Avoid any reprojection when using the GenImgProjTransformer
5480 8 : aosTO.SetNameValue("DST_SRS", osProjection.c_str());
5481 : }
5482 40 : aosTO.SetNameValue("SRC_COORDINATE_EPOCH", nullptr);
5483 40 : aosTO.SetNameValue("DST_COORDINATE_EPOCH", nullptr);
5484 40 : aosTO.SetNameValue("COORDINATE_OPERATION", nullptr);
5485 :
5486 : /* -------------------------------------------------------------------- */
5487 : /* It may be unwise to let the mask geometry be re-wrapped by */
5488 : /* the CENTER_LONG machinery as this can easily screw up world */
5489 : /* spanning masks and invert the mask topology. */
5490 : /* -------------------------------------------------------------------- */
5491 40 : aosTO.SetNameValue("INSERT_CENTER_LONG", "FALSE");
5492 :
5493 : /* -------------------------------------------------------------------- */
5494 : /* Transform the geometry to pixel/line coordinates. */
5495 : /* -------------------------------------------------------------------- */
5496 : /* The cutline transformer will *invert* the hSrcImageTransformer */
5497 : /* so it will convert from the source SRS to the source pixel/line */
5498 : /* coordinates */
5499 : CutlineTransformer oTransformer(GDALCreateGenImgProjTransformer2(
5500 80 : GDALDataset::ToHandle(poSrcDS), nullptr, aosTO.List()));
5501 :
5502 40 : if (oTransformer.hSrcImageTransformer == nullptr)
5503 : {
5504 0 : return CE_Failure;
5505 : }
5506 :
5507 : // Some transforms like RPC can transform a valid geometry into an invalid
5508 : // one if the node density of the input geometry isn't sufficient before
5509 : // reprojection. So after an initial reprojection, we check that the
5510 : // maximum length of a segment is no longer than 1 pixel, and if not,
5511 : // we densify the input geometry before doing a new reprojection
5512 : const double dfMaxLengthInSpatUnits =
5513 40 : GetMaximumSegmentLength(poMultiPolygon.get());
5514 40 : OGRErr eErr = OGRERR_NONE;
5515 40 : if (poCTCutlineToSrc)
5516 : {
5517 12 : poMultiPolygon.reset(OGRGeometryFactory::transformWithOptions(
5518 6 : poMultiPolygon.get(), poCTCutlineToSrc.get(), nullptr));
5519 6 : if (!poMultiPolygon)
5520 : {
5521 0 : eErr = OGRERR_FAILURE;
5522 0 : poMultiPolygon.reset(poCutline->clone());
5523 0 : poMultiPolygon->transform(poCTCutlineToSrc.get());
5524 : }
5525 : }
5526 40 : if (poMultiPolygon->transform(&oTransformer) != OGRERR_NONE)
5527 : {
5528 0 : CPLError(CE_Failure, CPLE_AppDefined,
5529 : "poMultiPolygon->transform(&oTransformer) failed at line %d",
5530 : __LINE__);
5531 0 : eErr = OGRERR_FAILURE;
5532 : }
5533 : const double dfInitialMaxLengthInPixels =
5534 40 : GetMaximumSegmentLength(poMultiPolygon.get());
5535 :
5536 40 : CPLPushErrorHandler(CPLQuietErrorHandler);
5537 : const bool bWasValidInitially =
5538 40 : ValidateCutline(poMultiPolygon.get(), false);
5539 40 : CPLPopErrorHandler();
5540 40 : if (!bWasValidInitially)
5541 : {
5542 3 : CPLDebug("WARP", "Cutline is not valid after initial reprojection");
5543 3 : char *pszWKT = nullptr;
5544 3 : poMultiPolygon->exportToWkt(&pszWKT);
5545 3 : CPLDebug("GDALWARP", "WKT = \"%s\"", pszWKT ? pszWKT : "(null)");
5546 3 : CPLFree(pszWKT);
5547 : }
5548 :
5549 40 : bool bDensify = false;
5550 40 : if (bMayNeedDensify && eErr == OGRERR_NONE &&
5551 : dfInitialMaxLengthInPixels > 1.0)
5552 : {
5553 : const char *pszDensifyCutline =
5554 16 : CPLGetConfigOption("GDALWARP_DENSIFY_CUTLINE", "YES");
5555 16 : if (EQUAL(pszDensifyCutline, "ONLY_IF_INVALID"))
5556 : {
5557 1 : bDensify = (OGRGeometryFactory::haveGEOS() && !bWasValidInitially);
5558 : }
5559 15 : else if (CSLFetchNameValue(*ppapszWarpOptions, "CUTLINE_BLEND_DIST") !=
5560 15 : nullptr &&
5561 0 : CPLGetConfigOption("GDALWARP_DENSIFY_CUTLINE", nullptr) ==
5562 : nullptr)
5563 : {
5564 : // TODO: we should only emit this message if a
5565 : // transform/reprojection will be actually done
5566 0 : CPLDebug("WARP",
5567 : "Densification of cutline could perhaps be useful but as "
5568 : "CUTLINE_BLEND_DIST is used, this could be very slow. So "
5569 : "disabled "
5570 : "unless GDALWARP_DENSIFY_CUTLINE=YES is explicitly "
5571 : "specified as configuration option");
5572 : }
5573 : else
5574 : {
5575 15 : bDensify = CPLTestBool(pszDensifyCutline);
5576 : }
5577 : }
5578 40 : if (bDensify)
5579 : {
5580 15 : CPLDebug("WARP",
5581 : "Cutline maximum segment size was %.0f pixel after "
5582 : "reprojection to source coordinates.",
5583 : dfInitialMaxLengthInPixels);
5584 :
5585 : // Densify and reproject with the aim of having a 1 pixel density
5586 15 : double dfSegmentSize =
5587 : dfMaxLengthInSpatUnits / dfInitialMaxLengthInPixels;
5588 15 : const int MAX_ITERATIONS = 10;
5589 16 : for (int i = 0; i < MAX_ITERATIONS; i++)
5590 : {
5591 16 : poMultiPolygon.reset(poCutline->clone());
5592 16 : poMultiPolygon->segmentize(dfSegmentSize);
5593 16 : if (i == MAX_ITERATIONS - 1)
5594 : {
5595 0 : char *pszWKT = nullptr;
5596 0 : poMultiPolygon->exportToWkt(&pszWKT);
5597 0 : CPLDebug("WARP",
5598 : "WKT of polygon after densification with segment size "
5599 : "= %f: %s",
5600 : dfSegmentSize, pszWKT);
5601 0 : CPLFree(pszWKT);
5602 : }
5603 16 : eErr = OGRERR_NONE;
5604 16 : if (poCTCutlineToSrc)
5605 : {
5606 12 : poMultiPolygon.reset(OGRGeometryFactory::transformWithOptions(
5607 6 : poMultiPolygon.get(), poCTCutlineToSrc.get(), nullptr));
5608 6 : if (!poMultiPolygon)
5609 : {
5610 0 : eErr = OGRERR_FAILURE;
5611 0 : break;
5612 : }
5613 : }
5614 16 : if (poMultiPolygon->transform(&oTransformer) != OGRERR_NONE)
5615 0 : eErr = OGRERR_FAILURE;
5616 16 : if (eErr == OGRERR_NONE)
5617 : {
5618 : const double dfMaxLengthInPixels =
5619 16 : GetMaximumSegmentLength(poMultiPolygon.get());
5620 16 : if (bWasValidInitially)
5621 : {
5622 : // In some cases, the densification itself results in a
5623 : // reprojected invalid polygon due to the non-linearity of
5624 : // RPC DEM transformation, so in those cases, try a less
5625 : // dense cutline
5626 14 : CPLPushErrorHandler(CPLQuietErrorHandler);
5627 : const bool bIsValid =
5628 14 : ValidateCutline(poMultiPolygon.get(), false);
5629 14 : CPLPopErrorHandler();
5630 14 : if (!bIsValid)
5631 : {
5632 1 : if (i == MAX_ITERATIONS - 1)
5633 : {
5634 0 : char *pszWKT = nullptr;
5635 0 : poMultiPolygon->exportToWkt(&pszWKT);
5636 0 : CPLDebug("WARP",
5637 : "After densification, cutline maximum "
5638 : "segment size is now %.0f pixel, "
5639 : "but cutline is invalid. %s",
5640 : dfMaxLengthInPixels, pszWKT);
5641 0 : CPLFree(pszWKT);
5642 0 : break;
5643 : }
5644 1 : CPLDebug("WARP",
5645 : "After densification, cutline maximum segment "
5646 : "size is now %.0f pixel, "
5647 : "but cutline is invalid. So trying a less "
5648 : "dense cutline.",
5649 : dfMaxLengthInPixels);
5650 1 : dfSegmentSize *= 2;
5651 1 : continue;
5652 : }
5653 : }
5654 15 : CPLDebug("WARP",
5655 : "After densification, cutline maximum segment size is "
5656 : "now %.0f pixel.",
5657 : dfMaxLengthInPixels);
5658 : }
5659 15 : break;
5660 : }
5661 : }
5662 :
5663 40 : if (eErr == OGRERR_FAILURE)
5664 : {
5665 0 : if (CPLTestBool(
5666 : CPLGetConfigOption("GDALWARP_IGNORE_BAD_CUTLINE", "NO")))
5667 0 : CPLError(CE_Warning, CPLE_AppDefined,
5668 : "Cutline transformation failed");
5669 : else
5670 : {
5671 0 : CPLError(CE_Failure, CPLE_AppDefined,
5672 : "Cutline transformation failed");
5673 0 : return CE_Failure;
5674 : }
5675 : }
5676 40 : else if (!ValidateCutline(poMultiPolygon.get(), true))
5677 : {
5678 1 : return CE_Failure;
5679 : }
5680 :
5681 : // Optimization: if the cutline contains the footprint of the source
5682 : // dataset, no need to use the cutline.
5683 39 : if (OGRGeometryFactory::haveGEOS()
5684 : #ifdef DEBUG
5685 : // Env var just for debugging purposes
5686 39 : && !CPLTestBool(CPLGetConfigOption(
5687 : "GDALWARP_SKIP_CUTLINE_CONTAINMENT_TEST", "NO"))
5688 : #endif
5689 : )
5690 : {
5691 38 : const double dfCutlineBlendDist = CPLAtof(CSLFetchNameValueDef(
5692 : *ppapszWarpOptions, "CUTLINE_BLEND_DIST", "0"));
5693 38 : auto poRing = std::make_unique<OGRLinearRing>();
5694 38 : poRing->addPoint(-dfCutlineBlendDist, -dfCutlineBlendDist);
5695 38 : poRing->addPoint(-dfCutlineBlendDist,
5696 38 : dfCutlineBlendDist + poSrcDS->GetRasterYSize());
5697 76 : poRing->addPoint(dfCutlineBlendDist + poSrcDS->GetRasterXSize(),
5698 38 : dfCutlineBlendDist + poSrcDS->GetRasterYSize());
5699 38 : poRing->addPoint(dfCutlineBlendDist + poSrcDS->GetRasterXSize(),
5700 : -dfCutlineBlendDist);
5701 38 : poRing->addPoint(-dfCutlineBlendDist, -dfCutlineBlendDist);
5702 38 : OGRPolygon oSrcDSFootprint;
5703 38 : oSrcDSFootprint.addRing(std::move(poRing));
5704 38 : OGREnvelope sSrcDSEnvelope;
5705 38 : oSrcDSFootprint.getEnvelope(&sSrcDSEnvelope);
5706 38 : OGREnvelope sCutlineEnvelope;
5707 38 : poMultiPolygon->getEnvelope(&sCutlineEnvelope);
5708 43 : if (sCutlineEnvelope.Contains(sSrcDSEnvelope) &&
5709 5 : poMultiPolygon->Contains(&oSrcDSFootprint))
5710 : {
5711 2 : CPLDebug("WARP", "Source dataset fully contained within cutline.");
5712 2 : return CE_None;
5713 : }
5714 : }
5715 :
5716 : /* -------------------------------------------------------------------- */
5717 : /* Convert aggregate geometry into WKT. */
5718 : /* -------------------------------------------------------------------- */
5719 37 : char *pszWKT = nullptr;
5720 37 : poMultiPolygon->exportToWkt(&pszWKT);
5721 : // fprintf(stderr, "WKT = \"%s\"\n", pszWKT ? pszWKT : "(null)");
5722 :
5723 37 : *ppapszWarpOptions = CSLSetNameValue(*ppapszWarpOptions, "CUTLINE", pszWKT);
5724 37 : CPLFree(pszWKT);
5725 37 : return CE_None;
5726 : }
5727 :
5728 47 : static void RemoveConflictingMetadata(GDALMajorObjectH hObj,
5729 : CSLConstList papszSrcMetadata,
5730 : const char *pszValueConflict)
5731 : {
5732 47 : if (hObj == nullptr)
5733 0 : return;
5734 :
5735 38 : for (const auto &[pszKey, pszValue] :
5736 85 : cpl::IterateNameValue(papszSrcMetadata))
5737 : {
5738 19 : const char *pszValueComp = GDALGetMetadataItem(hObj, pszKey, nullptr);
5739 19 : if (pszValueComp == nullptr || (!EQUAL(pszValue, pszValueComp) &&
5740 2 : !EQUAL(pszValueComp, pszValueConflict)))
5741 : {
5742 3 : if (STARTS_WITH(pszKey, "STATISTICS_"))
5743 1 : GDALSetMetadataItem(hObj, pszKey, nullptr, nullptr);
5744 : else
5745 2 : GDALSetMetadataItem(hObj, pszKey, pszValueConflict, nullptr);
5746 : }
5747 : }
5748 : }
5749 :
5750 : /************************************************************************/
5751 : /* IsValidSRS */
5752 : /************************************************************************/
5753 :
5754 260 : static bool IsValidSRS(const char *pszUserInput)
5755 :
5756 : {
5757 : OGRSpatialReferenceH hSRS;
5758 260 : bool bRes = true;
5759 :
5760 260 : hSRS = OSRNewSpatialReference(nullptr);
5761 260 : if (OSRSetFromUserInput(hSRS, pszUserInput) != OGRERR_NONE)
5762 : {
5763 0 : bRes = false;
5764 : }
5765 :
5766 260 : OSRDestroySpatialReference(hSRS);
5767 :
5768 260 : return bRes;
5769 : }
5770 :
5771 : /************************************************************************/
5772 : /* GDALWarpAppOptionsGetParser() */
5773 : /************************************************************************/
5774 :
5775 : static std::unique_ptr<GDALArgumentParser>
5776 1018 : GDALWarpAppOptionsGetParser(GDALWarpAppOptions *psOptions,
5777 : GDALWarpAppOptionsForBinary *psOptionsForBinary)
5778 : {
5779 : auto argParser = std::make_unique<GDALArgumentParser>(
5780 1018 : "gdalwarp", /* bForBinary=*/psOptionsForBinary != nullptr);
5781 :
5782 1018 : argParser->add_description(_("Image reprojection and warping utility."));
5783 :
5784 1018 : argParser->add_epilog(
5785 1018 : _("For more details, consult https://gdal.org/programs/gdalwarp.html"));
5786 :
5787 : argParser->add_quiet_argument(
5788 1018 : psOptionsForBinary ? &psOptionsForBinary->bQuiet : nullptr);
5789 :
5790 1018 : argParser->add_argument("-overwrite")
5791 1018 : .flag()
5792 : .action(
5793 90 : [psOptionsForBinary](const std::string &)
5794 : {
5795 49 : if (psOptionsForBinary)
5796 41 : psOptionsForBinary->bOverwrite = true;
5797 1018 : })
5798 1018 : .help(_("Overwrite the target dataset if it already exists."));
5799 :
5800 1018 : argParser->add_output_format_argument(psOptions->osFormat);
5801 :
5802 1018 : argParser->add_argument("-co")
5803 2036 : .metavar("<NAME>=<VALUE>")
5804 1018 : .append()
5805 : .action(
5806 285 : [psOptions, psOptionsForBinary](const std::string &s)
5807 : {
5808 139 : psOptions->aosCreateOptions.AddString(s.c_str());
5809 139 : psOptions->bCreateOutput = true;
5810 :
5811 139 : if (psOptionsForBinary)
5812 7 : psOptionsForBinary->aosCreateOptions.AddString(s.c_str());
5813 1018 : })
5814 1018 : .help(_("Creation option(s)."));
5815 :
5816 1018 : argParser->add_argument("-s_srs")
5817 2036 : .metavar("<srs_def>")
5818 : .action(
5819 90 : [psOptions](const std::string &s)
5820 : {
5821 45 : if (!IsValidSRS(s.c_str()))
5822 : {
5823 0 : throw std::invalid_argument("Invalid SRS for -s_srs");
5824 : }
5825 : psOptions->aosTransformerOptions.SetNameValue("SRC_SRS",
5826 45 : s.c_str());
5827 1063 : })
5828 1018 : .help(_("Set source spatial reference."));
5829 :
5830 1018 : argParser->add_argument("-t_srs")
5831 2036 : .metavar("<srs_def>")
5832 : .action(
5833 414 : [psOptions](const std::string &s)
5834 : {
5835 207 : if (!IsValidSRS(s.c_str()))
5836 : {
5837 0 : throw std::invalid_argument("Invalid SRS for -t_srs");
5838 : }
5839 : psOptions->aosTransformerOptions.SetNameValue("DST_SRS",
5840 207 : s.c_str());
5841 1225 : })
5842 1018 : .help(_("Set target spatial reference."));
5843 :
5844 : {
5845 1018 : auto &group = argParser->add_mutually_exclusive_group();
5846 1018 : group.add_argument("-srcalpha")
5847 1018 : .flag()
5848 1018 : .store_into(psOptions->bEnableSrcAlpha)
5849 : .help(_("Force the last band of a source image to be considered as "
5850 1018 : "a source alpha band."));
5851 1018 : group.add_argument("-nosrcalpha")
5852 1018 : .flag()
5853 1018 : .store_into(psOptions->bDisableSrcAlpha)
5854 : .help(_("Prevent the alpha band of a source image to be considered "
5855 1018 : "as such."));
5856 : }
5857 :
5858 1018 : argParser->add_argument("-dstalpha")
5859 1018 : .flag()
5860 1018 : .store_into(psOptions->bEnableDstAlpha)
5861 : .help(_("Create an output alpha band to identify nodata "
5862 1018 : "(unset/transparent) pixels."));
5863 :
5864 : // Parsing of that option is done in a preprocessing stage
5865 1018 : argParser->add_argument("-tr")
5866 2036 : .metavar("<xres> <yres>|square")
5867 1018 : .help(_("Target resolution."));
5868 :
5869 1018 : argParser->add_argument("-ts")
5870 2036 : .metavar("<width> <height>")
5871 1018 : .nargs(2)
5872 1018 : .scan<'i', int>()
5873 1018 : .help(_("Set output file size in pixels and lines."));
5874 :
5875 1018 : argParser->add_argument("-te")
5876 2036 : .metavar("<xmin> <ymin> <xmax> <ymax>")
5877 1018 : .nargs(4)
5878 1018 : .scan<'g', double>()
5879 1018 : .help(_("Set georeferenced extents of output file to be created."));
5880 :
5881 1018 : argParser->add_argument("-te_srs")
5882 2036 : .metavar("<srs_def>")
5883 : .action(
5884 15 : [psOptions](const std::string &s)
5885 : {
5886 5 : if (!IsValidSRS(s.c_str()))
5887 : {
5888 0 : throw std::invalid_argument("Invalid SRS for -te_srs");
5889 : }
5890 5 : psOptions->osTE_SRS = s;
5891 5 : psOptions->bCreateOutput = true;
5892 1023 : })
5893 1018 : .help(_("Set source spatial reference."));
5894 :
5895 1018 : argParser->add_argument("-r")
5896 : .metavar("near|bilinear|cubic|cubicspline|lanczos|average|rms|mode|min|"
5897 2036 : "max|med|q1|q3|sum")
5898 : .action(
5899 1135 : [psOptions](const std::string &s)
5900 : {
5901 568 : GDALGetWarpResampleAlg(s.c_str(), psOptions->eResampleAlg,
5902 : /*bThrow=*/true);
5903 567 : psOptions->bResampleAlgSpecifiedByUser = true;
5904 1018 : })
5905 1018 : .help(_("Resampling method to use."));
5906 :
5907 1018 : argParser->add_output_type_argument(psOptions->eOutputType);
5908 :
5909 : ///////////////////////////////////////////////////////////////////////
5910 1018 : argParser->add_group("Advanced options");
5911 :
5912 32 : const auto CheckSingleMethod = [psOptions]()
5913 : {
5914 : const char *pszMethod =
5915 16 : FetchSrcMethod(psOptions->aosTransformerOptions);
5916 16 : if (pszMethod)
5917 0 : CPLError(CE_Warning, CPLE_IllegalArg,
5918 : "Warning: only one METHOD can be used. Method %s is "
5919 : "already defined.",
5920 : pszMethod);
5921 : const char *pszMAX_GCP_ORDER =
5922 16 : psOptions->aosTransformerOptions.FetchNameValue("MAX_GCP_ORDER");
5923 16 : if (pszMAX_GCP_ORDER)
5924 0 : CPLError(CE_Warning, CPLE_IllegalArg,
5925 : "Warning: only one METHOD can be used. -order %s "
5926 : "option was specified, so it is likely that "
5927 : "GCP_POLYNOMIAL was implied.",
5928 : pszMAX_GCP_ORDER);
5929 1034 : };
5930 :
5931 1018 : argParser->add_argument("-wo")
5932 2036 : .metavar("<NAME>=<VALUE>")
5933 1018 : .append()
5934 159 : .action([psOptions](const std::string &s)
5935 1177 : { psOptions->aosWarpOptions.AddString(s.c_str()); })
5936 1018 : .help(_("Warping option(s)."));
5937 :
5938 1018 : argParser->add_argument("-multi")
5939 1018 : .flag()
5940 1018 : .store_into(psOptions->bMulti)
5941 1018 : .help(_("Multithreaded input/output."));
5942 :
5943 1018 : argParser->add_argument("-s_coord_epoch")
5944 2036 : .metavar("<epoch>")
5945 : .action(
5946 0 : [psOptions](const std::string &s)
5947 : {
5948 : psOptions->aosTransformerOptions.SetNameValue(
5949 0 : "SRC_COORDINATE_EPOCH", s.c_str());
5950 1018 : })
5951 : .help(_("Assign a coordinate epoch, linked with the source SRS when "
5952 1018 : "-s_srs is used."));
5953 :
5954 1018 : argParser->add_argument("-t_coord_epoch")
5955 2036 : .metavar("<epoch>")
5956 : .action(
5957 0 : [psOptions](const std::string &s)
5958 : {
5959 : psOptions->aosTransformerOptions.SetNameValue(
5960 0 : "DST_COORDINATE_EPOCH", s.c_str());
5961 1018 : })
5962 : .help(_("Assign a coordinate epoch, linked with the output SRS when "
5963 1018 : "-t_srs is used."));
5964 :
5965 1018 : argParser->add_argument("-ct")
5966 2036 : .metavar("<string>")
5967 : .action(
5968 4 : [psOptions](const std::string &s)
5969 : {
5970 : psOptions->aosTransformerOptions.SetNameValue(
5971 4 : "COORDINATE_OPERATION", s.c_str());
5972 1018 : })
5973 1018 : .help(_("Set a coordinate transformation."));
5974 :
5975 : {
5976 1018 : auto &group = argParser->add_mutually_exclusive_group();
5977 1018 : group.add_argument("-tps")
5978 1018 : .flag()
5979 : .action(
5980 10 : [psOptions, CheckSingleMethod](const std::string &)
5981 : {
5982 5 : CheckSingleMethod();
5983 : psOptions->aosTransformerOptions.SetNameValue("SRC_METHOD",
5984 5 : "GCP_TPS");
5985 1018 : })
5986 : .help(_("Force use of thin plate spline transformer based on "
5987 1018 : "available GCPs."));
5988 :
5989 1018 : group.add_argument("-rpc")
5990 1018 : .flag()
5991 : .action(
5992 4 : [psOptions, CheckSingleMethod](const std::string &)
5993 : {
5994 2 : CheckSingleMethod();
5995 : psOptions->aosTransformerOptions.SetNameValue("SRC_METHOD",
5996 2 : "RPC");
5997 1018 : })
5998 1018 : .help(_("Force use of RPCs."));
5999 :
6000 1018 : group.add_argument("-geoloc")
6001 1018 : .flag()
6002 : .action(
6003 18 : [psOptions, CheckSingleMethod](const std::string &)
6004 : {
6005 9 : CheckSingleMethod();
6006 : psOptions->aosTransformerOptions.SetNameValue(
6007 9 : "SRC_METHOD", "GEOLOC_ARRAY");
6008 1018 : })
6009 1018 : .help(_("Force use of Geolocation Arrays."));
6010 : }
6011 :
6012 1018 : argParser->add_argument("-order")
6013 2036 : .metavar("<1|2|3>")
6014 1018 : .choices("1", "2", "3")
6015 : .action(
6016 0 : [psOptions](const std::string &s)
6017 : {
6018 : const char *pszMethod =
6019 0 : FetchSrcMethod(psOptions->aosTransformerOptions);
6020 0 : if (pszMethod)
6021 0 : CPLError(
6022 : CE_Warning, CPLE_IllegalArg,
6023 : "Warning: only one METHOD can be used. Method %s is "
6024 : "already defined",
6025 : pszMethod);
6026 : psOptions->aosTransformerOptions.SetNameValue("MAX_GCP_ORDER",
6027 0 : s.c_str());
6028 1018 : })
6029 1018 : .help(_("Order of polynomial used for GCP warping."));
6030 :
6031 : // Parsing of that option is done in a preprocessing stage
6032 1018 : argParser->add_argument("-refine_gcps")
6033 2036 : .metavar("<tolerance> [<minimum_gcps>]")
6034 1018 : .help(_("Refines the GCPs by automatically eliminating outliers."));
6035 :
6036 1018 : argParser->add_argument("-to")
6037 2036 : .metavar("<NAME>=<VALUE>")
6038 1018 : .append()
6039 56 : .action([psOptions](const std::string &s)
6040 1074 : { psOptions->aosTransformerOptions.AddString(s.c_str()); })
6041 1018 : .help(_("Transform option(s)."));
6042 :
6043 1018 : argParser->add_argument("-et")
6044 2036 : .metavar("<err_threshold>")
6045 1018 : .store_into(psOptions->dfErrorThreshold)
6046 : .action(
6047 26 : [psOptions](const std::string &)
6048 : {
6049 13 : if (psOptions->dfErrorThreshold < 0)
6050 : {
6051 : throw std::invalid_argument(
6052 0 : "Invalid value for error threshold");
6053 : }
6054 : psOptions->aosWarpOptions.AddString(CPLSPrintf(
6055 13 : "ERROR_THRESHOLD=%.16g", psOptions->dfErrorThreshold));
6056 1031 : })
6057 1018 : .help(_("Error threshold."));
6058 :
6059 1018 : argParser->add_argument("-wm")
6060 2036 : .metavar("<memory_in_mb>")
6061 : .action(
6062 74 : [psOptions](const std::string &s)
6063 : {
6064 38 : bool bUnitSpecified = false;
6065 : GIntBig nBytes;
6066 38 : if (CPLParseMemorySize(s.c_str(), &nBytes, &bUnitSpecified) ==
6067 : CE_None)
6068 : {
6069 36 : if (!bUnitSpecified && nBytes < 10000)
6070 : {
6071 7 : nBytes *= (1024 * 1024);
6072 : }
6073 36 : psOptions->dfWarpMemoryLimit = static_cast<double>(nBytes);
6074 : }
6075 : else
6076 : {
6077 2 : throw std::invalid_argument("Failed to parse value of -wm");
6078 : }
6079 1054 : })
6080 1018 : .help(_("Set max warp memory."));
6081 :
6082 1018 : argParser->add_argument("-srcnodata")
6083 2036 : .metavar("\"<value>[ <value>]...\"")
6084 1018 : .store_into(psOptions->osSrcNodata)
6085 1018 : .help(_("Nodata masking values for input bands."));
6086 :
6087 1018 : argParser->add_argument("-dstnodata")
6088 2036 : .metavar("\"<value>[ <value>]...\"")
6089 1018 : .store_into(psOptions->osDstNodata)
6090 1018 : .help(_("Nodata masking values for output bands."));
6091 :
6092 1018 : argParser->add_argument("-tap")
6093 1018 : .flag()
6094 1018 : .store_into(psOptions->bTargetAlignedPixels)
6095 1018 : .help(_("Force target aligned pixels."));
6096 :
6097 1018 : argParser->add_argument("-wt")
6098 2036 : .metavar("Byte|Int8|[U]Int{16|32|64}|CInt{16|32}|[C]Float{32|64}")
6099 : .action(
6100 0 : [psOptions](const std::string &s)
6101 : {
6102 0 : psOptions->eWorkingType = GDALGetDataTypeByName(s.c_str());
6103 0 : if (psOptions->eWorkingType == GDT_Unknown)
6104 : {
6105 : throw std::invalid_argument(
6106 0 : std::string("Unknown output pixel type: ").append(s));
6107 : }
6108 1018 : })
6109 1018 : .help(_("Working data type."));
6110 :
6111 : // Non-documented alias of -r nearest
6112 1018 : argParser->add_argument("-rn")
6113 1018 : .flag()
6114 1018 : .hidden()
6115 1 : .action([psOptions](const std::string &)
6116 1018 : { psOptions->eResampleAlg = GRA_NearestNeighbour; })
6117 1018 : .help(_("Nearest neighbour resampling."));
6118 :
6119 : // Non-documented alias of -r bilinear
6120 1018 : argParser->add_argument("-rb")
6121 1018 : .flag()
6122 1018 : .hidden()
6123 2 : .action([psOptions](const std::string &)
6124 1018 : { psOptions->eResampleAlg = GRA_Bilinear; })
6125 1018 : .help(_("Bilinear resampling."));
6126 :
6127 : // Non-documented alias of -r cubic
6128 1018 : argParser->add_argument("-rc")
6129 1018 : .flag()
6130 1018 : .hidden()
6131 1 : .action([psOptions](const std::string &)
6132 1018 : { psOptions->eResampleAlg = GRA_Cubic; })
6133 1018 : .help(_("Cubic resampling."));
6134 :
6135 : // Non-documented alias of -r cubicspline
6136 1018 : argParser->add_argument("-rcs")
6137 1018 : .flag()
6138 1018 : .hidden()
6139 1 : .action([psOptions](const std::string &)
6140 1018 : { psOptions->eResampleAlg = GRA_CubicSpline; })
6141 1018 : .help(_("Cubic spline resampling."));
6142 :
6143 : // Non-documented alias of -r lanczos
6144 1018 : argParser->add_argument("-rl")
6145 1018 : .flag()
6146 1018 : .hidden()
6147 0 : .action([psOptions](const std::string &)
6148 1018 : { psOptions->eResampleAlg = GRA_Lanczos; })
6149 1018 : .help(_("Lanczos resampling."));
6150 :
6151 : // Non-documented alias of -r average
6152 1018 : argParser->add_argument("-ra")
6153 1018 : .flag()
6154 1018 : .hidden()
6155 0 : .action([psOptions](const std::string &)
6156 1018 : { psOptions->eResampleAlg = GRA_Average; })
6157 1018 : .help(_("Average resampling."));
6158 :
6159 : // Non-documented alias of -r rms
6160 1018 : argParser->add_argument("-rrms")
6161 1018 : .flag()
6162 1018 : .hidden()
6163 0 : .action([psOptions](const std::string &)
6164 1018 : { psOptions->eResampleAlg = GRA_RMS; })
6165 1018 : .help(_("RMS resampling."));
6166 :
6167 : // Non-documented alias of -r mode
6168 1018 : argParser->add_argument("-rm")
6169 1018 : .flag()
6170 1018 : .hidden()
6171 0 : .action([psOptions](const std::string &)
6172 1018 : { psOptions->eResampleAlg = GRA_Mode; })
6173 1018 : .help(_("Mode resampling."));
6174 :
6175 1018 : argParser->add_argument("-cutline")
6176 2036 : .metavar("<datasource>|<WKT>")
6177 1018 : .store_into(psOptions->osCutlineDSNameOrWKT)
6178 : .help(_("Enable use of a blend cutline from the name of a vector "
6179 1018 : "dataset or a WKT geometry."));
6180 :
6181 1018 : argParser->add_argument("-cutline_srs")
6182 2036 : .metavar("<srs_def>")
6183 : .action(
6184 6 : [psOptions](const std::string &s)
6185 : {
6186 3 : if (!IsValidSRS(s.c_str()))
6187 : {
6188 0 : throw std::invalid_argument("Invalid SRS for -cutline_srs");
6189 : }
6190 3 : psOptions->osCutlineSRS = s;
6191 1021 : })
6192 1018 : .help(_("Sets/overrides cutline SRS."));
6193 :
6194 1018 : argParser->add_argument("-cwhere")
6195 2036 : .metavar("<expression>")
6196 1018 : .store_into(psOptions->osCWHERE)
6197 1018 : .help(_("Restrict desired cutline features based on attribute query."));
6198 :
6199 : {
6200 1018 : auto &group = argParser->add_mutually_exclusive_group();
6201 1018 : group.add_argument("-cl")
6202 2036 : .metavar("<layername>")
6203 1018 : .store_into(psOptions->osCLayer)
6204 1018 : .help(_("Select the named layer from the cutline datasource."));
6205 :
6206 1018 : group.add_argument("-csql")
6207 2036 : .metavar("<query>")
6208 1018 : .store_into(psOptions->osCSQL)
6209 1018 : .help(_("Select cutline features using an SQL query."));
6210 : }
6211 :
6212 1018 : argParser->add_argument("-cblend")
6213 2036 : .metavar("<distance>")
6214 : .action(
6215 0 : [psOptions](const std::string &s) {
6216 : psOptions->aosWarpOptions.SetNameValue("CUTLINE_BLEND_DIST",
6217 0 : s.c_str());
6218 1018 : })
6219 : .help(_(
6220 1018 : "Set a blend distance to use to blend over cutlines (in pixels)."));
6221 :
6222 1018 : argParser->add_argument("-crop_to_cutline")
6223 1018 : .flag()
6224 : .action(
6225 18 : [psOptions](const std::string &)
6226 : {
6227 18 : psOptions->bCropToCutline = true;
6228 18 : psOptions->bCreateOutput = true;
6229 1018 : })
6230 : .help(_("Crop the extent of the target dataset to the extent of the "
6231 1018 : "cutline."));
6232 :
6233 1018 : argParser->add_argument("-nomd")
6234 1018 : .flag()
6235 : .action(
6236 0 : [psOptions](const std::string &)
6237 : {
6238 0 : psOptions->bCopyMetadata = false;
6239 0 : psOptions->bCopyBandInfo = false;
6240 1018 : })
6241 1018 : .help(_("Do not copy metadata."));
6242 :
6243 1018 : argParser->add_argument("-cvmd")
6244 2036 : .metavar("<meta_conflict_value>")
6245 1018 : .store_into(psOptions->osMDConflictValue)
6246 : .help(_("Value to set metadata items that conflict between source "
6247 1018 : "datasets."));
6248 :
6249 1018 : argParser->add_argument("-setci")
6250 1018 : .flag()
6251 1018 : .store_into(psOptions->bSetColorInterpretation)
6252 : .help(_("Set the color interpretation of the bands of the target "
6253 1018 : "dataset from the source dataset."));
6254 :
6255 : argParser->add_open_options_argument(
6256 1018 : psOptionsForBinary ? &(psOptionsForBinary->aosOpenOptions) : nullptr);
6257 :
6258 1018 : argParser->add_argument("-doo")
6259 2036 : .metavar("<NAME>=<VALUE>")
6260 1018 : .append()
6261 : .action(
6262 0 : [psOptionsForBinary](const std::string &s)
6263 : {
6264 0 : if (psOptionsForBinary)
6265 0 : psOptionsForBinary->aosDestOpenOptions.AddString(s.c_str());
6266 1018 : })
6267 1018 : .help(_("Open option(s) for output dataset."));
6268 :
6269 1018 : argParser->add_argument("-ovr")
6270 2036 : .metavar("<level>|AUTO|AUTO-<n>|NONE")
6271 : .action(
6272 24 : [psOptions](const std::string &s)
6273 : {
6274 12 : const char *pszOvLevel = s.c_str();
6275 12 : if (EQUAL(pszOvLevel, "AUTO"))
6276 1 : psOptions->nOvLevel = OVR_LEVEL_AUTO;
6277 11 : else if (STARTS_WITH_CI(pszOvLevel, "AUTO-"))
6278 1 : psOptions->nOvLevel =
6279 1 : OVR_LEVEL_AUTO - atoi(pszOvLevel + strlen("AUTO-"));
6280 10 : else if (EQUAL(pszOvLevel, "NONE"))
6281 5 : psOptions->nOvLevel = OVR_LEVEL_NONE;
6282 5 : else if (CPLGetValueType(pszOvLevel) == CPL_VALUE_INTEGER)
6283 5 : psOptions->nOvLevel = atoi(pszOvLevel);
6284 : else
6285 : {
6286 : throw std::invalid_argument(CPLSPrintf(
6287 0 : "Invalid value '%s' for -ov option", pszOvLevel));
6288 : }
6289 1030 : })
6290 1018 : .help(_("Specify which overview level of source files must be used."));
6291 :
6292 : {
6293 1018 : auto &group = argParser->add_mutually_exclusive_group();
6294 1018 : group.add_argument("-vshift")
6295 1018 : .flag()
6296 1018 : .store_into(psOptions->bVShift)
6297 1018 : .help(_("Force the use of vertical shift."));
6298 1018 : group.add_argument("-novshift", "-novshiftgrid")
6299 1018 : .flag()
6300 1018 : .store_into(psOptions->bNoVShift)
6301 1018 : .help(_("Disable the use of vertical shift."));
6302 : }
6303 :
6304 : argParser->add_input_format_argument(
6305 : psOptionsForBinary ? &psOptionsForBinary->aosAllowedInputDrivers
6306 1018 : : nullptr);
6307 :
6308 1018 : argParser->add_argument("-b", "-srcband")
6309 2036 : .metavar("<band>")
6310 1018 : .append()
6311 1018 : .store_into(psOptions->anSrcBands)
6312 1018 : .help(_("Specify input band(s) number to warp."));
6313 :
6314 1018 : argParser->add_argument("-dstband")
6315 2036 : .metavar("<band>")
6316 1018 : .append()
6317 1018 : .store_into(psOptions->anDstBands)
6318 1018 : .help(_("Specify the output band number in which to warp."));
6319 :
6320 1018 : if (psOptionsForBinary)
6321 : {
6322 92 : argParser->add_argument("src_dataset_name")
6323 184 : .metavar("<src_dataset_name>")
6324 92 : .nargs(argparse::nargs_pattern::at_least_one)
6325 93 : .action([psOptionsForBinary](const std::string &s)
6326 185 : { psOptionsForBinary->aosSrcFiles.AddString(s.c_str()); })
6327 92 : .help(_("Input dataset(s)."));
6328 :
6329 92 : argParser->add_argument("dst_dataset_name")
6330 184 : .metavar("<dst_dataset_name>")
6331 92 : .store_into(psOptionsForBinary->osDstFilename)
6332 92 : .help(_("Output dataset."));
6333 : }
6334 :
6335 2036 : return argParser;
6336 : }
6337 :
6338 : /************************************************************************/
6339 : /* GDALWarpAppGetParserUsage() */
6340 : /************************************************************************/
6341 :
6342 2 : std::string GDALWarpAppGetParserUsage()
6343 : {
6344 : try
6345 : {
6346 4 : GDALWarpAppOptions sOptions;
6347 4 : GDALWarpAppOptionsForBinary sOptionsForBinary;
6348 : auto argParser =
6349 4 : GDALWarpAppOptionsGetParser(&sOptions, &sOptionsForBinary);
6350 2 : return argParser->usage();
6351 : }
6352 0 : catch (const std::exception &err)
6353 : {
6354 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
6355 0 : err.what());
6356 0 : return std::string();
6357 : }
6358 : }
6359 :
6360 : /************************************************************************/
6361 : /* GDALWarpAppOptionsNew() */
6362 : /************************************************************************/
6363 :
6364 : #ifndef CheckHasEnoughAdditionalArgs_defined
6365 : #define CheckHasEnoughAdditionalArgs_defined
6366 :
6367 75 : static bool CheckHasEnoughAdditionalArgs(CSLConstList papszArgv, int i,
6368 : int nExtraArg, int nArgc)
6369 : {
6370 75 : if (i + nExtraArg >= nArgc)
6371 : {
6372 0 : CPLError(CE_Failure, CPLE_IllegalArg,
6373 0 : "%s option requires %d argument%s", papszArgv[i], nExtraArg,
6374 : nExtraArg == 1 ? "" : "s");
6375 0 : return false;
6376 : }
6377 75 : return true;
6378 : }
6379 : #endif
6380 :
6381 : #define CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(nExtraArg) \
6382 : if (!CheckHasEnoughAdditionalArgs(papszArgv, i, nExtraArg, nArgc)) \
6383 : { \
6384 : return nullptr; \
6385 : }
6386 :
6387 : /**
6388 : * Allocates a GDALWarpAppOptions struct.
6389 : *
6390 : * @param papszArgv NULL terminated list of options (potentially including
6391 : * filename and open options too), or NULL. The accepted options are the ones of
6392 : * the <a href="/programs/gdalwarp.html">gdalwarp</a> utility.
6393 : * @param psOptionsForBinary (output) may be NULL (and should generally be
6394 : * NULL), otherwise (gdal_translate_bin.cpp use case) must be allocated with
6395 : * GDALWarpAppOptionsForBinaryNew() prior to this
6396 : * function. Will be filled with potentially present filename, open options,...
6397 : * @return pointer to the allocated GDALWarpAppOptions struct. Must be freed
6398 : * with GDALWarpAppOptionsFree().
6399 : *
6400 : * @since GDAL 2.1
6401 : */
6402 :
6403 : GDALWarpAppOptions *
6404 1016 : GDALWarpAppOptionsNew(char **papszArgv,
6405 : GDALWarpAppOptionsForBinary *psOptionsForBinary)
6406 : {
6407 2032 : auto psOptions = std::make_unique<GDALWarpAppOptions>();
6408 :
6409 1016 : psOptions->aosArgs.Assign(CSLDuplicate(papszArgv), true);
6410 :
6411 : /* -------------------------------------------------------------------- */
6412 : /* Pre-processing for custom syntax that ArgumentParser does not */
6413 : /* support. */
6414 : /* -------------------------------------------------------------------- */
6415 :
6416 2032 : CPLStringList aosArgv;
6417 1016 : const int nArgc = CSLCount(papszArgv);
6418 6658 : for (int i = 0;
6419 6658 : i < nArgc && papszArgv != nullptr && papszArgv[i] != nullptr; i++)
6420 : {
6421 5642 : if (EQUAL(papszArgv[i], "-refine_gcps"))
6422 : {
6423 0 : CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
6424 0 : psOptions->aosTransformerOptions.SetNameValue("REFINE_TOLERANCE",
6425 0 : papszArgv[++i]);
6426 0 : if (CPLAtof(papszArgv[i]) < 0)
6427 : {
6428 0 : CPLError(CE_Failure, CPLE_IllegalArg,
6429 : "The tolerance for -refine_gcps may not be negative.");
6430 0 : return nullptr;
6431 : }
6432 0 : if (i < nArgc - 1 && atoi(papszArgv[i + 1]) >= 0 &&
6433 0 : isdigit(static_cast<unsigned char>(papszArgv[i + 1][0])))
6434 : {
6435 0 : psOptions->aosTransformerOptions.SetNameValue(
6436 0 : "REFINE_MINIMUM_GCPS", papszArgv[++i]);
6437 : }
6438 : else
6439 : {
6440 0 : psOptions->aosTransformerOptions.SetNameValue(
6441 0 : "REFINE_MINIMUM_GCPS", "-1");
6442 : }
6443 : }
6444 5642 : else if (EQUAL(papszArgv[i], "-tr") && i + 1 < nArgc &&
6445 76 : EQUAL(papszArgv[i + 1], "square"))
6446 : {
6447 1 : ++i;
6448 1 : psOptions->bSquarePixels = true;
6449 1 : psOptions->bCreateOutput = true;
6450 : }
6451 5641 : else if (EQUAL(papszArgv[i], "-tr"))
6452 : {
6453 75 : CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2);
6454 75 : psOptions->dfXRes = CPLAtofM(papszArgv[++i]);
6455 75 : psOptions->dfYRes = fabs(CPLAtofM(papszArgv[++i]));
6456 75 : if (psOptions->dfXRes == 0 || psOptions->dfYRes == 0)
6457 : {
6458 0 : CPLError(CE_Failure, CPLE_IllegalArg,
6459 : "Wrong value for -tr parameters.");
6460 0 : return nullptr;
6461 : }
6462 75 : psOptions->bCreateOutput = true;
6463 : }
6464 : // argparser will be confused if the value of a string argument
6465 : // starts with a negative sign.
6466 5566 : else if (EQUAL(papszArgv[i], "-srcnodata") && i + 1 < nArgc)
6467 : {
6468 28 : ++i;
6469 28 : psOptions->osSrcNodata = papszArgv[i];
6470 : }
6471 : // argparser will be confused if the value of a string argument
6472 : // starts with a negative sign.
6473 5538 : else if (EQUAL(papszArgv[i], "-dstnodata") && i + 1 < nArgc)
6474 : {
6475 56 : ++i;
6476 56 : psOptions->osDstNodata = papszArgv[i];
6477 : }
6478 : else
6479 : {
6480 5482 : aosArgv.AddString(papszArgv[i]);
6481 : }
6482 : }
6483 :
6484 : try
6485 : {
6486 : auto argParser =
6487 2032 : GDALWarpAppOptionsGetParser(psOptions.get(), psOptionsForBinary);
6488 :
6489 1016 : argParser->parse_args_without_binary_name(aosArgv.List());
6490 :
6491 1182 : if (auto oTS = argParser->present<std::vector<int>>("-ts"))
6492 : {
6493 170 : psOptions->nForcePixels = (*oTS)[0];
6494 170 : psOptions->nForceLines = (*oTS)[1];
6495 170 : psOptions->bCreateOutput = true;
6496 : }
6497 :
6498 1172 : if (auto oTE = argParser->present<std::vector<double>>("-te"))
6499 : {
6500 160 : psOptions->dfMinX = (*oTE)[0];
6501 160 : psOptions->dfMinY = (*oTE)[1];
6502 160 : psOptions->dfMaxX = (*oTE)[2];
6503 160 : psOptions->dfMaxY = (*oTE)[3];
6504 160 : psOptions->aosTransformerOptions.SetNameValue(
6505 : "TARGET_EXTENT",
6506 160 : CPLSPrintf("%.17g,%.17g,%.17g,%.17g", psOptions->dfMinX,
6507 320 : psOptions->dfMinY, psOptions->dfMaxX,
6508 160 : psOptions->dfMaxY));
6509 160 : psOptions->bCreateOutput = true;
6510 : }
6511 :
6512 1017 : if (!psOptions->anDstBands.empty() &&
6513 5 : psOptions->anSrcBands.size() != psOptions->anDstBands.size())
6514 : {
6515 1 : CPLError(
6516 : CE_Failure, CPLE_IllegalArg,
6517 : "-srcband should be specified as many times as -dstband is");
6518 1 : return nullptr;
6519 : }
6520 1029 : else if (!psOptions->anSrcBands.empty() &&
6521 18 : psOptions->anDstBands.empty())
6522 : {
6523 37 : for (int i = 0; i < static_cast<int>(psOptions->anSrcBands.size());
6524 : ++i)
6525 : {
6526 23 : psOptions->anDstBands.push_back(i + 1);
6527 : }
6528 : }
6529 :
6530 1517 : if (!psOptions->osFormat.empty() ||
6531 506 : psOptions->eOutputType != GDT_Unknown)
6532 : {
6533 511 : psOptions->bCreateOutput = true;
6534 : }
6535 :
6536 1011 : if (psOptionsForBinary)
6537 88 : psOptionsForBinary->bCreateOutput = psOptions->bCreateOutput;
6538 :
6539 1011 : return psOptions.release();
6540 : }
6541 4 : catch (const std::exception &err)
6542 : {
6543 4 : CPLError(CE_Failure, CPLE_AppDefined, "%s", err.what());
6544 4 : return nullptr;
6545 : }
6546 : }
6547 :
6548 : /************************************************************************/
6549 : /* GDALWarpAppOptionsFree() */
6550 : /************************************************************************/
6551 :
6552 : /**
6553 : * Frees the GDALWarpAppOptions struct.
6554 : *
6555 : * @param psOptions the options struct for GDALWarp().
6556 : *
6557 : * @since GDAL 2.1
6558 : */
6559 :
6560 1011 : void GDALWarpAppOptionsFree(GDALWarpAppOptions *psOptions)
6561 : {
6562 1011 : delete psOptions;
6563 1011 : }
6564 :
6565 : /************************************************************************/
6566 : /* GDALWarpAppOptionsSetProgress() */
6567 : /************************************************************************/
6568 :
6569 : /**
6570 : * Set a progress function.
6571 : *
6572 : * @param psOptions the options struct for GDALWarp().
6573 : * @param pfnProgress the progress callback.
6574 : * @param pProgressData the user data for the progress callback.
6575 : *
6576 : * @since GDAL 2.1
6577 : */
6578 :
6579 128 : void GDALWarpAppOptionsSetProgress(GDALWarpAppOptions *psOptions,
6580 : GDALProgressFunc pfnProgress,
6581 : void *pProgressData)
6582 : {
6583 128 : psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
6584 128 : psOptions->pProgressData = pProgressData;
6585 128 : if (pfnProgress == GDALTermProgress)
6586 0 : psOptions->bQuiet = false;
6587 128 : }
6588 :
6589 : /************************************************************************/
6590 : /* GDALWarpAppOptionsSetQuiet() */
6591 : /************************************************************************/
6592 :
6593 : /**
6594 : * Set a progress function.
6595 : *
6596 : * @param psOptions the options struct for GDALWarp().
6597 : * @param bQuiet whether GDALWarp() should emit messages on stdout.
6598 : *
6599 : * @since GDAL 2.3
6600 : */
6601 :
6602 81 : void GDALWarpAppOptionsSetQuiet(GDALWarpAppOptions *psOptions, int bQuiet)
6603 : {
6604 81 : psOptions->bQuiet = CPL_TO_BOOL(bQuiet);
6605 81 : }
6606 :
6607 : /************************************************************************/
6608 : /* GDALWarpAppOptionsSetWarpOption() */
6609 : /************************************************************************/
6610 :
6611 : /**
6612 : * Set a warp option
6613 : *
6614 : * @param psOptions the options struct for GDALWarp().
6615 : * @param pszKey key.
6616 : * @param pszValue value.
6617 : *
6618 : * @since GDAL 2.1
6619 : */
6620 :
6621 0 : void GDALWarpAppOptionsSetWarpOption(GDALWarpAppOptions *psOptions,
6622 : const char *pszKey, const char *pszValue)
6623 : {
6624 0 : psOptions->aosWarpOptions.SetNameValue(pszKey, pszValue);
6625 0 : }
6626 :
6627 : #undef CHECK_HAS_ENOUGH_ADDITIONAL_ARGS
|