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 2356 : 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 2356 : 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 2356 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] +
132 2356 : psDP->nRasterXSize * psDP->gt[GEOTRSFRM_WE_RES] <=
133 : minX)
134 0 : return FALSE;
135 2356 : if (psDP->gt[GEOTRSFRM_TOPLEFT_X] >= maxX)
136 1 : return FALSE;
137 2355 : if (psDP->gt[GEOTRSFRM_TOPLEFT_Y] +
138 2355 : psDP->nRasterYSize * psDP->gt[GEOTRSFRM_NS_RES] >=
139 : maxY)
140 0 : return FALSE;
141 2355 : if (psDP->gt[GEOTRSFRM_TOPLEFT_Y] <= minY)
142 0 : return FALSE;
143 :
144 2355 : 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 2352 : *pdfSrcXOff = 0.0;
153 2352 : *pdfDstXOff = ((psDP->gt[GEOTRSFRM_TOPLEFT_X] - minX) / we_res);
154 : }
155 2355 : 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 2350 : *pdfSrcYOff = 0.0;
164 2350 : *pdfDstYOff = ((maxY - psDP->gt[GEOTRSFRM_TOPLEFT_Y]) / -ns_res);
165 : }
166 :
167 2355 : *pdfSrcXSize = psDP->nRasterXSize;
168 2355 : *pdfSrcYSize = psDP->nRasterYSize;
169 2355 : if (*pdfSrcXOff > 0)
170 3 : *pdfSrcXSize -= *pdfSrcXOff;
171 2355 : if (*pdfSrcYOff > 0)
172 5 : *pdfSrcYSize -= *pdfSrcYOff;
173 :
174 2355 : const double dfSrcToDstXSize = psDP->gt[GEOTRSFRM_WE_RES] / we_res;
175 2355 : *pdfDstXSize = *pdfSrcXSize * dfSrcToDstXSize;
176 2355 : const double dfSrcToDstYSize = psDP->gt[GEOTRSFRM_NS_RES] / ns_res;
177 2355 : *pdfDstYSize = *pdfSrcYSize * dfSrcToDstYSize;
178 :
179 2355 : if (*pdfDstXOff + *pdfDstXSize > nTargetXSize)
180 : {
181 7 : *pdfDstXSize = nTargetXSize - *pdfDstXOff;
182 7 : *pdfSrcXSize = *pdfDstXSize / dfSrcToDstXSize;
183 : }
184 :
185 2355 : if (*pdfDstYOff + *pdfDstYSize > nTargetYSize)
186 : {
187 5 : *pdfDstYSize = nTargetYSize - *pdfDstYOff;
188 5 : *pdfSrcYSize = *pdfDstYSize / dfSrcToDstYSize;
189 : }
190 :
191 4710 : return *pdfSrcXSize > 0 && *pdfDstXSize > 0 && *pdfSrcYSize > 0 &&
192 4710 : *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 235 : 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 235 : const CPLStringList &aosCreateOptionsIn, bool bWriteAbsolutePathIn)
312 : : bStrict(bStrictIn), aosCreateOptions(aosCreateOptionsIn),
313 : aosPixelFunctionArgs(aosPixelFunctionArgsIn),
314 235 : bWriteAbsolutePath(bWriteAbsolutePathIn)
315 : {
316 235 : pszOutputFilename = CPLStrdup(pszOutputFilenameIn);
317 235 : nInputFiles = nInputFilesIn;
318 235 : papszOpenOptions = CSLDuplicate(const_cast<char **>(papszOpenOptionsIn));
319 :
320 235 : if (pszPixelFunctionIn != nullptr)
321 : {
322 3 : osPixelFunction = pszPixelFunctionIn;
323 : }
324 :
325 235 : if (ppszInputFilenamesIn)
326 : {
327 146 : ppszInputFilenames =
328 146 : static_cast<char **>(CPLMalloc(nInputFiles * sizeof(char *)));
329 1381 : for (int i = 0; i < nInputFiles; i++)
330 : {
331 1235 : ppszInputFilenames[i] = CPLStrdup(ppszInputFilenamesIn[i]);
332 : }
333 : }
334 89 : else if (pahSrcDSIn)
335 : {
336 89 : nSrcDSCount = nInputFiles;
337 89 : pahSrcDS = static_cast<GDALDatasetH *>(
338 89 : CPLMalloc(nInputFiles * sizeof(GDALDatasetH)));
339 89 : memcpy(pahSrcDS, pahSrcDSIn, nInputFiles * sizeof(GDALDatasetH));
340 89 : ppszInputFilenames =
341 89 : static_cast<char **>(CPLMalloc(nInputFiles * sizeof(char *)));
342 1229 : for (int i = 0; i < nInputFiles; i++)
343 : {
344 2280 : ppszInputFilenames[i] =
345 1140 : CPLStrdup(GDALGetDescription(pahSrcDSIn[i]));
346 : }
347 : }
348 :
349 235 : bExplicitBandList = nBandCount != 0;
350 235 : nSelectedBands = nBandCount;
351 235 : 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 235 : resolutionStrategy = resolutionStrategyIn;
360 235 : we_res = we_resIn;
361 235 : ns_res = ns_resIn;
362 235 : bTargetAlignedPixels = bTargetAlignedPixelsIn;
363 235 : minX = minXIn;
364 235 : minY = minYIn;
365 235 : maxX = maxXIn;
366 235 : maxY = maxYIn;
367 235 : bSeparate = bSeparateIn;
368 235 : bAllowProjectionDifference = bAllowProjectionDifferenceIn;
369 235 : bAddAlpha = bAddAlphaIn;
370 235 : bHideNoData = bHideNoDataIn;
371 235 : nSubdataset = nSubdatasetIn;
372 235 : pszSrcNoData = (pszSrcNoDataIn) ? CPLStrdup(pszSrcNoDataIn) : nullptr;
373 235 : pszVRTNoData = (pszVRTNoDataIn) ? CPLStrdup(pszVRTNoDataIn) : nullptr;
374 235 : pszOutputSRS = (pszOutputSRSIn) ? CPLStrdup(pszOutputSRSIn) : nullptr;
375 235 : pszResampling = (pszResamplingIn) ? CPLStrdup(pszResamplingIn) : nullptr;
376 235 : bUseSrcMaskBand = bUseSrcMaskBandIn;
377 235 : bNoDataFromMask = bNoDataFromMaskIn;
378 235 : dfMaskValueThreshold = dfMaskValueThresholdIn;
379 235 : }
380 :
381 : /************************************************************************/
382 : /* ~VRTBuilder() */
383 : /************************************************************************/
384 :
385 235 : VRTBuilder::~VRTBuilder()
386 : {
387 235 : CPLFree(pszOutputFilename);
388 235 : CPLFree(pszSrcNoData);
389 235 : CPLFree(pszVRTNoData);
390 235 : CPLFree(panSelectedBandList);
391 :
392 235 : if (ppszInputFilenames)
393 : {
394 2610 : for (int i = 0; i < nInputFiles; i++)
395 : {
396 2375 : CPLFree(ppszInputFilenames[i]);
397 : }
398 : }
399 235 : CPLFree(ppszInputFilenames);
400 235 : CPLFree(pahSrcDS);
401 :
402 235 : CPLFree(pszProjectionRef);
403 235 : CPLFree(padfSrcNoData);
404 235 : CPLFree(padfVRTNoData);
405 235 : CPLFree(pszOutputSRS);
406 235 : CPLFree(pszResampling);
407 235 : CSLDestroy(papszOpenOptions);
408 235 : }
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 2362 : static void checkNoDataValues(const std::vector<BandProperty> &asProperties)
453 : {
454 6046 : for (const auto &oProps : asProperties)
455 : {
456 3738 : 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 2362 : }
466 :
467 2373 : std::string VRTBuilder::AnalyseRaster(GDALDatasetH hDS,
468 : DatasetProperty *psDatasetProperties)
469 : {
470 2373 : GDALDataset *poDS = GDALDataset::FromHandle(hDS);
471 2373 : const char *dsFileName = poDS->GetDescription();
472 2373 : char **papszMetadata = poDS->GetMetadata("SUBDATASETS");
473 2373 : 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 2373 : const char *proj = poDS->GetProjectionRef();
520 2373 : auto > = psDatasetProperties->gt;
521 2373 : int bGotGeoTransform = poDS->GetGeoTransform(gt) == CE_None;
522 2373 : 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 2340 : if (!bGotGeoTransform)
564 : {
565 0 : return m_osProgramName + " does not support ungeoreferenced image.";
566 : }
567 2340 : bHasGeoTransform = TRUE;
568 : }
569 :
570 2373 : if (bGotGeoTransform)
571 : {
572 4742 : if (gt[GEOTRSFRM_ROTATION_PARAM1] != 0 ||
573 2371 : gt[GEOTRSFRM_ROTATION_PARAM2] != 0)
574 : {
575 0 : return m_osProgramName +
576 0 : " does not support rotated geo transforms.";
577 : }
578 2371 : if (gt[GEOTRSFRM_NS_RES] >= 0)
579 : {
580 0 : return m_osProgramName +
581 0 : " does not support positive NS resolution.";
582 : }
583 : }
584 :
585 2373 : psDatasetProperties->nRasterXSize = poDS->GetRasterXSize();
586 2373 : psDatasetProperties->nRasterYSize = poDS->GetRasterYSize();
587 2373 : if (bFirst && bSeparate && !bGotGeoTransform)
588 : {
589 1 : nRasterXSize = poDS->GetRasterXSize();
590 1 : nRasterYSize = poDS->GetRasterYSize();
591 : }
592 :
593 2373 : double ds_minX = gt[GEOTRSFRM_TOPLEFT_X];
594 2373 : double ds_maxY = gt[GEOTRSFRM_TOPLEFT_Y];
595 2373 : double ds_maxX = ds_minX + GDALGetRasterXSize(hDS) * gt[GEOTRSFRM_WE_RES];
596 2373 : double ds_minY = ds_maxY + GDALGetRasterYSize(hDS) * gt[GEOTRSFRM_NS_RES];
597 :
598 2373 : int _nBands = GDALGetRasterCount(hDS);
599 2373 : if (_nBands == 0)
600 : {
601 0 : return "Dataset has no bands";
602 : }
603 2382 : if (bNoDataFromMask &&
604 9 : poDS->GetRasterBand(_nBands)->GetColorInterpretation() == GCI_AlphaBand)
605 3 : _nBands--;
606 :
607 2373 : GDALRasterBand *poFirstBand = poDS->GetRasterBand(1);
608 2373 : poFirstBand->GetBlockSize(&psDatasetProperties->nBlockXSize,
609 : &psDatasetProperties->nBlockYSize);
610 :
611 : /* For the -separate case */
612 2373 : psDatasetProperties->aeBandType.resize(_nBands);
613 :
614 2373 : psDatasetProperties->adfNoDataValues.resize(_nBands);
615 2373 : psDatasetProperties->abHasNoData.resize(_nBands);
616 :
617 2373 : psDatasetProperties->adfOffset.resize(_nBands);
618 2373 : psDatasetProperties->abHasOffset.resize(_nBands);
619 :
620 2373 : psDatasetProperties->adfScale.resize(_nBands);
621 2373 : psDatasetProperties->abHasScale.resize(_nBands);
622 :
623 2373 : psDatasetProperties->abHasMaskBand.resize(_nBands);
624 :
625 2373 : psDatasetProperties->bHasDatasetMask =
626 2373 : poFirstBand->GetMaskFlags() == GMF_PER_DATASET;
627 2373 : if (psDatasetProperties->bHasDatasetMask)
628 17 : bHasDatasetMask = TRUE;
629 2373 : poFirstBand->GetMaskBand()->GetBlockSize(
630 : &psDatasetProperties->nMaskBlockXSize,
631 : &psDatasetProperties->nMaskBlockYSize);
632 :
633 2373 : psDatasetProperties->bLastBandIsAlpha = false;
634 2373 : 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 2373 : const int nOverviews = poFirstBand->GetOverviewCount();
639 2373 : int nExpectedOvFactor = 2;
640 2385 : 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 5941 : for (int j = 0; j < _nBands; j++)
662 : {
663 3568 : GDALRasterBand *poBand = poDS->GetRasterBand(j + 1);
664 :
665 3568 : psDatasetProperties->aeBandType[j] = poBand->GetRasterDataType();
666 :
667 3568 : 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 3564 : int bHasNoData = false;
679 7128 : psDatasetProperties->adfNoDataValues[j] =
680 3564 : poBand->GetNoDataValue(&bHasNoData);
681 3564 : psDatasetProperties->abHasNoData[j] = bHasNoData != 0;
682 : }
683 :
684 3568 : int bHasOffset = false;
685 3568 : psDatasetProperties->adfOffset[j] = poBand->GetOffset(&bHasOffset);
686 7136 : psDatasetProperties->abHasOffset[j] =
687 3568 : bHasOffset != 0 && psDatasetProperties->adfOffset[j] != 0.0;
688 :
689 3568 : int bHasScale = false;
690 3568 : psDatasetProperties->adfScale[j] = poBand->GetScale(&bHasScale);
691 7136 : psDatasetProperties->abHasScale[j] =
692 3568 : bHasScale != 0 && psDatasetProperties->adfScale[j] != 1.0;
693 :
694 3568 : const int nMaskFlags = poBand->GetMaskFlags();
695 3568 : psDatasetProperties->abHasMaskBand[j] =
696 7076 : (nMaskFlags != GMF_ALL_VALID && nMaskFlags != GMF_NODATA) ||
697 7076 : poBand->GetColorInterpretation() == GCI_AlphaBand;
698 : }
699 :
700 2373 : 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 2372 : if (bFirst)
713 : {
714 234 : nTotalBands = _nBands;
715 234 : if (bAddAlpha && psDatasetProperties->bLastBandIsAlpha)
716 : {
717 4 : bLastBandIsAlpha = true;
718 4 : nTotalBands--;
719 : }
720 :
721 234 : if (proj)
722 234 : pszProjectionRef = CPLStrdup(proj);
723 234 : if (!bUserExtent)
724 : {
725 221 : minX = ds_minX;
726 221 : minY = ds_minY;
727 221 : maxX = ds_maxX;
728 221 : maxY = ds_maxY;
729 : }
730 :
731 234 : if (!bSeparate)
732 : {
733 : // if not provided an explicit band list, take the one of the first
734 : // dataset
735 217 : if (nSelectedBands == 0)
736 : {
737 200 : nSelectedBands = nTotalBands;
738 200 : CPLFree(panSelectedBandList);
739 200 : panSelectedBandList =
740 200 : static_cast<int *>(CPLMalloc(nSelectedBands * sizeof(int)));
741 489 : for (int j = 0; j < nSelectedBands; j++)
742 : {
743 289 : panSelectedBandList[j] = j + 1;
744 : }
745 : }
746 735 : for (int j = 0; j < nSelectedBands; j++)
747 : {
748 518 : nMaxSelectedBandNo =
749 518 : std::max(nMaxSelectedBandNo, panSelectedBandList[j]);
750 : }
751 :
752 217 : asBandProperties.resize(nSelectedBands);
753 734 : for (int j = 0; j < nSelectedBands; j++)
754 : {
755 518 : const int nSelBand = panSelectedBandList[j];
756 518 : if (nSelBand <= 0 || nSelBand > nTotalBands)
757 : {
758 1 : return CPLSPrintf("Invalid band number: %d", nSelBand);
759 : }
760 517 : GDALRasterBand *poBand = poDS->GetRasterBand(nSelBand);
761 1034 : asBandProperties[j].colorInterpretation =
762 517 : poBand->GetColorInterpretation();
763 517 : asBandProperties[j].dataType = poBand->GetRasterDataType();
764 517 : 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 515 : asBandProperties[j].colorTable = nullptr;
775 :
776 517 : 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 491 : int bHasNoData = false;
788 982 : asBandProperties[j].noDataValue =
789 491 : poBand->GetNoDataValue(&bHasNoData);
790 491 : asBandProperties[j].bHasNoData = bHasNoData != 0;
791 : }
792 :
793 517 : int bHasOffset = false;
794 517 : asBandProperties[j].dfOffset = poBand->GetOffset(&bHasOffset);
795 517 : asBandProperties[j].bHasOffset =
796 517 : bHasOffset != 0 && asBandProperties[j].dfOffset != 0.0;
797 :
798 517 : int bHasScale = false;
799 517 : asBandProperties[j].dfScale = poBand->GetScale(&bHasScale);
800 517 : asBandProperties[j].bHasScale =
801 517 : 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 3 : minX = ds_minX;
970 2128 : if (ds_minY < minY)
971 25 : minY = ds_minY;
972 2128 : if (ds_maxX > maxX)
973 698 : maxX = ds_maxX;
974 2128 : if (ds_maxY > maxY)
975 37 : maxY = ds_maxY;
976 : }
977 : }
978 :
979 2364 : if (resolutionStrategy == AVERAGE_RESOLUTION)
980 : {
981 2284 : ++nCountValid;
982 : {
983 2284 : const double dfDelta = gt[GEOTRSFRM_WE_RES] - we_res;
984 2284 : we_res += dfDelta / nCountValid;
985 : }
986 : {
987 2284 : const double dfDelta = gt[GEOTRSFRM_NS_RES] - ns_res;
988 2284 : ns_res += dfDelta / nCountValid;
989 : }
990 : }
991 80 : else if (resolutionStrategy == SAME_RESOLUTION)
992 : {
993 43 : if (bFirst)
994 : {
995 37 : we_res = gt[GEOTRSFRM_WE_RES];
996 37 : 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 2362 : checkNoDataValues(asBandProperties);
1042 :
1043 2362 : 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 : cpl::down_cast<GDALProxyPoolDataset *>(
1133 : GDALDataset::FromHandle(hProxyDS))
1134 12 : ->SetOpenOptions(papszOpenOptions);
1135 :
1136 27 : for (int jBand = 0;
1137 27 : jBand <
1138 27 : static_cast<int>(psDatasetProperties->aeBandType.size());
1139 : ++jBand)
1140 : {
1141 15 : GDALProxyPoolDatasetAddSrcBandDescription(
1142 15 : hProxyDS, psDatasetProperties->aeBandType[jBand],
1143 : psDatasetProperties->nBlockXSize,
1144 : psDatasetProperties->nBlockYSize);
1145 : }
1146 : }
1147 :
1148 : const int nBandsToIter =
1149 32 : nSelectedBands > 0
1150 62 : ? nSelectedBands
1151 30 : : static_cast<int>(psDatasetProperties->aeBandType.size());
1152 72 : for (int iBandToIter = 0; iBandToIter < nBandsToIter; ++iBandToIter)
1153 : {
1154 : // 0-based
1155 80 : const int nSrcBandIdx = nSelectedBands > 0
1156 40 : ? panSelectedBandList[iBandToIter] - 1
1157 : : iBandToIter;
1158 40 : assert(nSrcBandIdx >= 0);
1159 40 : poVRTDS->AddBand(psDatasetProperties->aeBandType[nSrcBandIdx],
1160 40 : nullptr);
1161 :
1162 : VRTSourcedRasterBand *poVRTBand =
1163 : static_cast<VRTSourcedRasterBand *>(
1164 40 : poVRTDS->GetRasterBand(iBand));
1165 :
1166 40 : if (bHideNoData)
1167 0 : poVRTBand->SetMetadataItem("HideNoDataValue", "1", nullptr);
1168 :
1169 40 : if (bAllowVRTNoData)
1170 : {
1171 38 : if (nVRTNoDataCount > 0)
1172 : {
1173 4 : if (iBand - 1 < nVRTNoDataCount)
1174 4 : poVRTBand->SetNoDataValue(padfVRTNoData[iBand - 1]);
1175 : else
1176 0 : poVRTBand->SetNoDataValue(
1177 0 : padfVRTNoData[nVRTNoDataCount - 1]);
1178 : }
1179 34 : else if (psDatasetProperties->abHasNoData[nSrcBandIdx])
1180 : {
1181 2 : poVRTBand->SetNoDataValue(
1182 2 : psDatasetProperties->adfNoDataValues[nSrcBandIdx]);
1183 : }
1184 : }
1185 :
1186 : VRTSimpleSource *poSimpleSource;
1187 78 : if (bAllowSrcNoData &&
1188 72 : (nSrcNoDataCount > 0 ||
1189 74 : psDatasetProperties->abHasNoData[nSrcBandIdx]))
1190 : {
1191 6 : auto poComplexSource = new VRTComplexSource();
1192 6 : poSimpleSource = poComplexSource;
1193 6 : if (nSrcNoDataCount > 0)
1194 : {
1195 4 : if (iBand - 1 < nSrcNoDataCount)
1196 4 : poComplexSource->SetNoDataValue(
1197 4 : padfSrcNoData[iBand - 1]);
1198 : else
1199 0 : poComplexSource->SetNoDataValue(
1200 0 : padfSrcNoData[nSrcNoDataCount - 1]);
1201 : }
1202 : else /* if (psDatasetProperties->abHasNoData[nSrcBandIdx]) */
1203 : {
1204 2 : poComplexSource->SetNoDataValue(
1205 2 : psDatasetProperties->adfNoDataValues[nSrcBandIdx]);
1206 : }
1207 : }
1208 68 : else if (bUseSrcMaskBand &&
1209 68 : psDatasetProperties->abHasMaskBand[nSrcBandIdx])
1210 : {
1211 1 : auto poSource = new VRTComplexSource();
1212 1 : poSource->SetUseMaskBand(true);
1213 1 : poSimpleSource = poSource;
1214 : }
1215 : else
1216 33 : poSimpleSource = new VRTSimpleSource();
1217 :
1218 40 : if (pszResampling)
1219 0 : poSimpleSource->SetResampling(pszResampling);
1220 80 : poVRTBand->ConfigureSource(
1221 : poSimpleSource,
1222 : static_cast<GDALRasterBand *>(
1223 40 : GDALGetRasterBand(hSourceDS, nSrcBandIdx + 1)),
1224 : FALSE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1225 : dfDstYOff, dfDstXSize, dfDstYSize);
1226 :
1227 40 : if (bWriteAbsolutePath)
1228 3 : WriteAbsolutePath(poSimpleSource, dsFileName);
1229 :
1230 40 : if (psDatasetProperties->abHasOffset[nSrcBandIdx])
1231 0 : poVRTBand->SetOffset(
1232 0 : psDatasetProperties->adfOffset[nSrcBandIdx]);
1233 :
1234 40 : if (psDatasetProperties->abHasScale[nSrcBandIdx])
1235 0 : poVRTBand->SetScale(psDatasetProperties->adfScale[nSrcBandIdx]);
1236 :
1237 40 : poVRTBand->AddSource(poSimpleSource);
1238 :
1239 40 : iBand++;
1240 : }
1241 :
1242 32 : if (bDropRef)
1243 : {
1244 12 : GDALDereferenceDataset(hSourceDS);
1245 : }
1246 : }
1247 17 : }
1248 :
1249 : /************************************************************************/
1250 : /* CreateVRTNonSeparate() */
1251 : /************************************************************************/
1252 :
1253 212 : void VRTBuilder::CreateVRTNonSeparate(VRTDataset *poVRTDS)
1254 : {
1255 424 : CPLStringList aosOptions;
1256 :
1257 212 : if (!osPixelFunction.empty())
1258 : {
1259 3 : aosOptions.AddNameValue("subclass", "VRTDerivedRasterBand");
1260 3 : aosOptions.AddNameValue("PixelFunctionType", osPixelFunction.c_str());
1261 3 : aosOptions.AddNameValue("SkipNonContributingSources", "1");
1262 6 : CPLString osName;
1263 2 : for (const auto &[pszKey, pszValue] :
1264 5 : cpl::IterateNameValue(aosPixelFunctionArgs))
1265 : {
1266 1 : osName.Printf("_PIXELFN_ARG_%s", pszKey);
1267 1 : aosOptions.AddNameValue(osName.c_str(), pszValue);
1268 : }
1269 : }
1270 :
1271 725 : for (int j = 0; j < nSelectedBands; j++)
1272 : {
1273 513 : const char *pszSourceTransferType = "Float64";
1274 1025 : if (osPixelFunction == "mean" || osPixelFunction == "min" ||
1275 512 : osPixelFunction == "max")
1276 : {
1277 : pszSourceTransferType =
1278 1 : GDALGetDataTypeName(asBandProperties[j].dataType);
1279 : }
1280 513 : aosOptions.AddNameValue("SourceTransferType", pszSourceTransferType);
1281 :
1282 513 : poVRTDS->AddBand(asBandProperties[j].dataType, aosOptions.List());
1283 513 : GDALRasterBand *poBand = poVRTDS->GetRasterBand(j + 1);
1284 513 : poBand->SetColorInterpretation(asBandProperties[j].colorInterpretation);
1285 513 : if (asBandProperties[j].colorInterpretation == GCI_PaletteIndex)
1286 : {
1287 2 : poBand->SetColorTable(asBandProperties[j].colorTable.get());
1288 : }
1289 513 : if (bAllowVRTNoData && asBandProperties[j].bHasNoData)
1290 39 : poBand->SetNoDataValue(asBandProperties[j].noDataValue);
1291 513 : if (bHideNoData)
1292 2 : poBand->SetMetadataItem("HideNoDataValue", "1");
1293 :
1294 513 : if (asBandProperties[j].bHasOffset)
1295 0 : poBand->SetOffset(asBandProperties[j].dfOffset);
1296 :
1297 513 : if (asBandProperties[j].bHasScale)
1298 0 : poBand->SetScale(asBandProperties[j].dfScale);
1299 : }
1300 :
1301 212 : VRTSourcedRasterBand *poMaskVRTBand = nullptr;
1302 212 : if (bAddAlpha)
1303 : {
1304 11 : poVRTDS->AddBand(GDT_Byte);
1305 11 : GDALRasterBand *poBand = poVRTDS->GetRasterBand(nSelectedBands + 1);
1306 11 : poBand->SetColorInterpretation(GCI_AlphaBand);
1307 : }
1308 201 : else if (bHasDatasetMask)
1309 : {
1310 12 : poVRTDS->CreateMaskBand(GMF_PER_DATASET);
1311 : poMaskVRTBand = static_cast<VRTSourcedRasterBand *>(
1312 12 : poVRTDS->GetRasterBand(1)->GetMaskBand());
1313 : }
1314 :
1315 212 : bool bCanCollectOverviewFactors = true;
1316 424 : std::set<int> anOverviewFactorsSet;
1317 424 : std::vector<int> anIdxValidDatasets;
1318 :
1319 2545 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1320 : {
1321 2333 : DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1322 :
1323 2333 : if (psDatasetProperties->isFileOK == FALSE)
1324 8 : continue;
1325 :
1326 2326 : const char *dsFileName = ppszInputFilenames[i];
1327 :
1328 : double dfSrcXOff;
1329 : double dfSrcYOff;
1330 : double dfSrcXSize;
1331 : double dfSrcYSize;
1332 : double dfDstXOff;
1333 : double dfDstYOff;
1334 : double dfDstXSize;
1335 : double dfDstYSize;
1336 2326 : if (!GetSrcDstWin(psDatasetProperties, we_res, ns_res, minX, minY, maxX,
1337 : maxY, nRasterXSize, nRasterYSize, &dfSrcXOff,
1338 : &dfSrcYOff, &dfSrcXSize, &dfSrcYSize, &dfDstXOff,
1339 : &dfDstYOff, &dfDstXSize, &dfDstYSize))
1340 : {
1341 1 : CPLDebug("BuildVRT",
1342 : "Skipping %s as not intersecting area of interest",
1343 : dsFileName);
1344 1 : continue;
1345 : }
1346 :
1347 2325 : anIdxValidDatasets.push_back(i);
1348 :
1349 2325 : if (bCanCollectOverviewFactors)
1350 : {
1351 2310 : if (std::abs(psDatasetProperties->gt[1] - we_res) >
1352 4601 : 1e-8 * std::abs(we_res) ||
1353 2291 : std::abs(psDatasetProperties->gt[5] - ns_res) >
1354 2291 : 1e-8 * std::abs(ns_res))
1355 : {
1356 19 : bCanCollectOverviewFactors = false;
1357 19 : anOverviewFactorsSet.clear();
1358 : }
1359 : }
1360 2325 : if (bCanCollectOverviewFactors)
1361 : {
1362 2300 : for (int nOvFactor : psDatasetProperties->anOverviewFactors)
1363 9 : anOverviewFactorsSet.insert(nOvFactor);
1364 : }
1365 :
1366 : GDALDatasetH hSourceDS;
1367 2325 : bool bDropRef = false;
1368 :
1369 5760 : if (nSrcDSCount == nInputFiles &&
1370 3435 : GDALGetDatasetDriver(pahSrcDS[i]) != nullptr &&
1371 1110 : (dsFileName[0] == '\0' || // could be a unnamed VRT file
1372 53 : EQUAL(GDALGetDescription(GDALGetDatasetDriver(pahSrcDS[i])),
1373 : "MEM")))
1374 : {
1375 1091 : hSourceDS = pahSrcDS[i];
1376 : }
1377 : else
1378 : {
1379 1234 : bDropRef = true;
1380 2468 : GDALProxyPoolDatasetH hProxyDS = GDALProxyPoolDatasetCreate(
1381 : dsFileName, psDatasetProperties->nRasterXSize,
1382 : psDatasetProperties->nRasterYSize, GA_ReadOnly, TRUE,
1383 1234 : pszProjectionRef, psDatasetProperties->gt.data());
1384 : cpl::down_cast<GDALProxyPoolDataset *>(
1385 : GDALDataset::FromHandle(hProxyDS))
1386 1234 : ->SetOpenOptions(papszOpenOptions);
1387 :
1388 3582 : for (int j = 0;
1389 3582 : j < nMaxSelectedBandNo +
1390 42 : (bAddAlpha && psDatasetProperties->bLastBandIsAlpha
1391 3624 : ? 1
1392 : : 0);
1393 : j++)
1394 : {
1395 2348 : GDALProxyPoolDatasetAddSrcBandDescription(
1396 : hProxyDS,
1397 2348 : j < static_cast<int>(asBandProperties.size())
1398 2343 : ? asBandProperties[j].dataType
1399 : : GDT_Byte,
1400 : psDatasetProperties->nBlockXSize,
1401 : psDatasetProperties->nBlockYSize);
1402 : }
1403 1234 : if (bHasDatasetMask && !bAddAlpha)
1404 : {
1405 : static_cast<GDALProxyPoolRasterBand *>(
1406 13 : cpl::down_cast<GDALProxyPoolDataset *>(
1407 : GDALDataset::FromHandle(hProxyDS))
1408 13 : ->GetRasterBand(1))
1409 13 : ->AddSrcMaskBandDescription(
1410 : GDT_Byte, psDatasetProperties->nMaskBlockXSize,
1411 : psDatasetProperties->nMaskBlockYSize);
1412 : }
1413 :
1414 1234 : hSourceDS = static_cast<GDALDatasetH>(hProxyDS);
1415 : }
1416 :
1417 6012 : for (int j = 0;
1418 6012 : j <
1419 6012 : nSelectedBands +
1420 6012 : (bAddAlpha && psDatasetProperties->bLastBandIsAlpha ? 1 : 0);
1421 : j++)
1422 : {
1423 : VRTSourcedRasterBandH hVRTBand = static_cast<VRTSourcedRasterBandH>(
1424 3687 : poVRTDS->GetRasterBand(j + 1));
1425 3687 : const int nSelBand = j == nSelectedBands ? nSelectedBands + 1
1426 3679 : : panSelectedBandList[j];
1427 :
1428 : /* Place the raster band at the right position in the VRT */
1429 3687 : VRTSourcedRasterBand *poVRTBand =
1430 : static_cast<VRTSourcedRasterBand *>(hVRTBand);
1431 :
1432 : VRTSimpleSource *poSimpleSource;
1433 3687 : if (bNoDataFromMask)
1434 : {
1435 15 : auto poNoDataFromMaskSource = new VRTNoDataFromMaskSource();
1436 15 : poSimpleSource = poNoDataFromMaskSource;
1437 15 : poNoDataFromMaskSource->SetParameters(
1438 15 : (nVRTNoDataCount > 0)
1439 15 : ? ((j < nVRTNoDataCount)
1440 15 : ? padfVRTNoData[j]
1441 6 : : padfVRTNoData[nVRTNoDataCount - 1])
1442 : : 0,
1443 : dfMaskValueThreshold);
1444 : }
1445 7344 : else if (bAllowSrcNoData &&
1446 7344 : psDatasetProperties->abHasNoData[nSelBand - 1])
1447 : {
1448 27 : auto poComplexSource = new VRTComplexSource();
1449 27 : poSimpleSource = poComplexSource;
1450 27 : poComplexSource->SetNoDataValue(
1451 27 : psDatasetProperties->adfNoDataValues[nSelBand - 1]);
1452 : }
1453 7290 : else if (bUseSrcMaskBand &&
1454 7290 : psDatasetProperties->abHasMaskBand[nSelBand - 1])
1455 : {
1456 58 : auto poSource = new VRTComplexSource();
1457 58 : poSource->SetUseMaskBand(true);
1458 58 : poSimpleSource = poSource;
1459 : }
1460 : else
1461 3587 : poSimpleSource = new VRTSimpleSource();
1462 3687 : if (pszResampling)
1463 23 : poSimpleSource->SetResampling(pszResampling);
1464 3687 : auto poSrcBand = GDALRasterBand::FromHandle(
1465 : GDALGetRasterBand(hSourceDS, nSelBand));
1466 3687 : poVRTBand->ConfigureSource(poSimpleSource, poSrcBand, FALSE,
1467 : dfSrcXOff, dfSrcYOff, dfSrcXSize,
1468 : dfSrcYSize, dfDstXOff, dfDstYOff,
1469 : dfDstXSize, dfDstYSize);
1470 :
1471 3687 : if (bWriteAbsolutePath)
1472 3 : WriteAbsolutePath(poSimpleSource, dsFileName);
1473 :
1474 3687 : poVRTBand->AddSource(poSimpleSource);
1475 : }
1476 :
1477 2325 : if (bAddAlpha && !psDatasetProperties->bLastBandIsAlpha)
1478 : {
1479 : VRTSourcedRasterBand *poVRTBand =
1480 : static_cast<VRTSourcedRasterBand *>(
1481 12 : poVRTDS->GetRasterBand(nSelectedBands + 1));
1482 12 : if (psDatasetProperties->bHasDatasetMask && bUseSrcMaskBand)
1483 : {
1484 1 : auto poComplexSource = new VRTComplexSource();
1485 1 : poComplexSource->SetUseMaskBand(true);
1486 1 : poVRTBand->ConfigureSource(
1487 : poComplexSource,
1488 : GDALRasterBand::FromHandle(GDALGetRasterBand(hSourceDS, 1)),
1489 : TRUE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize,
1490 : dfDstXOff, dfDstYOff, dfDstXSize, dfDstYSize);
1491 :
1492 1 : if (bWriteAbsolutePath)
1493 0 : WriteAbsolutePath(poComplexSource, dsFileName);
1494 :
1495 1 : poVRTBand->AddSource(poComplexSource);
1496 : }
1497 : else
1498 : {
1499 : /* Little trick : we use an offset of 255 and a scaling of 0, so
1500 : * that in areas covered */
1501 : /* by the source, the value of the alpha band will be 255, otherwise
1502 : * it will be 0 */
1503 11 : poVRTBand->AddComplexSource(
1504 : GDALRasterBand::FromHandle(GDALGetRasterBand(hSourceDS, 1)),
1505 : dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1506 : dfDstYOff, dfDstXSize, dfDstYSize, 255, 0,
1507 : VRT_NODATA_UNSET);
1508 12 : }
1509 : }
1510 2313 : else if (bHasDatasetMask)
1511 : {
1512 : VRTSimpleSource *poSource;
1513 15 : if (bUseSrcMaskBand)
1514 : {
1515 15 : auto poComplexSource = new VRTComplexSource();
1516 15 : poComplexSource->SetUseMaskBand(true);
1517 15 : poSource = poComplexSource;
1518 : }
1519 : else
1520 : {
1521 0 : poSource = new VRTSimpleSource();
1522 : }
1523 15 : if (pszResampling)
1524 4 : poSource->SetResampling(pszResampling);
1525 15 : assert(poMaskVRTBand);
1526 15 : poMaskVRTBand->ConfigureSource(
1527 : poSource,
1528 : GDALRasterBand::FromHandle(GDALGetRasterBand(hSourceDS, 1)),
1529 : TRUE, dfSrcXOff, dfSrcYOff, dfSrcXSize, dfSrcYSize, dfDstXOff,
1530 : dfDstYOff, dfDstXSize, dfDstYSize);
1531 :
1532 15 : if (bWriteAbsolutePath)
1533 1 : WriteAbsolutePath(poSource, dsFileName);
1534 :
1535 15 : poMaskVRTBand->AddSource(poSource);
1536 : }
1537 :
1538 2325 : if (bDropRef)
1539 : {
1540 1234 : GDALDereferenceDataset(hSourceDS);
1541 : }
1542 : }
1543 :
1544 2537 : for (int i : anIdxValidDatasets)
1545 : {
1546 2325 : const DatasetProperty *psDatasetProperties = &asDatasetProperties[i];
1547 2325 : for (auto oIter = anOverviewFactorsSet.begin();
1548 2334 : oIter != anOverviewFactorsSet.end();)
1549 : {
1550 9 : const int nGlobalOvrFactor = *oIter;
1551 9 : auto oIterNext = oIter;
1552 9 : ++oIterNext;
1553 :
1554 9 : if (psDatasetProperties->nRasterXSize / nGlobalOvrFactor < 128 &&
1555 0 : psDatasetProperties->nRasterYSize / nGlobalOvrFactor < 128)
1556 : {
1557 0 : break;
1558 : }
1559 9 : if (std::find(psDatasetProperties->anOverviewFactors.begin(),
1560 : psDatasetProperties->anOverviewFactors.end(),
1561 9 : nGlobalOvrFactor) ==
1562 18 : psDatasetProperties->anOverviewFactors.end())
1563 : {
1564 0 : anOverviewFactorsSet.erase(oIter);
1565 : }
1566 :
1567 9 : oIter = oIterNext;
1568 : }
1569 : }
1570 215 : if (!anOverviewFactorsSet.empty() &&
1571 3 : CPLTestBool(CPLGetConfigOption("VRT_VIRTUAL_OVERVIEWS", "YES")))
1572 : {
1573 6 : std::vector<int> anOverviewFactors;
1574 3 : anOverviewFactors.insert(anOverviewFactors.end(),
1575 : anOverviewFactorsSet.begin(),
1576 6 : anOverviewFactorsSet.end());
1577 3 : const char *const apszOptions[] = {"VRT_VIRTUAL_OVERVIEWS=YES",
1578 : nullptr};
1579 3 : poVRTDS->BuildOverviews(pszResampling ? pszResampling : "nearest",
1580 3 : static_cast<int>(anOverviewFactors.size()),
1581 3 : &anOverviewFactors[0], 0, nullptr, nullptr,
1582 : nullptr, apszOptions);
1583 : }
1584 212 : }
1585 :
1586 : /************************************************************************/
1587 : /* Build() */
1588 : /************************************************************************/
1589 :
1590 235 : std::unique_ptr<GDALDataset> VRTBuilder::Build(GDALProgressFunc pfnProgress,
1591 : void *pProgressData)
1592 : {
1593 235 : if (bHasRunBuild)
1594 0 : return nullptr;
1595 235 : bHasRunBuild = TRUE;
1596 :
1597 235 : if (pfnProgress == nullptr)
1598 0 : pfnProgress = GDALDummyProgress;
1599 :
1600 235 : bUserExtent = (minX != 0 || minY != 0 || maxX != 0 || maxY != 0);
1601 235 : if (bUserExtent)
1602 : {
1603 13 : if (minX >= maxX || minY >= maxY)
1604 : {
1605 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Invalid user extent");
1606 0 : return nullptr;
1607 : }
1608 : }
1609 :
1610 235 : if (resolutionStrategy == USER_RESOLUTION)
1611 : {
1612 8 : if (we_res <= 0 || ns_res <= 0)
1613 : {
1614 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Invalid user resolution");
1615 0 : return nullptr;
1616 : }
1617 :
1618 : /* We work with negative north-south resolution in all the following
1619 : * code */
1620 8 : ns_res = -ns_res;
1621 : }
1622 : else
1623 : {
1624 227 : we_res = ns_res = 0;
1625 : }
1626 :
1627 235 : asDatasetProperties.resize(nInputFiles);
1628 :
1629 235 : if (pszSrcNoData != nullptr)
1630 : {
1631 6 : if (EQUAL(pszSrcNoData, "none"))
1632 : {
1633 1 : bAllowSrcNoData = FALSE;
1634 : }
1635 : else
1636 : {
1637 5 : char **papszTokens = CSLTokenizeString(pszSrcNoData);
1638 5 : nSrcNoDataCount = CSLCount(papszTokens);
1639 5 : padfSrcNoData = static_cast<double *>(
1640 5 : CPLMalloc(sizeof(double) * nSrcNoDataCount));
1641 12 : for (int i = 0; i < nSrcNoDataCount; i++)
1642 : {
1643 7 : if (!ArgIsNumeric(papszTokens[i]) &&
1644 0 : !EQUAL(papszTokens[i], "nan") &&
1645 7 : !EQUAL(papszTokens[i], "-inf") &&
1646 0 : !EQUAL(papszTokens[i], "inf"))
1647 : {
1648 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1649 : "Invalid -srcnodata value");
1650 0 : CSLDestroy(papszTokens);
1651 0 : return nullptr;
1652 : }
1653 7 : padfSrcNoData[i] = CPLAtofM(papszTokens[i]);
1654 : }
1655 5 : CSLDestroy(papszTokens);
1656 : }
1657 : }
1658 :
1659 235 : if (pszVRTNoData != nullptr)
1660 : {
1661 23 : if (EQUAL(pszVRTNoData, "none"))
1662 : {
1663 1 : bAllowVRTNoData = FALSE;
1664 : }
1665 : else
1666 : {
1667 22 : char **papszTokens = CSLTokenizeString(pszVRTNoData);
1668 22 : nVRTNoDataCount = CSLCount(papszTokens);
1669 22 : padfVRTNoData = static_cast<double *>(
1670 22 : CPLMalloc(sizeof(double) * nVRTNoDataCount));
1671 46 : for (int i = 0; i < nVRTNoDataCount; i++)
1672 : {
1673 24 : if (!ArgIsNumeric(papszTokens[i]) &&
1674 1 : !EQUAL(papszTokens[i], "nan") &&
1675 25 : !EQUAL(papszTokens[i], "-inf") &&
1676 0 : !EQUAL(papszTokens[i], "inf"))
1677 : {
1678 0 : CPLError(CE_Failure, CPLE_IllegalArg,
1679 : "Invalid -vrtnodata value");
1680 0 : CSLDestroy(papszTokens);
1681 0 : return nullptr;
1682 : }
1683 24 : padfVRTNoData[i] = CPLAtofM(papszTokens[i]);
1684 : }
1685 22 : CSLDestroy(papszTokens);
1686 : }
1687 : }
1688 :
1689 235 : bool bFoundValid = false;
1690 2606 : for (int i = 0; ppszInputFilenames != nullptr && i < nInputFiles; i++)
1691 : {
1692 2375 : const char *dsFileName = ppszInputFilenames[i];
1693 :
1694 2375 : if (!pfnProgress(1.0 * (i + 1) / nInputFiles, nullptr, pProgressData))
1695 : {
1696 0 : return nullptr;
1697 : }
1698 :
1699 2375 : GDALDatasetH hDS = (pahSrcDS)
1700 2375 : ? pahSrcDS[i]
1701 1235 : : GDALOpenEx(dsFileName, GDAL_OF_RASTER, nullptr,
1702 1235 : papszOpenOptions, nullptr);
1703 2375 : asDatasetProperties[i].isFileOK = FALSE;
1704 :
1705 2375 : if (hDS)
1706 : {
1707 2373 : const auto osErrorMsg = AnalyseRaster(hDS, &asDatasetProperties[i]);
1708 2373 : if (osErrorMsg.empty())
1709 : {
1710 2362 : asDatasetProperties[i].isFileOK = TRUE;
1711 2362 : bFoundValid = true;
1712 2362 : bFirst = FALSE;
1713 : }
1714 2373 : if (pahSrcDS == nullptr)
1715 1233 : GDALClose(hDS);
1716 2373 : if (!osErrorMsg.empty() && osErrorMsg != "SILENTLY_IGNORE")
1717 : {
1718 11 : if (bStrict)
1719 : {
1720 3 : CPLError(CE_Failure, CPLE_AppDefined, "%s",
1721 : osErrorMsg.c_str());
1722 3 : return nullptr;
1723 : }
1724 : else
1725 : {
1726 8 : CPLError(CE_Warning, CPLE_AppDefined, "%s Skipping %s",
1727 : osErrorMsg.c_str(), dsFileName);
1728 : }
1729 : }
1730 : }
1731 : else
1732 : {
1733 2 : if (bStrict)
1734 : {
1735 1 : CPLError(CE_Failure, CPLE_AppDefined, "Can't open %s.",
1736 : dsFileName);
1737 1 : return nullptr;
1738 : }
1739 : else
1740 : {
1741 1 : CPLError(CE_Warning, CPLE_AppDefined,
1742 : "Can't open %s. Skipping it", dsFileName);
1743 : }
1744 : }
1745 : }
1746 :
1747 231 : if (!bFoundValid)
1748 2 : return nullptr;
1749 :
1750 229 : if (bHasGeoTransform)
1751 : {
1752 228 : if (bTargetAlignedPixels)
1753 : {
1754 2 : minX = floor(minX / we_res) * we_res;
1755 2 : maxX = ceil(maxX / we_res) * we_res;
1756 2 : minY = floor(minY / -ns_res) * -ns_res;
1757 2 : maxY = ceil(maxY / -ns_res) * -ns_res;
1758 : }
1759 :
1760 228 : nRasterXSize = static_cast<int>(0.5 + (maxX - minX) / we_res);
1761 228 : nRasterYSize = static_cast<int>(0.5 + (maxY - minY) / -ns_res);
1762 : }
1763 :
1764 229 : if (nRasterXSize == 0 || nRasterYSize == 0)
1765 : {
1766 0 : CPLError(CE_Failure, CPLE_AppDefined,
1767 : "Computed VRT dimension is invalid. You've probably "
1768 : "specified inappropriate resolution.");
1769 0 : return nullptr;
1770 : }
1771 :
1772 229 : auto poDS = VRTDataset::CreateVRTDataset(pszOutputFilename, nRasterXSize,
1773 : nRasterYSize, 0, GDT_Unknown,
1774 458 : aosCreateOptions.List());
1775 229 : if (!poDS)
1776 : {
1777 0 : return nullptr;
1778 : }
1779 :
1780 229 : if (pszOutputSRS)
1781 : {
1782 1 : poDS->SetProjection(pszOutputSRS);
1783 : }
1784 228 : else if (pszProjectionRef)
1785 : {
1786 228 : poDS->SetProjection(pszProjectionRef);
1787 : }
1788 :
1789 229 : if (bHasGeoTransform)
1790 : {
1791 228 : GDALGeoTransform gt;
1792 228 : gt[GEOTRSFRM_TOPLEFT_X] = minX;
1793 228 : gt[GEOTRSFRM_WE_RES] = we_res;
1794 228 : gt[GEOTRSFRM_ROTATION_PARAM1] = 0;
1795 228 : gt[GEOTRSFRM_TOPLEFT_Y] = maxY;
1796 228 : gt[GEOTRSFRM_ROTATION_PARAM2] = 0;
1797 228 : gt[GEOTRSFRM_NS_RES] = ns_res;
1798 228 : poDS->SetGeoTransform(gt);
1799 : }
1800 :
1801 229 : if (bSeparate)
1802 : {
1803 17 : CreateVRTSeparate(poDS.get());
1804 : }
1805 : else
1806 : {
1807 212 : CreateVRTNonSeparate(poDS.get());
1808 : }
1809 :
1810 229 : return poDS;
1811 : }
1812 :
1813 : /************************************************************************/
1814 : /* add_file_to_list() */
1815 : /************************************************************************/
1816 :
1817 45 : static bool add_file_to_list(const char *filename, const char *tile_index,
1818 : CPLStringList &aosList)
1819 : {
1820 :
1821 45 : if (EQUAL(CPLGetExtensionSafe(filename).c_str(), "SHP"))
1822 : {
1823 : /* Handle gdaltindex Shapefile as a special case */
1824 1 : auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(filename));
1825 1 : if (poDS == nullptr)
1826 : {
1827 0 : CPLError(CE_Failure, CPLE_AppDefined,
1828 : "Unable to open shapefile `%s'.", filename);
1829 0 : return false;
1830 : }
1831 :
1832 1 : auto poLayer = poDS->GetLayer(0);
1833 1 : const auto poFDefn = poLayer->GetLayerDefn();
1834 :
1835 2 : if (poFDefn->GetFieldIndex("LOCATION") >= 0 &&
1836 1 : strcmp("LOCATION", tile_index) != 0)
1837 : {
1838 1 : CPLError(CE_Failure, CPLE_AppDefined,
1839 : "This shapefile seems to be a tile index of "
1840 : "OGR features and not GDAL products.");
1841 : }
1842 1 : const int ti_field = poFDefn->GetFieldIndex(tile_index);
1843 1 : if (ti_field < 0)
1844 : {
1845 0 : CPLError(CE_Failure, CPLE_AppDefined,
1846 : "Unable to find field `%s' in DBF file `%s'.", tile_index,
1847 : filename);
1848 0 : return false;
1849 : }
1850 :
1851 : /* Load in memory existing file names in SHP */
1852 1 : const auto nTileIndexFiles = poLayer->GetFeatureCount(TRUE);
1853 1 : if (nTileIndexFiles == 0)
1854 : {
1855 0 : CPLError(CE_Warning, CPLE_AppDefined,
1856 : "Tile index %s is empty. Skipping it.", filename);
1857 0 : return true;
1858 : }
1859 1 : if (nTileIndexFiles > 100 * 1024 * 1024)
1860 : {
1861 0 : CPLError(CE_Failure, CPLE_AppDefined,
1862 : "Too large feature count in tile index");
1863 0 : return false;
1864 : }
1865 :
1866 5 : for (auto &&poFeature : poLayer)
1867 : {
1868 4 : aosList.AddString(poFeature->GetFieldAsString(ti_field));
1869 : }
1870 : }
1871 : else
1872 : {
1873 44 : aosList.AddString(filename);
1874 : }
1875 :
1876 45 : return true;
1877 : }
1878 :
1879 : /************************************************************************/
1880 : /* GDALBuildVRTOptions */
1881 : /************************************************************************/
1882 :
1883 : /** Options for use with GDALBuildVRT(). GDALBuildVRTOptions* must be allocated
1884 : * and freed with GDALBuildVRTOptionsNew() and GDALBuildVRTOptionsFree()
1885 : * respectively.
1886 : */
1887 : struct GDALBuildVRTOptions
1888 : {
1889 : std::string osProgramName = "gdalbuildvrt";
1890 : std::string osTileIndex = "location";
1891 : bool bStrict = false;
1892 : std::string osResolution{};
1893 : bool bSeparate = false;
1894 : bool bAllowProjectionDifference = false;
1895 : double we_res = 0;
1896 : double ns_res = 0;
1897 : bool bTargetAlignedPixels = false;
1898 : double xmin = 0;
1899 : double ymin = 0;
1900 : double xmax = 0;
1901 : double ymax = 0;
1902 : bool bAddAlpha = false;
1903 : bool bHideNoData = false;
1904 : int nSubdataset = -1;
1905 : std::string osSrcNoData{};
1906 : std::string osVRTNoData{};
1907 : std::string osOutputSRS{};
1908 : std::vector<int> anSelectedBandList{};
1909 : std::string osResampling{};
1910 : CPLStringList aosOpenOptions{};
1911 : CPLStringList aosCreateOptions{};
1912 : bool bUseSrcMaskBand = true;
1913 : bool bNoDataFromMask = false;
1914 : double dfMaskValueThreshold = 0;
1915 : bool bWriteAbsolutePath = false;
1916 : std::string osPixelFunction{};
1917 : CPLStringList aosPixelFunctionArgs{};
1918 :
1919 : /*! allow or suppress progress monitor and other non-error output */
1920 : bool bQuiet = true;
1921 :
1922 : /*! the progress function to use */
1923 : GDALProgressFunc pfnProgress = GDALDummyProgress;
1924 :
1925 : /*! pointer to the progress data variable */
1926 : void *pProgressData = nullptr;
1927 : };
1928 :
1929 : /************************************************************************/
1930 : /* GDALBuildVRT() */
1931 : /************************************************************************/
1932 :
1933 : /* clang-format off */
1934 : /**
1935 : * Build a VRT from a list of datasets.
1936 : *
1937 : * This is the equivalent of the
1938 : * <a href="/programs/gdalbuildvrt.html">gdalbuildvrt</a> utility.
1939 : *
1940 : * GDALBuildVRTOptions* must be allocated and freed with
1941 : * GDALBuildVRTOptionsNew() and GDALBuildVRTOptionsFree() respectively. pahSrcDS
1942 : * and papszSrcDSNames cannot be used at the same time.
1943 : *
1944 : * @param pszDest the destination dataset path.
1945 : * @param nSrcCount the number of input datasets.
1946 : * @param pahSrcDS the list of input datasets (or NULL, exclusive with
1947 : * papszSrcDSNames). For practical purposes, the type
1948 : * of this argument should be considered as "const GDALDatasetH* const*", that
1949 : * is neither the array nor its values are mutated by this function.
1950 : * @param papszSrcDSNames the list of input dataset names (or NULL, exclusive
1951 : * with pahSrcDS)
1952 : * @param psOptionsIn the options struct returned by GDALBuildVRTOptionsNew() or
1953 : * NULL.
1954 : * @param pbUsageError pointer to a integer output variable to store if any
1955 : * usage error has occurred.
1956 : * @return the output dataset (new dataset that must be closed using
1957 : * GDALClose()) or NULL in case of error. If using pahSrcDS, the returned VRT
1958 : * dataset has a reference to each pahSrcDS[] element. Hence pahSrcDS[] elements
1959 : * should be closed after the returned dataset if using GDALClose().
1960 : * A safer alternative is to use GDALReleaseDataset() instead of using
1961 : * GDALClose(), in which case you can close datasets in any order.
1962 :
1963 : *
1964 : * @since GDAL 2.1
1965 : */
1966 : /* clang-format on */
1967 :
1968 236 : GDALDatasetH GDALBuildVRT(const char *pszDest, int nSrcCount,
1969 : GDALDatasetH *pahSrcDS,
1970 : const char *const *papszSrcDSNames,
1971 : const GDALBuildVRTOptions *psOptionsIn,
1972 : int *pbUsageError)
1973 : {
1974 236 : if (pszDest == nullptr)
1975 0 : pszDest = "";
1976 :
1977 236 : if (nSrcCount == 0)
1978 : {
1979 0 : CPLError(CE_Failure, CPLE_AppDefined, "No input dataset specified.");
1980 :
1981 0 : if (pbUsageError)
1982 0 : *pbUsageError = TRUE;
1983 0 : return nullptr;
1984 : }
1985 :
1986 : // cppcheck-suppress unreadVariable
1987 : GDALBuildVRTOptions sOptions(psOptionsIn ? *psOptionsIn
1988 472 : : GDALBuildVRTOptions());
1989 :
1990 8 : if (sOptions.we_res != 0 && sOptions.ns_res != 0 &&
1991 244 : !sOptions.osResolution.empty() &&
1992 0 : !EQUAL(sOptions.osResolution.c_str(), "user"))
1993 : {
1994 0 : CPLError(CE_Failure, CPLE_NotSupported,
1995 : "-tr option is not compatible with -resolution %s",
1996 : sOptions.osResolution.c_str());
1997 0 : if (pbUsageError)
1998 0 : *pbUsageError = TRUE;
1999 0 : return nullptr;
2000 : }
2001 :
2002 236 : if (sOptions.bTargetAlignedPixels && sOptions.we_res == 0 &&
2003 1 : sOptions.ns_res == 0)
2004 : {
2005 1 : CPLError(CE_Failure, CPLE_NotSupported,
2006 : "-tap option cannot be used without using -tr");
2007 1 : if (pbUsageError)
2008 1 : *pbUsageError = TRUE;
2009 1 : return nullptr;
2010 : }
2011 :
2012 235 : if (sOptions.bAddAlpha && sOptions.bSeparate)
2013 : {
2014 0 : CPLError(CE_Failure, CPLE_NotSupported,
2015 : "-addalpha option is not compatible with -separate.");
2016 0 : if (pbUsageError)
2017 0 : *pbUsageError = TRUE;
2018 0 : return nullptr;
2019 : }
2020 :
2021 235 : ResolutionStrategy eStrategy = AVERAGE_RESOLUTION;
2022 285 : if (sOptions.osResolution.empty() ||
2023 50 : EQUAL(sOptions.osResolution.c_str(), "user"))
2024 : {
2025 185 : if (sOptions.we_res != 0 || sOptions.ns_res != 0)
2026 8 : eStrategy = USER_RESOLUTION;
2027 177 : else if (EQUAL(sOptions.osResolution.c_str(), "user"))
2028 : {
2029 0 : CPLError(CE_Failure, CPLE_NotSupported,
2030 : "-tr option must be used with -resolution user.");
2031 0 : if (pbUsageError)
2032 0 : *pbUsageError = TRUE;
2033 0 : return nullptr;
2034 : }
2035 : }
2036 50 : else if (EQUAL(sOptions.osResolution.c_str(), "average"))
2037 1 : eStrategy = AVERAGE_RESOLUTION;
2038 49 : else if (EQUAL(sOptions.osResolution.c_str(), "highest"))
2039 1 : eStrategy = HIGHEST_RESOLUTION;
2040 48 : else if (EQUAL(sOptions.osResolution.c_str(), "lowest"))
2041 1 : eStrategy = LOWEST_RESOLUTION;
2042 47 : else if (EQUAL(sOptions.osResolution.c_str(), "same"))
2043 37 : eStrategy = SAME_RESOLUTION;
2044 10 : else if (EQUAL(sOptions.osResolution.c_str(), "common"))
2045 10 : eStrategy = COMMON_RESOLUTION;
2046 :
2047 : /* If -srcnodata is specified, use it as the -vrtnodata if the latter is not
2048 : */
2049 : /* specified */
2050 235 : if (!sOptions.osSrcNoData.empty() && sOptions.osVRTNoData.empty())
2051 2 : sOptions.osVRTNoData = sOptions.osSrcNoData;
2052 :
2053 : VRTBuilder oBuilder(
2054 235 : sOptions.bStrict, pszDest, nSrcCount, papszSrcDSNames, pahSrcDS,
2055 235 : sOptions.anSelectedBandList.empty()
2056 : ? nullptr
2057 19 : : sOptions.anSelectedBandList.data(),
2058 235 : static_cast<int>(sOptions.anSelectedBandList.size()), eStrategy,
2059 235 : sOptions.we_res, sOptions.ns_res, sOptions.bTargetAlignedPixels,
2060 : sOptions.xmin, sOptions.ymin, sOptions.xmax, sOptions.ymax,
2061 235 : sOptions.bSeparate, sOptions.bAllowProjectionDifference,
2062 235 : sOptions.bAddAlpha, sOptions.bHideNoData, sOptions.nSubdataset,
2063 241 : sOptions.osSrcNoData.empty() ? nullptr : sOptions.osSrcNoData.c_str(),
2064 23 : sOptions.osVRTNoData.empty() ? nullptr : sOptions.osVRTNoData.c_str(),
2065 235 : sOptions.bUseSrcMaskBand, sOptions.bNoDataFromMask,
2066 : sOptions.dfMaskValueThreshold,
2067 236 : sOptions.osOutputSRS.empty() ? nullptr : sOptions.osOutputSRS.c_str(),
2068 250 : sOptions.osResampling.empty() ? nullptr : sOptions.osResampling.c_str(),
2069 235 : sOptions.osPixelFunction.empty() ? nullptr
2070 3 : : sOptions.osPixelFunction.c_str(),
2071 235 : sOptions.aosPixelFunctionArgs, sOptions.aosOpenOptions.List(),
2072 1201 : sOptions.aosCreateOptions, sOptions.bWriteAbsolutePath);
2073 235 : oBuilder.m_osProgramName = sOptions.osProgramName;
2074 :
2075 235 : return GDALDataset::ToHandle(
2076 470 : oBuilder.Build(sOptions.pfnProgress, sOptions.pProgressData).release());
2077 : }
2078 :
2079 : /************************************************************************/
2080 : /* SanitizeSRS */
2081 : /************************************************************************/
2082 :
2083 1 : static char *SanitizeSRS(const char *pszUserInput)
2084 :
2085 : {
2086 : OGRSpatialReferenceH hSRS;
2087 1 : char *pszResult = nullptr;
2088 :
2089 1 : CPLErrorReset();
2090 :
2091 1 : hSRS = OSRNewSpatialReference(nullptr);
2092 1 : if (OSRSetFromUserInput(hSRS, pszUserInput) == OGRERR_NONE)
2093 1 : OSRExportToWkt(hSRS, &pszResult);
2094 : else
2095 : {
2096 0 : CPLError(CE_Failure, CPLE_AppDefined, "Translating SRS failed:\n%s",
2097 : pszUserInput);
2098 : }
2099 :
2100 1 : OSRDestroySpatialReference(hSRS);
2101 :
2102 1 : return pszResult;
2103 : }
2104 :
2105 : /************************************************************************/
2106 : /* GDALBuildVRTOptionsGetParser() */
2107 : /************************************************************************/
2108 :
2109 : static std::unique_ptr<GDALArgumentParser>
2110 239 : GDALBuildVRTOptionsGetParser(GDALBuildVRTOptions *psOptions,
2111 : GDALBuildVRTOptionsForBinary *psOptionsForBinary)
2112 : {
2113 : auto argParser = std::make_unique<GDALArgumentParser>(
2114 239 : "gdalbuildvrt", /* bForBinary=*/psOptionsForBinary != nullptr);
2115 :
2116 239 : argParser->add_description(_("Builds a VRT from a list of datasets."));
2117 :
2118 239 : argParser->add_epilog(_(
2119 : "\n"
2120 : "e.g.\n"
2121 : " % gdalbuildvrt doq_index.vrt doq/*.tif\n"
2122 : " % gdalbuildvrt -input_file_list my_list.txt doq_index.vrt\n"
2123 : "\n"
2124 : "NOTES:\n"
2125 : " o With -separate, each files goes into a separate band in the VRT "
2126 : "band.\n"
2127 : " Otherwise, the files are considered as tiles of a larger mosaic.\n"
2128 : " o -b option selects a band to add into vrt. Multiple bands can be "
2129 : "listed.\n"
2130 : " By default all bands are queried.\n"
2131 : " o The default tile index field is 'location' unless otherwise "
2132 : "specified by\n"
2133 : " -tileindex.\n"
2134 : " o In case the resolution of all input files is not the same, the "
2135 : "-resolution\n"
2136 : " flag enable the user to control the way the output resolution is "
2137 : "computed.\n"
2138 : " Average is the default.\n"
2139 : " o Input files may be any valid GDAL dataset or a GDAL raster tile "
2140 : "index.\n"
2141 : " o For a GDAL raster tile index, all entries will be added to the "
2142 : "VRT.\n"
2143 : " o If one GDAL dataset is made of several subdatasets and has 0 "
2144 : "raster bands,\n"
2145 : " its datasets will be added to the VRT rather than the dataset "
2146 : "itself.\n"
2147 : " Single subdataset could be selected by its number using the -sd "
2148 : "option.\n"
2149 : " o By default, only datasets of same projection and band "
2150 : "characteristics\n"
2151 : " may be added to the VRT.\n"
2152 : "\n"
2153 : "For more details, consult "
2154 239 : "https://gdal.org/programs/gdalbuildvrt.html"));
2155 :
2156 : argParser->add_quiet_argument(
2157 239 : psOptionsForBinary ? &psOptionsForBinary->bQuiet : nullptr);
2158 :
2159 : {
2160 239 : auto &group = argParser->add_mutually_exclusive_group();
2161 :
2162 239 : group.add_argument("-strict")
2163 239 : .flag()
2164 239 : .store_into(psOptions->bStrict)
2165 239 : .help(_("Turn warnings as failures."));
2166 :
2167 239 : group.add_argument("-non_strict")
2168 239 : .flag()
2169 0 : .action([psOptions](const std::string &)
2170 239 : { psOptions->bStrict = false; })
2171 : .help(_("Skip source datasets that have issues with warnings, and "
2172 239 : "continue processing."));
2173 : }
2174 :
2175 239 : argParser->add_argument("-tile_index")
2176 478 : .metavar("<field_name>")
2177 239 : .store_into(psOptions->osTileIndex)
2178 : .help(_("Use the specified value as the tile index field, instead of "
2179 239 : "the default value which is 'location'."));
2180 :
2181 239 : argParser->add_argument("-resolution")
2182 478 : .metavar("user|average|common|highest|lowest|same")
2183 : .action(
2184 304 : [psOptions](const std::string &s)
2185 : {
2186 50 : psOptions->osResolution = s;
2187 50 : if (!EQUAL(psOptions->osResolution.c_str(), "user") &&
2188 50 : !EQUAL(psOptions->osResolution.c_str(), "average") &&
2189 49 : !EQUAL(psOptions->osResolution.c_str(), "highest") &&
2190 48 : !EQUAL(psOptions->osResolution.c_str(), "lowest") &&
2191 110 : !EQUAL(psOptions->osResolution.c_str(), "same") &&
2192 10 : !EQUAL(psOptions->osResolution.c_str(), "common"))
2193 : {
2194 : throw std::invalid_argument(
2195 : CPLSPrintf("Illegal resolution value (%s).",
2196 0 : psOptions->osResolution.c_str()));
2197 : }
2198 289 : })
2199 239 : .help(_("Control the way the output resolution is computed."));
2200 :
2201 239 : argParser->add_argument("-tr")
2202 478 : .metavar("<xres> <yes>")
2203 239 : .nargs(2)
2204 239 : .scan<'g', double>()
2205 239 : .help(_("Set target resolution."));
2206 :
2207 239 : if (psOptionsForBinary)
2208 : {
2209 20 : argParser->add_argument("-input_file_list")
2210 40 : .metavar("<filename>")
2211 : .action(
2212 5 : [psOptions, psOptionsForBinary](const std::string &s)
2213 : {
2214 1 : const char *input_file_list = s.c_str();
2215 : auto f = VSIVirtualHandleUniquePtr(
2216 2 : VSIFOpenL(input_file_list, "r"));
2217 1 : if (f)
2218 : {
2219 : while (1)
2220 : {
2221 5 : const char *filename = CPLReadLineL(f.get());
2222 5 : if (filename == nullptr)
2223 1 : break;
2224 4 : if (!add_file_to_list(
2225 : filename, psOptions->osTileIndex.c_str(),
2226 4 : psOptionsForBinary->aosSrcFiles))
2227 : {
2228 : throw std::invalid_argument(
2229 0 : std::string("Cannot add ")
2230 0 : .append(filename)
2231 0 : .append(" to input file list"));
2232 : }
2233 4 : }
2234 : }
2235 21 : })
2236 20 : .help(_("Text file with an input filename on each line"));
2237 : }
2238 :
2239 : {
2240 239 : auto &group = argParser->add_mutually_exclusive_group();
2241 :
2242 239 : group.add_argument("-separate")
2243 239 : .flag()
2244 239 : .store_into(psOptions->bSeparate)
2245 239 : .help(_("Place each input file into a separate band."));
2246 :
2247 239 : group.add_argument("-pixel-function")
2248 478 : .metavar("<function>")
2249 : .action(
2250 9 : [psOptions](const std::string &s)
2251 : {
2252 : auto *poPixFun =
2253 5 : VRTDerivedRasterBand::GetPixelFunction(s.c_str());
2254 5 : if (poPixFun == nullptr)
2255 : {
2256 : throw std::invalid_argument(
2257 1 : s + " is not a registered pixel function.");
2258 : }
2259 :
2260 4 : psOptions->osPixelFunction = s;
2261 243 : })
2262 :
2263 239 : .help("Function to calculate value from overlapping inputs");
2264 : }
2265 :
2266 239 : argParser->add_argument("-pixel-function-arg")
2267 478 : .metavar("<NAME>=<VALUE>")
2268 239 : .append()
2269 2 : .action([psOptions](const std::string &s)
2270 241 : { psOptions->aosPixelFunctionArgs.AddString(s); })
2271 239 : .help(_("Pixel function argument(s)"));
2272 :
2273 239 : argParser->add_argument("-allow_projection_difference")
2274 239 : .flag()
2275 239 : .store_into(psOptions->bAllowProjectionDifference)
2276 : .help(_("Accept source files not in the same projection (but without "
2277 239 : "reprojecting them!)."));
2278 :
2279 239 : argParser->add_argument("-sd")
2280 478 : .metavar("<n>")
2281 239 : .store_into(psOptions->nSubdataset)
2282 : .help(_("Use subdataset of specified index (starting at 1), instead of "
2283 239 : "the source dataset itself."));
2284 :
2285 239 : argParser->add_argument("-tap")
2286 239 : .flag()
2287 239 : .store_into(psOptions->bTargetAlignedPixels)
2288 : .help(_("Align the coordinates of the extent of the output file to the "
2289 239 : "values of the resolution."));
2290 :
2291 239 : argParser->add_argument("-te")
2292 478 : .metavar("<xmin> <ymin> <xmax> <ymax>")
2293 239 : .nargs(4)
2294 239 : .scan<'g', double>()
2295 239 : .help(_("Set georeferenced extents of output file to be created."));
2296 :
2297 239 : argParser->add_argument("-addalpha")
2298 239 : .flag()
2299 239 : .store_into(psOptions->bAddAlpha)
2300 : .help(_("Adds an alpha mask band to the VRT when the source raster "
2301 239 : "have none."));
2302 :
2303 239 : argParser->add_argument("-b")
2304 478 : .metavar("<band>")
2305 239 : .append()
2306 239 : .store_into(psOptions->anSelectedBandList)
2307 239 : .help(_("Specify input band(s) number."));
2308 :
2309 239 : argParser->add_argument("-hidenodata")
2310 239 : .flag()
2311 239 : .store_into(psOptions->bHideNoData)
2312 239 : .help(_("Makes the VRT band not report the NoData."));
2313 :
2314 239 : if (psOptionsForBinary)
2315 : {
2316 20 : argParser->add_argument("-overwrite")
2317 20 : .flag()
2318 20 : .store_into(psOptionsForBinary->bOverwrite)
2319 20 : .help(_("Overwrite the VRT if it already exists."));
2320 : }
2321 :
2322 239 : argParser->add_argument("-srcnodata")
2323 478 : .metavar("\"<value>[ <value>]...\"")
2324 239 : .store_into(psOptions->osSrcNoData)
2325 239 : .help(_("Set nodata values for input bands."));
2326 :
2327 239 : argParser->add_argument("-vrtnodata")
2328 478 : .metavar("\"<value>[ <value>]...\"")
2329 239 : .store_into(psOptions->osVRTNoData)
2330 239 : .help(_("Set nodata values at the VRT band level."));
2331 :
2332 239 : argParser->add_argument("-a_srs")
2333 478 : .metavar("<srs_def>")
2334 : .action(
2335 2 : [psOptions](const std::string &s)
2336 : {
2337 1 : char *pszSRS = SanitizeSRS(s.c_str());
2338 1 : if (pszSRS == nullptr)
2339 : {
2340 0 : throw std::invalid_argument("Invalid value for -a_srs");
2341 : }
2342 1 : psOptions->osOutputSRS = pszSRS;
2343 1 : CPLFree(pszSRS);
2344 240 : })
2345 239 : .help(_("Override the projection for the output file.."));
2346 :
2347 239 : argParser->add_argument("-r")
2348 478 : .metavar("nearest|bilinear|cubic|cubicspline|lanczos|average|mode")
2349 239 : .store_into(psOptions->osResampling)
2350 239 : .help(_("Resampling algorithm."));
2351 :
2352 239 : argParser->add_open_options_argument(&psOptions->aosOpenOptions);
2353 :
2354 239 : argParser->add_creation_options_argument(psOptions->aosCreateOptions);
2355 :
2356 239 : argParser->add_argument("-write_absolute_path")
2357 239 : .flag()
2358 239 : .store_into(psOptions->bWriteAbsolutePath)
2359 : .help(_("Write the absolute path of the raster files in the tile index "
2360 239 : "file."));
2361 :
2362 239 : argParser->add_argument("-ignore_srcmaskband")
2363 239 : .flag()
2364 0 : .action([psOptions](const std::string &)
2365 239 : { psOptions->bUseSrcMaskBand = false; })
2366 239 : .help(_("Cause mask band of sources will not be taken into account."));
2367 :
2368 239 : argParser->add_argument("-nodata_max_mask_threshold")
2369 478 : .metavar("<threshold>")
2370 239 : .scan<'g', double>()
2371 : .action(
2372 18 : [psOptions](const std::string &s)
2373 : {
2374 9 : psOptions->bNoDataFromMask = true;
2375 9 : psOptions->dfMaskValueThreshold = CPLAtofM(s.c_str());
2376 239 : })
2377 : .help(_("Replaces the value of the source with the value of -vrtnodata "
2378 : "when the value of the mask band of the source is less or "
2379 239 : "equal to the threshold."));
2380 :
2381 239 : argParser->add_argument("-program_name")
2382 239 : .store_into(psOptions->osProgramName)
2383 239 : .hidden();
2384 :
2385 239 : if (psOptionsForBinary)
2386 : {
2387 20 : if (psOptionsForBinary->osDstFilename.empty())
2388 : {
2389 : // We normally go here, unless undocumented -o switch is used
2390 20 : argParser->add_argument("vrt_dataset_name")
2391 40 : .metavar("<vrt_dataset_name>")
2392 20 : .store_into(psOptionsForBinary->osDstFilename)
2393 20 : .help(_("Output VRT."));
2394 : }
2395 :
2396 20 : argParser->add_argument("src_dataset_name")
2397 40 : .metavar("<src_dataset_name>")
2398 20 : .nargs(argparse::nargs_pattern::any)
2399 : .action(
2400 41 : [psOptions, psOptionsForBinary](const std::string &s)
2401 : {
2402 41 : if (!add_file_to_list(s.c_str(),
2403 : psOptions->osTileIndex.c_str(),
2404 41 : psOptionsForBinary->aosSrcFiles))
2405 : {
2406 : throw std::invalid_argument(
2407 0 : std::string("Cannot add ")
2408 0 : .append(s)
2409 0 : .append(" to input file list"));
2410 : }
2411 61 : })
2412 20 : .help(_("Input dataset(s)."));
2413 : }
2414 :
2415 239 : return argParser;
2416 : }
2417 :
2418 : /************************************************************************/
2419 : /* GDALBuildVRTGetParserUsage() */
2420 : /************************************************************************/
2421 :
2422 1 : std::string GDALBuildVRTGetParserUsage()
2423 : {
2424 : try
2425 : {
2426 2 : GDALBuildVRTOptions sOptions;
2427 2 : GDALBuildVRTOptionsForBinary sOptionsForBinary;
2428 : auto argParser =
2429 2 : GDALBuildVRTOptionsGetParser(&sOptions, &sOptionsForBinary);
2430 1 : return argParser->usage();
2431 : }
2432 0 : catch (const std::exception &err)
2433 : {
2434 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
2435 0 : err.what());
2436 0 : return std::string();
2437 : }
2438 : }
2439 :
2440 : /************************************************************************/
2441 : /* GDALBuildVRTOptionsNew() */
2442 : /************************************************************************/
2443 :
2444 : /**
2445 : * Allocates a GDALBuildVRTOptions struct.
2446 : *
2447 : * @param papszArgv NULL terminated list of options (potentially including
2448 : * filename and open options too), or NULL. The accepted options are the ones of
2449 : * the <a href="/programs/gdalbuildvrt.html">gdalbuildvrt</a> utility.
2450 : * @param psOptionsForBinary (output) may be NULL (and should generally be
2451 : * NULL), otherwise (gdalbuildvrt_bin.cpp use case) must be allocated with
2452 : * GDALBuildVRTOptionsForBinaryNew() prior to this function. Will be filled
2453 : * with potentially present filename, open options,...
2454 : * @return pointer to the allocated GDALBuildVRTOptions struct. Must be freed
2455 : * with GDALBuildVRTOptionsFree().
2456 : *
2457 : * @since GDAL 2.1
2458 : */
2459 :
2460 : GDALBuildVRTOptions *
2461 238 : GDALBuildVRTOptionsNew(char **papszArgv,
2462 : GDALBuildVRTOptionsForBinary *psOptionsForBinary)
2463 : {
2464 476 : auto psOptions = std::make_unique<GDALBuildVRTOptions>();
2465 :
2466 476 : CPLStringList aosArgv;
2467 238 : const int nArgc = CSLCount(papszArgv);
2468 1234 : for (int i = 0;
2469 1234 : i < nArgc && papszArgv != nullptr && papszArgv[i] != nullptr; i++)
2470 : {
2471 996 : if (psOptionsForBinary && EQUAL(papszArgv[i], "-o") && i + 1 < nArgc &&
2472 0 : papszArgv[i + 1] != nullptr)
2473 : {
2474 : // Undocumented alternate way of specifying the destination file
2475 0 : psOptionsForBinary->osDstFilename = papszArgv[i + 1];
2476 0 : ++i;
2477 : }
2478 : // argparser will be confused if the value of a string argument
2479 : // starts with a negative sign.
2480 996 : else if (EQUAL(papszArgv[i], "-srcnodata") && i + 1 < nArgc)
2481 : {
2482 6 : ++i;
2483 6 : psOptions->osSrcNoData = papszArgv[i];
2484 : }
2485 : // argparser will be confused if the value of a string argument
2486 : // starts with a negative sign.
2487 990 : else if (EQUAL(papszArgv[i], "-vrtnodata") && i + 1 < nArgc)
2488 : {
2489 21 : ++i;
2490 21 : psOptions->osVRTNoData = papszArgv[i];
2491 : }
2492 :
2493 : else
2494 : {
2495 969 : aosArgv.AddString(papszArgv[i]);
2496 : }
2497 : }
2498 :
2499 : try
2500 : {
2501 : auto argParser =
2502 476 : GDALBuildVRTOptionsGetParser(psOptions.get(), psOptionsForBinary);
2503 :
2504 238 : argParser->parse_args_without_binary_name(aosArgv.List());
2505 :
2506 244 : if (auto adfTargetRes = argParser->present<std::vector<double>>("-tr"))
2507 : {
2508 8 : psOptions->we_res = (*adfTargetRes)[0];
2509 8 : psOptions->ns_res = (*adfTargetRes)[1];
2510 : }
2511 :
2512 249 : if (auto oTE = argParser->present<std::vector<double>>("-te"))
2513 : {
2514 13 : psOptions->xmin = (*oTE)[0];
2515 13 : psOptions->ymin = (*oTE)[1];
2516 13 : psOptions->xmax = (*oTE)[2];
2517 13 : psOptions->ymax = (*oTE)[3];
2518 : }
2519 :
2520 469 : if (psOptions->osPixelFunction.empty() &&
2521 233 : !psOptions->aosPixelFunctionArgs.empty())
2522 : {
2523 : throw std::runtime_error(
2524 1 : "Pixel function arguments provided without a pixel function");
2525 : }
2526 :
2527 235 : return psOptions.release();
2528 : }
2529 3 : catch (const std::exception &err)
2530 : {
2531 3 : CPLError(CE_Failure, CPLE_AppDefined, "%s", err.what());
2532 3 : return nullptr;
2533 : }
2534 : }
2535 :
2536 : /************************************************************************/
2537 : /* GDALBuildVRTOptionsFree() */
2538 : /************************************************************************/
2539 :
2540 : /**
2541 : * Frees the GDALBuildVRTOptions struct.
2542 : *
2543 : * @param psOptions the options struct for GDALBuildVRT().
2544 : *
2545 : * @since GDAL 2.1
2546 : */
2547 :
2548 234 : void GDALBuildVRTOptionsFree(GDALBuildVRTOptions *psOptions)
2549 : {
2550 234 : delete psOptions;
2551 234 : }
2552 :
2553 : /************************************************************************/
2554 : /* GDALBuildVRTOptionsSetProgress() */
2555 : /************************************************************************/
2556 :
2557 : /**
2558 : * Set a progress function.
2559 : *
2560 : * @param psOptions the options struct for GDALBuildVRT().
2561 : * @param pfnProgress the progress callback.
2562 : * @param pProgressData the user data for the progress callback.
2563 : *
2564 : * @since GDAL 2.1
2565 : */
2566 :
2567 20 : void GDALBuildVRTOptionsSetProgress(GDALBuildVRTOptions *psOptions,
2568 : GDALProgressFunc pfnProgress,
2569 : void *pProgressData)
2570 : {
2571 20 : psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
2572 20 : psOptions->pProgressData = pProgressData;
2573 20 : if (pfnProgress == GDALTermProgress)
2574 19 : psOptions->bQuiet = false;
2575 20 : }
|