1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
|
/******************************************************************************
*
* Project: MapServer
* Purpose: Commandline App to build tile index for raster files.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2001, Frank Warmerdam, DM Solutions Group Inc
* Copyright (c) 2007-2023, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "cpl_conv.h"
#include "cpl_minixml.h"
#include "cpl_string.h"
#include "gdal_utils.h"
#include "gdal_priv.h"
#include "gdal_utils_priv.h"
#include "ogr_api.h"
#include "ogrsf_frmts.h"
#include "ogr_spatialref.h"
#include "commonutils.h"
#include "gdalargumentparser.h"
#include <ctype.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
typedef enum
{
FORMAT_AUTO,
FORMAT_WKT,
FORMAT_EPSG,
FORMAT_PROJ
} SrcSRSFormat;
/************************************************************************/
/* GDALTileIndexRasterMetadata */
/************************************************************************/
struct GDALTileIndexRasterMetadata
{
OGRFieldType eType = OFTString;
std::string osFieldName{};
std::string osRasterItemName{};
};
/************************************************************************/
/* GDALTileIndexOptions */
/************************************************************************/
struct GDALTileIndexOptions
{
bool bInvokedFromGdalRasterIndex = false;
bool bOverwrite = false;
bool bSkipErrors = false;
std::string osFormat{};
std::string osIndexLayerName{};
std::string osLocationField = "location";
CPLStringList aosLCO{};
std::string osTargetSRS{};
bool bWriteAbsolutePath = false;
bool bSkipDifferentProjection = false;
std::string osSrcSRSFieldName{};
SrcSRSFormat eSrcSRSFormat = FORMAT_AUTO;
double xres = std::numeric_limits<double>::quiet_NaN();
double yres = std::numeric_limits<double>::quiet_NaN();
double xmin = std::numeric_limits<double>::quiet_NaN();
double ymin = std::numeric_limits<double>::quiet_NaN();
double xmax = std::numeric_limits<double>::quiet_NaN();
double ymax = std::numeric_limits<double>::quiet_NaN();
std::string osBandCount{};
std::string osNodata{};
std::string osColorInterp{};
std::string osDataType{};
bool bMaskBand = false;
std::vector<std::string> aosMetadata{};
std::string osGTIFilename{};
bool bRecursive = false;
double dfMinPixelSize = std::numeric_limits<double>::quiet_NaN();
double dfMaxPixelSize = std::numeric_limits<double>::quiet_NaN();
std::vector<GDALTileIndexRasterMetadata> aoFetchMD{};
std::set<std::string> oSetFilenameFilters{};
GDALProgressFunc pfnProgress = nullptr;
void *pProgressData = nullptr;
};
/************************************************************************/
/* GDALTileIndexAppOptionsGetParser() */
/************************************************************************/
static std::unique_ptr<GDALArgumentParser> GDALTileIndexAppOptionsGetParser(
GDALTileIndexOptions *psOptions,
GDALTileIndexOptionsForBinary *psOptionsForBinary)
{
auto argParser = std::make_unique<GDALArgumentParser>(
"gdaltindex", /* bForBinary=*/psOptionsForBinary != nullptr);
argParser->add_description(
_("Build a tile index from a list of datasets."));
argParser->add_epilog(
_("For more details, see the full documentation for gdaltindex at\n"
"https://gdal.org/programs/gdaltindex.html"));
// Hidden as used by gdal raster index
argParser->add_argument("--invoked-from-gdal-raster-index")
.store_into(psOptions->bInvokedFromGdalRasterIndex)
.hidden();
// Hidden as used by gdal raster index
argParser->add_argument("-skip_errors")
.store_into(psOptions->bSkipErrors)
.hidden();
argParser->add_argument("-overwrite")
.flag()
.store_into(psOptions->bOverwrite)
.help(_("Overwrite the output tile index file if it already exists."));
argParser->add_argument("-recursive")
.flag()
.store_into(psOptions->bRecursive)
.help(_("Whether directories specified in <file_or_dir> should be "
"explored recursively."));
argParser->add_argument("-filename_filter")
.metavar("<val>")
.append()
.store_into(psOptions->oSetFilenameFilters)
.help(_("Pattern that the filenames contained in directories pointed "
"by <file_or_dir> should follow."));
argParser->add_argument("-min_pixel_size")
.metavar("<val>")
.store_into(psOptions->dfMinPixelSize)
.help(_("Minimum pixel size in term of geospatial extent per pixel "
"(resolution) that a raster should have to be selected."));
argParser->add_argument("-max_pixel_size")
.metavar("<val>")
.store_into(psOptions->dfMaxPixelSize)
.help(_("Maximum pixel size in term of geospatial extent per pixel "
"(resolution) that a raster should have to be selected."));
argParser->add_output_format_argument(psOptions->osFormat);
argParser->add_argument("-tileindex")
.metavar("<field_name>")
.store_into(psOptions->osLocationField)
.help(_("Name of the layer in the tile index file."));
argParser->add_argument("-write_absolute_path")
.flag()
.store_into(psOptions->bWriteAbsolutePath)
.help(_("Write the absolute path of the raster files in the tile index "
"file."));
argParser->add_argument("-skip_different_projection")
.flag()
.store_into(psOptions->bSkipDifferentProjection)
.help(_(
"Only files with the same projection as files already inserted in "
"the tile index will be inserted (unless -t_srs is specified)."));
argParser->add_argument("-t_srs")
.metavar("<srs_def>")
.store_into(psOptions->osTargetSRS)
.help(_("Geometries of input files will be transformed to the desired "
"target coordinate reference system."));
argParser->add_argument("-src_srs_name")
.metavar("<field_name>")
.store_into(psOptions->osSrcSRSFieldName)
.help(_("Name of the field in the tile index file where the source SRS "
"will be stored."));
argParser->add_argument("-src_srs_format")
.metavar("{AUTO|WKT|EPSG|PROJ}")
.choices("AUTO", "WKT", "EPSG", "PROJ")
.action(
[psOptions](const auto &f)
{
if (f == "WKT")
psOptions->eSrcSRSFormat = FORMAT_WKT;
else if (f == "EPSG")
psOptions->eSrcSRSFormat = FORMAT_EPSG;
else if (f == "PROJ")
psOptions->eSrcSRSFormat = FORMAT_PROJ;
else
psOptions->eSrcSRSFormat = FORMAT_AUTO;
})
.help(_("Format of the source SRS to store in the tile index file."));
argParser->add_argument("-lyr_name")
.metavar("<name>")
.store_into(psOptions->osIndexLayerName)
.help(_("Name of the layer in the tile index file."));
argParser->add_layer_creation_options_argument(psOptions->aosLCO);
// GTI driver options
argParser->add_argument("-gti_filename")
.metavar("<filename>")
.store_into(psOptions->osGTIFilename)
.help(_("Filename of the XML Virtual Tile Index file to generate."));
// NOTE: no store_into
argParser->add_argument("-tr")
.metavar("<xres> <yres>")
.nargs(2)
.scan<'g', double>()
.help(_("Set target resolution."));
// NOTE: no store_into
argParser->add_argument("-te")
.metavar("<xmin> <ymin> <xmax> <ymax>")
.nargs(4)
.scan<'g', double>()
.help(_("Set target extent in SRS unit."));
argParser->add_argument("-ot")
.metavar("<datatype>")
.store_into(psOptions->osDataType)
.help(_("Output data type."));
argParser->add_argument("-bandcount")
.metavar("<val>")
.store_into(psOptions->osBandCount)
.help(_("Number of bands of the tiles of the tile index."));
argParser->add_argument("-nodata")
.metavar("<val>")
.append()
.store_into(psOptions->osNodata)
.help(_("Nodata value of the tiles of the tile index."));
// Should we use choices here?
argParser->add_argument("-colorinterp")
.metavar("<val>")
.append()
.store_into(psOptions->osColorInterp)
.help(_("Color interpretation of of the tiles of the tile index: red, "
"green, blue, alpha, gray, undefined."));
argParser->add_argument("-mask")
.flag()
.store_into(psOptions->bMaskBand)
.help(_("Add a mask band to the tiles of the tile index."));
argParser->add_argument("-mo")
.metavar("<name>=<value>")
.append()
.store_into(psOptions->aosMetadata)
.help(_("Write an arbitrary layer metadata item, for formats that "
"support layer metadata."));
// NOTE: no store_into
argParser->add_argument("-fetch_md")
.nargs(3)
.metavar("<gdal_md_name> <fld_name> <fld_type>")
.append()
.help("Fetch a metadata item from the raster tile and write it as a "
"field in the tile index.");
if (psOptionsForBinary)
{
argParser->add_quiet_argument(&psOptionsForBinary->bQuiet);
argParser->add_argument("index_file")
.metavar("<index_file>")
.store_into(psOptionsForBinary->osDest)
.help(_("The name of the output file to create/append to."));
argParser->add_argument("file_or_dir")
.metavar("<file_or_dir>")
.nargs(argparse::nargs_pattern::at_least_one)
.action([psOptionsForBinary](const std::string &s)
{ psOptionsForBinary->aosSrcFiles.AddString(s.c_str()); })
.help(_(
"The input GDAL raster files or directory, can be multiple "
"locations separated by spaces. Wildcards may also be used."));
}
return argParser;
}
/************************************************************************/
/* GDALTileIndexAppGetParserUsage() */
/************************************************************************/
std::string GDALTileIndexAppGetParserUsage()
{
try
{
GDALTileIndexOptions sOptions;
GDALTileIndexOptionsForBinary sOptionsForBinary;
auto argParser =
GDALTileIndexAppOptionsGetParser(&sOptions, &sOptionsForBinary);
return argParser->usage();
}
catch (const std::exception &err)
{
CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
err.what());
return std::string();
}
}
/************************************************************************/
/* GDALTileIndexTileIterator */
/************************************************************************/
struct GDALTileIndexTileIterator
{
const GDALTileIndexOptions *psOptions = nullptr;
int nSrcCount = 0;
const char *const *papszSrcDSNames = nullptr;
std::string osCurDir{};
int iCurSrc = 0;
VSIDIR *psDir = nullptr;
CPL_DISALLOW_COPY_ASSIGN(GDALTileIndexTileIterator)
GDALTileIndexTileIterator(const GDALTileIndexOptions *psOptionsIn,
int nSrcCountIn,
const char *const *papszSrcDSNamesIn)
: psOptions(psOptionsIn), nSrcCount(nSrcCountIn),
papszSrcDSNames(papszSrcDSNamesIn)
{
}
void reset()
{
if (psDir)
VSICloseDir(psDir);
psDir = nullptr;
iCurSrc = 0;
}
std::string next()
{
while (true)
{
if (!psDir)
{
if (iCurSrc == nSrcCount)
{
break;
}
VSIStatBufL sStatBuf;
const char *pszCurName = papszSrcDSNames[iCurSrc++];
if (VSIStatL(pszCurName, &sStatBuf) == 0 &&
VSI_ISDIR(sStatBuf.st_mode))
{
auto poSrcDS = std::unique_ptr<GDALDataset>(
GDALDataset::Open(pszCurName, GDAL_OF_RASTER, nullptr,
nullptr, nullptr));
if (poSrcDS)
return pszCurName;
osCurDir = pszCurName;
psDir = VSIOpenDir(
osCurDir.c_str(),
/*nDepth=*/psOptions->bRecursive ? -1 : 0, nullptr);
if (!psDir)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot open directory %s", osCurDir.c_str());
return std::string();
}
}
else
{
return pszCurName;
}
}
auto psEntry = VSIGetNextDirEntry(psDir);
if (!psEntry)
{
VSICloseDir(psDir);
psDir = nullptr;
continue;
}
if (!psOptions->oSetFilenameFilters.empty())
{
bool bMatchFound = false;
const std::string osFilenameOnly =
CPLGetFilename(psEntry->pszName);
for (const auto &osFilter : psOptions->oSetFilenameFilters)
{
if (GDALPatternMatch(osFilenameOnly.c_str(),
osFilter.c_str()))
{
bMatchFound = true;
break;
}
}
if (!bMatchFound)
continue;
}
std::string osFilename = CPLFormFilenameSafe(
osCurDir.c_str(), psEntry->pszName, nullptr);
if (VSI_ISDIR(psEntry->nMode))
{
auto poSrcDS = std::unique_ptr<GDALDataset>(
GDALDataset::Open(osFilename.c_str(), GDAL_OF_RASTER,
nullptr, nullptr, nullptr));
if (poSrcDS)
{
return osFilename;
}
continue;
}
return osFilename;
}
return std::string();
}
};
/************************************************************************/
/* GDALTileIndex() */
/************************************************************************/
/* clang-format off */
/**
* Build a tile index from a list of datasets.
*
* This is the equivalent of the
* <a href="/programs/gdaltindex.html">gdaltindex</a> utility.
*
* GDALTileIndexOptions* must be allocated and freed with
* GDALTileIndexOptionsNew() and GDALTileIndexOptionsFree() respectively.
*
* @param pszDest the destination dataset path.
* @param nSrcCount the number of input datasets.
* @param papszSrcDSNames the list of input dataset names
* @param psOptionsIn the options struct returned by GDALTileIndexOptionsNew() or
* NULL.
* @param pbUsageError pointer to a integer output variable to store if any
* usage error has occurred.
* @return the output dataset (new dataset that must be closed using
* GDALClose()) or NULL in case of error.
*
* @since GDAL3.9
*/
/* clang-format on */
GDALDatasetH GDALTileIndex(const char *pszDest, int nSrcCount,
const char *const *papszSrcDSNames,
const GDALTileIndexOptions *psOptionsIn,
int *pbUsageError)
{
return GDALTileIndexInternal(pszDest, nullptr, nullptr, nSrcCount,
papszSrcDSNames, psOptionsIn, pbUsageError);
}
GDALDatasetH GDALTileIndexInternal(const char *pszDest,
GDALDatasetH hTileIndexDS, OGRLayerH hLayer,
int nSrcCount,
const char *const *papszSrcDSNames,
const GDALTileIndexOptions *psOptionsIn,
int *pbUsageError)
{
if (nSrcCount == 0)
{
CPLError(CE_Failure, CPLE_AppDefined, "No input dataset specified.");
if (pbUsageError)
*pbUsageError = TRUE;
return nullptr;
}
auto psOptions = psOptionsIn
? std::make_unique<GDALTileIndexOptions>(*psOptionsIn)
: std::make_unique<GDALTileIndexOptions>();
GDALTileIndexTileIterator oGDALTileIndexTileIterator(
psOptions.get(), nSrcCount, papszSrcDSNames);
/* -------------------------------------------------------------------- */
/* Create and validate target SRS if given. */
/* -------------------------------------------------------------------- */
OGRSpatialReference oTargetSRS;
if (!psOptions->osTargetSRS.empty())
{
if (psOptions->bSkipDifferentProjection)
{
CPLError(CE_Warning, CPLE_AppDefined,
"-skip_different_projections does not apply "
"when -t_srs is requested.");
}
oTargetSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
// coverity[tainted_data]
oTargetSRS.SetFromUserInput(psOptions->osTargetSRS.c_str());
}
/* -------------------------------------------------------------------- */
/* Open or create the target datasource */
/* -------------------------------------------------------------------- */
std::unique_ptr<GDALDataset> poTileIndexDSUnique;
GDALDataset *poTileIndexDS = GDALDataset::FromHandle(hTileIndexDS);
OGRLayer *poLayer = OGRLayer::FromHandle(hLayer);
bool bExistingLayer = false;
std::string osFormat;
if (!hTileIndexDS)
{
if (psOptions->bOverwrite)
{
CPLPushErrorHandler(CPLQuietErrorHandler);
auto hDriver = GDALIdentifyDriver(pszDest, nullptr);
if (hDriver)
GDALDeleteDataset(hDriver, pszDest);
else
VSIUnlink(pszDest);
CPLPopErrorHandler();
}
poTileIndexDSUnique.reset(
GDALDataset::Open(pszDest, GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr,
nullptr, nullptr));
if (poTileIndexDSUnique != nullptr)
{
auto poDriver = poTileIndexDSUnique->GetDriver();
if (poDriver)
osFormat = poDriver->GetDescription();
if (poTileIndexDSUnique->GetLayerCount() == 1)
{
poLayer = poTileIndexDSUnique->GetLayer(0);
}
else
{
if (psOptions->osIndexLayerName.empty())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Multiple layers detected: -lyr_name must be "
"specified.");
if (pbUsageError)
*pbUsageError = true;
return nullptr;
}
CPLPushErrorHandler(CPLQuietErrorHandler);
poLayer = poTileIndexDSUnique->GetLayerByName(
psOptions->osIndexLayerName.c_str());
CPLPopErrorHandler();
}
}
else
{
if (psOptions->osFormat.empty())
{
const auto aoDrivers =
GetOutputDriversFor(pszDest, GDAL_OF_VECTOR);
if (aoDrivers.empty())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot guess driver for %s", pszDest);
return nullptr;
}
else
{
if (aoDrivers.size() > 1)
{
CPLError(
CE_Warning, CPLE_AppDefined,
"Several drivers matching %s extension. Using %s",
CPLGetExtensionSafe(pszDest).c_str(),
aoDrivers[0].c_str());
}
osFormat = aoDrivers[0];
}
}
else
{
osFormat = psOptions->osFormat;
}
auto poDriver =
GetGDALDriverManager()->GetDriverByName(osFormat.c_str());
if (poDriver == nullptr)
{
CPLError(CE_Warning, CPLE_AppDefined,
"%s driver not available.", osFormat.c_str());
return nullptr;
}
poTileIndexDSUnique.reset(
poDriver->Create(pszDest, 0, 0, 0, GDT_Unknown, nullptr));
if (!poTileIndexDSUnique)
return nullptr;
}
poTileIndexDS = poTileIndexDSUnique.get();
}
auto poOutDrv = poTileIndexDS->GetDriver();
if (osFormat.empty() && poOutDrv)
osFormat = poOutDrv->GetDescription();
const char *pszVal =
poOutDrv ? poOutDrv->GetMetadataItem(GDAL_DMD_MAX_STRING_LENGTH)
: nullptr;
const int nMaxFieldSize = pszVal ? atoi(pszVal) : 0;
const bool bFailOnErrors =
psOptions->bInvokedFromGdalRasterIndex && !psOptions->bSkipErrors;
bool bSkipFirstTile = false;
if (poLayer)
{
bExistingLayer = true;
}
else
{
std::string osLayerName;
if (psOptions->osIndexLayerName.empty())
{
VSIStatBuf sStat;
if (EQUAL(osFormat.c_str(), "ESRI Shapefile") ||
VSIStat(pszDest, &sStat) == 0)
{
osLayerName = CPLGetBasenameSafe(pszDest);
}
else
{
CPLError(CE_Failure, CPLE_AppDefined,
"-lyr_name must be specified.");
if (pbUsageError)
*pbUsageError = true;
return nullptr;
}
}
else
{
if (psOptions->bOverwrite)
{
for (int i = 0; i < poTileIndexDS->GetLayerCount(); ++i)
{
auto poExistingLayer = poTileIndexDS->GetLayer(i);
if (poExistingLayer && poExistingLayer->GetName() ==
psOptions->osIndexLayerName)
{
if (poTileIndexDS->DeleteLayer(i) != OGRERR_NONE)
return nullptr;
break;
}
}
}
osLayerName = psOptions->osIndexLayerName;
}
/* get spatial reference for output file from target SRS (if set) */
/* or from first input file */
OGRSpatialReference oSRS;
if (!oTargetSRS.IsEmpty())
{
oSRS = oTargetSRS;
}
else
{
std::string osFilename = oGDALTileIndexTileIterator.next();
if (osFilename.empty())
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot find any tile");
return nullptr;
}
oGDALTileIndexTileIterator.reset();
std::unique_ptr<CPLTurnFailureIntoWarningBackuper>
poFailureIntoWarning;
if (!bFailOnErrors)
poFailureIntoWarning =
std::make_unique<CPLTurnFailureIntoWarningBackuper>();
CPL_IGNORE_RET_VAL(poFailureIntoWarning);
auto poSrcDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
osFilename.c_str(), GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
nullptr, nullptr, nullptr));
if (!poSrcDS)
{
CPLError(bFailOnErrors ? CE_Failure : CE_Warning,
CPLE_AppDefined, "Unable to open %s%s.",
osFilename.c_str(), bFailOnErrors ? "" : ", skipping");
if (bFailOnErrors)
return nullptr;
bSkipFirstTile = true;
}
else
{
auto poSrcSRS = poSrcDS->GetSpatialRef();
if (poSrcSRS)
oSRS = *poSrcSRS;
}
}
poLayer = poTileIndexDS->CreateLayer(
osLayerName.c_str(), oSRS.IsEmpty() ? nullptr : &oSRS, wkbPolygon,
psOptions->aosLCO.List());
if (!poLayer)
return nullptr;
OGRFieldDefn oLocationField(psOptions->osLocationField.c_str(),
OFTString);
oLocationField.SetWidth(nMaxFieldSize);
if (poLayer->CreateField(&oLocationField) != OGRERR_NONE)
return nullptr;
if (!psOptions->osSrcSRSFieldName.empty())
{
OGRFieldDefn oSrcSRSField(psOptions->osSrcSRSFieldName.c_str(),
OFTString);
oSrcSRSField.SetWidth(nMaxFieldSize);
if (poLayer->CreateField(&oSrcSRSField) != OGRERR_NONE)
return nullptr;
}
}
auto poLayerDefn = poLayer->GetLayerDefn();
for (const auto &oFetchMD : psOptions->aoFetchMD)
{
if (poLayerDefn->GetFieldIndex(oFetchMD.osFieldName.c_str()) < 0)
{
OGRFieldDefn oField(oFetchMD.osFieldName.c_str(), oFetchMD.eType);
if (poLayer->CreateField(&oField) != OGRERR_NONE)
return nullptr;
}
}
if (!psOptions->osGTIFilename.empty())
{
if (!psOptions->aosMetadata.empty())
{
CPLError(CE_Failure, CPLE_NotSupported,
"-mo is not supported when -gti_filename is used");
return nullptr;
}
CPLXMLNode *psRoot =
CPLCreateXMLNode(nullptr, CXT_Element, "GDALTileIndexDataset");
CPLCreateXMLElementAndValue(psRoot, "IndexDataset", pszDest);
CPLCreateXMLElementAndValue(psRoot, "IndexLayer", poLayer->GetName());
CPLCreateXMLElementAndValue(psRoot, "LocationField",
psOptions->osLocationField.c_str());
if (!std::isnan(psOptions->xres))
{
CPLCreateXMLElementAndValue(psRoot, "ResX",
CPLSPrintf("%.18g", psOptions->xres));
CPLCreateXMLElementAndValue(psRoot, "ResY",
CPLSPrintf("%.18g", psOptions->yres));
}
if (!std::isnan(psOptions->xmin))
{
CPLCreateXMLElementAndValue(psRoot, "MinX",
CPLSPrintf("%.18g", psOptions->xmin));
CPLCreateXMLElementAndValue(psRoot, "MinY",
CPLSPrintf("%.18g", psOptions->ymin));
CPLCreateXMLElementAndValue(psRoot, "MaxX",
CPLSPrintf("%.18g", psOptions->xmax));
CPLCreateXMLElementAndValue(psRoot, "MaxY",
CPLSPrintf("%.18g", psOptions->ymax));
}
int nBandCount = 0;
if (!psOptions->osBandCount.empty())
{
nBandCount = atoi(psOptions->osBandCount.c_str());
}
else
{
if (!psOptions->osDataType.empty())
{
nBandCount = std::max(
nBandCount,
CPLStringList(CSLTokenizeString2(
psOptions->osDataType.c_str(), ", ", 0))
.size());
}
if (!psOptions->osNodata.empty())
{
nBandCount = std::max(
nBandCount,
CPLStringList(CSLTokenizeString2(
psOptions->osNodata.c_str(), ", ", 0))
.size());
}
if (!psOptions->osColorInterp.empty())
{
nBandCount =
std::max(nBandCount,
CPLStringList(
CSLTokenizeString2(
psOptions->osColorInterp.c_str(), ", ", 0))
.size());
}
}
for (int i = 0; i < nBandCount; ++i)
{
auto psBand = CPLCreateXMLNode(psRoot, CXT_Element, "Band");
CPLAddXMLAttributeAndValue(psBand, "band", CPLSPrintf("%d", i + 1));
if (!psOptions->osDataType.empty())
{
const CPLStringList aosTokens(
CSLTokenizeString2(psOptions->osDataType.c_str(), ", ", 0));
if (aosTokens.size() == 1)
CPLAddXMLAttributeAndValue(psBand, "dataType",
aosTokens[0]);
else if (i < aosTokens.size())
CPLAddXMLAttributeAndValue(psBand, "dataType",
aosTokens[i]);
}
if (!psOptions->osNodata.empty())
{
const CPLStringList aosTokens(
CSLTokenizeString2(psOptions->osNodata.c_str(), ", ", 0));
if (aosTokens.size() == 1)
CPLCreateXMLElementAndValue(psBand, "NoDataValue",
aosTokens[0]);
else if (i < aosTokens.size())
CPLCreateXMLElementAndValue(psBand, "NoDataValue",
aosTokens[i]);
}
if (!psOptions->osColorInterp.empty())
{
const CPLStringList aosTokens(CSLTokenizeString2(
psOptions->osColorInterp.c_str(), ", ", 0));
if (aosTokens.size() == 1)
CPLCreateXMLElementAndValue(psBand, "ColorInterp",
aosTokens[0]);
else if (i < aosTokens.size())
CPLCreateXMLElementAndValue(psBand, "ColorInterp",
aosTokens[i]);
}
}
if (psOptions->bMaskBand)
{
CPLCreateXMLElementAndValue(psRoot, "MaskBand", "true");
}
int res =
CPLSerializeXMLTreeToFile(psRoot, psOptions->osGTIFilename.c_str());
CPLDestroyXMLNode(psRoot);
if (!res)
return nullptr;
}
else
{
poLayer->SetMetadataItem("LOCATION_FIELD",
psOptions->osLocationField.c_str());
if (!std::isnan(psOptions->xres))
{
poLayer->SetMetadataItem("RESX",
CPLSPrintf("%.18g", psOptions->xres));
poLayer->SetMetadataItem("RESY",
CPLSPrintf("%.18g", psOptions->yres));
}
if (!std::isnan(psOptions->xmin))
{
poLayer->SetMetadataItem("MINX",
CPLSPrintf("%.18g", psOptions->xmin));
poLayer->SetMetadataItem("MINY",
CPLSPrintf("%.18g", psOptions->ymin));
poLayer->SetMetadataItem("MAXX",
CPLSPrintf("%.18g", psOptions->xmax));
poLayer->SetMetadataItem("MAXY",
CPLSPrintf("%.18g", psOptions->ymax));
}
if (!psOptions->osBandCount.empty())
{
poLayer->SetMetadataItem("BAND_COUNT",
psOptions->osBandCount.c_str());
}
if (!psOptions->osDataType.empty())
{
poLayer->SetMetadataItem("DATA_TYPE",
psOptions->osDataType.c_str());
}
if (!psOptions->osNodata.empty())
{
poLayer->SetMetadataItem("NODATA", psOptions->osNodata.c_str());
}
if (!psOptions->osColorInterp.empty())
{
poLayer->SetMetadataItem("COLOR_INTERPRETATION",
psOptions->osColorInterp.c_str());
}
if (psOptions->bMaskBand)
{
poLayer->SetMetadataItem("MASK_BAND", "YES");
}
const CPLStringList aosMetadata(psOptions->aosMetadata);
for (const auto &[pszKey, pszValue] :
cpl::IterateNameValue(aosMetadata))
{
poLayer->SetMetadataItem(pszKey, pszValue);
}
}
const int ti_field =
poLayerDefn->GetFieldIndex(psOptions->osLocationField.c_str());
if (ti_field < 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unable to find field `%s' in file `%s'.",
psOptions->osLocationField.c_str(), pszDest);
return nullptr;
}
int i_SrcSRSName = -1;
if (!psOptions->osSrcSRSFieldName.empty())
{
i_SrcSRSName =
poLayerDefn->GetFieldIndex(psOptions->osSrcSRSFieldName.c_str());
if (i_SrcSRSName < 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unable to find field `%s' in file `%s'.",
psOptions->osSrcSRSFieldName.c_str(), pszDest);
return nullptr;
}
}
// Load in memory existing file names in tile index.
std::set<std::string> oSetExistingFiles;
OGRSpatialReference oAlreadyExistingSRS;
if (bExistingLayer)
{
for (auto &&poFeature : poLayer)
{
if (poFeature->IsFieldSetAndNotNull(ti_field))
{
if (oSetExistingFiles.empty())
{
auto poSrcDS =
std::unique_ptr<GDALDataset>(GDALDataset::Open(
poFeature->GetFieldAsString(ti_field),
GDAL_OF_RASTER, nullptr, nullptr, nullptr));
if (poSrcDS)
{
auto poSrcSRS = poSrcDS->GetSpatialRef();
if (poSrcSRS)
oAlreadyExistingSRS = *poSrcSRS;
}
}
oSetExistingFiles.insert(poFeature->GetFieldAsString(ti_field));
}
}
}
std::string osCurrentPath;
if (psOptions->bWriteAbsolutePath)
{
char *pszCurrentPath = CPLGetCurrentDir();
if (pszCurrentPath)
{
osCurrentPath = pszCurrentPath;
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"This system does not support the CPLGetCurrentDir call. "
"The option -bWriteAbsolutePath will have no effect.");
}
CPLFree(pszCurrentPath);
}
const bool bIsGTIContext =
!std::isnan(psOptions->xres) || !std::isnan(psOptions->xmin) ||
!psOptions->osBandCount.empty() || !psOptions->osNodata.empty() ||
!psOptions->osColorInterp.empty() || !psOptions->osDataType.empty() ||
psOptions->bMaskBand || !psOptions->aosMetadata.empty() ||
!psOptions->osGTIFilename.empty();
/* -------------------------------------------------------------------- */
/* loop over GDAL files, processing. */
/* -------------------------------------------------------------------- */
int iCur = 0;
int nTotal = nSrcCount + 1;
while (true)
{
const std::string osSrcFilename = oGDALTileIndexTileIterator.next();
if (osSrcFilename.empty())
break;
if (bSkipFirstTile)
{
bSkipFirstTile = false;
continue;
}
std::string osFileNameToWrite;
VSIStatBuf sStatBuf;
// Make sure it is a file before building absolute path name.
if (!osCurrentPath.empty() &&
CPLIsFilenameRelative(osSrcFilename.c_str()) &&
VSIStat(osSrcFilename.c_str(), &sStatBuf) == 0)
{
osFileNameToWrite = CPLProjectRelativeFilenameSafe(
osCurrentPath.c_str(), osSrcFilename.c_str());
}
else
{
osFileNameToWrite = osSrcFilename.c_str();
}
// Checks that file is not already in tileindex.
if (oSetExistingFiles.find(osFileNameToWrite) !=
oSetExistingFiles.end())
{
CPLError(CE_Warning, CPLE_AppDefined,
"File %s is already in tileindex. Skipping it.",
osFileNameToWrite.c_str());
continue;
}
std::unique_ptr<GDALDataset> poSrcDS;
{
std::unique_ptr<CPLTurnFailureIntoWarningBackuper>
poFailureIntoWarning;
if (!bFailOnErrors)
poFailureIntoWarning =
std::make_unique<CPLTurnFailureIntoWarningBackuper>();
CPL_IGNORE_RET_VAL(poFailureIntoWarning);
poSrcDS.reset(GDALDataset::Open(
osSrcFilename.c_str(), GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
nullptr, nullptr, nullptr));
if (poSrcDS == nullptr)
{
CPLError(bFailOnErrors ? CE_Failure : CE_Warning,
CPLE_AppDefined, "Unable to open %s%s.",
osSrcFilename.c_str(),
bFailOnErrors ? "" : ", skipping");
if (bFailOnErrors)
return nullptr;
continue;
}
}
GDALGeoTransform gt;
if (poSrcDS->GetGeoTransform(gt) != CE_None)
{
CPLError(bFailOnErrors ? CE_Failure : CE_Warning, CPLE_AppDefined,
"It appears no georeferencing is available for\n"
"`%s'%s.",
osSrcFilename.c_str(), bFailOnErrors ? "" : ", skipping");
if (bFailOnErrors)
return nullptr;
continue;
}
auto poSrcSRS = poSrcDS->GetSpatialRef();
// If not set target srs, test that the current file uses same
// projection as others.
if (oTargetSRS.IsEmpty())
{
if (!oAlreadyExistingSRS.IsEmpty())
{
if (poSrcSRS == nullptr ||
!poSrcSRS->IsSame(&oAlreadyExistingSRS))
{
CPLError(
CE_Warning, CPLE_AppDefined,
"%s is not using the same projection system "
"as other files in the tileindex.\n"
"This may cause problems when using it in MapServer "
"for example.\n"
"Use -t_srs option to set target projection system. %s",
osSrcFilename.c_str(),
psOptions->bSkipDifferentProjection
? "Skipping this file."
: "");
if (psOptions->bSkipDifferentProjection)
{
continue;
}
}
}
else
{
if (poSrcSRS)
oAlreadyExistingSRS = *poSrcSRS;
}
}
const int nXSize = poSrcDS->GetRasterXSize();
const int nYSize = poSrcDS->GetRasterYSize();
if (nXSize == 0 || nYSize == 0)
{
CPLError(bFailOnErrors ? CE_Failure : CE_Warning, CPLE_AppDefined,
"%s has 0 width or height%s", osSrcFilename.c_str(),
bFailOnErrors ? "" : ", skipping");
if (bFailOnErrors)
return nullptr;
continue;
}
double adfX[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
double adfY[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
adfX[0] = gt[0] + 0 * gt[1] + 0 * gt[2];
adfY[0] = gt[3] + 0 * gt[4] + 0 * gt[5];
adfX[1] = gt[0] + nXSize * gt[1] + 0 * gt[2];
adfY[1] = gt[3] + nXSize * gt[4] + 0 * gt[5];
adfX[2] = gt[0] + nXSize * gt[1] + nYSize * gt[2];
adfY[2] = gt[3] + nXSize * gt[4] + nYSize * gt[5];
adfX[3] = gt[0] + 0 * gt[1] + nYSize * gt[2];
adfY[3] = gt[3] + 0 * gt[4] + nYSize * gt[5];
adfX[4] = gt[0] + 0 * gt[1] + 0 * gt[2];
adfY[4] = gt[3] + 0 * gt[4] + 0 * gt[5];
// If set target srs, do the forward transformation of all points.
if (!oTargetSRS.IsEmpty() && poSrcSRS)
{
if (!poSrcSRS->IsSame(&oTargetSRS))
{
auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
OGRCreateCoordinateTransformation(poSrcSRS, &oTargetSRS));
if (!poCT || !poCT->Transform(5, adfX, adfY, nullptr))
{
CPLError(bFailOnErrors ? CE_Failure : CE_Warning,
CPLE_AppDefined,
"unable to transform points from source "
"SRS `%s' to target SRS `%s' for file `%s'%s",
poSrcDS->GetProjectionRef(),
psOptions->osTargetSRS.c_str(),
osFileNameToWrite.c_str(),
bFailOnErrors ? "" : ", skipping");
if (bFailOnErrors)
return nullptr;
continue;
}
}
}
else if (bIsGTIContext && !oAlreadyExistingSRS.IsEmpty() &&
(poSrcSRS == nullptr ||
!poSrcSRS->IsSame(&oAlreadyExistingSRS)))
{
CPLError(
CE_Failure, CPLE_AppDefined,
"%s is not using the same projection system "
"as other files in the tileindex. This is not compatible of "
"GTI use. Use -t_srs option to reproject tile extents "
"to a common SRS.",
osSrcFilename.c_str());
return nullptr;
}
const double dfMinX =
std::min(std::min(adfX[0], adfX[1]), std::min(adfX[2], adfX[3]));
const double dfMinY =
std::min(std::min(adfY[0], adfY[1]), std::min(adfY[2], adfY[3]));
const double dfMaxX =
std::max(std::max(adfX[0], adfX[1]), std::max(adfX[2], adfX[3]));
const double dfMaxY =
std::max(std::max(adfY[0], adfY[1]), std::max(adfY[2], adfY[3]));
const double dfRes =
sqrt((dfMaxX - dfMinX) * (dfMaxY - dfMinY) / nXSize / nYSize);
if (!std::isnan(psOptions->dfMinPixelSize) &&
dfRes < psOptions->dfMinPixelSize)
{
CPLError(CE_Warning, CPLE_AppDefined,
"%s has %f as pixel size (< %f). Skipping",
osSrcFilename.c_str(), dfRes, psOptions->dfMinPixelSize);
continue;
}
if (!std::isnan(psOptions->dfMaxPixelSize) &&
dfRes > psOptions->dfMaxPixelSize)
{
CPLError(CE_Warning, CPLE_AppDefined,
"%s has %f as pixel size (> %f). Skipping",
osSrcFilename.c_str(), dfRes, psOptions->dfMaxPixelSize);
continue;
}
auto poFeature = std::make_unique<OGRFeature>(poLayerDefn);
poFeature->SetField(ti_field, osFileNameToWrite.c_str());
if (i_SrcSRSName >= 0 && poSrcSRS)
{
const char *pszAuthorityCode = poSrcSRS->GetAuthorityCode(nullptr);
const char *pszAuthorityName = poSrcSRS->GetAuthorityName(nullptr);
if (psOptions->eSrcSRSFormat == FORMAT_AUTO)
{
if (pszAuthorityName != nullptr && pszAuthorityCode != nullptr)
{
poFeature->SetField(i_SrcSRSName,
CPLSPrintf("%s:%s", pszAuthorityName,
pszAuthorityCode));
}
else if (nMaxFieldSize == 0 ||
strlen(poSrcDS->GetProjectionRef()) <=
static_cast<size_t>(nMaxFieldSize))
{
poFeature->SetField(i_SrcSRSName,
poSrcDS->GetProjectionRef());
}
else
{
char *pszProj4 = nullptr;
if (poSrcSRS->exportToProj4(&pszProj4) == OGRERR_NONE)
{
poFeature->SetField(i_SrcSRSName, pszProj4);
}
else
{
poFeature->SetField(i_SrcSRSName,
poSrcDS->GetProjectionRef());
}
CPLFree(pszProj4);
}
}
else if (psOptions->eSrcSRSFormat == FORMAT_WKT)
{
if (nMaxFieldSize == 0 ||
strlen(poSrcDS->GetProjectionRef()) <=
static_cast<size_t>(nMaxFieldSize))
{
poFeature->SetField(i_SrcSRSName,
poSrcDS->GetProjectionRef());
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Cannot write WKT for file %s as it is too long!",
osFileNameToWrite.c_str());
}
}
else if (psOptions->eSrcSRSFormat == FORMAT_PROJ)
{
char *pszProj4 = nullptr;
if (poSrcSRS->exportToProj4(&pszProj4) == OGRERR_NONE)
{
poFeature->SetField(i_SrcSRSName, pszProj4);
}
CPLFree(pszProj4);
}
else if (psOptions->eSrcSRSFormat == FORMAT_EPSG)
{
if (pszAuthorityName != nullptr && pszAuthorityCode != nullptr)
poFeature->SetField(i_SrcSRSName,
CPLSPrintf("%s:%s", pszAuthorityName,
pszAuthorityCode));
}
}
for (const auto &oFetchMD : psOptions->aoFetchMD)
{
if (EQUAL(oFetchMD.osRasterItemName.c_str(), "{PIXEL_SIZE}"))
{
poFeature->SetField(oFetchMD.osFieldName.c_str(), dfRes);
continue;
}
const char *pszMD =
poSrcDS->GetMetadataItem(oFetchMD.osRasterItemName.c_str());
if (pszMD)
{
if (EQUAL(oFetchMD.osRasterItemName.c_str(),
"TIFFTAG_DATETIME"))
{
int nYear, nMonth, nDay, nHour, nMin, nSec;
if (sscanf(pszMD, "%04d:%02d:%02d %02d:%02d:%02d", &nYear,
&nMonth, &nDay, &nHour, &nMin, &nSec) == 6)
{
poFeature->SetField(
oFetchMD.osFieldName.c_str(),
CPLSPrintf("%04d/%02d/%02d %02d:%02d:%02d", nYear,
nMonth, nDay, nHour, nMin, nSec));
continue;
}
}
poFeature->SetField(oFetchMD.osFieldName.c_str(), pszMD);
}
}
auto poPoly = std::make_unique<OGRPolygon>();
auto poRing = std::make_unique<OGRLinearRing>();
for (int k = 0; k < 5; k++)
poRing->addPoint(adfX[k], adfY[k]);
poPoly->addRing(std::move(poRing));
poFeature->SetGeometryDirectly(poPoly.release());
if (poLayer->CreateFeature(poFeature.get()) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to create feature in tile index.");
return nullptr;
}
++iCur;
if (psOptions->pfnProgress &&
!psOptions->pfnProgress(static_cast<double>(iCur) / nTotal, "",
psOptions->pProgressData))
{
return nullptr;
}
if (iCur >= nSrcCount)
++nTotal;
}
if (psOptions->pfnProgress)
psOptions->pfnProgress(1.0, "", psOptions->pProgressData);
if (poTileIndexDSUnique)
return GDALDataset::ToHandle(poTileIndexDSUnique.release());
else
return GDALDataset::ToHandle(poTileIndexDS);
}
/************************************************************************/
/* SanitizeSRS */
/************************************************************************/
static char *SanitizeSRS(const char *pszUserInput)
{
OGRSpatialReferenceH hSRS;
char *pszResult = nullptr;
CPLErrorReset();
hSRS = OSRNewSpatialReference(nullptr);
if (OSRSetFromUserInput(hSRS, pszUserInput) == OGRERR_NONE)
OSRExportToWkt(hSRS, &pszResult);
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Translating SRS failed:\n%s",
pszUserInput);
}
OSRDestroySpatialReference(hSRS);
return pszResult;
}
/************************************************************************/
/* GDALTileIndexOptionsNew() */
/************************************************************************/
/**
* Allocates a GDALTileIndexOptions struct.
*
* @param papszArgv NULL terminated list of options (potentially including
* filename and open options too), or NULL. The accepted options are the ones of
* the <a href="/programs/gdaltindex.html">gdaltindex</a> utility.
* @param psOptionsForBinary (output) may be NULL (and should generally be
* NULL), otherwise (gdaltindex_bin.cpp use case) must be allocated with
* GDALTileIndexOptionsForBinaryNew() prior to this function. Will be filled
* with potentially present filename, open options,...
* @return pointer to the allocated GDALTileIndexOptions struct. Must be freed
* with GDALTileIndexOptionsFree().
*
* @since GDAL 3.9
*/
GDALTileIndexOptions *
GDALTileIndexOptionsNew(char **papszArgv,
GDALTileIndexOptionsForBinary *psOptionsForBinary)
{
auto psOptions = std::make_unique<GDALTileIndexOptions>();
/* -------------------------------------------------------------------- */
/* Parse arguments. */
/* -------------------------------------------------------------------- */
CPLStringList aosArgv;
if (papszArgv)
{
const int nArgc = CSLCount(papszArgv);
for (int i = 0; i < nArgc; i++)
{
aosArgv.AddString(papszArgv[i]);
}
}
try
{
auto argParser = GDALTileIndexAppOptionsGetParser(psOptions.get(),
psOptionsForBinary);
argParser->parse_args_without_binary_name(aosArgv.List());
// Check all no store_into args
if (auto oTr = argParser->present<std::vector<double>>("-tr"))
{
psOptions->xres = (*oTr)[0];
psOptions->yres = (*oTr)[1];
}
if (auto oTargetExtent = argParser->present<std::vector<double>>("-te"))
{
psOptions->xmin = (*oTargetExtent)[0];
psOptions->ymin = (*oTargetExtent)[1];
psOptions->xmax = (*oTargetExtent)[2];
psOptions->ymax = (*oTargetExtent)[3];
}
if (auto fetchMd =
argParser->present<std::vector<std::string>>("-fetch_md"))
{
CPLAssert(fetchMd->size() % 3 == 0);
// Loop
for (size_t i = 0; i < fetchMd->size(); i += 3)
{
OGRFieldType type;
const auto &typeName{fetchMd->at(i + 2)};
if (typeName == "String")
{
type = OFTString;
}
else if (typeName == "Integer")
{
type = OFTInteger;
}
else if (typeName == "Integer64")
{
type = OFTInteger64;
}
else if (typeName == "Real")
{
type = OFTReal;
}
else if (typeName == "Date")
{
type = OFTDate;
}
else if (typeName == "DateTime")
{
type = OFTDateTime;
}
else
{
CPLError(CE_Failure, CPLE_AppDefined,
"-fetch_md requires a valid type name as third "
"argument: %s was given.",
fetchMd->at(i).c_str());
return nullptr;
}
const GDALTileIndexRasterMetadata oMD{type, fetchMd->at(i + 1),
fetchMd->at(i)};
psOptions->aoFetchMD.push_back(std::move(oMD));
}
}
// Check -t_srs
if (!psOptions->osTargetSRS.empty())
{
auto sanitized{SanitizeSRS(psOptions->osTargetSRS.c_str())};
if (sanitized)
{
psOptions->osTargetSRS = sanitized;
CPLFree(sanitized);
}
else
{
// Error was already reported by SanitizeSRS, just return nullptr
psOptions->osTargetSRS.clear();
return nullptr;
}
}
}
catch (const std::exception &error)
{
CPLError(CE_Failure, CPLE_AppDefined, "%s", error.what());
return nullptr;
}
return psOptions.release();
}
/************************************************************************/
/* GDALTileIndexOptionsFree() */
/************************************************************************/
/**
* Frees the GDALTileIndexOptions struct.
*
* @param psOptions the options struct for GDALTileIndex().
*
* @since GDAL 3.9
*/
void GDALTileIndexOptionsFree(GDALTileIndexOptions *psOptions)
{
delete psOptions;
}
/************************************************************************/
/* GDALTileIndexOptionsSetProgress() */
/************************************************************************/
/**
* Set a progress function.
*
* @param psOptions the options struct for GDALTileIndex().
* @param pfnProgress the progress callback.
* @param pProgressData the user data for the progress callback.
*
* @since GDAL 3.11
*/
void GDALTileIndexOptionsSetProgress(GDALTileIndexOptions *psOptions,
GDALProgressFunc pfnProgress,
void *pProgressData)
{
psOptions->pfnProgress = pfnProgress;
psOptions->pProgressData = pProgressData;
}
#undef CHECK_HAS_ENOUGH_ADDITIONAL_ARGS
|