Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL Utilities
4 : * Purpose: Command line application to build VRT datasets from raster products
5 : * or content of SHP tile index
6 : * Author: Even Rouault, <even dot rouault at spatialys dot com>
7 : *
8 : ******************************************************************************
9 : * Copyright (c) 2007-2016, Even Rouault <even dot rouault at spatialys dot com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "ogr_api.h"
15 : #include "ogr_srs_api.h"
16 :
17 : #include "cpl_port.h"
18 : #include "gdal_utils.h"
19 : #include "gdal_utils_priv.h"
20 : #include "gdalargumentparser.h"
21 :
22 : #include <cassert>
23 : #include <cmath>
24 : #include <cstdio>
25 : #include <cstdlib>
26 : #include <cstring>
27 :
28 : #include <algorithm>
29 : #include <memory>
30 : #include <set>
31 : #include <string>
32 : #include <vector>
33 :
34 : #include "commonutils.h"
35 : #include "cpl_conv.h"
36 : #include "cpl_error.h"
37 : #include "cpl_float.h"
38 : #include "cpl_progress.h"
39 : #include "cpl_string.h"
40 : #include "cpl_vsi.h"
41 : #include "cpl_vsi_virtual.h"
42 : #include "gdal.h"
43 : #include "gdal_vrt.h"
44 : #include "gdal_priv.h"
45 : #include "gdal_proxy.h"
46 : #include "ogr_api.h"
47 : #include "ogr_core.h"
48 : #include "ogr_srs_api.h"
49 : #include "ogr_spatialref.h"
50 : #include "ogrsf_frmts.h"
51 : #include "vrtdataset.h"
52 :
53 : #define GEOTRSFRM_TOPLEFT_X 0
54 : #define GEOTRSFRM_WE_RES 1
55 : #define GEOTRSFRM_ROTATION_PARAM1 2
56 : #define GEOTRSFRM_TOPLEFT_Y 3
57 : #define GEOTRSFRM_ROTATION_PARAM2 4
58 : #define GEOTRSFRM_NS_RES 5
59 :
60 : namespace gdal::GDALBuildVRT
61 : {
62 : typedef enum
63 : {
64 : LOWEST_RESOLUTION,
65 : HIGHEST_RESOLUTION,
66 : AVERAGE_RESOLUTION,
67 : SAME_RESOLUTION,
68 : USER_RESOLUTION,
69 : COMMON_RESOLUTION,
70 : } ResolutionStrategy;
71 :
72 : struct DatasetProperty
73 : {
74 : int isFileOK = FALSE;
75 : int nRasterXSize = 0;
76 : int nRasterYSize = 0;
77 : GDALGeoTransform gt{};
78 : int nBlockXSize = 0;
79 : int nBlockYSize = 0;
80 : std::vector<GDALDataType> aeBandType{};
81 : std::vector<bool> abHasNoData{};
82 : std::vector<double> adfNoDataValues{};
83 : std::vector<bool> abHasOffset{};
84 : std::vector<double> adfOffset{};
85 : std::vector<bool> abHasScale{};
86 : std::vector<bool> abHasMaskBand{};
87 : std::vector<double> adfScale{};
88 : int bHasDatasetMask = 0;
89 : bool bLastBandIsAlpha = false;
90 : int nMaskBlockXSize = 0;
91 : int nMaskBlockYSize = 0;
92 : std::vector<int> anOverviewFactors{};
93 : };
94 :
95 : struct BandProperty
96 : {
97 : GDALColorInterp colorInterpretation = GCI_Undefined;
98 : GDALDataType dataType = GDT_Unknown;
99 : std::unique_ptr<GDALColorTable> colorTable{};
100 : bool bHasNoData = false;
101 : double noDataValue = 0;
102 : bool bHasOffset = false;
103 : double dfOffset = 0;
104 : bool bHasScale = false;
105 : double dfScale = 0;
106 : };
107 : } // namespace gdal::GDALBuildVRT
108 :
109 : using namespace gdal::GDALBuildVRT;
110 :
111 : /************************************************************************/
112 : /* GetSrcDstWin() */
113 : /************************************************************************/
114 :
115 2342 : static int GetSrcDstWin(DatasetProperty *psDP, double we_res, double ns_res,
116 : double minX, double minY, double maxX, double maxY,
117 : int nTargetXSize, int nTargetYSize, double *pdfSrcXOff,
118 : double *pdfSrcYOff, double *pdfSrcXSize,
119 : double *pdfSrcYSize, double *pdfDstXOff,
120 : double *pdfDstYOff, double *pdfDstXSize,
121 : double *pdfDstYSize)
122 : {
123 2342 : if (we_res == 0 || ns_res == 0)
124 : {
125 : // should not happen. to please Coverity
126 0 : return FALSE;
127 : }
128 :
129 : /* Check that the destination bounding box intersects the source bounding
130 : * box */
131 2342 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] +
132 2342 : psDP->nRasterXSize * psDP->gt[GEOTRSFRM_WE_RES] <=
133 : minX)
134 0 : return FALSE;
135 2342 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] >= maxX)
136 1 : return FALSE;
137 2341 : if (psDP->gt[GEOTRSFRM_TOPLEFT_Y] +
138 2341 : psDP->nRasterYSize * psDP->gt[GEOTRSFRM_NS_RES] >=
139 : maxY)
140 0 : return FALSE;
141 2341 : if (psDP->gt[GEOTRSFRM_TOPLEFT_Y] <= minY)
142 0 : return FALSE;
143 :
144 2341 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] < minX)
145 : {
146 3 : *pdfSrcXOff =
147 3 : (minX - psDP->gt[GEOTRSFRM_TOPLEFT_X]) / psDP->gt[GEOTRSFRM_WE_RES];
148 3 : *pdfDstXOff = 0.0;
149 : }
150 : else
151 : {
152 2338 : *pdfSrcXOff = 0.0;
153 2338 : *pdfDstXOff = ((psDP->gt[GEOTRSFRM_TOPLEFT_X] - minX) / we_res);
154 : }
155 2341 : if (maxY < psDP->gt[GEOTRSFRM_TOPLEFT_Y])
156 : {
157 5 : *pdfSrcYOff = (psDP->gt[GEOTRSFRM_TOPLEFT_Y] - maxY) /
158 5 : -psDP->gt[GEOTRSFRM_NS_RES];
159 5 : *pdfDstYOff = 0.0;
160 : }
161 : else
162 : {
163 2336 : *pdfSrcYOff = 0.0;
164 2336 : *pdfDstYOff = ((maxY - psDP->gt[GEOTRSFRM_TOPLEFT_Y]) / -ns_res);
165 : }
166 :
167 2341 : *pdfSrcXSize = psDP->nRasterXSize;
168 2341 : *pdfSrcYSize = psDP->nRasterYSize;
169 2341 : if (*pdfSrcXOff > 0)
170 3 : *pdfSrcXSize -= *pdfSrcXOff;
171 2341 : if (*pdfSrcYOff > 0)
172 5 : *pdfSrcYSize -= *pdfSrcYOff;
173 :
174 2341 : const double dfSrcToDstXSize = psDP->gt[GEOTRSFRM_WE_RES] / we_res;
175 2341 : *pdfDstXSize = *pdfSrcXSize * dfSrcToDstXSize;
176 2341 : const double dfSrcToDstYSize = psDP->gt[GEOTRSFRM_NS_RES] / ns_res;
177 2341 : *pdfDstYSize = *pdfSrcYSize * dfSrcToDstYSize;
178 :
179 2341 : if (*pdfDstXOff + *pdfDstXSize > nTargetXSize)
180 : {
181 7 : *pdfDstXSize = nTargetXSize - *pdfDstXOff;
182 7 : *pdfSrcXSize = *pdfDstXSize / dfSrcToDstXSize;
183 : }
184 :
185 2341 : if (*pdfDstYOff + *pdfDstYSize > nTargetYSize)
186 : {
187 5 : *pdfDstYSize = nTargetYSize - *pdfDstYOff;
188 5 : *pdfSrcYSize = *pdfDstYSize / dfSrcToDstYSize;
189 : }
190 :
191 4682 : return *pdfSrcXSize > 0 && *pdfDstXSize > 0 && *pdfSrcYSize > 0 &&
192 4682 : *pdfDstYSize > 0;
193 : }
194 :
195 : /************************************************************************/
196 : /* VRTBuilder */
197 : /************************************************************************/
198 :
199 : class VRTBuilder
200 : {
201 : /* Input parameters */
202 : bool bStrict = false;
203 : char *pszOutputFilename = nullptr;
204 : int nInputFiles = 0;
205 : char **ppszInputFilenames = nullptr;
206 : int nSrcDSCount = 0;
207 : GDALDatasetH *pahSrcDS = nullptr;
208 : int nTotalBands = 0;
209 : bool bLastBandIsAlpha = false;
210 : bool bExplicitBandList = false;
211 : int nMaxSelectedBandNo = 0;
212 : int nSelectedBands = 0;
213 : int *panSelectedBandList = nullptr;
214 : ResolutionStrategy resolutionStrategy = AVERAGE_RESOLUTION;
215 : int nCountValid = 0;
216 : double we_res = 0;
217 : double ns_res = 0;
218 : int bTargetAlignedPixels = 0;
219 : double minX = 0;
220 : double minY = 0;
221 : double maxX = 0;
222 : double maxY = 0;
223 : int bSeparate = 0;
224 : int bAllowProjectionDifference = 0;
225 : int bAddAlpha = 0;
226 : int bHideNoData = 0;
227 : int nSubdataset = 0;
228 : char *pszSrcNoData = nullptr;
229 : char *pszVRTNoData = nullptr;
230 : char *pszOutputSRS = nullptr;
231 : char *pszResampling = nullptr;
232 : char **papszOpenOptions = nullptr;
233 : bool bUseSrcMaskBand = true;
234 : bool bNoDataFromMask = false;
235 : double dfMaskValueThreshold = 0;
236 : const CPLStringList aosCreateOptions;
237 : std::string osPixelFunction{};
238 : const CPLStringList aosPixelFunctionArgs;
239 : const bool bWriteAbsolutePath;
240 :
241 : /* Internal variables */
242 : char *pszProjectionRef = nullptr;
243 : std::vector<BandProperty> asBandProperties{};
244 : int bFirst = TRUE;
245 : int bHasGeoTransform = 0;
246 : int nRasterXSize = 0;
247 : int nRasterYSize = 0;
248 : std::vector<DatasetProperty> asDatasetProperties{};
249 : int bUserExtent = 0;
250 : int bAllowSrcNoData = TRUE;
251 : double *padfSrcNoData = nullptr;
252 : int nSrcNoDataCount = 0;
253 : int bAllowVRTNoData = TRUE;
254 : double *padfVRTNoData = nullptr;
255 : int nVRTNoDataCount = 0;
256 : int bHasRunBuild = 0;
257 : int bHasDatasetMask = 0;
258 :
259 : std::string AnalyseRaster(GDALDatasetH hDS,
260 : DatasetProperty *psDatasetProperties);
261 :
262 : void CreateVRTSeparate(VRTDataset *poVTDS);
263 : void CreateVRTNonSeparate(VRTDataset *poVRTDS);
264 :
265 : CPL_DISALLOW_COPY_ASSIGN(VRTBuilder)
266 :
267 : public:
268 : VRTBuilder(bool bStrictIn, const char *pszOutputFilename, int nInputFiles,
269 : const char *const *ppszInputFilenames, GDALDatasetH *pahSrcDSIn,
270 : const int *panSelectedBandListIn, int nBandCount,
271 : ResolutionStrategy resolutionStrategy, double we_res,
272 : double ns_res, int bTargetAlignedPixels, double minX,
273 : double minY, double maxX, double maxY, int bSeparate,
274 : int bAllowProjectionDifference, int bAddAlpha, int bHideNoData,
275 : int nSubdataset, const char *pszSrcNoData,
276 : const char *pszVRTNoData, bool bUseSrcMaskBand,
277 : bool bNoDataFromMask, double dfMaskValueThreshold,
278 : const char *pszOutputSRS, const char *pszResampling,
279 : const char *pszPixelFunctionName,
280 : const CPLStringList &aosPixelFunctionArgs,
281 : const char *const *papszOpenOptionsIn,
282 : const CPLStringList &aosCreateOptionsIn,
283 : bool bWriteAbsolutePathIn);
284 :
285 : ~VRTBuilder();
286 :
287 : std::unique_ptr<GDALDataset> Build(GDALProgressFunc pfnProgress,
288 : void *pProgressData);
289 :
290 : std::string m_osProgramName{};
291 : };
292 :
293 : /************************************************************************/
294 : /* VRTBuilder() */
295 : /************************************************************************/
296 :
297 221 : VRTBuilder::VRTBuilder(
298 : bool bStrictIn, const char *pszOutputFilenameIn, int nInputFilesIn,
299 : const char *const *ppszInputFilenamesIn, GDALDatasetH *pahSrcDSIn,
300 : const int *panSelectedBandListIn, int nBandCount,
301 : ResolutionStrategy resolutionStrategyIn, double we_resIn, double ns_resIn,
302 : int bTargetAlignedPixelsIn, double minXIn, double minYIn, double maxXIn,
303 : double maxYIn, int bSeparateIn, int bAllowProjectionDifferenceIn,
304 : int bAddAlphaIn, int bHideNoDataIn, int nSubdatasetIn,
305 : const char *pszSrcNoDataIn, const char *pszVRTNoDataIn,
306 : bool bUseSrcMaskBandIn, bool bNoDataFromMaskIn,
307 : double dfMaskValueThresholdIn, const char *pszOutputSRSIn,
308 : const char *pszResamplingIn, const char *pszPixelFunctionIn,
309 : const CPLStringList &aosPixelFunctionArgsIn,
310 : const char *const *papszOpenOptionsIn,
311 221 : const CPLStringList &aosCreateOptionsIn, bool bWriteAbsolutePathIn)
312 : : bStrict(bStrictIn), aosCreateOptions(aosCreateOptionsIn),
313 : aosPixelFunctionArgs(aosPixelFunctionArgsIn),
314 221 : bWriteAbsolutePath(bWriteAbsolutePathIn)
315 : {
316 221 : pszOutputFilename = CPLStrdup(pszOutputFilenameIn);
317 221 : nInputFiles = nInputFilesIn;
318 221 : papszOpenOptions = CSLDuplicate(const_cast<char **>(papszOpenOptionsIn));
319 :
320 221 : if (pszPixelFunctionIn != nullptr)
321 : {
322 3 : osPixelFunction = pszPixelFunctionIn;
323 : }
324 :
325 221 : if (ppszInputFilenamesIn)
326 : {
327 133 : ppszInputFilenames =
328 133 : static_cast<char **>(CPLMalloc(nInputFiles * sizeof(char *)));
329 1355 : for (int i = 0; i < nInputFiles; i++)
330 : {
331 1222 : ppszInputFilenames[i] = CPLStrdup(ppszInputFilenamesIn[i]);
332 : }
333 : }
334 88 : else if (pahSrcDSIn)
335 : {
336 88 : nSrcDSCount = nInputFiles;
337 88 : pahSrcDS = static_cast<GDALDatasetH *>(
338 88 : CPLMalloc(nInputFiles * sizeof(GDALDatasetH)));
339 88 : memcpy(pahSrcDS, pahSrcDSIn, nInputFiles * sizeof(GDALDatasetH));
340 88 : ppszInputFilenames =
341 88 : static_cast<char **>(CPLMalloc(nInputFiles * sizeof(char *)));
342 1227 : for (int i = 0; i < nInputFiles; i++)
343 : {
344 2278 : ppszInputFilenames[i] =
345 1139 : CPLStrdup(GDALGetDescription(pahSrcDSIn[i]));
346 : }
347 : }
348 :
349 221 : bExplicitBandList = nBandCount != 0;
350 221 : nSelectedBands = nBandCount;
351 221 : if (nBandCount)
352 : {
353 19 : panSelectedBandList =
354 19 : static_cast<int *>(CPLMalloc(nSelectedBands * sizeof(int)));
355 19 : memcpy(panSelectedBandList, panSelectedBandListIn,
356 19 : nSelectedBands * sizeof(int));
357 : }
358 :
359 221 : resolutionStrategy = resolutionStrategyIn;
360 221 : we_res = we_resIn;
361 221 : ns_res = ns_resIn;
362 221 : bTargetAlignedPixels = bTargetAlignedPixelsIn;
363 221 : minX = minXIn;
364 221 : minY = minYIn;
365 221 : maxX = maxXIn;
366 221 : maxY = maxYIn;
367 221 : bSeparate = bSeparateIn;
368 221 : bAllowProjectionDifference = bAllowProjectionDifferenceIn;
369 221 : bAddAlpha = bAddAlphaIn;
370 221 : bHideNoData = bHideNoDataIn;
371 221 : nSubdataset = nSubdatasetIn;
372 221 : pszSrcNoData = (pszSrcNoDataIn) ? CPLStrdup(pszSrcNoDataIn) : nullptr;
373 221 : pszVRTNoData = (pszVRTNoDataIn) ? CPLStrdup(pszVRTNoDataIn) : nullptr;
374 221 : pszOutputSRS = (pszOutputSRSIn) ? CPLStrdup(pszOutputSRSIn) : nullptr;
375 221 : pszResampling = (pszResamplingIn) ? CPLStrdup(pszResamplingIn) : nullptr;
376 221 : bUseSrcMaskBand = bUseSrcMaskBandIn;
377 221 : bNoDataFromMask = bNoDataFromMaskIn;
378 221 : dfMaskValueThreshold = dfMaskValueThresholdIn;
379 221 : }
380 :
381 : /************************************************************************/
382 : /* ~VRTBuilder() */
383 : /************************************************************************/
384 :
385 221 : VRTBuilder::~VRTBuilder()
386 : {
387 221 : CPLFree(pszOutputFilename);
388 221 : CPLFree(pszSrcNoData);
389 221 : CPLFree(pszVRTNoData);
390 221 : CPLFree(panSelectedBandList);
391 :
392 221 : if (ppszInputFilenames)
393 : {
394 2582 : for (int i = 0; i < nInputFiles; i++)
395 : {
396 2361 : CPLFree(ppszInputFilenames[i]);
397 : }
398 : }
399 221 : CPLFree(ppszInputFilenames);
400 221 : CPLFree(pahSrcDS);
401 :
402 221 : CPLFree(pszProjectionRef);
403 221 : CPLFree(padfSrcNoData);
404 221 : CPLFree(padfVRTNoData);
405 221 : CPLFree(pszOutputSRS);
406 221 : CPLFree(pszResampling);
407 221 : CSLDestroy(papszOpenOptions);
408 221 : }
409 :
410 : /************************************************************************/
411 : /* ProjAreEqual() */
412 : /************************************************************************/
413 :
414 2138 : static int ProjAreEqual(const char *pszWKT1, const char *pszWKT2)
415 : {
416 2138 : if (EQUAL(pszWKT1, pszWKT2))
417 2136 : return TRUE;
418 :
419 2 : OGRSpatialReferenceH hSRS1 = OSRNewSpatialReference(pszWKT1);
420 2 : OGRSpatialReferenceH hSRS2 = OSRNewSpatialReference(pszWKT2);
421 2 : int bRet = hSRS1 != nullptr && hSRS2 != nullptr && OSRIsSame(hSRS1, hSRS2);
422 2 : if (hSRS1)
423 2 : OSRDestroySpatialReference(hSRS1);
424 2 : if (hSRS2)
425 2 : OSRDestroySpatialReference(hSRS2);
426 2 : return bRet;
427 : }
428 :
429 : /************************************************************************/
430 : /* GetProjectionName() */
431 : /************************************************************************/
432 :
433 4 : static CPLString GetProjectionName(const char *pszProjection)
434 : {
435 4 : if (!pszProjection)
436 0 : return "(null)";
437 :
438 8 : OGRSpatialReference oSRS;
439 4 : oSRS.SetFromUserInput(pszProjection);
440 4 : const char *pszRet = nullptr;
441 4 : if (oSRS.IsProjected())
442 0 : pszRet = oSRS.GetAttrValue("PROJCS");
443 4 : else if (oSRS.IsGeographic())
444 3 : pszRet = oSRS.GetAttrValue("GEOGCS");
445 4 : return pszRet ? pszRet : "(null)";
446 : }
447 :
448 : /************************************************************************/
449 : /* AnalyseRaster() */
450 : /************************************************************************/
451 :
452 2348 : static void checkNoDataValues(const std::vector<BandProperty> &asProperties)
453 : {
454 5992 : for (const auto &oProps : asProperties)
455 : {
456 3698 : if (oProps.bHasNoData && GDALDataTypeIsInteger(oProps.dataType) &&
457 54 : !GDALIsValueExactAs(oProps.noDataValue, oProps.dataType))
458 : {
459 2 : CPLError(CE_Warning, CPLE_NotSupported,
460 : "Band data type of %s cannot represent the specified "
461 : "NoData value of %g",
462 2 : GDALGetDataTypeName(oProps.dataType), oProps.noDataValue);
463 : }
464 : }
465 2348 : }
466 :
467 2359 : std::string VRTBuilder::AnalyseRaster(GDALDatasetH hDS,
468 : DatasetProperty *psDatasetProperties)
469 : {
470 2359 : GDALDataset *poDS = GDALDataset::FromHandle(hDS);
471 2359 : const char *dsFileName = poDS->GetDescription();
472 2359 : char **papszMetadata = poDS->GetMetadata("SUBDATASETS");
473 2359 : if (CSLCount(papszMetadata) > 0 && poDS->GetRasterCount() == 0)
474 : {
475 0 : ppszInputFilenames = static_cast<char **>(CPLRealloc(
476 0 : ppszInputFilenames,
477 0 : sizeof(char *) * (nInputFiles + CSLCount(papszMetadata))));
478 0 : if (nSubdataset < 0)
479 : {
480 0 : int count = 1;
481 : char subdatasetNameKey[80];
482 0 : snprintf(subdatasetNameKey, sizeof(subdatasetNameKey),
483 : "SUBDATASET_%d_NAME", count);
484 0 : while (*papszMetadata != nullptr)
485 : {
486 0 : if (EQUALN(*papszMetadata, subdatasetNameKey,
487 : strlen(subdatasetNameKey)))
488 : {
489 0 : asDatasetProperties.resize(nInputFiles + 1);
490 0 : ppszInputFilenames[nInputFiles] = CPLStrdup(
491 0 : *papszMetadata + strlen(subdatasetNameKey) + 1);
492 0 : nInputFiles++;
493 0 : count++;
494 0 : snprintf(subdatasetNameKey, sizeof(subdatasetNameKey),
495 : "SUBDATASET_%d_NAME", count);
496 : }
497 0 : papszMetadata++;
498 : }
499 : }
500 : else
501 : {
502 : char subdatasetNameKey[80];
503 : const char *pszSubdatasetName;
504 :
505 0 : snprintf(subdatasetNameKey, sizeof(subdatasetNameKey),
506 : "SUBDATASET_%d_NAME", nSubdataset);
507 : pszSubdatasetName =
508 0 : CSLFetchNameValue(papszMetadata, subdatasetNameKey);
509 0 : if (pszSubdatasetName)
510 : {
511 0 : asDatasetProperties.resize(nInputFiles + 1);
512 0 : ppszInputFilenames[nInputFiles] = CPLStrdup(pszSubdatasetName);
513 0 : nInputFiles++;
514 : }
515 : }
516 0 : return "SILENTLY_IGNORE";
517 : }
518 :
519 2359 : const char *proj = poDS->GetProjectionRef();
520 2359 : auto > = psDatasetProperties->gt;
521 2359 : int bGotGeoTransform = poDS->GetGeoTransform(gt) == CE_None;
522 2359 : if (bSeparate)
523 : {
524 33 : std::string osProgramName(m_osProgramName);
525 33 : if (osProgramName == "gdalbuildvrt")
526 27 : osProgramName += " -separate";
527 :
528 33 : if (bFirst)
529 : {
530 18 : bHasGeoTransform = bGotGeoTransform;
531 18 : if (!bHasGeoTransform)
532 : {
533 1 : if (bUserExtent)
534 : {
535 0 : CPLError(CE_Warning, CPLE_NotSupported, "%s",
536 0 : ("User extent ignored by " + osProgramName +
537 : "with ungeoreferenced images.")
538 : .c_str());
539 : }
540 1 : if (resolutionStrategy == USER_RESOLUTION)
541 : {
542 0 : CPLError(CE_Warning, CPLE_NotSupported, "%s",
543 0 : ("User resolution ignored by " + osProgramName +
544 : " with ungeoreferenced images.")
545 : .c_str());
546 : }
547 : }
548 : }
549 15 : else if (bHasGeoTransform != bGotGeoTransform)
550 : {
551 : return osProgramName + " cannot stack ungeoreferenced and "
552 0 : "georeferenced images.";
553 : }
554 16 : else if (!bHasGeoTransform && (nRasterXSize != poDS->GetRasterXSize() ||
555 1 : nRasterYSize != poDS->GetRasterYSize()))
556 : {
557 : return osProgramName + " cannot stack ungeoreferenced images "
558 0 : "that have not the same dimensions.";
559 : }
560 : }
561 : else
562 : {
563 2326 : if (!bGotGeoTransform)
564 : {
565 0 : return m_osProgramName + " does not support ungeoreferenced image.";
566 : }
567 2326 : bHasGeoTransform = TRUE;
568 : }
569 :
570 2359 : if (bGotGeoTransform)
571 : {
572 4714 : if (gt[GEOTRSFRM_ROTATION_PARAM1] != 0 ||
573 2357 : gt[GEOTRSFRM_ROTATION_PARAM2] != 0)
574 : {
575 0 : return m_osProgramName +
576 0 : " does not support rotated geo transforms.";
577 : }
578 2357 : if (gt[GEOTRSFRM_NS_RES] >= 0)
579 : {
580 0 : return m_osProgramName +
581 0 : " does not support positive NS resolution.";
582 : }
583 : }
584 :
585 2359 : psDatasetProperties->nRasterXSize = poDS->GetRasterXSize();
586 2359 : psDatasetProperties->nRasterYSize = poDS->GetRasterYSize();
587 2359 : if (bFirst && bSeparate && !bGotGeoTransform)
588 : {
589 1 : nRasterXSize = poDS->GetRasterXSize();
590 1 : nRasterYSize = poDS->GetRasterYSize();
591 : }
592 :
593 2359 : double ds_minX = gt[GEOTRSFRM_TOPLEFT_X];
594 2359 : double ds_maxY = gt[GEOTRSFRM_TOPLEFT_Y];
595 2359 : double ds_maxX = ds_minX + GDALGetRasterXSize(hDS) * gt[GEOTRSFRM_WE_RES];
596 2359 : double ds_minY = ds_maxY + GDALGetRasterYSize(hDS) * gt[GEOTRSFRM_NS_RES];
597 :
598 2359 : int _nBands = GDALGetRasterCount(hDS);
599 2359 : if (_nBands == 0)
600 : {
601 0 : return "Dataset has no bands";
602 : }
603 2368 : if (bNoDataFromMask &&
604 9 : poDS->GetRasterBand(_nBands)->GetColorInterpretation() == GCI_AlphaBand)
605 3 : _nBands--;
606 :
607 2359 : GDALRasterBand *poFirstBand = poDS->GetRasterBand(1);
608 2359 : poFirstBand->GetBlockSize(&psDatasetProperties->nBlockXSize,
609 : &psDatasetProperties->nBlockYSize);
610 :
611 : /* For the -separate case */
612 2359 : psDatasetProperties->aeBandType.resize(_nBands);
613 :
614 2359 : psDatasetProperties->adfNoDataValues.resize(_nBands);
615 2359 : psDatasetProperties->abHasNoData.resize(_nBands);
616 :
617 2359 : psDatasetProperties->adfOffset.resize(_nBands);
618 2359 : psDatasetProperties->abHasOffset.resize(_nBands);
619 :
620 2359 : psDatasetProperties->adfScale.resize(_nBands);
621 2359 : psDatasetProperties->abHasScale.resize(_nBands);
622 :
623 2359 : psDatasetProperties->abHasMaskBand.resize(_nBands);
624 :
625 2359 : psDatasetProperties->bHasDatasetMask =
626 2359 : poFirstBand->GetMaskFlags() == GMF_PER_DATASET;
627 2359 : if (psDatasetProperties->bHasDatasetMask)
628 16 : bHasDatasetMask = TRUE;
629 2359 : poFirstBand->GetMaskBand()->GetBlockSize(
630 : &psDatasetProperties->nMaskBlockXSize,
631 : &psDatasetProperties->nMaskBlockYSize);
632 :
633 2359 : psDatasetProperties->bLastBandIsAlpha = false;
634 2359 : if (poDS->GetRasterBand(_nBands)->GetColorInterpretation() == GCI_AlphaBand)
635 14 : psDatasetProperties->bLastBandIsAlpha = true;
636 :
637 : // Collect overview factors. We only handle power-of-two situations for now
638 2359 : const int nOverviews = poFirstBand->GetOverviewCount();
639 2359 : int nExpectedOvFactor = 2;
640 2371 : for (int j = 0; j < nOverviews; j++)
641 : {
642 23 : GDALRasterBand *poOverview = poFirstBand->GetOverview(j);
643 23 : if (!poOverview)
644 0 : continue;
645 23 : if (poOverview->GetXSize() < 128 && poOverview->GetYSize() < 128)
646 : {
647 11 : break;
648 : }
649 :
650 12 : const int nOvFactor = GDALComputeOvFactor(
651 : poOverview->GetXSize(), poFirstBand->GetXSize(),
652 12 : poOverview->GetYSize(), poFirstBand->GetYSize());
653 :
654 12 : if (nOvFactor != nExpectedOvFactor)
655 0 : break;
656 :
657 12 : psDatasetProperties->anOverviewFactors.push_back(nOvFactor);
658 12 : nExpectedOvFactor *= 2;
659 : }
660 :
661 5887 : for (int j = 0; j < _nBands; j++)
662 : {
663 3528 : GDALRasterBand *poBand = poDS->GetRasterBand(j + 1);
664 :
665 3528 : psDatasetProperties->aeBandType[j] = poBand->GetRasterDataType();
666 :
667 3528 : if (!bSeparate && nSrcNoDataCount > 0)
668 : {
669 4 : psDatasetProperties->abHasNoData[j] = true;
670 4 : if (j < nSrcNoDataCount)
671 4 : psDatasetProperties->adfNoDataValues[j] = padfSrcNoData[j];
672 : else
673 0 : psDatasetProperties->adfNoDataValues[j] =
674 0 : padfSrcNoData[nSrcNoDataCount - 1];
675 : }
676 : else
677 : {
678 3524 : int bHasNoData = false;
679 7048 : psDatasetProperties->adfNoDataValues[j] =
680 3524 : poBand->GetNoDataValue(&bHasNoData);
681 3524 : psDatasetProperties->abHasNoData[j] = bHasNoData != 0;
682 : }
683 :
684 3528 : int bHasOffset = false;
685 3528 : psDatasetProperties->adfOffset[j] = poBand->GetOffset(&bHasOffset);
686 7056 : psDatasetProperties->abHasOffset[j] =
687 3528 : bHasOffset != 0 && psDatasetProperties->adfOffset[j] != 0.0;
688 :
689 3528 : int bHasScale = false;
690 3528 : psDatasetProperties->adfScale[j] = poBand->GetScale(&bHasScale);
691 7056 : psDatasetProperties->abHasScale[j] =
692 3528 : bHasScale != 0 && psDatasetProperties->adfScale[j] != 1.0;
693 :
694 3528 : const int nMaskFlags = poBand->GetMaskFlags();
695 3528 : psDatasetProperties->abHasMaskBand[j] =
696 6997 : (nMaskFlags != GMF_ALL_VALID && nMaskFlags != GMF_NODATA) ||
697 6997 : poBand->GetColorInterpretation() == GCI_AlphaBand;
698 : }
699 :
700 2359 : if (bSeparate)
701 : {
702 39 : for (int j = 0; j < nSelectedBands; j++)
703 : {
704 7 : if (panSelectedBandList[j] > _nBands)
705 : {
706 : return CPLSPrintf("%s has %d bands, but %d is requested",
707 1 : dsFileName, _nBands, panSelectedBandList[j]);
708 : }
709 : }
710 : }
711 :
712 2358 : if (bFirst)
713 : {
714 220 : nTotalBands = _nBands;
715 220 : if (bAddAlpha && psDatasetProperties->bLastBandIsAlpha)
716 : {
717 4 : bLastBandIsAlpha = true;
718 4 : nTotalBands--;
719 : }
720 :
721 220 : if (proj)
722 220 : pszProjectionRef = CPLStrdup(proj);
723 220 : if (!bUserExtent)
724 : {
725 207 : minX = ds_minX;
726 207 : minY = ds_minY;
727 207 : maxX = ds_maxX;
728 207 : maxY = ds_maxY;
729 : }
730 :
731 220 : if (!bSeparate)
732 : {
733 : // if not provided an explicit band list, take the one of the first
734 : // dataset
735 203 : if (nSelectedBands == 0)
736 : {
737 186 : nSelectedBands = nTotalBands;
738 186 : CPLFree(panSelectedBandList);
739 186 : panSelectedBandList =
740 186 : static_cast<int *>(CPLMalloc(nSelectedBands * sizeof(int)));
741 435 : for (int j = 0; j < nSelectedBands; j++)
742 : {
743 249 : panSelectedBandList[j] = j + 1;
744 : }
745 : }
746 681 : for (int j = 0; j < nSelectedBands; j++)
747 : {
748 478 : nMaxSelectedBandNo =
749 478 : std::max(nMaxSelectedBandNo, panSelectedBandList[j]);
750 : }
751 :
752 203 : asBandProperties.resize(nSelectedBands);
753 680 : for (int j = 0; j < nSelectedBands; j++)
754 : {
755 478 : const int nSelBand = panSelectedBandList[j];
756 478 : if (nSelBand <= 0 || nSelBand > nTotalBands)
757 : {
758 1 : return CPLSPrintf("Invalid band number: %d", nSelBand);
759 : }
760 477 : GDALRasterBand *poBand = poDS->GetRasterBand(nSelBand);
761 954 : asBandProperties[j].colorInterpretation =
762 477 : poBand->GetColorInterpretation();
763 477 : asBandProperties[j].dataType = poBand->GetRasterDataType();
764 477 : if (asBandProperties[j].colorInterpretation == GCI_PaletteIndex)
765 : {
766 2 : auto colorTable = poBand->GetColorTable();
767 2 : if (colorTable)
768 : {
769 2 : asBandProperties[j].colorTable.reset(
770 : colorTable->Clone());
771 : }
772 : }
773 : else
774 475 : asBandProperties[j].colorTable = nullptr;
775 :
776 477 : if (nVRTNoDataCount > 0)
777 : {
778 26 : asBandProperties[j].bHasNoData = true;
779 26 : if (j < nVRTNoDataCount)
780 20 : asBandProperties[j].noDataValue = padfVRTNoData[j];
781 : else
782 6 : asBandProperties[j].noDataValue =
783 6 : padfVRTNoData[nVRTNoDataCount - 1];
784 : }
785 : else
786 : {
787 451 : int bHasNoData = false;
788 902 : asBandProperties[j].noDataValue =
789 451 : poBand->GetNoDataValue(&bHasNoData);
790 451 : asBandProperties[j].bHasNoData = bHasNoData != 0;
791 : }
792 :
793 477 : int bHasOffset = false;
794 477 : asBandProperties[j].dfOffset = poBand->GetOffset(&bHasOffset);
795 477 : asBandProperties[j].bHasOffset =
796 477 : bHasOffset != 0 && asBandProperties[j].dfOffset != 0.0;
797 :
798 477 : int bHasScale = false;
799 477 : asBandProperties[j].dfScale = poBand->GetScale(&bHasScale);
800 477 : asBandProperties[j].bHasScale =
801 477 : bHasScale != 0 && asBandProperties[j].dfScale != 1.0;
802 : }
803 : }
804 : }
805 : else
806 : {
807 2138 : if ((proj != nullptr && pszProjectionRef == nullptr) ||
808 6414 : (proj == nullptr && pszProjectionRef != nullptr) ||
809 2138 : (proj != nullptr && pszProjectionRef != nullptr &&
810 2138 : ProjAreEqual(proj, pszProjectionRef) == FALSE))
811 : {
812 2 : if (!bAllowProjectionDifference)
813 : {
814 4 : CPLString osExpected = GetProjectionName(pszProjectionRef);
815 4 : CPLString osGot = GetProjectionName(proj);
816 2 : return m_osProgramName +
817 : CPLSPrintf(" does not support heterogeneous "
818 : "projection: expected %s, got %s.",
819 2 : osExpected.c_str(), osGot.c_str());
820 : }
821 : }
822 2136 : if (!bSeparate)
823 : {
824 2121 : if (!bExplicitBandList && _nBands != nTotalBands)
825 : {
826 9 : if (bAddAlpha && _nBands == nTotalBands + 1 &&
827 4 : psDatasetProperties->bLastBandIsAlpha)
828 : {
829 4 : bLastBandIsAlpha = true;
830 : }
831 : else
832 : {
833 5 : return m_osProgramName +
834 : CPLSPrintf(" does not support heterogeneous band "
835 : "numbers: expected %d, got %d.",
836 5 : nTotalBands, _nBands);
837 : }
838 : }
839 2112 : else if (bExplicitBandList && _nBands < nMaxSelectedBandNo)
840 : {
841 0 : return m_osProgramName +
842 : CPLSPrintf(" does not support heterogeneous band "
843 : "numbers: expected at least %d, got %d.",
844 0 : nMaxSelectedBandNo, _nBands);
845 : }
846 :
847 5285 : for (int j = 0; j < nSelectedBands; j++)
848 : {
849 3169 : const int nSelBand = panSelectedBandList[j];
850 3169 : CPLAssert(nSelBand >= 1 && nSelBand <= _nBands);
851 3169 : GDALRasterBand *poBand = poDS->GetRasterBand(nSelBand);
852 3169 : if (asBandProperties[j].colorInterpretation !=
853 3169 : poBand->GetColorInterpretation())
854 : {
855 0 : return m_osProgramName +
856 : CPLSPrintf(
857 : " does not support heterogeneous "
858 : "band color interpretation: expected %s, got "
859 : "%s.",
860 : GDALGetColorInterpretationName(
861 0 : asBandProperties[j].colorInterpretation),
862 : GDALGetColorInterpretationName(
863 0 : poBand->GetColorInterpretation()));
864 : }
865 3169 : if (asBandProperties[j].dataType != poBand->GetRasterDataType())
866 : {
867 0 : return m_osProgramName +
868 : CPLSPrintf(" does not support heterogeneous "
869 : "band data type: expected %s, got %s.",
870 : GDALGetDataTypeName(
871 0 : asBandProperties[j].dataType),
872 : GDALGetDataTypeName(
873 0 : poBand->GetRasterDataType()));
874 : }
875 3169 : if (asBandProperties[j].colorTable)
876 : {
877 2 : const GDALColorTable *colorTable = poBand->GetColorTable();
878 : int nRefColorEntryCount =
879 2 : asBandProperties[j].colorTable->GetColorEntryCount();
880 4 : if (colorTable == nullptr ||
881 2 : colorTable->GetColorEntryCount() != nRefColorEntryCount)
882 : {
883 0 : return m_osProgramName +
884 : " does not support rasters with "
885 : "different color tables (different number of "
886 0 : "color table entries)";
887 : }
888 :
889 : /* Check that the palette are the same too */
890 : /* We just warn and still process the file. It is not a
891 : * technical no-go, but the user */
892 : /* should check that the end result is OK for him. */
893 260 : for (int i = 0; i < nRefColorEntryCount; i++)
894 : {
895 : const GDALColorEntry *psEntry =
896 258 : colorTable->GetColorEntry(i);
897 : const GDALColorEntry *psEntryRef =
898 258 : asBandProperties[j].colorTable->GetColorEntry(i);
899 258 : if (psEntry->c1 != psEntryRef->c1 ||
900 258 : psEntry->c2 != psEntryRef->c2 ||
901 258 : psEntry->c3 != psEntryRef->c3 ||
902 258 : psEntry->c4 != psEntryRef->c4)
903 : {
904 : static int bFirstWarningPCT = TRUE;
905 0 : if (bFirstWarningPCT)
906 0 : CPLError(
907 : CE_Warning, CPLE_NotSupported,
908 : "%s has different values than the first "
909 : "raster for some entries in the color "
910 : "table.\n"
911 : "The end result might produce weird "
912 : "colors.\n"
913 : "You're advised to pre-process your "
914 : "rasters with other tools, such as "
915 : "pct2rgb.py or gdal_translate -expand RGB\n"
916 : "to operate %s on RGB rasters "
917 : "instead",
918 : dsFileName, m_osProgramName.c_str());
919 : else
920 0 : CPLError(CE_Warning, CPLE_NotSupported,
921 : "%s has different values than the "
922 : "first raster for some entries in the "
923 : "color table.",
924 : dsFileName);
925 0 : bFirstWarningPCT = FALSE;
926 0 : break;
927 : }
928 : }
929 : }
930 :
931 3169 : if (psDatasetProperties->abHasOffset[j] !=
932 6338 : asBandProperties[j].bHasOffset ||
933 3169 : (asBandProperties[j].bHasOffset &&
934 0 : psDatasetProperties->adfOffset[j] !=
935 0 : asBandProperties[j].dfOffset))
936 : {
937 0 : return m_osProgramName +
938 : CPLSPrintf(
939 : " does not support heterogeneous "
940 : "band offset: expected (%d,%f), got (%d,%f).",
941 0 : static_cast<int>(asBandProperties[j].bHasOffset),
942 0 : asBandProperties[j].dfOffset,
943 : static_cast<int>(
944 0 : psDatasetProperties->abHasOffset[j]),
945 0 : psDatasetProperties->adfOffset[j]);
946 : }
947 :
948 3169 : if (psDatasetProperties->abHasScale[j] !=
949 6338 : asBandProperties[j].bHasScale ||
950 3169 : (asBandProperties[j].bHasScale &&
951 0 : psDatasetProperties->adfScale[j] !=
952 0 : asBandProperties[j].dfScale))
953 : {
954 0 : return m_osProgramName +
955 : CPLSPrintf(
956 : " does not support heterogeneous "
957 : "band scale: expected (%d,%f), got (%d,%f).",
958 0 : static_cast<int>(asBandProperties[j].bHasScale),
959 0 : asBandProperties[j].dfScale,
960 : static_cast<int>(
961 0 : psDatasetProperties->abHasScale[j]),
962 0 : psDatasetProperties->adfScale[j]);
963 : }
964 : }
965 : }
966 2131 : if (!bUserExtent)
967 : {
968 2128 : if (ds_minX < minX)
969 4 : minX = ds_minX;
970 2128 : if (ds_minY < minY)
971 27 : minY = ds_minY;
972 2128 : if (ds_maxX > maxX)
973 693 : maxX = ds_maxX;
974 2128 : if (ds_maxY > maxY)
975 34 : maxY = ds_maxY;
976 : }
977 : }
978 :
979 2350 : if (resolutionStrategy == AVERAGE_RESOLUTION)
980 : {
981 2283 : ++nCountValid;
982 : {
983 2283 : const double dfDelta = gt[GEOTRSFRM_WE_RES] - we_res;
984 2283 : we_res += dfDelta / nCountValid;
985 : }
986 : {
987 2283 : const double dfDelta = gt[GEOTRSFRM_NS_RES] - ns_res;
988 2283 : ns_res += dfDelta / nCountValid;
989 : }
990 : }
991 67 : else if (resolutionStrategy == SAME_RESOLUTION)
992 : {
993 30 : if (bFirst)
994 : {
995 24 : we_res = gt[GEOTRSFRM_WE_RES];
996 24 : ns_res = gt[GEOTRSFRM_NS_RES];
997 : }
998 11 : else if (we_res != gt[GEOTRSFRM_WE_RES] ||
999 5 : ns_res != gt[GEOTRSFRM_NS_RES])
1000 : {
1001 : return CPLSPrintf("Dataset %s has resolution %f x %f, whereas "
1002 : "previous sources have resolution %f x %f",
1003 1 : dsFileName, gt[GEOTRSFRM_WE_RES],
1004 1 : gt[GEOTRSFRM_NS_RES], we_res, ns_res);
1005 : }
1006 : }
1007 37 : else if (resolutionStrategy != USER_RESOLUTION)
1008 : {
1009 24 : if (bFirst)
1010 : {
1011 12 : we_res = gt[GEOTRSFRM_WE_RES];
1012 12 : ns_res = gt[GEOTRSFRM_NS_RES];
1013 : }
1014 12 : else if (resolutionStrategy == HIGHEST_RESOLUTION)
1015 : {
1016 1 : we_res = std::min(we_res, gt[GEOTRSFRM_WE_RES]);
1017 : // ns_res is negative, the highest resolution is the max value.
1018 1 : ns_res = std::max(ns_res, gt[GEOTRSFRM_NS_RES]);
1019 : }
1020 11 : else if (resolutionStrategy == COMMON_RESOLUTION)
1021 : {
1022 10 : we_res = CPLGreatestCommonDivisor(we_res, gt[GEOTRSFRM_WE_RES]);
1023 10 : if (we_res == 0)
1024 : {
1025 1 : return "Failed to get common resolution";
1026 : }
1027 9 : ns_res = CPLGreatestCommonDivisor(ns_res, gt[GEOTRSFRM_NS_RES]);
1028 9 : if (ns_res == 0)
1029 : {
1030 0 : return "Failed to get common resolution";
1031 : }
1032 : }
1033 : else
1034 : {
1035 1 : we_res = std::max(we_res, gt[GEOTRSFRM_WE_RES]);
1036 : // ns_res is negative, the lowest resolution is the min value.
1037 1 : ns_res = std::min(ns_res, gt[GEOTRSFRM_NS_RES]);
1038 : }
1039 : }
1040 :
1041 2348 : checkNoDataValues(asBandProperties);
1042 :
1043 2348 : return "";
1044 : }
1045 :
1046 : /************************************************************************/
1047 : /* WriteAbsolutePath() */
1048 : /************************************************************************/
1049 :
1050 7 : static void WriteAbsolutePath(VRTSimpleSource *poSource, const char *dsFileName)
1051 : {
1052 7 : if (dsFileName[0])
1053 : {
1054 7 : if (CPLIsFilenameRelative(dsFileName))
1055 : {
1056 : VSIStatBufL sStat;
1057 2 : if (VSIStatL(dsFileName, &sStat) == 0)
1058 : {
1059 2 : if (char *pszCurDir = CPLGetCurrentDir())
1060 : {
1061 2 : poSource->SetSourceDatasetName(
1062 4 : CPLFormFilenameSafe(pszCurDir, dsFileName, nullptr)
1063 : .c_str(),
1064 : false);
1065 2 : CPLFree(pszCurDir);
1066 : }
1067 : }
1068 : }
1069 : else
1070 : {
1071 5 : poSource->SetSourceDatasetName(dsFileName, false);
1072 : }
1073 : }
1074 7 : }
1075 :
1076 : /************************************************************************/
1077 : /* CreateVRTSeparate() */
1078 : /************************************************************************/
1079 :
1080 17 : void VRTBuilder::CreateVRTSeparate(VRTDataset *poVRTDS)
1081 : {
1082 17 : int iBand = 1;
1083 49 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1084 : {
1085 32 : DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1086 :
1087 32 : if (psDatasetProperties->isFileOK == FALSE)
1088 0 : continue;
1089 :
1090 32 : const char *dsFileName = ppszInputFilenames[i];
1091 :
1092 : double dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1093 : dfDstYOff, dfDstXSize, dfDstYSize;
1094 32 : if (bHasGeoTransform)
1095 : {
1096 30 : if (!GetSrcDstWin(psDatasetProperties, we_res, ns_res, minX, minY,
1097 : maxX, maxY, nRasterXSize, nRasterYSize,
1098 : &dfSrcXOff, &dfSrcYOff, &dfSrcXSize, &dfSrcYSize,
1099 : &dfDstXOff, &dfDstYOff, &dfDstXSize, &dfDstYSize))
1100 : {
1101 0 : CPLDebug("BuildVRT",
1102 : "Skipping %s as not intersecting area of interest",
1103 : dsFileName);
1104 0 : continue;
1105 : }
1106 : }
1107 : else
1108 : {
1109 2 : dfSrcXOff = dfSrcYOff = dfDstXOff = dfDstYOff = 0;
1110 2 : dfSrcXSize = dfDstXSize = nRasterXSize;
1111 2 : dfSrcYSize = dfDstYSize = nRasterYSize;
1112 : }
1113 :
1114 : GDALDatasetH hSourceDS;
1115 32 : bool bDropRef = false;
1116 84 : if (nSrcDSCount == nInputFiles &&
1117 52 : GDALGetDatasetDriver(pahSrcDS[i]) != nullptr &&
1118 20 : (dsFileName[0] == '\0' || // could be a unnamed VRT file
1119 2 : EQUAL(GDALGetDescription(GDALGetDatasetDriver(pahSrcDS[i])),
1120 : "MEM")))
1121 : {
1122 20 : hSourceDS = pahSrcDS[i];
1123 : }
1124 : else
1125 : {
1126 12 : bDropRef = true;
1127 24 : GDALProxyPoolDatasetH hProxyDS = GDALProxyPoolDatasetCreate(
1128 : dsFileName, psDatasetProperties->nRasterXSize,
1129 : psDatasetProperties->nRasterYSize, GA_ReadOnly, TRUE,
1130 12 : pszProjectionRef, psDatasetProperties->gt.data());
1131 12 : hSourceDS = static_cast<GDALDatasetH>(hProxyDS);
1132 12 : reinterpret_cast<GDALProxyPoolDataset *>(hProxyDS)->SetOpenOptions(
1133 12 : papszOpenOptions);
1134 :
1135 27 : for (int jBand = 0;
1136 27 : jBand <
1137 27 : static_cast<int>(psDatasetProperties->aeBandType.size());
1138 : ++jBand)
1139 : {
1140 15 : GDALProxyPoolDatasetAddSrcBandDescription(
1141 15 : hProxyDS, psDatasetProperties->aeBandType[jBand],
1142 : psDatasetProperties->nBlockXSize,
1143 : psDatasetProperties->nBlockYSize);
1144 : }
1145 : }
1146 :
1147 : const int nBandsToIter =
1148 32 : nSelectedBands > 0
1149 62 : ? nSelectedBands
1150 30 : : static_cast<int>(psDatasetProperties->aeBandType.size());
1151 72 : for (int iBandToIter = 0; iBandToIter < nBandsToIter; ++iBandToIter)
1152 : {
1153 : // 0-based
1154 80 : const int nSrcBandIdx = nSelectedBands > 0
1155 40 : ? panSelectedBandList[iBandToIter] - 1
1156 : : iBandToIter;
1157 40 : assert(nSrcBandIdx >= 0);
1158 40 : poVRTDS->AddBand(psDatasetProperties->aeBandType[nSrcBandIdx],
1159 40 : nullptr);
1160 :
1161 : VRTSourcedRasterBand *poVRTBand =
1162 : static_cast<VRTSourcedRasterBand *>(
1163 40 : poVRTDS->GetRasterBand(iBand));
1164 :
1165 40 : if (bHideNoData)
1166 0 : poVRTBand->SetMetadataItem("HideNoDataValue", "1", nullptr);
1167 :
1168 40 : if (bAllowVRTNoData)
1169 : {
1170 38 : if (nVRTNoDataCount > 0)
1171 : {
1172 4 : if (iBand - 1 < nVRTNoDataCount)
1173 4 : poVRTBand->SetNoDataValue(padfVRTNoData[iBand - 1]);
1174 : else
1175 0 : poVRTBand->SetNoDataValue(
1176 0 : padfVRTNoData[nVRTNoDataCount - 1]);
1177 : }
1178 34 : else if (psDatasetProperties->abHasNoData[nSrcBandIdx])
1179 : {
1180 2 : poVRTBand->SetNoDataValue(
1181 2 : psDatasetProperties->adfNoDataValues[nSrcBandIdx]);
1182 : }
1183 : }
1184 :
1185 : VRTSimpleSource *poSimpleSource;
1186 78 : if (bAllowSrcNoData &&
1187 72 : (nSrcNoDataCount > 0 ||
1188 74 : psDatasetProperties->abHasNoData[nSrcBandIdx]))
1189 : {
1190 6 : auto poComplexSource = new VRTComplexSource();
1191 6 : poSimpleSource = poComplexSource;
1192 6 : if (nSrcNoDataCount > 0)
1193 : {
1194 4 : if (iBand - 1 < nSrcNoDataCount)
1195 4 : poComplexSource->SetNoDataValue(
1196 4 : padfSrcNoData[iBand - 1]);
1197 : else
1198 0 : poComplexSource->SetNoDataValue(
1199 0 : padfSrcNoData[nSrcNoDataCount - 1]);
1200 : }
1201 : else /* if (psDatasetProperties->abHasNoData[nSrcBandIdx]) */
1202 : {
1203 2 : poComplexSource->SetNoDataValue(
1204 2 : psDatasetProperties->adfNoDataValues[nSrcBandIdx]);
1205 : }
1206 : }
1207 68 : else if (bUseSrcMaskBand &&
1208 68 : psDatasetProperties->abHasMaskBand[nSrcBandIdx])
1209 : {
1210 1 : auto poSource = new VRTComplexSource();
1211 1 : poSource->SetUseMaskBand(true);
1212 1 : poSimpleSource = poSource;
1213 : }
1214 : else
1215 33 : poSimpleSource = new VRTSimpleSource();
1216 :
1217 40 : if (pszResampling)
1218 0 : poSimpleSource->SetResampling(pszResampling);
1219 80 : poVRTBand->ConfigureSource(
1220 : poSimpleSource,
1221 : static_cast<GDALRasterBand *>(
1222 40 : GDALGetRasterBand(hSourceDS, nSrcBandIdx + 1)),
1223 : FALSE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1224 : dfDstYOff, dfDstXSize, dfDstYSize);
1225 :
1226 40 : if (bWriteAbsolutePath)
1227 3 : WriteAbsolutePath(poSimpleSource, dsFileName);
1228 :
1229 40 : if (psDatasetProperties->abHasOffset[nSrcBandIdx])
1230 0 : poVRTBand->SetOffset(
1231 0 : psDatasetProperties->adfOffset[nSrcBandIdx]);
1232 :
1233 40 : if (psDatasetProperties->abHasScale[nSrcBandIdx])
1234 0 : poVRTBand->SetScale(psDatasetProperties->adfScale[nSrcBandIdx]);
1235 :
1236 40 : poVRTBand->AddSource(poSimpleSource);
1237 :
1238 40 : iBand++;
1239 : }
1240 :
1241 32 : if (bDropRef)
1242 : {
1243 12 : GDALDereferenceDataset(hSourceDS);
1244 : }
1245 : }
1246 17 : }
1247 :
1248 : /************************************************************************/
1249 : /* CreateVRTNonSeparate() */
1250 : /************************************************************************/
1251 :
1252 198 : void VRTBuilder::CreateVRTNonSeparate(VRTDataset *poVRTDS)
1253 : {
1254 396 : CPLStringList aosOptions;
1255 :
1256 198 : if (!osPixelFunction.empty())
1257 : {
1258 3 : aosOptions.AddNameValue("subclass", "VRTDerivedRasterBand");
1259 3 : aosOptions.AddNameValue("PixelFunctionType", osPixelFunction.c_str());
1260 3 : aosOptions.AddNameValue("SkipNonContributingSources", "1");
1261 6 : CPLString osName;
1262 2 : for (const auto &[pszKey, pszValue] :
1263 5 : cpl::IterateNameValue(aosPixelFunctionArgs))
1264 : {
1265 1 : osName.Printf("_PIXELFN_ARG_%s", pszKey);
1266 1 : aosOptions.AddNameValue(osName.c_str(), pszValue);
1267 : }
1268 : }
1269 :
1270 671 : for (int j = 0; j < nSelectedBands; j++)
1271 : {
1272 473 : const char *pszSourceTransferType = "Float64";
1273 945 : if (osPixelFunction == "mean" || osPixelFunction == "min" ||
1274 472 : osPixelFunction == "max")
1275 : {
1276 : pszSourceTransferType =
1277 1 : GDALGetDataTypeName(asBandProperties[j].dataType);
1278 : }
1279 473 : aosOptions.AddNameValue("SourceTransferType", pszSourceTransferType);
1280 :
1281 473 : poVRTDS->AddBand(asBandProperties[j].dataType, aosOptions.List());
1282 473 : GDALRasterBand *poBand = poVRTDS->GetRasterBand(j + 1);
1283 473 : poBand->SetColorInterpretation(asBandProperties[j].colorInterpretation);
1284 473 : if (asBandProperties[j].colorInterpretation == GCI_PaletteIndex)
1285 : {
1286 2 : poBand->SetColorTable(asBandProperties[j].colorTable.get());
1287 : }
1288 473 : if (bAllowVRTNoData && asBandProperties[j].bHasNoData)
1289 39 : poBand->SetNoDataValue(asBandProperties[j].noDataValue);
1290 473 : if (bHideNoData)
1291 2 : poBand->SetMetadataItem("HideNoDataValue", "1");
1292 :
1293 473 : if (asBandProperties[j].bHasOffset)
1294 0 : poBand->SetOffset(asBandProperties[j].dfOffset);
1295 :
1296 473 : if (asBandProperties[j].bHasScale)
1297 0 : poBand->SetScale(asBandProperties[j].dfScale);
1298 : }
1299 :
1300 198 : VRTSourcedRasterBand *poMaskVRTBand = nullptr;
1301 198 : if (bAddAlpha)
1302 : {
1303 10 : poVRTDS->AddBand(GDT_Byte);
1304 10 : GDALRasterBand *poBand = poVRTDS->GetRasterBand(nSelectedBands + 1);
1305 10 : poBand->SetColorInterpretation(GCI_AlphaBand);
1306 : }
1307 188 : else if (bHasDatasetMask)
1308 : {
1309 12 : poVRTDS->CreateMaskBand(GMF_PER_DATASET);
1310 : poMaskVRTBand = static_cast<VRTSourcedRasterBand *>(
1311 12 : poVRTDS->GetRasterBand(1)->GetMaskBand());
1312 : }
1313 :
1314 198 : bool bCanCollectOverviewFactors = true;
1315 396 : std::set<int> anOverviewFactorsSet;
1316 396 : std::vector<int> anIdxValidDatasets;
1317 :
1318 2517 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1319 : {
1320 2319 : DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1321 :
1322 2319 : if (psDatasetProperties->isFileOK == FALSE)
1323 8 : continue;
1324 :
1325 2312 : const char *dsFileName = ppszInputFilenames[i];
1326 :
1327 : double dfSrcXOff;
1328 : double dfSrcYOff;
1329 : double dfSrcXSize;
1330 : double dfSrcYSize;
1331 : double dfDstXOff;
1332 : double dfDstYOff;
1333 : double dfDstXSize;
1334 : double dfDstYSize;
1335 2312 : if (!GetSrcDstWin(psDatasetProperties, we_res, ns_res, minX, minY, maxX,
1336 : maxY, nRasterXSize, nRasterYSize, &dfSrcXOff,
1337 : &dfSrcYOff, &dfSrcXSize, &dfSrcYSize, &dfDstXOff,
1338 : &dfDstYOff, &dfDstXSize, &dfDstYSize))
1339 : {
1340 1 : CPLDebug("BuildVRT",
1341 : "Skipping %s as not intersecting area of interest",
1342 : dsFileName);
1343 1 : continue;
1344 : }
1345 :
1346 2311 : anIdxValidDatasets.push_back(i);
1347 :
1348 2311 : if (bCanCollectOverviewFactors)
1349 : {
1350 2296 : if (std::abs(psDatasetProperties->gt[1] - we_res) >
1351 4573 : 1e-8 * std::abs(we_res) ||
1352 2277 : std::abs(psDatasetProperties->gt[5] - ns_res) >
1353 2277 : 1e-8 * std::abs(ns_res))
1354 : {
1355 19 : bCanCollectOverviewFactors = false;
1356 19 : anOverviewFactorsSet.clear();
1357 : }
1358 : }
1359 2311 : if (bCanCollectOverviewFactors)
1360 : {
1361 2286 : for (int nOvFactor : psDatasetProperties->anOverviewFactors)
1362 9 : anOverviewFactorsSet.insert(nOvFactor);
1363 : }
1364 :
1365 : GDALDatasetH hSourceDS;
1366 2311 : bool bDropRef = false;
1367 :
1368 5731 : if (nSrcDSCount == nInputFiles &&
1369 3420 : GDALGetDatasetDriver(pahSrcDS[i]) != nullptr &&
1370 1109 : (dsFileName[0] == '\0' || // could be a unnamed VRT file
1371 53 : EQUAL(GDALGetDescription(GDALGetDatasetDriver(pahSrcDS[i])),
1372 : "MEM")))
1373 : {
1374 1090 : hSourceDS = pahSrcDS[i];
1375 : }
1376 : else
1377 : {
1378 1221 : bDropRef = true;
1379 2442 : GDALProxyPoolDatasetH hProxyDS = GDALProxyPoolDatasetCreate(
1380 : dsFileName, psDatasetProperties->nRasterXSize,
1381 : psDatasetProperties->nRasterYSize, GA_ReadOnly, TRUE,
1382 1221 : pszProjectionRef, psDatasetProperties->gt.data());
1383 1221 : reinterpret_cast<GDALProxyPoolDataset *>(hProxyDS)->SetOpenOptions(
1384 1221 : papszOpenOptions);
1385 :
1386 3530 : for (int j = 0;
1387 3530 : j < nMaxSelectedBandNo +
1388 42 : (bAddAlpha && psDatasetProperties->bLastBandIsAlpha
1389 3572 : ? 1
1390 : : 0);
1391 : j++)
1392 : {
1393 2309 : GDALProxyPoolDatasetAddSrcBandDescription(
1394 : hProxyDS,
1395 2309 : j < static_cast<int>(asBandProperties.size())
1396 2304 : ? asBandProperties[j].dataType
1397 : : GDT_Byte,
1398 : psDatasetProperties->nBlockXSize,
1399 : psDatasetProperties->nBlockYSize);
1400 : }
1401 1221 : if (bHasDatasetMask && !bAddAlpha)
1402 : {
1403 : static_cast<GDALProxyPoolRasterBand *>(
1404 : reinterpret_cast<GDALProxyPoolDataset *>(hProxyDS)
1405 13 : ->GetRasterBand(1))
1406 13 : ->AddSrcMaskBandDescription(
1407 : GDT_Byte, psDatasetProperties->nMaskBlockXSize,
1408 : psDatasetProperties->nMaskBlockYSize);
1409 : }
1410 :
1411 1221 : hSourceDS = static_cast<GDALDatasetH>(hProxyDS);
1412 : }
1413 :
1414 5958 : for (int j = 0;
1415 5958 : j <
1416 5958 : nSelectedBands +
1417 5958 : (bAddAlpha && psDatasetProperties->bLastBandIsAlpha ? 1 : 0);
1418 : j++)
1419 : {
1420 : VRTSourcedRasterBandH hVRTBand = static_cast<VRTSourcedRasterBandH>(
1421 3647 : poVRTDS->GetRasterBand(j + 1));
1422 3647 : const int nSelBand = j == nSelectedBands ? nSelectedBands + 1
1423 3639 : : panSelectedBandList[j];
1424 :
1425 : /* Place the raster band at the right position in the VRT */
1426 3647 : VRTSourcedRasterBand *poVRTBand =
1427 : static_cast<VRTSourcedRasterBand *>(hVRTBand);
1428 :
1429 : VRTSimpleSource *poSimpleSource;
1430 3647 : if (bNoDataFromMask)
1431 : {
1432 15 : auto poNoDataFromMaskSource = new VRTNoDataFromMaskSource();
1433 15 : poSimpleSource = poNoDataFromMaskSource;
1434 15 : poNoDataFromMaskSource->SetParameters(
1435 15 : (nVRTNoDataCount > 0)
1436 15 : ? ((j < nVRTNoDataCount)
1437 15 : ? padfVRTNoData[j]
1438 6 : : padfVRTNoData[nVRTNoDataCount - 1])
1439 : : 0,
1440 : dfMaskValueThreshold);
1441 : }
1442 7264 : else if (bAllowSrcNoData &&
1443 7264 : psDatasetProperties->abHasNoData[nSelBand - 1])
1444 : {
1445 27 : auto poComplexSource = new VRTComplexSource();
1446 27 : poSimpleSource = poComplexSource;
1447 27 : poComplexSource->SetNoDataValue(
1448 27 : psDatasetProperties->adfNoDataValues[nSelBand - 1]);
1449 : }
1450 7210 : else if (bUseSrcMaskBand &&
1451 7210 : psDatasetProperties->abHasMaskBand[nSelBand - 1])
1452 : {
1453 57 : auto poSource = new VRTComplexSource();
1454 57 : poSource->SetUseMaskBand(true);
1455 57 : poSimpleSource = poSource;
1456 : }
1457 : else
1458 3548 : poSimpleSource = new VRTSimpleSource();
1459 3647 : if (pszResampling)
1460 23 : poSimpleSource->SetResampling(pszResampling);
1461 3647 : auto poSrcBand = GDALRasterBand::FromHandle(
1462 : GDALGetRasterBand(hSourceDS, nSelBand));
1463 3647 : poVRTBand->ConfigureSource(poSimpleSource, poSrcBand, FALSE,
1464 : dfSrcXOff, dfSrcYOff, dfSrcXSize,
1465 : dfSrcYSize, dfDstXOff, dfDstYOff,
1466 : dfDstXSize, dfDstYSize);
1467 :
1468 3647 : if (bWriteAbsolutePath)
1469 3 : WriteAbsolutePath(poSimpleSource, dsFileName);
1470 :
1471 3647 : poVRTBand->AddSource(poSimpleSource);
1472 : }
1473 :
1474 2311 : if (bAddAlpha && !psDatasetProperties->bLastBandIsAlpha)
1475 : {
1476 : VRTSourcedRasterBand *poVRTBand =
1477 : static_cast<VRTSourcedRasterBand *>(
1478 11 : poVRTDS->GetRasterBand(nSelectedBands + 1));
1479 : /* Little trick : we use an offset of 255 and a scaling of 0, so
1480 : * that in areas covered */
1481 : /* by the source, the value of the alpha band will be 255, otherwise
1482 : * it will be 0 */
1483 11 : poVRTBand->AddComplexSource(
1484 : GDALRasterBand::FromHandle(GDALGetRasterBand(hSourceDS, 1)),
1485 : dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1486 11 : dfDstYOff, dfDstXSize, dfDstYSize, 255, 0, VRT_NODATA_UNSET);
1487 : }
1488 2300 : else if (bHasDatasetMask)
1489 : {
1490 : VRTSimpleSource *poSource;
1491 15 : if (bUseSrcMaskBand)
1492 : {
1493 15 : auto poComplexSource = new VRTComplexSource();
1494 15 : poComplexSource->SetUseMaskBand(true);
1495 15 : poSource = poComplexSource;
1496 : }
1497 : else
1498 : {
1499 0 : poSource = new VRTSimpleSource();
1500 : }
1501 15 : if (pszResampling)
1502 4 : poSource->SetResampling(pszResampling);
1503 15 : assert(poMaskVRTBand);
1504 30 : poMaskVRTBand->ConfigureSource(
1505 : poSource,
1506 15 : static_cast<GDALRasterBand *>(GDALGetRasterBand(hSourceDS, 1)),
1507 : TRUE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1508 : dfDstYOff, dfDstXSize, dfDstYSize);
1509 :
1510 15 : if (bWriteAbsolutePath)
1511 1 : WriteAbsolutePath(poSource, dsFileName);
1512 :
1513 15 : poMaskVRTBand->AddSource(poSource);
1514 : }
1515 :
1516 2311 : if (bDropRef)
1517 : {
1518 1221 : GDALDereferenceDataset(hSourceDS);
1519 : }
1520 : }
1521 :
1522 2509 : for (int i : anIdxValidDatasets)
1523 : {
1524 2311 : const DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1525 2311 : for (auto oIter = anOverviewFactorsSet.begin();
1526 2320 : oIter != anOverviewFactorsSet.end();)
1527 : {
1528 9 : const int nGlobalOvrFactor = *oIter;
1529 9 : auto oIterNext = oIter;
1530 9 : ++oIterNext;
1531 :
1532 9 : if (psDatasetProperties->nRasterXSize / nGlobalOvrFactor < 128 &&
1533 0 : psDatasetProperties->nRasterYSize / nGlobalOvrFactor < 128)
1534 : {
1535 0 : break;
1536 : }
1537 9 : if (std::find(psDatasetProperties->anOverviewFactors.begin(),
1538 : psDatasetProperties->anOverviewFactors.end(),
1539 9 : nGlobalOvrFactor) ==
1540 18 : psDatasetProperties->anOverviewFactors.end())
1541 : {
1542 0 : anOverviewFactorsSet.erase(oIter);
1543 : }
1544 :
1545 9 : oIter = oIterNext;
1546 : }
1547 : }
1548 201 : if (!anOverviewFactorsSet.empty() &&
1549 3 : CPLTestBool(CPLGetConfigOption("VRT_VIRTUAL_OVERVIEWS", "YES")))
1550 : {
1551 6 : std::vector<int> anOverviewFactors;
1552 3 : anOverviewFactors.insert(anOverviewFactors.end(),
1553 : anOverviewFactorsSet.begin(),
1554 6 : anOverviewFactorsSet.end());
1555 3 : const char *const apszOptions[] = {"VRT_VIRTUAL_OVERVIEWS=YES",
1556 : nullptr};
1557 3 : poVRTDS->BuildOverviews(pszResampling ? pszResampling : "nearest",
1558 3 : static_cast<int>(anOverviewFactors.size()),
1559 3 : &anOverviewFactors[0], 0, nullptr, nullptr,
1560 : nullptr, apszOptions);
1561 : }
1562 198 : }
1563 :
1564 : /************************************************************************/
1565 : /* Build() */
1566 : /************************************************************************/
1567 :
1568 221 : std::unique_ptr<GDALDataset> VRTBuilder::Build(GDALProgressFunc pfnProgress,
1569 : void *pProgressData)
1570 : {
1571 221 : if (bHasRunBuild)
1572 0 : return nullptr;
1573 221 : bHasRunBuild = TRUE;
1574 :
1575 221 : if (pfnProgress == nullptr)
1576 0 : pfnProgress = GDALDummyProgress;
1577 :
1578 221 : bUserExtent = (minX != 0 || minY != 0 || maxX != 0 || maxY != 0);
1579 221 : if (bUserExtent)
1580 : {
1581 13 : if (minX >= maxX || minY >= maxY)
1582 : {
1583 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Invalid user extent");
1584 0 : return nullptr;
1585 : }
1586 : }
1587 :
1588 221 : if (resolutionStrategy == USER_RESOLUTION)
1589 : {
1590 8 : if (we_res <= 0 || ns_res <= 0)
1591 : {
1592 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Invalid user resolution");
1593 0 : return nullptr;
1594 : }
1595 :
1596 : /* We work with negative north-south resolution in all the following
1597 : * code */
1598 8 : ns_res = -ns_res;
1599 : }
1600 : else
1601 : {
1602 213 : we_res = ns_res = 0;
1603 : }
1604 :
1605 221 : asDatasetProperties.resize(nInputFiles);
1606 :
1607 221 : if (pszSrcNoData != nullptr)
1608 : {
1609 6 : if (EQUAL(pszSrcNoData, "none"))
1610 : {
1611 1 : bAllowSrcNoData = FALSE;
1612 : }
1613 : else
1614 : {
1615 5 : char **papszTokens = CSLTokenizeString(pszSrcNoData);
1616 5 : nSrcNoDataCount = CSLCount(papszTokens);
1617 5 : padfSrcNoData = static_cast<double *>(
1618 5 : CPLMalloc(sizeof(double) * nSrcNoDataCount));
1619 12 : for (int i = 0; i < nSrcNoDataCount; i++)
1620 : {
1621 7 : if (!ArgIsNumeric(papszTokens[i]) &&
1622 0 : !EQUAL(papszTokens[i], "nan") &&
1623 7 : !EQUAL(papszTokens[i], "-inf") &&
1624 0 : !EQUAL(papszTokens[i], "inf"))
1625 : {
1626 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1627 : "Invalid -srcnodata value");
1628 0 : CSLDestroy(papszTokens);
1629 0 : return nullptr;
1630 : }
1631 7 : padfSrcNoData[i] = CPLAtofM(papszTokens[i]);
1632 : }
1633 5 : CSLDestroy(papszTokens);
1634 : }
1635 : }
1636 :
1637 221 : if (pszVRTNoData != nullptr)
1638 : {
1639 23 : if (EQUAL(pszVRTNoData, "none"))
1640 : {
1641 1 : bAllowVRTNoData = FALSE;
1642 : }
1643 : else
1644 : {
1645 22 : char **papszTokens = CSLTokenizeString(pszVRTNoData);
1646 22 : nVRTNoDataCount = CSLCount(papszTokens);
1647 22 : padfVRTNoData = static_cast<double *>(
1648 22 : CPLMalloc(sizeof(double) * nVRTNoDataCount));
1649 46 : for (int i = 0; i < nVRTNoDataCount; i++)
1650 : {
1651 24 : if (!ArgIsNumeric(papszTokens[i]) &&
1652 1 : !EQUAL(papszTokens[i], "nan") &&
1653 25 : !EQUAL(papszTokens[i], "-inf") &&
1654 0 : !EQUAL(papszTokens[i], "inf"))
1655 : {
1656 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1657 : "Invalid -vrtnodata value");
1658 0 : CSLDestroy(papszTokens);
1659 0 : return nullptr;
1660 : }
1661 24 : padfVRTNoData[i] = CPLAtofM(papszTokens[i]);
1662 : }
1663 22 : CSLDestroy(papszTokens);
1664 : }
1665 : }
1666 :
1667 221 : bool bFoundValid = false;
1668 2578 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1669 : {
1670 2361 : const char *dsFileName = ppszInputFilenames[i];
1671 :
1672 2361 : if (!pfnProgress(1.0 * (i + 1) / nInputFiles, nullptr, pProgressData))
1673 : {
1674 0 : return nullptr;
1675 : }
1676 :
1677 2361 : GDALDatasetH hDS = (pahSrcDS)
1678 2361 : ? pahSrcDS[i]
1679 1222 : : GDALOpenEx(dsFileName, GDAL_OF_RASTER, nullptr,
1680 1222 : papszOpenOptions, nullptr);
1681 2361 : asDatasetProperties[i].isFileOK = FALSE;
1682 :
1683 2361 : if (hDS)
1684 : {
1685 2359 : const auto osErrorMsg = AnalyseRaster(hDS, &asDatasetProperties[i]);
1686 2359 : if (osErrorMsg.empty())
1687 : {
1688 2348 : asDatasetProperties[i].isFileOK = TRUE;
1689 2348 : bFoundValid = true;
1690 2348 : bFirst = FALSE;
1691 : }
1692 2359 : if (pahSrcDS == nullptr)
1693 1220 : GDALClose(hDS);
1694 2359 : if (!osErrorMsg.empty() && osErrorMsg != "SILENTLY_IGNORE")
1695 : {
1696 11 : if (bStrict)
1697 : {
1698 3 : CPLError(CE_Failure, CPLE_AppDefined, "%s",
1699 : osErrorMsg.c_str());
1700 3 : return nullptr;
1701 : }
1702 : else
1703 : {
1704 8 : CPLError(CE_Warning, CPLE_AppDefined, "%s Skipping %s",
1705 : osErrorMsg.c_str(), dsFileName);
1706 : }
1707 : }
1708 : }
1709 : else
1710 : {
1711 2 : if (bStrict)
1712 : {
1713 1 : CPLError(CE_Failure, CPLE_AppDefined, "Can't open %s.",
1714 : dsFileName);
1715 1 : return nullptr;
1716 : }
1717 : else
1718 : {
1719 1 : CPLError(CE_Warning, CPLE_AppDefined,
1720 : "Can't open %s. Skipping it", dsFileName);
1721 : }
1722 : }
1723 : }
1724 :
1725 217 : if (!bFoundValid)
1726 2 : return nullptr;
1727 :
1728 215 : if (bHasGeoTransform)
1729 : {
1730 214 : if (bTargetAlignedPixels)
1731 : {
1732 2 : minX = floor(minX / we_res) * we_res;
1733 2 : maxX = ceil(maxX / we_res) * we_res;
1734 2 : minY = floor(minY / -ns_res) * -ns_res;
1735 2 : maxY = ceil(maxY / -ns_res) * -ns_res;
1736 : }
1737 :
1738 214 : nRasterXSize = static_cast<int>(0.5 + (maxX - minX) / we_res);
1739 214 : nRasterYSize = static_cast<int>(0.5 + (maxY - minY) / -ns_res);
1740 : }
1741 :
1742 215 : if (nRasterXSize == 0 || nRasterYSize == 0)
1743 : {
1744 0 : CPLError(CE_Failure, CPLE_AppDefined,
1745 : "Computed VRT dimension is invalid. You've probably "
1746 : "specified inappropriate resolution.");
1747 0 : return nullptr;
1748 : }
1749 :
1750 215 : auto poDS = VRTDataset::CreateVRTDataset(pszOutputFilename, nRasterXSize,
1751 : nRasterYSize, 0, GDT_Unknown,
1752 430 : aosCreateOptions.List());
1753 215 : if (!poDS)
1754 : {
1755 0 : return nullptr;
1756 : }
1757 :
1758 215 : if (pszOutputSRS)
1759 : {
1760 1 : poDS->SetProjection(pszOutputSRS);
1761 : }
1762 214 : else if (pszProjectionRef)
1763 : {
1764 214 : poDS->SetProjection(pszProjectionRef);
1765 : }
1766 :
1767 215 : if (bHasGeoTransform)
1768 : {
1769 214 : GDALGeoTransform gt;
1770 214 : gt[GEOTRSFRM_TOPLEFT_X] = minX;
1771 214 : gt[GEOTRSFRM_WE_RES] = we_res;
1772 214 : gt[GEOTRSFRM_ROTATION_PARAM1] = 0;
1773 214 : gt[GEOTRSFRM_TOPLEFT_Y] = maxY;
1774 214 : gt[GEOTRSFRM_ROTATION_PARAM2] = 0;
1775 214 : gt[GEOTRSFRM_NS_RES] = ns_res;
1776 214 : poDS->SetGeoTransform(gt);
1777 : }
1778 :
1779 215 : if (bSeparate)
1780 : {
1781 17 : CreateVRTSeparate(poDS.get());
1782 : }
1783 : else
1784 : {
1785 198 : CreateVRTNonSeparate(poDS.get());
1786 : }
1787 :
1788 215 : return poDS;
1789 : }
1790 :
1791 : /************************************************************************/
1792 : /* add_file_to_list() */
1793 : /************************************************************************/
1794 :
1795 45 : static bool add_file_to_list(const char *filename, const char *tile_index,
1796 : CPLStringList &aosList)
1797 : {
1798 :
1799 45 : if (EQUAL(CPLGetExtensionSafe(filename).c_str(), "SHP"))
1800 : {
1801 : /* Handle gdaltindex Shapefile as a special case */
1802 1 : auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(filename));
1803 1 : if (poDS == nullptr)
1804 : {
1805 0 : CPLError(CE_Failure, CPLE_AppDefined,
1806 : "Unable to open shapefile `%s'.", filename);
1807 0 : return false;
1808 : }
1809 :
1810 1 : auto poLayer = poDS->GetLayer(0);
1811 1 : const auto poFDefn = poLayer->GetLayerDefn();
1812 :
1813 2 : if (poFDefn->GetFieldIndex("LOCATION") >= 0 &&
1814 1 : strcmp("LOCATION", tile_index) != 0)
1815 : {
1816 1 : CPLError(CE_Failure, CPLE_AppDefined,
1817 : "This shapefile seems to be a tile index of "
1818 : "OGR features and not GDAL products.");
1819 : }
1820 1 : const int ti_field = poFDefn->GetFieldIndex(tile_index);
1821 1 : if (ti_field < 0)
1822 : {
1823 0 : CPLError(CE_Failure, CPLE_AppDefined,
1824 : "Unable to find field `%s' in DBF file `%s'.", tile_index,
1825 : filename);
1826 0 : return false;
1827 : }
1828 :
1829 : /* Load in memory existing file names in SHP */
1830 1 : const auto nTileIndexFiles = poLayer->GetFeatureCount(TRUE);
1831 1 : if (nTileIndexFiles == 0)
1832 : {
1833 0 : CPLError(CE_Warning, CPLE_AppDefined,
1834 : "Tile index %s is empty. Skipping it.", filename);
1835 0 : return true;
1836 : }
1837 1 : if (nTileIndexFiles > 100 * 1024 * 1024)
1838 : {
1839 0 : CPLError(CE_Failure, CPLE_AppDefined,
1840 : "Too large feature count in tile index");
1841 0 : return false;
1842 : }
1843 :
1844 5 : for (auto &&poFeature : poLayer)
1845 : {
1846 4 : aosList.AddString(poFeature->GetFieldAsString(ti_field));
1847 : }
1848 : }
1849 : else
1850 : {
1851 44 : aosList.AddString(filename);
1852 : }
1853 :
1854 45 : return true;
1855 : }
1856 :
1857 : /************************************************************************/
1858 : /* GDALBuildVRTOptions */
1859 : /************************************************************************/
1860 :
1861 : /** Options for use with GDALBuildVRT(). GDALBuildVRTOptions* must be allocated
1862 : * and freed with GDALBuildVRTOptionsNew() and GDALBuildVRTOptionsFree()
1863 : * respectively.
1864 : */
1865 : struct GDALBuildVRTOptions
1866 : {
1867 : std::string osProgramName = "gdalbuildvrt";
1868 : std::string osTileIndex = "location";
1869 : bool bStrict = false;
1870 : std::string osResolution{};
1871 : bool bSeparate = false;
1872 : bool bAllowProjectionDifference = false;
1873 : double we_res = 0;
1874 : double ns_res = 0;
1875 : bool bTargetAlignedPixels = false;
1876 : double xmin = 0;
1877 : double ymin = 0;
1878 : double xmax = 0;
1879 : double ymax = 0;
1880 : bool bAddAlpha = false;
1881 : bool bHideNoData = false;
1882 : int nSubdataset = -1;
1883 : std::string osSrcNoData{};
1884 : std::string osVRTNoData{};
1885 : std::string osOutputSRS{};
1886 : std::vector<int> anSelectedBandList{};
1887 : std::string osResampling{};
1888 : CPLStringList aosOpenOptions{};
1889 : CPLStringList aosCreateOptions{};
1890 : bool bUseSrcMaskBand = true;
1891 : bool bNoDataFromMask = false;
1892 : double dfMaskValueThreshold = 0;
1893 : bool bWriteAbsolutePath = false;
1894 : std::string osPixelFunction{};
1895 : CPLStringList aosPixelFunctionArgs{};
1896 :
1897 : /*! allow or suppress progress monitor and other non-error output */
1898 : bool bQuiet = true;
1899 :
1900 : /*! the progress function to use */
1901 : GDALProgressFunc pfnProgress = GDALDummyProgress;
1902 :
1903 : /*! pointer to the progress data variable */
1904 : void *pProgressData = nullptr;
1905 : };
1906 :
1907 : /************************************************************************/
1908 : /* GDALBuildVRT() */
1909 : /************************************************************************/
1910 :
1911 : /* clang-format off */
1912 : /**
1913 : * Build a VRT from a list of datasets.
1914 : *
1915 : * This is the equivalent of the
1916 : * <a href="/programs/gdalbuildvrt.html">gdalbuildvrt</a> utility.
1917 : *
1918 : * GDALBuildVRTOptions* must be allocated and freed with
1919 : * GDALBuildVRTOptionsNew() and GDALBuildVRTOptionsFree() respectively. pahSrcDS
1920 : * and papszSrcDSNames cannot be used at the same time.
1921 : *
1922 : * @param pszDest the destination dataset path.
1923 : * @param nSrcCount the number of input datasets.
1924 : * @param pahSrcDS the list of input datasets (or NULL, exclusive with
1925 : * papszSrcDSNames). For practical purposes, the type
1926 : * of this argument should be considered as "const GDALDatasetH* const*", that
1927 : * is neither the array nor its values are mutated by this function.
1928 : * @param papszSrcDSNames the list of input dataset names (or NULL, exclusive
1929 : * with pahSrcDS)
1930 : * @param psOptionsIn the options struct returned by GDALBuildVRTOptionsNew() or
1931 : * NULL.
1932 : * @param pbUsageError pointer to a integer output variable to store if any
1933 : * usage error has occurred.
1934 : * @return the output dataset (new dataset that must be closed using
1935 : * GDALClose()) or NULL in case of error. If using pahSrcDS, the returned VRT
1936 : * dataset has a reference to each pahSrcDS[] element. Hence pahSrcDS[] elements
1937 : * should be closed after the returned dataset if using GDALClose().
1938 : * A safer alternative is to use GDALReleaseDataset() instead of using
1939 : * GDALClose(), in which case you can close datasets in any order.
1940 :
1941 : *
1942 : * @since GDAL 2.1
1943 : */
1944 : /* clang-format on */
1945 :
1946 222 : GDALDatasetH GDALBuildVRT(const char *pszDest, int nSrcCount,
1947 : GDALDatasetH *pahSrcDS,
1948 : const char *const *papszSrcDSNames,
1949 : const GDALBuildVRTOptions *psOptionsIn,
1950 : int *pbUsageError)
1951 : {
1952 222 : if (pszDest == nullptr)
1953 0 : pszDest = "";
1954 :
1955 222 : if (nSrcCount == 0)
1956 : {
1957 0 : CPLError(CE_Failure, CPLE_AppDefined, "No input dataset specified.");
1958 :
1959 0 : if (pbUsageError)
1960 0 : *pbUsageError = TRUE;
1961 0 : return nullptr;
1962 : }
1963 :
1964 : // cppcheck-suppress unreadVariable
1965 : GDALBuildVRTOptions sOptions(psOptionsIn ? *psOptionsIn
1966 444 : : GDALBuildVRTOptions());
1967 :
1968 8 : if (sOptions.we_res != 0 && sOptions.ns_res != 0 &&
1969 230 : !sOptions.osResolution.empty() &&
1970 0 : !EQUAL(sOptions.osResolution.c_str(), "user"))
1971 : {
1972 0 : CPLError(CE_Failure, CPLE_NotSupported,
1973 : "-tr option is not compatible with -resolution %s",
1974 : sOptions.osResolution.c_str());
1975 0 : if (pbUsageError)
1976 0 : *pbUsageError = TRUE;
1977 0 : return nullptr;
1978 : }
1979 :
1980 222 : if (sOptions.bTargetAlignedPixels && sOptions.we_res == 0 &&
1981 1 : sOptions.ns_res == 0)
1982 : {
1983 1 : CPLError(CE_Failure, CPLE_NotSupported,
1984 : "-tap option cannot be used without using -tr");
1985 1 : if (pbUsageError)
1986 1 : *pbUsageError = TRUE;
1987 1 : return nullptr;
1988 : }
1989 :
1990 221 : if (sOptions.bAddAlpha && sOptions.bSeparate)
1991 : {
1992 0 : CPLError(CE_Failure, CPLE_NotSupported,
1993 : "-addalpha option is not compatible with -separate.");
1994 0 : if (pbUsageError)
1995 0 : *pbUsageError = TRUE;
1996 0 : return nullptr;
1997 : }
1998 :
1999 221 : ResolutionStrategy eStrategy = AVERAGE_RESOLUTION;
2000 258 : if (sOptions.osResolution.empty() ||
2001 37 : EQUAL(sOptions.osResolution.c_str(), "user"))
2002 : {
2003 184 : if (sOptions.we_res != 0 || sOptions.ns_res != 0)
2004 8 : eStrategy = USER_RESOLUTION;
2005 176 : else if (EQUAL(sOptions.osResolution.c_str(), "user"))
2006 : {
2007 0 : CPLError(CE_Failure, CPLE_NotSupported,
2008 : "-tr option must be used with -resolution user.");
2009 0 : if (pbUsageError)
2010 0 : *pbUsageError = TRUE;
2011 0 : return nullptr;
2012 : }
2013 : }
2014 37 : else if (EQUAL(sOptions.osResolution.c_str(), "average"))
2015 1 : eStrategy = AVERAGE_RESOLUTION;
2016 36 : else if (EQUAL(sOptions.osResolution.c_str(), "highest"))
2017 1 : eStrategy = HIGHEST_RESOLUTION;
2018 35 : else if (EQUAL(sOptions.osResolution.c_str(), "lowest"))
2019 1 : eStrategy = LOWEST_RESOLUTION;
2020 34 : else if (EQUAL(sOptions.osResolution.c_str(), "same"))
2021 24 : eStrategy = SAME_RESOLUTION;
2022 10 : else if (EQUAL(sOptions.osResolution.c_str(), "common"))
2023 10 : eStrategy = COMMON_RESOLUTION;
2024 :
2025 : /* If -srcnodata is specified, use it as the -vrtnodata if the latter is not
2026 : */
2027 : /* specified */
2028 221 : if (!sOptions.osSrcNoData.empty() && sOptions.osVRTNoData.empty())
2029 2 : sOptions.osVRTNoData = sOptions.osSrcNoData;
2030 :
2031 : VRTBuilder oBuilder(
2032 221 : sOptions.bStrict, pszDest, nSrcCount, papszSrcDSNames, pahSrcDS,
2033 221 : sOptions.anSelectedBandList.empty()
2034 : ? nullptr
2035 19 : : sOptions.anSelectedBandList.data(),
2036 221 : static_cast<int>(sOptions.anSelectedBandList.size()), eStrategy,
2037 221 : sOptions.we_res, sOptions.ns_res, sOptions.bTargetAlignedPixels,
2038 : sOptions.xmin, sOptions.ymin, sOptions.xmax, sOptions.ymax,
2039 221 : sOptions.bSeparate, sOptions.bAllowProjectionDifference,
2040 221 : sOptions.bAddAlpha, sOptions.bHideNoData, sOptions.nSubdataset,
2041 227 : sOptions.osSrcNoData.empty() ? nullptr : sOptions.osSrcNoData.c_str(),
2042 23 : sOptions.osVRTNoData.empty() ? nullptr : sOptions.osVRTNoData.c_str(),
2043 221 : sOptions.bUseSrcMaskBand, sOptions.bNoDataFromMask,
2044 : sOptions.dfMaskValueThreshold,
2045 222 : sOptions.osOutputSRS.empty() ? nullptr : sOptions.osOutputSRS.c_str(),
2046 236 : sOptions.osResampling.empty() ? nullptr : sOptions.osResampling.c_str(),
2047 221 : sOptions.osPixelFunction.empty() ? nullptr
2048 3 : : sOptions.osPixelFunction.c_str(),
2049 221 : sOptions.aosPixelFunctionArgs, sOptions.aosOpenOptions.List(),
2050 1131 : sOptions.aosCreateOptions, sOptions.bWriteAbsolutePath);
2051 221 : oBuilder.m_osProgramName = sOptions.osProgramName;
2052 :
2053 221 : return GDALDataset::ToHandle(
2054 442 : oBuilder.Build(sOptions.pfnProgress, sOptions.pProgressData).release());
2055 : }
2056 :
2057 : /************************************************************************/
2058 : /* SanitizeSRS */
2059 : /************************************************************************/
2060 :
2061 1 : static char *SanitizeSRS(const char *pszUserInput)
2062 :
2063 : {
2064 : OGRSpatialReferenceH hSRS;
2065 1 : char *pszResult = nullptr;
2066 :
2067 1 : CPLErrorReset();
2068 :
2069 1 : hSRS = OSRNewSpatialReference(nullptr);
2070 1 : if (OSRSetFromUserInput(hSRS, pszUserInput) == OGRERR_NONE)
2071 1 : OSRExportToWkt(hSRS, &pszResult);
2072 : else
2073 : {
2074 0 : CPLError(CE_Failure, CPLE_AppDefined, "Translating SRS failed:\n%s",
2075 : pszUserInput);
2076 : }
2077 :
2078 1 : OSRDestroySpatialReference(hSRS);
2079 :
2080 1 : return pszResult;
2081 : }
2082 :
2083 : /************************************************************************/
2084 : /* GDALBuildVRTOptionsGetParser() */
2085 : /************************************************************************/
2086 :
2087 : static std::unique_ptr<GDALArgumentParser>
2088 225 : GDALBuildVRTOptionsGetParser(GDALBuildVRTOptions *psOptions,
2089 : GDALBuildVRTOptionsForBinary *psOptionsForBinary)
2090 : {
2091 : auto argParser = std::make_unique<GDALArgumentParser>(
2092 225 : "gdalbuildvrt", /* bForBinary=*/psOptionsForBinary != nullptr);
2093 :
2094 225 : argParser->add_description(_("Builds a VRT from a list of datasets."));
2095 :
2096 225 : argParser->add_epilog(_(
2097 : "\n"
2098 : "e.g.\n"
2099 : " % gdalbuildvrt doq_index.vrt doq/*.tif\n"
2100 : " % gdalbuildvrt -input_file_list my_list.txt doq_index.vrt\n"
2101 : "\n"
2102 : "NOTES:\n"
2103 : " o With -separate, each files goes into a separate band in the VRT "
2104 : "band.\n"
2105 : " Otherwise, the files are considered as tiles of a larger mosaic.\n"
2106 : " o -b option selects a band to add into vrt. Multiple bands can be "
2107 : "listed.\n"
2108 : " By default all bands are queried.\n"
2109 : " o The default tile index field is 'location' unless otherwise "
2110 : "specified by\n"
2111 : " -tileindex.\n"
2112 : " o In case the resolution of all input files is not the same, the "
2113 : "-resolution\n"
2114 : " flag enable the user to control the way the output resolution is "
2115 : "computed.\n"
2116 : " Average is the default.\n"
2117 : " o Input files may be any valid GDAL dataset or a GDAL raster tile "
2118 : "index.\n"
2119 : " o For a GDAL raster tile index, all entries will be added to the "
2120 : "VRT.\n"
2121 : " o If one GDAL dataset is made of several subdatasets and has 0 "
2122 : "raster bands,\n"
2123 : " its datasets will be added to the VRT rather than the dataset "
2124 : "itself.\n"
2125 : " Single subdataset could be selected by its number using the -sd "
2126 : "option.\n"
2127 : " o By default, only datasets of same projection and band "
2128 : "characteristics\n"
2129 : " may be added to the VRT.\n"
2130 : "\n"
2131 : "For more details, consult "
2132 225 : "https://gdal.org/programs/gdalbuildvrt.html"));
2133 :
2134 : argParser->add_quiet_argument(
2135 225 : psOptionsForBinary ? &psOptionsForBinary->bQuiet : nullptr);
2136 :
2137 : {
2138 225 : auto &group = argParser->add_mutually_exclusive_group();
2139 :
2140 225 : group.add_argument("-strict")
2141 225 : .flag()
2142 225 : .store_into(psOptions->bStrict)
2143 225 : .help(_("Turn warnings as failures."));
2144 :
2145 225 : group.add_argument("-non_strict")
2146 225 : .flag()
2147 0 : .action([psOptions](const std::string &)
2148 225 : { psOptions->bStrict = false; })
2149 : .help(_("Skip source datasets that have issues with warnings, and "
2150 225 : "continue processing."));
2151 : }
2152 :
2153 225 : argParser->add_argument("-tile_index")
2154 450 : .metavar("<field_name>")
2155 225 : .store_into(psOptions->osTileIndex)
2156 : .help(_("Use the specified value as the tile index field, instead of "
2157 225 : "the default value which is 'location'."));
2158 :
2159 225 : argParser->add_argument("-resolution")
2160 450 : .metavar("user|average|common|highest|lowest|same")
2161 : .action(
2162 226 : [psOptions](const std::string &s)
2163 : {
2164 37 : psOptions->osResolution = s;
2165 37 : if (!EQUAL(psOptions->osResolution.c_str(), "user") &&
2166 37 : !EQUAL(psOptions->osResolution.c_str(), "average") &&
2167 36 : !EQUAL(psOptions->osResolution.c_str(), "highest") &&
2168 35 : !EQUAL(psOptions->osResolution.c_str(), "lowest") &&
2169 84 : !EQUAL(psOptions->osResolution.c_str(), "same") &&
2170 10 : !EQUAL(psOptions->osResolution.c_str(), "common"))
2171 : {
2172 : throw std::invalid_argument(
2173 : CPLSPrintf("Illegal resolution value (%s).",
2174 0 : psOptions->osResolution.c_str()));
2175 : }
2176 262 : })
2177 225 : .help(_("Control the way the output resolution is computed."));
2178 :
2179 225 : argParser->add_argument("-tr")
2180 450 : .metavar("<xres> <yes>")
2181 225 : .nargs(2)
2182 225 : .scan<'g', double>()
2183 225 : .help(_("Set target resolution."));
2184 :
2185 225 : if (psOptionsForBinary)
2186 : {
2187 20 : argParser->add_argument("-input_file_list")
2188 40 : .metavar("<filename>")
2189 : .action(
2190 5 : [psOptions, psOptionsForBinary](const std::string &s)
2191 : {
2192 1 : const char *input_file_list = s.c_str();
2193 : auto f = VSIVirtualHandleUniquePtr(
2194 2 : VSIFOpenL(input_file_list, "r"));
2195 1 : if (f)
2196 : {
2197 : while (1)
2198 : {
2199 5 : const char *filename = CPLReadLineL(f.get());
2200 5 : if (filename == nullptr)
2201 1 : break;
2202 4 : if (!add_file_to_list(
2203 : filename, psOptions->osTileIndex.c_str(),
2204 4 : psOptionsForBinary->aosSrcFiles))
2205 : {
2206 : throw std::invalid_argument(
2207 0 : std::string("Cannot add ")
2208 0 : .append(filename)
2209 0 : .append(" to input file list"));
2210 : }
2211 4 : }
2212 : }
2213 21 : })
2214 20 : .help(_("Text file with an input filename on each line"));
2215 : }
2216 :
2217 : {
2218 225 : auto &group = argParser->add_mutually_exclusive_group();
2219 :
2220 225 : group.add_argument("-separate")
2221 225 : .flag()
2222 225 : .store_into(psOptions->bSeparate)
2223 225 : .help(_("Place each input file into a separate band."));
2224 :
2225 225 : group.add_argument("-pixel-function")
2226 450 : .metavar("<function>")
2227 : .action(
2228 9 : [psOptions](const std::string &s)
2229 : {
2230 : auto *poPixFun =
2231 5 : VRTDerivedRasterBand::GetPixelFunction(s.c_str());
2232 5 : if (poPixFun == nullptr)
2233 : {
2234 : throw std::invalid_argument(
2235 1 : s + " is not a registered pixel function.");
2236 : }
2237 :
2238 4 : psOptions->osPixelFunction = s;
2239 229 : })
2240 :
2241 225 : .help("Function to calculate value from overlapping inputs");
2242 : }
2243 :
2244 225 : argParser->add_argument("-pixel-function-arg")
2245 450 : .metavar("<NAME>=<VALUE>")
2246 225 : .append()
2247 2 : .action([psOptions](const std::string &s)
2248 227 : { psOptions->aosPixelFunctionArgs.AddString(s); })
2249 225 : .help(_("Pixel function argument(s)"));
2250 :
2251 225 : argParser->add_argument("-allow_projection_difference")
2252 225 : .flag()
2253 225 : .store_into(psOptions->bAllowProjectionDifference)
2254 : .help(_("Accept source files not in the same projection (but without "
2255 225 : "reprojecting them!)."));
2256 :
2257 225 : argParser->add_argument("-sd")
2258 450 : .metavar("<n>")
2259 225 : .store_into(psOptions->nSubdataset)
2260 : .help(_("Use subdataset of specified index (starting at 1), instead of "
2261 225 : "the source dataset itself."));
2262 :
2263 225 : argParser->add_argument("-tap")
2264 225 : .flag()
2265 225 : .store_into(psOptions->bTargetAlignedPixels)
2266 : .help(_("Align the coordinates of the extent of the output file to the "
2267 225 : "values of the resolution."));
2268 :
2269 225 : argParser->add_argument("-te")
2270 450 : .metavar("<xmin> <ymin> <xmax> <ymax>")
2271 225 : .nargs(4)
2272 225 : .scan<'g', double>()
2273 225 : .help(_("Set georeferenced extents of output file to be created."));
2274 :
2275 225 : argParser->add_argument("-addalpha")
2276 225 : .flag()
2277 225 : .store_into(psOptions->bAddAlpha)
2278 : .help(_("Adds an alpha mask band to the VRT when the source raster "
2279 225 : "have none."));
2280 :
2281 225 : argParser->add_argument("-b")
2282 450 : .metavar("<band>")
2283 225 : .append()
2284 225 : .store_into(psOptions->anSelectedBandList)
2285 225 : .help(_("Specify input band(s) number."));
2286 :
2287 225 : argParser->add_argument("-hidenodata")
2288 225 : .flag()
2289 225 : .store_into(psOptions->bHideNoData)
2290 225 : .help(_("Makes the VRT band not report the NoData."));
2291 :
2292 225 : if (psOptionsForBinary)
2293 : {
2294 20 : argParser->add_argument("-overwrite")
2295 20 : .flag()
2296 20 : .store_into(psOptionsForBinary->bOverwrite)
2297 20 : .help(_("Overwrite the VRT if it already exists."));
2298 : }
2299 :
2300 225 : argParser->add_argument("-srcnodata")
2301 450 : .metavar("\"<value>[ <value>]...\"")
2302 225 : .store_into(psOptions->osSrcNoData)
2303 225 : .help(_("Set nodata values for input bands."));
2304 :
2305 225 : argParser->add_argument("-vrtnodata")
2306 450 : .metavar("\"<value>[ <value>]...\"")
2307 225 : .store_into(psOptions->osVRTNoData)
2308 225 : .help(_("Set nodata values at the VRT band level."));
2309 :
2310 225 : argParser->add_argument("-a_srs")
2311 450 : .metavar("<srs_def>")
2312 : .action(
2313 2 : [psOptions](const std::string &s)
2314 : {
2315 1 : char *pszSRS = SanitizeSRS(s.c_str());
2316 1 : if (pszSRS == nullptr)
2317 : {
2318 0 : throw std::invalid_argument("Invalid value for -a_srs");
2319 : }
2320 1 : psOptions->osOutputSRS = pszSRS;
2321 1 : CPLFree(pszSRS);
2322 226 : })
2323 225 : .help(_("Override the projection for the output file.."));
2324 :
2325 225 : argParser->add_argument("-r")
2326 450 : .metavar("nearest|bilinear|cubic|cubicspline|lanczos|average|mode")
2327 225 : .store_into(psOptions->osResampling)
2328 225 : .help(_("Resampling algorithm."));
2329 :
2330 225 : argParser->add_open_options_argument(&psOptions->aosOpenOptions);
2331 :
2332 225 : argParser->add_creation_options_argument(psOptions->aosCreateOptions);
2333 :
2334 225 : argParser->add_argument("-write_absolute_path")
2335 225 : .flag()
2336 225 : .store_into(psOptions->bWriteAbsolutePath)
2337 : .help(_("Write the absolute path of the raster files in the tile index "
2338 225 : "file."));
2339 :
2340 225 : argParser->add_argument("-ignore_srcmaskband")
2341 225 : .flag()
2342 0 : .action([psOptions](const std::string &)
2343 225 : { psOptions->bUseSrcMaskBand = false; })
2344 225 : .help(_("Cause mask band of sources will not be taken into account."));
2345 :
2346 225 : argParser->add_argument("-nodata_max_mask_threshold")
2347 450 : .metavar("<threshold>")
2348 225 : .scan<'g', double>()
2349 : .action(
2350 18 : [psOptions](const std::string &s)
2351 : {
2352 9 : psOptions->bNoDataFromMask = true;
2353 9 : psOptions->dfMaskValueThreshold = CPLAtofM(s.c_str());
2354 225 : })
2355 : .help(_("Replaces the value of the source with the value of -vrtnodata "
2356 : "when the value of the mask band of the source is less or "
2357 225 : "equal to the threshold."));
2358 :
2359 225 : argParser->add_argument("-program_name")
2360 225 : .store_into(psOptions->osProgramName)
2361 225 : .hidden();
2362 :
2363 225 : if (psOptionsForBinary)
2364 : {
2365 20 : if (psOptionsForBinary->osDstFilename.empty())
2366 : {
2367 : // We normally go here, unless undocumented -o switch is used
2368 20 : argParser->add_argument("vrt_dataset_name")
2369 40 : .metavar("<vrt_dataset_name>")
2370 20 : .store_into(psOptionsForBinary->osDstFilename)
2371 20 : .help(_("Output VRT."));
2372 : }
2373 :
2374 20 : argParser->add_argument("src_dataset_name")
2375 40 : .metavar("<src_dataset_name>")
2376 20 : .nargs(argparse::nargs_pattern::any)
2377 : .action(
2378 41 : [psOptions, psOptionsForBinary](const std::string &s)
2379 : {
2380 41 : if (!add_file_to_list(s.c_str(),
2381 : psOptions->osTileIndex.c_str(),
2382 41 : psOptionsForBinary->aosSrcFiles))
2383 : {
2384 : throw std::invalid_argument(
2385 0 : std::string("Cannot add ")
2386 0 : .append(s)
2387 0 : .append(" to input file list"));
2388 : }
2389 61 : })
2390 20 : .help(_("Input dataset(s)."));
2391 : }
2392 :
2393 225 : return argParser;
2394 : }
2395 :
2396 : /************************************************************************/
2397 : /* GDALBuildVRTGetParserUsage() */
2398 : /************************************************************************/
2399 :
2400 1 : std::string GDALBuildVRTGetParserUsage()
2401 : {
2402 : try
2403 : {
2404 2 : GDALBuildVRTOptions sOptions;
2405 2 : GDALBuildVRTOptionsForBinary sOptionsForBinary;
2406 : auto argParser =
2407 2 : GDALBuildVRTOptionsGetParser(&sOptions, &sOptionsForBinary);
2408 1 : return argParser->usage();
2409 : }
2410 0 : catch (const std::exception &err)
2411 : {
2412 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
2413 0 : err.what());
2414 0 : return std::string();
2415 : }
2416 : }
2417 :
2418 : /************************************************************************/
2419 : /* GDALBuildVRTOptionsNew() */
2420 : /************************************************************************/
2421 :
2422 : /**
2423 : * Allocates a GDALBuildVRTOptions struct.
2424 : *
2425 : * @param papszArgv NULL terminated list of options (potentially including
2426 : * filename and open options too), or NULL. The accepted options are the ones of
2427 : * the <a href="/programs/gdalbuildvrt.html">gdalbuildvrt</a> utility.
2428 : * @param psOptionsForBinary (output) may be NULL (and should generally be
2429 : * NULL), otherwise (gdalbuildvrt_bin.cpp use case) must be allocated with
2430 : * GDALBuildVRTOptionsForBinaryNew() prior to this function. Will be filled
2431 : * with potentially present filename, open options,...
2432 : * @return pointer to the allocated GDALBuildVRTOptions struct. Must be freed
2433 : * with GDALBuildVRTOptionsFree().
2434 : *
2435 : * @since GDAL 2.1
2436 : */
2437 :
2438 : GDALBuildVRTOptions *
2439 224 : GDALBuildVRTOptionsNew(char **papszArgv,
2440 : GDALBuildVRTOptionsForBinary *psOptionsForBinary)
2441 : {
2442 448 : auto psOptions = std::make_unique<GDALBuildVRTOptions>();
2443 :
2444 448 : CPLStringList aosArgv;
2445 224 : const int nArgc = CSLCount(papszArgv);
2446 1154 : for (int i = 0;
2447 1154 : i < nArgc && papszArgv != nullptr && papszArgv[i] != nullptr; i++)
2448 : {
2449 930 : if (psOptionsForBinary && EQUAL(papszArgv[i], "-o") && i + 1 < nArgc &&
2450 0 : papszArgv[i + 1] != nullptr)
2451 : {
2452 : // Undocumented alternate way of specifying the destination file
2453 0 : psOptionsForBinary->osDstFilename = papszArgv[i + 1];
2454 0 : ++i;
2455 : }
2456 : // argparser will be confused if the value of a string argument
2457 : // starts with a negative sign.
2458 930 : else if (EQUAL(papszArgv[i], "-srcnodata") && i + 1 < nArgc)
2459 : {
2460 6 : ++i;
2461 6 : psOptions->osSrcNoData = papszArgv[i];
2462 : }
2463 : // argparser will be confused if the value of a string argument
2464 : // starts with a negative sign.
2465 924 : else if (EQUAL(papszArgv[i], "-vrtnodata") && i + 1 < nArgc)
2466 : {
2467 21 : ++i;
2468 21 : psOptions->osVRTNoData = papszArgv[i];
2469 : }
2470 :
2471 : else
2472 : {
2473 903 : aosArgv.AddString(papszArgv[i]);
2474 : }
2475 : }
2476 :
2477 : try
2478 : {
2479 : auto argParser =
2480 448 : GDALBuildVRTOptionsGetParser(psOptions.get(), psOptionsForBinary);
2481 :
2482 224 : argParser->parse_args_without_binary_name(aosArgv.List());
2483 :
2484 230 : if (auto adfTargetRes = argParser->present<std::vector<double>>("-tr"))
2485 : {
2486 8 : psOptions->we_res = (*adfTargetRes)[0];
2487 8 : psOptions->ns_res = (*adfTargetRes)[1];
2488 : }
2489 :
2490 235 : if (auto oTE = argParser->present<std::vector<double>>("-te"))
2491 : {
2492 13 : psOptions->xmin = (*oTE)[0];
2493 13 : psOptions->ymin = (*oTE)[1];
2494 13 : psOptions->xmax = (*oTE)[2];
2495 13 : psOptions->ymax = (*oTE)[3];
2496 : }
2497 :
2498 441 : if (psOptions->osPixelFunction.empty() &&
2499 219 : !psOptions->aosPixelFunctionArgs.empty())
2500 : {
2501 : throw std::runtime_error(
2502 1 : "Pixel function arguments provided without a pixel function");
2503 : }
2504 :
2505 221 : return psOptions.release();
2506 : }
2507 3 : catch (const std::exception &err)
2508 : {
2509 3 : CPLError(CE_Failure, CPLE_AppDefined, "%s", err.what());
2510 3 : return nullptr;
2511 : }
2512 : }
2513 :
2514 : /************************************************************************/
2515 : /* GDALBuildVRTOptionsFree() */
2516 : /************************************************************************/
2517 :
2518 : /**
2519 : * Frees the GDALBuildVRTOptions struct.
2520 : *
2521 : * @param psOptions the options struct for GDALBuildVRT().
2522 : *
2523 : * @since GDAL 2.1
2524 : */
2525 :
2526 220 : void GDALBuildVRTOptionsFree(GDALBuildVRTOptions *psOptions)
2527 : {
2528 220 : delete psOptions;
2529 220 : }
2530 :
2531 : /************************************************************************/
2532 : /* GDALBuildVRTOptionsSetProgress() */
2533 : /************************************************************************/
2534 :
2535 : /**
2536 : * Set a progress function.
2537 : *
2538 : * @param psOptions the options struct for GDALBuildVRT().
2539 : * @param pfnProgress the progress callback.
2540 : * @param pProgressData the user data for the progress callback.
2541 : *
2542 : * @since GDAL 2.1
2543 : */
2544 :
2545 20 : void GDALBuildVRTOptionsSetProgress(GDALBuildVRTOptions *psOptions,
2546 : GDALProgressFunc pfnProgress,
2547 : void *pProgressData)
2548 : {
2549 20 : psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
2550 20 : psOptions->pProgressData = pProgressData;
2551 20 : if (pfnProgress == GDALTermProgress)
2552 19 : psOptions->bQuiet = false;
2553 20 : }
|