LCOV - code coverage report
Current view: top level - apps - gdal_rasterize_lib.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 639 773 82.7 %
Date: 2026-05-13 23:47:50 Functions: 22 26 84.6 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL Utilities
       4             :  * Purpose:  Rasterize OGR shapes into a GDAL raster.
       5             :  * Author:   Frank Warmerdam <warmerdam@pobox.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.com>
       9             :  * Copyright (c) 2008-2015, Even Rouault <even dot rouault at spatialys dot com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "cpl_port.h"
      15             : #include "gdal_utils.h"
      16             : #include "gdal_utils_priv.h"
      17             : 
      18             : #include <cinttypes>
      19             : #include <cmath>
      20             : #include <cstdio>
      21             : #include <cstdlib>
      22             : #include <cstring>
      23             : #include <algorithm>
      24             : #include <limits>
      25             : #include <vector>
      26             : 
      27             : #include "commonutils.h"
      28             : #include "cpl_conv.h"
      29             : #include "cpl_error.h"
      30             : #include "cpl_progress.h"
      31             : #include "cpl_string.h"
      32             : #include "gdal.h"
      33             : #include "gdal_alg.h"
      34             : #include "gdal_priv.h"
      35             : #include "ogr_api.h"
      36             : #include "ogr_core.h"
      37             : #include "ogr_srs_api.h"
      38             : #include "gdalargumentparser.h"
      39             : 
      40             : /************************************************************************/
      41             : /*                        GDALRasterizeOptions()                        */
      42             : /************************************************************************/
      43             : 
      44             : struct GDALRasterizeOptions
      45             : {
      46             :     std::vector<int> anBandList{};
      47             :     std::vector<double> adfBurnValues{};
      48             :     bool bInverse = false;
      49             :     std::string osFormat{};
      50             :     bool b3D = false;
      51             :     GDALProgressFunc pfnProgress = GDALDummyProgress;
      52             :     void *pProgressData = nullptr;
      53             :     std::vector<std::string> aosLayers{};
      54             :     std::string osSQL{};
      55             :     std::string osDialect{};
      56             :     std::string osBurnAttribute{};
      57             :     std::string osWHERE{};
      58             :     CPLStringList aosRasterizeOptions{};
      59             :     CPLStringList aosTO{};
      60             :     double dfXRes = 0;
      61             :     double dfYRes = 0;
      62             :     CPLStringList aosCreationOptions{};
      63             :     GDALDataType eOutputType = GDT_Unknown;
      64             :     std::vector<double> adfInitVals{};
      65             :     std::string osNoData{};
      66             :     OGREnvelope sEnvelop{};
      67             :     int nXSize = 0;
      68             :     int nYSize = 0;
      69             :     OGRSpatialReference oOutputSRS{};
      70             : 
      71             :     bool bTargetAlignedPixels = false;
      72             :     bool bCreateOutput = false;
      73             : };
      74             : 
      75             : /************************************************************************/
      76             : /*                   GDALRasterizeOptionsGetParser()                    */
      77             : /************************************************************************/
      78             : 
      79             : static std::unique_ptr<GDALArgumentParser>
      80          76 : GDALRasterizeOptionsGetParser(GDALRasterizeOptions *psOptions,
      81             :                               GDALRasterizeOptionsForBinary *psOptionsForBinary)
      82             : {
      83             :     auto argParser = std::make_unique<GDALArgumentParser>(
      84          76 :         "gdal_rasterize", /* bForBinary=*/psOptionsForBinary != nullptr);
      85             : 
      86          76 :     argParser->add_description(_("Burns vector geometries into a raster."));
      87             : 
      88          76 :     argParser->add_epilog(
      89             :         _("This program burns vector geometries (points, lines, and polygons) "
      90          76 :           "into the raster band(s) of a raster image."));
      91             : 
      92             :     // Dealt manually as argparse::nargs_pattern::at_least_one is problematic
      93          76 :     argParser->add_argument("-b")
      94         152 :         .metavar("<band>")
      95          76 :         .append()
      96          76 :         .scan<'i', int>()
      97             :         //.nargs(argparse::nargs_pattern::at_least_one)
      98          76 :         .help(_("The band(s) to burn values into."));
      99             : 
     100          76 :     argParser->add_argument("-i")
     101          76 :         .flag()
     102          76 :         .store_into(psOptions->bInverse)
     103          76 :         .help(_("Invert rasterization."));
     104             : 
     105          76 :     argParser->add_argument("-at")
     106          76 :         .flag()
     107             :         .action(
     108          32 :             [psOptions](const std::string &)
     109             :             {
     110             :                 psOptions->aosRasterizeOptions.SetNameValue("ALL_TOUCHED",
     111          32 :                                                             "TRUE");
     112          76 :             })
     113          76 :         .help(_("Enables the ALL_TOUCHED rasterization option."));
     114             : 
     115             :     // Mutually exclusive options: -burn, -3d, -a
     116             :     {
     117             :         // Required if options for binary
     118          76 :         auto &group = argParser->add_mutually_exclusive_group(
     119          76 :             psOptionsForBinary != nullptr);
     120             : 
     121             :         // Dealt manually as argparse::nargs_pattern::at_least_one is problematic
     122          76 :         group.add_argument("-burn")
     123         152 :             .metavar("<value>")
     124          76 :             .scan<'g', double>()
     125          76 :             .append()
     126             :             //.nargs(argparse::nargs_pattern::at_least_one)
     127          76 :             .help(_("A fixed value to burn into the raster band(s)."));
     128             : 
     129          76 :         group.add_argument("-a")
     130         152 :             .metavar("<attribute_name>")
     131          76 :             .store_into(psOptions->osBurnAttribute)
     132             :             .help(_("Name of the field in the input layer to get the burn "
     133          76 :                     "values from."));
     134             : 
     135          76 :         group.add_argument("-3d")
     136          76 :             .flag()
     137          76 :             .store_into(psOptions->b3D)
     138             :             .action(
     139           5 :                 [psOptions](const std::string &)
     140             :                 {
     141             :                     psOptions->aosRasterizeOptions.SetNameValue(
     142           5 :                         "BURN_VALUE_FROM", "Z");
     143          76 :                 })
     144             :             .help(_("Indicates that a burn value should be extracted from the "
     145          76 :                     "\"Z\" values of the feature."));
     146             :     }
     147             : 
     148          76 :     argParser->add_argument("-add")
     149          76 :         .flag()
     150             :         .action(
     151           1 :             [psOptions](const std::string &)
     152             :             {
     153           1 :                 psOptions->aosRasterizeOptions.SetNameValue("MERGE_ALG", "ADD");
     154          76 :             })
     155             :         .help(_("Instead of burning a new value, this adds the new value to "
     156          76 :                 "the existing raster."));
     157             : 
     158             :     // Undocumented
     159          76 :     argParser->add_argument("-chunkysize")
     160          76 :         .flag()
     161          76 :         .hidden()
     162             :         .action(
     163           0 :             [psOptions](const std::string &s)
     164             :             {
     165             :                 psOptions->aosRasterizeOptions.SetNameValue("CHUNKYSIZE",
     166           0 :                                                             s.c_str());
     167          76 :             });
     168             : 
     169             :     // Mutually exclusive -l, -sql
     170             :     {
     171          76 :         auto &group = argParser->add_mutually_exclusive_group(false);
     172             : 
     173          76 :         group.add_argument("-l")
     174         152 :             .metavar("<layer_name>")
     175          76 :             .append()
     176          76 :             .store_into(psOptions->aosLayers)
     177          76 :             .help(_("Name of the layer(s) to process."));
     178             : 
     179          76 :         group.add_argument("-sql")
     180         152 :             .metavar("<sql_statement>")
     181          76 :             .store_into(psOptions->osSQL)
     182             :             .action(
     183          10 :                 [psOptions](const std::string &sql)
     184             :                 {
     185           9 :                     GByte *pabyRet = nullptr;
     186          10 :                     if (!sql.empty() && sql.at(0) == '@' &&
     187          10 :                         VSIIngestFile(nullptr, sql.substr(1).c_str(), &pabyRet,
     188             :                                       nullptr, 10 * 1024 * 1024))
     189             :                     {
     190           1 :                         GDALRemoveBOM(pabyRet);
     191           1 :                         char *pszSQLStatement =
     192             :                             reinterpret_cast<char *>(pabyRet);
     193             :                         psOptions->osSQL =
     194           1 :                             CPLRemoveSQLComments(pszSQLStatement);
     195           1 :                         VSIFree(pszSQLStatement);
     196             :                     }
     197          85 :                 })
     198             :             .help(
     199             :                 _("An SQL statement to be evaluated against the datasource to "
     200          76 :                   "produce a virtual layer of features to be burned in."));
     201             :     }
     202             : 
     203          76 :     argParser->add_argument("-where")
     204         152 :         .metavar("<expression>")
     205          76 :         .store_into(psOptions->osWHERE)
     206             :         .help(_("An optional SQL WHERE style query expression to be applied to "
     207             :                 "select features "
     208          76 :                 "to burn in from the input layer(s)."));
     209             : 
     210          76 :     argParser->add_argument("-dialect")
     211         152 :         .metavar("<sql_dialect>")
     212          76 :         .store_into(psOptions->osDialect)
     213          76 :         .help(_("The SQL dialect to use for the SQL expression."));
     214             : 
     215             :     // Store later
     216          76 :     argParser->add_argument("-a_nodata")
     217         152 :         .metavar("<value>")
     218          76 :         .help(_("Assign a specified nodata value to output bands."));
     219             : 
     220             :     // Dealt manually as argparse::nargs_pattern::at_least_one is problematic
     221          76 :     argParser->add_argument("-init")
     222         152 :         .metavar("<value>")
     223          76 :         .append()
     224             :         //.nargs(argparse::nargs_pattern::at_least_one)
     225          76 :         .scan<'g', double>()
     226          76 :         .help(_("Initialize the output bands to the specified value."));
     227             : 
     228          76 :     argParser->add_argument("-a_srs")
     229         152 :         .metavar("<srs_def>")
     230             :         .action(
     231           4 :             [psOptions](const std::string &osOutputSRSDef)
     232             :             {
     233           2 :                 if (psOptions->oOutputSRS.SetFromUserInput(
     234           2 :                         osOutputSRSDef.c_str()) != OGRERR_NONE)
     235             :                 {
     236             :                     throw std::invalid_argument(
     237           0 :                         std::string("Failed to process SRS definition: ")
     238           0 :                             .append(osOutputSRSDef));
     239             :                 }
     240           2 :                 psOptions->bCreateOutput = true;
     241          78 :             })
     242          76 :         .help(_("The spatial reference system to use for the output raster."));
     243             : 
     244          76 :     argParser->add_argument("-to")
     245         152 :         .metavar("<NAME>=<VALUE>")
     246          76 :         .append()
     247           1 :         .action([psOptions](const std::string &s)
     248          77 :                 { psOptions->aosTO.AddString(s.c_str()); })
     249          76 :         .help(_("Set a transformer option."));
     250             : 
     251             :     // Store later
     252          76 :     argParser->add_argument("-te")
     253         152 :         .metavar("<xmin> <ymin> <xmax> <ymax>")
     254          76 :         .nargs(4)
     255          76 :         .scan<'g', double>()
     256          76 :         .help(_("Set georeferenced extents of output file to be created."));
     257             : 
     258             :     // Mutex with tr
     259             :     {
     260          76 :         auto &group = argParser->add_mutually_exclusive_group(false);
     261             : 
     262             :         // Store later
     263          76 :         group.add_argument("-tr")
     264         152 :             .metavar("<xres> <yres>")
     265          76 :             .nargs(2)
     266          76 :             .scan<'g', double>()
     267             :             .help(
     268          76 :                 _("Set output file resolution in target georeferenced units."));
     269             : 
     270             :         // Store later
     271             :         // Note: this is supposed to be int but for backward compatibility, we
     272             :         //       use double
     273          76 :         auto &arg = group.add_argument("-ts")
     274         152 :                         .metavar("<width> <height>")
     275          76 :                         .nargs(2)
     276          76 :                         .scan<'g', double>()
     277          76 :                         .help(_("Set output file size in pixels and lines."));
     278             : 
     279          76 :         argParser->add_hidden_alias_for(arg, "-outsize");
     280             :     }
     281             : 
     282          76 :     argParser->add_argument("-tap")
     283          76 :         .flag()
     284          76 :         .store_into(psOptions->bTargetAlignedPixels)
     285           1 :         .action([psOptions](const std::string &)
     286          76 :                 { psOptions->bCreateOutput = true; })
     287             :         .help(_("Align the coordinates of the extent to the values of the "
     288          76 :                 "output raster."));
     289             : 
     290          76 :     argParser->add_argument("-optim")
     291         152 :         .metavar("AUTO|VECTOR|RASTER")
     292             :         .action(
     293          43 :             [psOptions](const std::string &s)
     294             :             {
     295          43 :                 psOptions->aosRasterizeOptions.SetNameValue("OPTIM", s.c_str());
     296          76 :             })
     297          76 :         .help(_("Force the algorithm used."));
     298             : 
     299          76 :     argParser->add_creation_options_argument(psOptions->aosCreationOptions)
     300           2 :         .action([psOptions](const std::string &)
     301          76 :                 { psOptions->bCreateOutput = true; });
     302             : 
     303          76 :     argParser->add_output_type_argument(psOptions->eOutputType)
     304           3 :         .action([psOptions](const std::string &)
     305          76 :                 { psOptions->bCreateOutput = true; });
     306             : 
     307          76 :     argParser->add_output_format_argument(psOptions->osFormat)
     308          14 :         .action([psOptions](const std::string &)
     309          76 :                 { psOptions->bCreateOutput = true; });
     310             : 
     311             :     // Written that way so that in library mode, users can still use the -q
     312             :     // switch, even if it has no effect
     313             :     argParser->add_quiet_argument(
     314          76 :         psOptionsForBinary ? &(psOptionsForBinary->bQuiet) : nullptr);
     315             : 
     316          76 :     if (psOptionsForBinary)
     317             :     {
     318             : 
     319             :         argParser->add_open_options_argument(
     320          11 :             psOptionsForBinary->aosOpenOptions);
     321             : 
     322          11 :         argParser->add_argument("src_datasource")
     323          22 :             .metavar("<src_datasource>")
     324          11 :             .store_into(psOptionsForBinary->osSource)
     325          11 :             .help(_("Any vector supported readable datasource."));
     326             : 
     327          11 :         argParser->add_argument("dst_filename")
     328          22 :             .metavar("<dst_filename>")
     329          11 :             .store_into(psOptionsForBinary->osDest)
     330          11 :             .help(_("The GDAL raster supported output file."));
     331             :     }
     332             : 
     333          76 :     return argParser;
     334             : }
     335             : 
     336             : /************************************************************************/
     337             : /*                   GDALRasterizeAppGetParserUsage()                   */
     338             : /************************************************************************/
     339             : 
     340           0 : std::string GDALRasterizeAppGetParserUsage()
     341             : {
     342             :     try
     343             :     {
     344           0 :         GDALRasterizeOptions sOptions;
     345           0 :         GDALRasterizeOptionsForBinary sOptionsForBinary;
     346             :         auto argParser =
     347           0 :             GDALRasterizeOptionsGetParser(&sOptions, &sOptionsForBinary);
     348           0 :         return argParser->usage();
     349             :     }
     350           0 :     catch (const std::exception &err)
     351             :     {
     352           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
     353           0 :                  err.what());
     354           0 :         return std::string();
     355             :     }
     356             : }
     357             : 
     358             : /************************************************************************/
     359             : /*                          InvertGeometries()                          */
     360             : /************************************************************************/
     361             : 
     362           3 : static void InvertGeometries(GDALDatasetH hDstDS,
     363             :                              std::vector<OGRGeometryH> &ahGeometries)
     364             : 
     365             : {
     366           3 :     OGRMultiPolygon *poInvertMP = new OGRMultiPolygon();
     367             : 
     368             :     /* -------------------------------------------------------------------- */
     369             :     /*      Create a ring that is a bit outside the raster dataset.         */
     370             :     /* -------------------------------------------------------------------- */
     371           3 :     const int brx = GDALGetRasterXSize(hDstDS) + 2;
     372           3 :     const int bry = GDALGetRasterYSize(hDstDS) + 2;
     373             : 
     374           3 :     double adfGeoTransform[6] = {};
     375           3 :     GDALGetGeoTransform(hDstDS, adfGeoTransform);
     376             : 
     377           3 :     auto poUniverseRing = std::make_unique<OGRLinearRing>();
     378             : 
     379           3 :     poUniverseRing->addPoint(
     380           3 :         adfGeoTransform[0] + -2 * adfGeoTransform[1] + -2 * adfGeoTransform[2],
     381           3 :         adfGeoTransform[3] + -2 * adfGeoTransform[4] + -2 * adfGeoTransform[5]);
     382             : 
     383           3 :     poUniverseRing->addPoint(adfGeoTransform[0] + brx * adfGeoTransform[1] +
     384           3 :                                  -2 * adfGeoTransform[2],
     385           3 :                              adfGeoTransform[3] + brx * adfGeoTransform[4] +
     386           3 :                                  -2 * adfGeoTransform[5]);
     387             : 
     388           3 :     poUniverseRing->addPoint(adfGeoTransform[0] + brx * adfGeoTransform[1] +
     389           3 :                                  bry * adfGeoTransform[2],
     390           3 :                              adfGeoTransform[3] + brx * adfGeoTransform[4] +
     391           3 :                                  bry * adfGeoTransform[5]);
     392             : 
     393           3 :     poUniverseRing->addPoint(adfGeoTransform[0] + -2 * adfGeoTransform[1] +
     394           3 :                                  bry * adfGeoTransform[2],
     395           3 :                              adfGeoTransform[3] + -2 * adfGeoTransform[4] +
     396           3 :                                  bry * adfGeoTransform[5]);
     397             : 
     398           3 :     poUniverseRing->addPoint(
     399           3 :         adfGeoTransform[0] + -2 * adfGeoTransform[1] + -2 * adfGeoTransform[2],
     400           3 :         adfGeoTransform[3] + -2 * adfGeoTransform[4] + -2 * adfGeoTransform[5]);
     401             : 
     402           3 :     auto poUniversePoly = std::make_unique<OGRPolygon>();
     403           3 :     poUniversePoly->addRing(std::move(poUniverseRing));
     404           3 :     poInvertMP->addGeometry(std::move(poUniversePoly));
     405             : 
     406           3 :     bool bFoundNonPoly = false;
     407             :     // If we have GEOS, use it to "subtract" each polygon from the universe
     408             :     // multipolygon
     409           3 :     if (OGRGeometryFactory::haveGEOS())
     410             :     {
     411           3 :         OGRGeometry *poInvertMPAsGeom = poInvertMP;
     412           3 :         poInvertMP = nullptr;
     413           3 :         CPL_IGNORE_RET_VAL(poInvertMP);
     414          10 :         for (unsigned int iGeom = 0; iGeom < ahGeometries.size(); iGeom++)
     415             :         {
     416           7 :             auto poGeom = OGRGeometry::FromHandle(ahGeometries[iGeom]);
     417           7 :             const auto eGType = OGR_GT_Flatten(poGeom->getGeometryType());
     418           7 :             if (eGType != wkbPolygon && eGType != wkbMultiPolygon)
     419             :             {
     420           1 :                 if (!bFoundNonPoly)
     421             :                 {
     422           1 :                     bFoundNonPoly = true;
     423           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
     424             :                              "Ignoring non-polygon geometries in -i mode");
     425             :                 }
     426             :             }
     427             :             else
     428             :             {
     429           6 :                 auto poNewGeom = poInvertMPAsGeom->Difference(poGeom);
     430           6 :                 if (poNewGeom)
     431             :                 {
     432           6 :                     delete poInvertMPAsGeom;
     433           6 :                     poInvertMPAsGeom = poNewGeom;
     434             :                 }
     435             :             }
     436             : 
     437           7 :             delete poGeom;
     438             :         }
     439             : 
     440           3 :         ahGeometries.resize(1);
     441           3 :         ahGeometries[0] = OGRGeometry::ToHandle(poInvertMPAsGeom);
     442           3 :         return;
     443             :     }
     444             : 
     445             :     OGRPolygon &hUniversePoly =
     446           0 :         *poInvertMP->getGeometryRef(poInvertMP->getNumGeometries() - 1);
     447             : 
     448             :     /* -------------------------------------------------------------------- */
     449             :     /*      If we don't have GEOS, add outer rings of polygons as inner     */
     450             :     /*      rings of poUniversePoly and inner rings as sub-polygons. Note   */
     451             :     /*      that this only works properly if the polygons are disjoint, in  */
     452             :     /*      the sense that the outer ring of any polygon is not inside the  */
     453             :     /*      outer ring of another one. So the scenario of                   */
     454             :     /*      https://github.com/OSGeo/gdal/issues/8689 with an "island" in   */
     455             :     /*      the middle of a hole will not work properly.                    */
     456             :     /* -------------------------------------------------------------------- */
     457           0 :     for (unsigned int iGeom = 0; iGeom < ahGeometries.size(); iGeom++)
     458             :     {
     459             :         const auto eGType =
     460           0 :             OGR_GT_Flatten(OGR_G_GetGeometryType(ahGeometries[iGeom]));
     461           0 :         if (eGType != wkbPolygon && eGType != wkbMultiPolygon)
     462             :         {
     463           0 :             if (!bFoundNonPoly)
     464             :             {
     465           0 :                 bFoundNonPoly = true;
     466           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     467             :                          "Ignoring non-polygon geometries in -i mode");
     468             :             }
     469           0 :             OGR_G_DestroyGeometry(ahGeometries[iGeom]);
     470           0 :             continue;
     471             :         }
     472             : 
     473             :         const auto ProcessPoly =
     474           0 :             [&hUniversePoly, poInvertMP](OGRPolygon *poPoly)
     475             :         {
     476           0 :             for (int i = poPoly->getNumInteriorRings() - 1; i >= 0; --i)
     477             :             {
     478           0 :                 auto poNewPoly = std::make_unique<OGRPolygon>();
     479             :                 std::unique_ptr<OGRLinearRing> poRing(
     480           0 :                     poPoly->stealInteriorRing(i));
     481           0 :                 poNewPoly->addRing(std::move(poRing));
     482           0 :                 poInvertMP->addGeometry(std::move(poNewPoly));
     483             :             }
     484           0 :             std::unique_ptr<OGRLinearRing> poShell(poPoly->stealExteriorRing());
     485           0 :             hUniversePoly.addRing(std::move(poShell));
     486           0 :         };
     487             : 
     488           0 :         if (eGType == wkbPolygon)
     489             :         {
     490             :             auto poPoly =
     491           0 :                 OGRGeometry::FromHandle(ahGeometries[iGeom])->toPolygon();
     492           0 :             ProcessPoly(poPoly);
     493           0 :             delete poPoly;
     494             :         }
     495             :         else
     496             :         {
     497             :             auto poMulti =
     498           0 :                 OGRGeometry::FromHandle(ahGeometries[iGeom])->toMultiPolygon();
     499           0 :             for (auto *poPoly : *poMulti)
     500             :             {
     501           0 :                 ProcessPoly(poPoly);
     502             :             }
     503           0 :             delete poMulti;
     504             :         }
     505             :     }
     506             : 
     507           0 :     ahGeometries.resize(1);
     508           0 :     ahGeometries[0] = OGRGeometry::ToHandle(poInvertMP);
     509             : }
     510             : 
     511             : /************************************************************************/
     512             : /*                            ProcessLayer()                            */
     513             : /*                                                                      */
     514             : /*      Process all the features in a layer selection, collecting       */
     515             : /*      geometries and burn values.                                     */
     516             : /************************************************************************/
     517             : 
     518          64 : static CPLErr ProcessLayer(OGRLayerH hSrcLayer, bool bSRSIsSet,
     519             :                            GDALDataset *poDstDS,
     520             :                            const std::vector<int> &anBandList,
     521             :                            const std::vector<double> &adfBurnValues, bool b3D,
     522             :                            bool bInverse, const std::string &osBurnAttribute,
     523             :                            CSLConstList papszRasterizeOptions,
     524             :                            CSLConstList papszTO, GDALProgressFunc pfnProgress,
     525             :                            void *pProgressData)
     526             : 
     527             : {
     528          64 :     GDALDatasetH hDstDS = GDALDataset::ToHandle(poDstDS);
     529             : 
     530             :     /* -------------------------------------------------------------------- */
     531             :     /*      Checkout that SRS are the same.                                 */
     532             :     /*      If -a_srs is specified, skip the test                           */
     533             :     /* -------------------------------------------------------------------- */
     534          64 :     OGRCoordinateTransformationH hCT = nullptr;
     535          64 :     if (!bSRSIsSet)
     536             :     {
     537          62 :         OGRSpatialReferenceH hDstSRS = GDALGetSpatialRef(hDstDS);
     538             : 
     539          62 :         if (hDstSRS)
     540          22 :             hDstSRS = OSRClone(hDstSRS);
     541          40 :         else if (GDALGetMetadata(hDstDS, "RPC") != nullptr)
     542             :         {
     543           2 :             hDstSRS = OSRNewSpatialReference(nullptr);
     544           2 :             CPL_IGNORE_RET_VAL(
     545           2 :                 OSRSetFromUserInput(hDstSRS, SRS_WKT_WGS84_LAT_LONG));
     546           2 :             OSRSetAxisMappingStrategy(hDstSRS, OAMS_TRADITIONAL_GIS_ORDER);
     547             :         }
     548             : 
     549          62 :         OGRSpatialReferenceH hSrcSRS = OGR_L_GetSpatialRef(hSrcLayer);
     550          62 :         if (hDstSRS != nullptr && hSrcSRS != nullptr)
     551             :         {
     552          23 :             if (OSRIsSame(hSrcSRS, hDstSRS) == FALSE)
     553             :             {
     554           1 :                 hCT = OCTNewCoordinateTransformation(hSrcSRS, hDstSRS);
     555           1 :                 if (hCT == nullptr)
     556             :                 {
     557           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
     558             :                              "The output raster dataset and the input vector "
     559             :                              "layer do not have the same SRS.\n"
     560             :                              "And reprojection of input data did not work. "
     561             :                              "Results might be incorrect.");
     562             :                 }
     563             :             }
     564             :         }
     565          39 :         else if (hDstSRS != nullptr && hSrcSRS == nullptr)
     566             :         {
     567           1 :             CPLError(CE_Warning, CPLE_AppDefined,
     568             :                      "The output raster dataset has a SRS, but the input "
     569             :                      "vector layer SRS is unknown.\n"
     570             :                      "Ensure input vector has the same SRS, otherwise results "
     571             :                      "might be incorrect.");
     572             :         }
     573          38 :         else if (hDstSRS == nullptr && hSrcSRS != nullptr)
     574             :         {
     575           2 :             CPLError(CE_Warning, CPLE_AppDefined,
     576             :                      "The input vector layer has a SRS, but the output raster "
     577             :                      "dataset SRS is unknown.\n"
     578             :                      "Ensure output raster dataset has the same SRS, otherwise "
     579             :                      "results might be incorrect.");
     580             :         }
     581             : 
     582          62 :         if (hDstSRS != nullptr)
     583             :         {
     584          24 :             OSRDestroySpatialReference(hDstSRS);
     585             :         }
     586             :     }
     587             : 
     588             :     /* -------------------------------------------------------------------- */
     589             :     /*      Get field index, and check.                                     */
     590             :     /* -------------------------------------------------------------------- */
     591          64 :     int iBurnField = -1;
     592          64 :     bool bUseInt64 = false;
     593          64 :     OGRFieldType eBurnAttributeType = OFTInteger;
     594          64 :     if (!osBurnAttribute.empty())
     595             :     {
     596           7 :         OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn(hSrcLayer);
     597           7 :         iBurnField = OGR_FD_GetFieldIndex(hLayerDefn, osBurnAttribute.c_str());
     598           7 :         if (iBurnField == -1)
     599             :         {
     600           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     601             :                      "Failed to find field %s on layer %s.",
     602             :                      osBurnAttribute.c_str(),
     603             :                      OGR_FD_GetName(OGR_L_GetLayerDefn(hSrcLayer)));
     604           1 :             if (hCT != nullptr)
     605           0 :                 OCTDestroyCoordinateTransformation(hCT);
     606           1 :             return CE_Failure;
     607             :         }
     608             : 
     609             :         eBurnAttributeType =
     610           6 :             OGR_Fld_GetType(OGR_FD_GetFieldDefn(hLayerDefn, iBurnField));
     611             : 
     612           6 :         if (eBurnAttributeType == OFTInteger64)
     613             :         {
     614           1 :             GDALRasterBandH hBand = GDALGetRasterBand(hDstDS, anBandList[0]);
     615           1 :             if (hBand && GDALGetRasterDataType(hBand) == GDT_Int64)
     616             :             {
     617           1 :                 bUseInt64 = true;
     618             :             }
     619             :         }
     620             :     }
     621             : 
     622             :     /* -------------------------------------------------------------------- */
     623             :     /*      Collect the geometries from this layer, and build list of       */
     624             :     /*      burn values.                                                    */
     625             :     /* -------------------------------------------------------------------- */
     626          63 :     OGRFeatureH hFeat = nullptr;
     627         126 :     std::vector<OGRGeometryH> ahGeometries;
     628         126 :     std::vector<double> adfFullBurnValues;
     629          63 :     std::vector<int64_t> anFullBurnValues;
     630             : 
     631          63 :     OGR_L_ResetReading(hSrcLayer);
     632             : 
     633        2138 :     while ((hFeat = OGR_L_GetNextFeature(hSrcLayer)) != nullptr)
     634             :     {
     635        2075 :         OGRGeometryH hGeom = OGR_F_StealGeometry(hFeat);
     636        2075 :         if (hGeom == nullptr)
     637             :         {
     638           5 :             OGR_F_Destroy(hFeat);
     639           5 :             continue;
     640             :         }
     641             : 
     642        2070 :         if (hCT != nullptr)
     643             :         {
     644           1 :             if (OGR_G_Transform(hGeom, hCT) != OGRERR_NONE)
     645             :             {
     646           0 :                 OGR_F_Destroy(hFeat);
     647           0 :                 OGR_G_DestroyGeometry(hGeom);
     648           0 :                 continue;
     649             :             }
     650             :         }
     651        2070 :         ahGeometries.push_back(hGeom);
     652             : 
     653        4296 :         for (unsigned int iBand = 0; iBand < anBandList.size(); iBand++)
     654             :         {
     655             :             GDALRasterBandH hBand =
     656        2226 :                 GDALGetRasterBand(hDstDS, anBandList[iBand]);
     657        2226 :             GDALDataType eDT = GDALGetRasterDataType(hBand);
     658             : 
     659        2226 :             if (!adfBurnValues.empty())
     660         327 :                 adfFullBurnValues.push_back(adfBurnValues[std::min(
     661             :                     iBand,
     662         654 :                     static_cast<unsigned int>(adfBurnValues.size()) - 1)]);
     663        1899 :             else if (!osBurnAttribute.empty())
     664             :             {
     665          36 :                 if (bUseInt64)
     666           1 :                     anFullBurnValues.push_back(
     667           1 :                         OGR_F_GetFieldAsInteger64(hFeat, iBurnField));
     668             :                 else
     669             :                 {
     670             :                     double dfBurnValue;
     671             : 
     672          35 :                     if (eBurnAttributeType == OFTInteger ||
     673             :                         eBurnAttributeType == OFTReal)
     674             :                     {
     675           0 :                         dfBurnValue = OGR_F_GetFieldAsDouble(hFeat, iBurnField);
     676             :                     }
     677             :                     else
     678             :                     {
     679             :                         const char *pszAttribute =
     680          35 :                             OGR_F_GetFieldAsString(hFeat, iBurnField);
     681             :                         char *end;
     682          35 :                         dfBurnValue = CPLStrtod(pszAttribute, &end);
     683             : 
     684          35 :                         while (isspace(*end) && *end != '\0')
     685             :                         {
     686           0 :                             end++;
     687             :                         }
     688             : 
     689          35 :                         if (*end != '\0')
     690             :                         {
     691          10 :                             CPLErrorOnce(
     692             :                                 CE_Warning, CPLE_AppDefined,
     693             :                                 "Failed to parse attribute value %s of feature "
     694             :                                 "%" PRId64 " as a number. A value of zero will "
     695             :                                 "be burned for this feature.",
     696             :                                 pszAttribute,
     697             :                                 static_cast<int64_t>(OGR_F_GetFID(hFeat)));
     698             :                         }
     699             :                     }
     700             : 
     701          35 :                     if (!GDALIsValueExactAs(dfBurnValue, eDT))
     702             :                     {
     703             :                         const char *pszAttribute =
     704          10 :                             OGR_F_GetFieldAsString(hFeat, iBurnField);
     705          10 :                         CPLErrorOnce(CE_Warning, CPLE_AppDefined,
     706             :                                      "Attribute value %s of feature %" PRId64
     707             :                                      " cannot be exactly burned to an output "
     708             :                                      "band of type %s.",
     709             :                                      pszAttribute,
     710             :                                      static_cast<int64_t>(OGR_F_GetFID(hFeat)),
     711             :                                      GDALGetDataTypeName(eDT));
     712             :                     }
     713             : 
     714          35 :                     adfFullBurnValues.push_back(dfBurnValue);
     715             :                 }
     716             :             }
     717        1863 :             else if (b3D)
     718             :             {
     719             :                 /* Points and Lines will have their "z" values collected at the
     720             :                    point and line levels respectively. Not implemented for
     721             :                    polygons */
     722        1863 :                 adfFullBurnValues.push_back(0.0);
     723             :             }
     724             :         }
     725             : 
     726        2070 :         OGR_F_Destroy(hFeat);
     727             :     }
     728             : 
     729          63 :     if (hCT != nullptr)
     730           1 :         OCTDestroyCoordinateTransformation(hCT);
     731             : 
     732             :     /* -------------------------------------------------------------------- */
     733             :     /*      If we are in inverse mode, we add one extra ring around the     */
     734             :     /*      whole dataset to invert the concept of insideness and then      */
     735             :     /*      merge everything into one geometry collection.                  */
     736             :     /* -------------------------------------------------------------------- */
     737          63 :     if (bInverse)
     738             :     {
     739           3 :         if (ahGeometries.empty())
     740             :         {
     741           0 :             for (unsigned int iBand = 0; iBand < anBandList.size(); iBand++)
     742             :             {
     743           0 :                 if (!adfBurnValues.empty())
     744           0 :                     adfFullBurnValues.push_back(adfBurnValues[std::min(
     745             :                         iBand,
     746           0 :                         static_cast<unsigned int>(adfBurnValues.size()) - 1)]);
     747             :                 else /* FIXME? Not sure what to do exactly in the else case, but
     748             :                         we must insert a value */
     749             :                 {
     750           0 :                     adfFullBurnValues.push_back(0.0);
     751           0 :                     anFullBurnValues.push_back(0);
     752             :                 }
     753             :             }
     754             :         }
     755             : 
     756           3 :         InvertGeometries(hDstDS, ahGeometries);
     757             :     }
     758             : 
     759             :     /* -------------------------------------------------------------------- */
     760             :     /*      If we have transformer options, create the transformer here     */
     761             :     /*      Coordinate transformation to the target SRS has already been    */
     762             :     /*      done, so we just need to convert to target raster space.        */
     763             :     /*      Note: this is somewhat identical to what is done in             */
     764             :     /*      GDALRasterizeGeometries() itself, except we can pass transformer*/
     765             :     /*      options.                                                        */
     766             :     /* -------------------------------------------------------------------- */
     767             : 
     768          63 :     void *pTransformArg = nullptr;
     769          63 :     GDALTransformerFunc pfnTransformer = nullptr;
     770          63 :     CPLErr eErr = CE_None;
     771          63 :     if (papszTO != nullptr)
     772             :     {
     773           1 :         GDALDataset *poDS = GDALDataset::FromHandle(hDstDS);
     774           2 :         CPLStringList aosTransformerOptions(CSLDuplicate(papszTO));
     775           1 :         GDALGeoTransform gt;
     776           2 :         if (poDS->GetGeoTransform(gt) != CE_None && poDS->GetGCPCount() == 0 &&
     777           1 :             poDS->GetMetadata("RPC") == nullptr)
     778             :         {
     779           0 :             aosTransformerOptions.SetNameValue("DST_METHOD", "NO_GEOTRANSFORM");
     780             :         }
     781             : 
     782           1 :         pTransformArg = GDALCreateGenImgProjTransformer2(
     783           1 :             nullptr, hDstDS, aosTransformerOptions.List());
     784             : 
     785           1 :         pfnTransformer = GDALGenImgProjTransform;
     786           1 :         if (pTransformArg == nullptr)
     787             :         {
     788           0 :             eErr = CE_Failure;
     789             :         }
     790             :     }
     791             : 
     792             :     /* -------------------------------------------------------------------- */
     793             :     /*      Perform the burn.                                               */
     794             :     /* -------------------------------------------------------------------- */
     795          63 :     if (eErr == CE_None)
     796             :     {
     797          63 :         if (bUseInt64)
     798             :         {
     799           2 :             eErr = GDALRasterizeGeometriesInt64(
     800           1 :                 hDstDS, static_cast<int>(anBandList.size()), anBandList.data(),
     801           1 :                 static_cast<int>(ahGeometries.size()), ahGeometries.data(),
     802           1 :                 pfnTransformer, pTransformArg, anFullBurnValues.data(),
     803             :                 papszRasterizeOptions, pfnProgress, pProgressData);
     804             :         }
     805             :         else
     806             :         {
     807         124 :             eErr = GDALRasterizeGeometries(
     808          62 :                 hDstDS, static_cast<int>(anBandList.size()), anBandList.data(),
     809          62 :                 static_cast<int>(ahGeometries.size()), ahGeometries.data(),
     810          62 :                 pfnTransformer, pTransformArg, adfFullBurnValues.data(),
     811             :                 papszRasterizeOptions, pfnProgress, pProgressData);
     812             :         }
     813             :     }
     814             : 
     815             :     /* -------------------------------------------------------------------- */
     816             :     /*      Cleanup                                                         */
     817             :     /* -------------------------------------------------------------------- */
     818             : 
     819          63 :     if (pTransformArg)
     820           1 :         GDALDestroyTransformer(pTransformArg);
     821             : 
     822        2129 :     for (int iGeom = static_cast<int>(ahGeometries.size()) - 1; iGeom >= 0;
     823             :          iGeom--)
     824        2066 :         OGR_G_DestroyGeometry(ahGeometries[iGeom]);
     825             : 
     826          63 :     return eErr;
     827             : }
     828             : 
     829             : /************************************************************************/
     830             : /*                        CreateOutputDataset()                         */
     831             : /************************************************************************/
     832             : 
     833          37 : static std::unique_ptr<GDALDataset> CreateOutputDataset(
     834             :     const std::vector<OGRLayerH> &ahLayers, OGRSpatialReferenceH hSRS,
     835             :     OGREnvelope sEnvelop, GDALDriverH hDriver, const char *pszDest, int nXSize,
     836             :     int nYSize, double dfXRes, double dfYRes, bool bTargetAlignedPixels,
     837             :     int nBandCount, GDALDataType eOutputType, CSLConstList papszCreationOptions,
     838             :     const std::vector<double> &adfInitVals, const char *pszNoData)
     839             : {
     840          37 :     bool bFirstLayer = true;
     841          37 :     const bool bBoundsSpecifiedByUser = CPL_TO_BOOL(sEnvelop.IsInit());
     842             : 
     843          73 :     for (unsigned int i = 0; i < ahLayers.size(); i++)
     844             :     {
     845          37 :         OGRLayerH hLayer = ahLayers[i];
     846             : 
     847          37 :         if (!bBoundsSpecifiedByUser)
     848             :         {
     849          34 :             OGREnvelope sLayerEnvelop;
     850             : 
     851          34 :             if (OGR_L_GetExtent(hLayer, &sLayerEnvelop, TRUE) != OGRERR_NONE)
     852             :             {
     853           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
     854             :                          "Cannot get layer extent");
     855           1 :                 return nullptr;
     856             :             }
     857             : 
     858             :             /* Voluntarily increase the extent by a half-pixel size to avoid */
     859             :             /* missing points on the border */
     860          33 :             if (!bTargetAlignedPixels && dfXRes != 0 && dfYRes != 0)
     861             :             {
     862           9 :                 sLayerEnvelop.MinX -= dfXRes / 2;
     863           9 :                 sLayerEnvelop.MaxX += dfXRes / 2;
     864           9 :                 sLayerEnvelop.MinY -= dfYRes / 2;
     865           9 :                 sLayerEnvelop.MaxY += dfYRes / 2;
     866             :             }
     867             : 
     868          33 :             sEnvelop.Merge(sLayerEnvelop);
     869             :         }
     870             : 
     871          36 :         if (bFirstLayer)
     872             :         {
     873          36 :             if (hSRS == nullptr)
     874          34 :                 hSRS = OGR_L_GetSpatialRef(hLayer);
     875             : 
     876          36 :             bFirstLayer = false;
     877             :         }
     878             :     }
     879             : 
     880          36 :     if (!sEnvelop.IsInit())
     881             :     {
     882           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Could not determine bounds");
     883           0 :         return nullptr;
     884             :     }
     885             : 
     886          36 :     if (dfXRes == 0 && dfYRes == 0)
     887             :     {
     888          23 :         if (nXSize == 0 || nYSize == 0)
     889             :         {
     890           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     891             :                      "Size and resolution are missing");
     892           1 :             return nullptr;
     893             :         }
     894          22 :         dfXRes = (sEnvelop.MaxX - sEnvelop.MinX) / nXSize;
     895          22 :         dfYRes = (sEnvelop.MaxY - sEnvelop.MinY) / nYSize;
     896             :     }
     897          13 :     else if (bTargetAlignedPixels && dfXRes != 0 && dfYRes != 0)
     898             :     {
     899           1 :         sEnvelop.MinX = floor(sEnvelop.MinX / dfXRes) * dfXRes;
     900           1 :         sEnvelop.MaxX = ceil(sEnvelop.MaxX / dfXRes) * dfXRes;
     901           1 :         sEnvelop.MinY = floor(sEnvelop.MinY / dfYRes) * dfYRes;
     902           1 :         sEnvelop.MaxY = ceil(sEnvelop.MaxY / dfYRes) * dfYRes;
     903             :     }
     904             : 
     905          35 :     if (dfXRes == 0 || dfYRes == 0)
     906             :     {
     907           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Could not determine bounds");
     908           0 :         return nullptr;
     909             :     }
     910             : 
     911          35 :     if (nXSize == 0 && nYSize == 0)
     912             :     {
     913             :         // coverity[divide_by_zero]
     914          13 :         const double dfXSize = 0.5 + (sEnvelop.MaxX - sEnvelop.MinX) / dfXRes;
     915             :         // coverity[divide_by_zero]
     916          13 :         const double dfYSize = 0.5 + (sEnvelop.MaxY - sEnvelop.MinY) / dfYRes;
     917          13 :         if (dfXSize > std::numeric_limits<int>::max() ||
     918          12 :             dfXSize < std::numeric_limits<int>::min() ||
     919          36 :             dfYSize > std::numeric_limits<int>::max() ||
     920          11 :             dfYSize < std::numeric_limits<int>::min())
     921             :         {
     922           2 :             CPLError(CE_Failure, CPLE_AppDefined,
     923             :                      "Invalid computed output raster size: %f x %f", dfXSize,
     924             :                      dfYSize);
     925           2 :             return nullptr;
     926             :         }
     927          11 :         nXSize = static_cast<int>(dfXSize);
     928          11 :         nYSize = static_cast<int>(dfYSize);
     929             :     }
     930             : 
     931             :     auto poDstDS =
     932             :         std::unique_ptr<GDALDataset>(GDALDriver::FromHandle(hDriver)->Create(
     933             :             pszDest, nXSize, nYSize, nBandCount, eOutputType,
     934          66 :             papszCreationOptions));
     935          33 :     if (poDstDS == nullptr)
     936             :     {
     937           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot create %s", pszDest);
     938           0 :         return nullptr;
     939             :     }
     940             : 
     941             :     GDALGeoTransform gt = {sEnvelop.MinX, dfXRes, 0.0,
     942          33 :                            sEnvelop.MaxY, 0.0,    -dfYRes};
     943          33 :     poDstDS->SetGeoTransform(gt);
     944             : 
     945          33 :     if (hSRS)
     946          14 :         poDstDS->SetSpatialRef(OGRSpatialReference::FromHandle(hSRS));
     947             : 
     948          33 :     if (pszNoData)
     949             :     {
     950          92 :         for (int iBand = 0; iBand < nBandCount; iBand++)
     951             :         {
     952          59 :             auto poBand = poDstDS->GetRasterBand(iBand + 1);
     953          59 :             if (poBand->GetRasterDataType() == GDT_Int64)
     954           1 :                 poBand->SetNoDataValueAsInt64(CPLAtoGIntBig(pszNoData));
     955             :             else
     956          58 :                 poBand->SetNoDataValue(CPLAtof(pszNoData));
     957             :         }
     958             :     }
     959             : 
     960          33 :     if (!adfInitVals.empty())
     961             :     {
     962          30 :         for (int iBand = 0;
     963          30 :              iBand < std::min(nBandCount, static_cast<int>(adfInitVals.size()));
     964             :              iBand++)
     965             :         {
     966          21 :             auto poBand = poDstDS->GetRasterBand(iBand + 1);
     967          21 :             poBand->Fill(adfInitVals[iBand]);
     968             :         }
     969             :     }
     970             : 
     971          33 :     return poDstDS;
     972             : }
     973             : 
     974             : /************************************************************************/
     975             : /*                           GDALRasterize()                            */
     976             : /************************************************************************/
     977             : 
     978             : /* clang-format off */
     979             : /**
     980             :  * Burns vector geometries into a raster
     981             :  *
     982             :  * This is the equivalent of the
     983             :  * <a href="/programs/gdal_rasterize.html">gdal_rasterize</a> utility.
     984             :  *
     985             :  * GDALRasterizeOptions* must be allocated and freed with
     986             :  * GDALRasterizeOptionsNew() and GDALRasterizeOptionsFree() respectively.
     987             :  * pszDest and hDstDS cannot be used at the same time.
     988             :  *
     989             :  * @param pszDest the destination dataset path or NULL.
     990             :  * @param hDstDS the destination dataset or NULL.
     991             :  * @param hSrcDataset the source dataset handle.
     992             :  * @param psOptionsIn the options struct returned by GDALRasterizeOptionsNew()
     993             :  * or NULL.
     994             :  * @param pbUsageError pointer to an integer output variable to store if any
     995             :  * usage error has occurred or NULL.
     996             :  * @return the output dataset (new dataset that must be closed using
     997             :  * GDALClose(), or hDstDS is not NULL) or NULL in case of error.
     998             :  *
     999             :  * @since GDAL 2.1
    1000             :  */
    1001             : /* clang-format on */
    1002             : 
    1003          73 : GDALDatasetH GDALRasterize(const char *pszDest, GDALDatasetH hDstDS,
    1004             :                            GDALDatasetH hSrcDataset,
    1005             :                            const GDALRasterizeOptions *psOptionsIn,
    1006             :                            int *pbUsageError)
    1007             : {
    1008          73 :     GDALDataset *poOutDS = GDALDataset::FromHandle(hDstDS);
    1009             : #define hDstDS no_longer_use_hDstDS
    1010          73 :     if (pszDest == nullptr && poOutDS == nullptr)
    1011             :     {
    1012           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1013             :                  "pszDest == NULL && hDstDS == NULL");
    1014             : 
    1015           0 :         if (pbUsageError)
    1016           0 :             *pbUsageError = TRUE;
    1017           0 :         return nullptr;
    1018             :     }
    1019          73 :     if (hSrcDataset == nullptr)
    1020             :     {
    1021           0 :         CPLError(CE_Failure, CPLE_AppDefined, "hSrcDataset== NULL");
    1022             : 
    1023           0 :         if (pbUsageError)
    1024           0 :             *pbUsageError = TRUE;
    1025           0 :         return nullptr;
    1026             :     }
    1027          73 :     if (poOutDS != nullptr && psOptionsIn && psOptionsIn->bCreateOutput)
    1028             :     {
    1029           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1030             :                  "hDstDS != NULL but options that imply creating a new dataset "
    1031             :                  "have been set.");
    1032             : 
    1033           0 :         if (pbUsageError)
    1034           0 :             *pbUsageError = TRUE;
    1035           0 :         return nullptr;
    1036             :     }
    1037             : 
    1038             :     std::unique_ptr<GDALRasterizeOptions, decltype(&GDALRasterizeOptionsFree)>
    1039         146 :         psOptionsToFree(nullptr, GDALRasterizeOptionsFree);
    1040         146 :     GDALRasterizeOptions sOptions;
    1041          73 :     if (psOptionsIn)
    1042          73 :         sOptions = *psOptionsIn;
    1043             : 
    1044          73 :     std::unique_ptr<GDALDataset> poNewOutDS;
    1045          73 :     if (pszDest == nullptr)
    1046          15 :         pszDest = poOutDS->GetDescription();
    1047             : 
    1048         108 :     if (sOptions.osSQL.empty() && sOptions.aosLayers.empty() &&
    1049          35 :         GDALDatasetGetLayerCount(hSrcDataset) != 1)
    1050             :     {
    1051           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1052             :                  "Neither -sql nor -l are specified, but the source dataset "
    1053             :                  "has not one single layer.");
    1054           0 :         if (pbUsageError)
    1055           0 :             *pbUsageError = TRUE;
    1056           0 :         return nullptr;
    1057             :     }
    1058             : 
    1059             :     /* -------------------------------------------------------------------- */
    1060             :     /*      Open target raster file.  Eventually we will add optional       */
    1061             :     /*      creation.                                                       */
    1062             :     /* -------------------------------------------------------------------- */
    1063          73 :     const bool bCreateOutput = sOptions.bCreateOutput || poOutDS == nullptr;
    1064             : 
    1065          73 :     GDALDriverH hDriver = nullptr;
    1066          73 :     if (bCreateOutput)
    1067             :     {
    1068          42 :         CPLString osFormat;
    1069          42 :         if (sOptions.osFormat.empty())
    1070             :         {
    1071          28 :             osFormat = GetOutputDriverForRaster(pszDest);
    1072          28 :             if (osFormat.empty())
    1073             :             {
    1074           0 :                 return nullptr;
    1075             :             }
    1076             :         }
    1077             :         else
    1078             :         {
    1079          14 :             osFormat = sOptions.osFormat;
    1080             :         }
    1081             : 
    1082             :         /* ------------------------------------------------------------------ */
    1083             :         /*      Find the output driver. */
    1084             :         /* ------------------------------------------------------------------ */
    1085          42 :         hDriver = GDALGetDriverByName(osFormat);
    1086             :         CSLConstList papszDriverMD =
    1087          42 :             hDriver ? GDALGetMetadata(hDriver, nullptr) : nullptr;
    1088          42 :         if (hDriver == nullptr)
    1089             :         {
    1090           1 :             CPLError(CE_Failure, CPLE_NotSupported,
    1091             :                      "Output driver `%s' not recognised.", osFormat.c_str());
    1092           1 :             return nullptr;
    1093             :         }
    1094          41 :         if (!CPLTestBool(
    1095             :                 CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE")))
    1096             :         {
    1097           1 :             CPLError(CE_Failure, CPLE_NotSupported,
    1098             :                      "Output driver `%s' is not a raster driver.",
    1099             :                      osFormat.c_str());
    1100           1 :             return nullptr;
    1101             :         }
    1102          40 :         if (!CPLTestBool(
    1103             :                 CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE")))
    1104             :         {
    1105           1 :             CPLError(CE_Failure, CPLE_NotSupported,
    1106             :                      "Output driver `%s' does not support direct output file "
    1107             :                      "creation. "
    1108             :                      "To write a file to this format, first write to a "
    1109             :                      "different format such as "
    1110             :                      "GeoTIFF and then convert the output.",
    1111             :                      osFormat.c_str());
    1112           1 :             return nullptr;
    1113             :         }
    1114             :     }
    1115             : 
    1116           4 :     auto calculateSize = [&](const OGREnvelope &sEnvelope) -> bool
    1117             :     {
    1118           4 :         const double width{sEnvelope.MaxX - sEnvelope.MinX};
    1119           4 :         if (std::isnan(width))
    1120             :         {
    1121           0 :             return false;
    1122             :         }
    1123             : 
    1124           4 :         const double height{sEnvelope.MaxY - sEnvelope.MinY};
    1125           4 :         if (std::isnan(height))
    1126             :         {
    1127           0 :             return false;
    1128             :         }
    1129             : 
    1130           4 :         if (height == 0 || width == 0)
    1131             :         {
    1132           0 :             return false;
    1133             :         }
    1134             : 
    1135           4 :         if (sOptions.nXSize == 0)
    1136             :         {
    1137           2 :             const double xSize{
    1138           2 :                 (sEnvelope.MaxX - sEnvelope.MinX) /
    1139           2 :                 ((sEnvelope.MaxY - sEnvelope.MinY) / sOptions.nYSize)};
    1140           4 :             if (std::isnan(xSize) || xSize > std::numeric_limits<int>::max() ||
    1141           2 :                 xSize < std::numeric_limits<int>::min())
    1142             :             {
    1143           0 :                 return false;
    1144             :             }
    1145           2 :             sOptions.nXSize = static_cast<int>(xSize);
    1146             :         }
    1147             :         else
    1148             :         {
    1149           2 :             const double ySize{
    1150           2 :                 (sEnvelope.MaxY - sEnvelope.MinY) /
    1151           2 :                 ((sEnvelope.MaxX - sEnvelope.MinX) / sOptions.nXSize)};
    1152           4 :             if (std::isnan(ySize) || ySize > std::numeric_limits<int>::max() ||
    1153           2 :                 ySize < std::numeric_limits<int>::min())
    1154             :             {
    1155           0 :                 return false;
    1156             :             }
    1157           2 :             sOptions.nYSize = static_cast<int>(ySize);
    1158             :         }
    1159           4 :         return sOptions.nXSize > 0 && sOptions.nYSize > 0;
    1160          70 :     };
    1161             : 
    1162             :     const int nLayerCount =
    1163         131 :         (sOptions.osSQL.empty() && sOptions.aosLayers.empty())
    1164         140 :             ? 1
    1165          38 :             : static_cast<int>(sOptions.aosLayers.size());
    1166             : 
    1167          70 :     const bool bOneSizeNeedsCalculation{
    1168          70 :         static_cast<bool>((sOptions.nXSize == 0) ^ (sOptions.nYSize == 0))};
    1169             : 
    1170             :     // Calculate the size if either nXSize or nYSize is 0
    1171          70 :     if (sOptions.osSQL.empty() && bOneSizeNeedsCalculation)
    1172             :     {
    1173           2 :         CPLErr eErr = CE_None;
    1174             :         // Get the extent of the source dataset
    1175           2 :         OGREnvelope sEnvelope;
    1176           2 :         bool bFirstLayer = true;
    1177           4 :         for (int i = 0; i < nLayerCount; i++)
    1178             :         {
    1179             :             OGRLayerH hLayer;
    1180           2 :             if (sOptions.aosLayers.size() > static_cast<size_t>(i))
    1181           2 :                 hLayer = GDALDatasetGetLayerByName(
    1182           2 :                     hSrcDataset, sOptions.aosLayers[i].c_str());
    1183             :             else
    1184           0 :                 hLayer = GDALDatasetGetLayer(hSrcDataset, 0);
    1185           2 :             if (hLayer == nullptr)
    1186             :             {
    1187           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1188             :                          "Unable to find layer \"%s\".",
    1189           0 :                          sOptions.aosLayers.size() > static_cast<size_t>(i)
    1190           0 :                              ? sOptions.aosLayers[i].c_str()
    1191             :                              : "0");
    1192           0 :                 eErr = CE_Failure;
    1193           0 :                 break;
    1194             :             }
    1195           2 :             OGREnvelope sLayerEnvelop;
    1196           2 :             if (OGR_L_GetExtent(hLayer, &sLayerEnvelop, TRUE) != OGRERR_NONE)
    1197             :             {
    1198           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1199             :                          "Cannot get layer extent");
    1200           0 :                 eErr = CE_Failure;
    1201           0 :                 break;
    1202             :             }
    1203           2 :             if (bFirstLayer)
    1204             :             {
    1205           2 :                 sEnvelope = sLayerEnvelop;
    1206           2 :                 bFirstLayer = false;
    1207             :             }
    1208             :             else
    1209             :             {
    1210           0 :                 sEnvelope.Merge(sLayerEnvelop);
    1211             :             }
    1212             :         }
    1213             : 
    1214           2 :         if (!calculateSize(sEnvelope))
    1215             :         {
    1216           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1217             :                      "Cannot calculate size from layer extent");
    1218           0 :             eErr = CE_Failure;
    1219             :         }
    1220             : 
    1221           2 :         if (eErr == CE_Failure)
    1222             :         {
    1223           0 :             return nullptr;
    1224             :         }
    1225             :     }
    1226             : 
    1227          34 :     const auto GetOutputDataType = [&](OGRLayerH hLayer)
    1228             :     {
    1229          34 :         CPLAssert(bCreateOutput);
    1230          34 :         CPLAssert(hDriver);
    1231          70 :         GDALDataType eOutputType = sOptions.eOutputType;
    1232          34 :         if (eOutputType == GDT_Unknown && !sOptions.osBurnAttribute.empty())
    1233             :         {
    1234           2 :             OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn(hLayer);
    1235           2 :             const int iBurnField = OGR_FD_GetFieldIndex(
    1236             :                 hLayerDefn, sOptions.osBurnAttribute.c_str());
    1237           2 :             if (iBurnField >= 0 && OGR_Fld_GetType(OGR_FD_GetFieldDefn(
    1238             :                                        hLayerDefn, iBurnField)) == OFTInteger64)
    1239             :             {
    1240           1 :                 const char *pszMD = GDALGetMetadataItem(
    1241             :                     hDriver, GDAL_DMD_CREATIONDATATYPES, nullptr);
    1242           2 :                 if (pszMD && CPLStringList(CSLTokenizeString2(pszMD, " ", 0))
    1243           1 :                                      .FindString("Int64") >= 0)
    1244             :                 {
    1245           1 :                     eOutputType = GDT_Int64;
    1246             :                 }
    1247             :             }
    1248             :         }
    1249          34 :         if (eOutputType == GDT_Unknown)
    1250             :         {
    1251          33 :             eOutputType = GDT_Float64;
    1252             :         }
    1253          34 :         return eOutputType;
    1254          70 :     };
    1255             : 
    1256             :     // Store SRS handle
    1257             :     OGRSpatialReferenceH hSRS =
    1258          70 :         sOptions.oOutputSRS.IsEmpty()
    1259          70 :             ? nullptr
    1260           2 :             : OGRSpatialReference::ToHandle(
    1261          70 :                   const_cast<OGRSpatialReference *>(&sOptions.oOutputSRS));
    1262             : 
    1263             :     /* -------------------------------------------------------------------- */
    1264             :     /*      Process SQL request.                                            */
    1265             :     /* -------------------------------------------------------------------- */
    1266          70 :     CPLErr eErr = CE_Failure;
    1267             : 
    1268          70 :     if (!sOptions.osSQL.empty())
    1269             :     {
    1270             :         OGRLayerH hLayer =
    1271           9 :             GDALDatasetExecuteSQL(hSrcDataset, sOptions.osSQL.c_str(), nullptr,
    1272           9 :                                   sOptions.osDialect.c_str());
    1273           9 :         if (hLayer != nullptr)
    1274             :         {
    1275             : 
    1276           9 :             if (bOneSizeNeedsCalculation)
    1277             :             {
    1278           3 :                 OGREnvelope sEnvelope;
    1279             :                 bool bSizeCalculationError{
    1280           3 :                     OGR_L_GetExtent(hLayer, &sEnvelope, TRUE) != OGRERR_NONE};
    1281           3 :                 if (!bSizeCalculationError)
    1282             :                 {
    1283           2 :                     bSizeCalculationError = !calculateSize(sEnvelope);
    1284             :                 }
    1285             : 
    1286           3 :                 if (bSizeCalculationError)
    1287             :                 {
    1288           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1289             :                              "Cannot get layer extent");
    1290           1 :                     GDALDatasetReleaseResultSet(hSrcDataset, hLayer);
    1291           1 :                     return nullptr;
    1292             :                 }
    1293             :             }
    1294             : 
    1295           8 :             if (bCreateOutput)
    1296             :             {
    1297           4 :                 std::vector<OGRLayerH> ahLayers;
    1298           4 :                 ahLayers.push_back(hLayer);
    1299             : 
    1300           4 :                 const GDALDataType eOutputType = GetOutputDataType(hLayer);
    1301          12 :                 poNewOutDS = CreateOutputDataset(
    1302             :                     ahLayers, hSRS, sOptions.sEnvelop, hDriver, pszDest,
    1303             :                     sOptions.nXSize, sOptions.nYSize, sOptions.dfXRes,
    1304           4 :                     sOptions.dfYRes, sOptions.bTargetAlignedPixels,
    1305           4 :                     static_cast<int>(sOptions.anBandList.size()), eOutputType,
    1306             :                     sOptions.aosCreationOptions, sOptions.adfInitVals,
    1307           8 :                     sOptions.osNoData.c_str());
    1308           4 :                 if (poNewOutDS == nullptr)
    1309             :                 {
    1310           0 :                     GDALDatasetReleaseResultSet(hSrcDataset, hLayer);
    1311           0 :                     return nullptr;
    1312             :                 }
    1313           4 :                 poOutDS = poNewOutDS.get();
    1314             :             }
    1315             : 
    1316             :             const bool bCloseReportsProgress =
    1317           8 :                 bCreateOutput && poOutDS->GetCloseReportsProgress();
    1318             : 
    1319             :             std::unique_ptr<void, decltype(&GDALDestroyScaledProgress)>
    1320             :                 pScaledProgressArg(GDALCreateScaledProgress(
    1321             :                                        0.0, bCloseReportsProgress ? 0.5 : 1.0,
    1322             :                                        sOptions.pfnProgress,
    1323             :                                        sOptions.pProgressData),
    1324          16 :                                    GDALDestroyScaledProgress);
    1325             : 
    1326          24 :             eErr = ProcessLayer(
    1327             :                 hLayer, hSRS != nullptr, poOutDS, sOptions.anBandList,
    1328           8 :                 sOptions.adfBurnValues, sOptions.b3D, sOptions.bInverse,
    1329             :                 sOptions.osBurnAttribute.c_str(), sOptions.aosRasterizeOptions,
    1330           8 :                 sOptions.aosTO, GDALScaledProgress, pScaledProgressArg.get());
    1331             : 
    1332           8 :             GDALDatasetReleaseResultSet(hSrcDataset, hLayer);
    1333             :         }
    1334             :     }
    1335             : 
    1336             :     /* -------------------------------------------------------------------- */
    1337             :     /*      Create output file if necessary.                                */
    1338             :     /* -------------------------------------------------------------------- */
    1339             : 
    1340          69 :     if (bCreateOutput && poOutDS == nullptr)
    1341             :     {
    1342          34 :         std::vector<OGRLayerH> ahLayers;
    1343             : 
    1344          34 :         GDALDataType eOutputType = sOptions.eOutputType;
    1345             : 
    1346          67 :         for (int i = 0; i < nLayerCount; i++)
    1347             :         {
    1348             :             OGRLayerH hLayer;
    1349          34 :             if (sOptions.aosLayers.size() > static_cast<size_t>(i))
    1350          15 :                 hLayer = GDALDatasetGetLayerByName(
    1351          15 :                     hSrcDataset, sOptions.aosLayers[i].c_str());
    1352             :             else
    1353          19 :                 hLayer = GDALDatasetGetLayer(hSrcDataset, 0);
    1354          34 :             if (hLayer == nullptr)
    1355             :             {
    1356           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1357             :                          "Unable to find layer \"%s\".",
    1358           1 :                          sOptions.aosLayers.size() > static_cast<size_t>(i)
    1359           1 :                              ? sOptions.aosLayers[i].c_str()
    1360             :                              : "0");
    1361           1 :                 return nullptr;
    1362             :             }
    1363          33 :             if (eOutputType == GDT_Unknown)
    1364             :             {
    1365          30 :                 if (GetOutputDataType(hLayer) == GDT_Int64)
    1366           1 :                     eOutputType = GDT_Int64;
    1367             :             }
    1368             : 
    1369          33 :             ahLayers.push_back(hLayer);
    1370             :         }
    1371             : 
    1372          33 :         if (eOutputType == GDT_Unknown)
    1373             :         {
    1374          29 :             eOutputType = GDT_Float64;
    1375             :         }
    1376             : 
    1377          99 :         poNewOutDS = CreateOutputDataset(
    1378             :             ahLayers, hSRS, sOptions.sEnvelop, hDriver, pszDest,
    1379             :             sOptions.nXSize, sOptions.nYSize, sOptions.dfXRes, sOptions.dfYRes,
    1380          33 :             sOptions.bTargetAlignedPixels,
    1381          33 :             static_cast<int>(sOptions.anBandList.size()), eOutputType,
    1382             :             sOptions.aosCreationOptions, sOptions.adfInitVals,
    1383          66 :             sOptions.osNoData.c_str());
    1384          33 :         if (poNewOutDS == nullptr)
    1385             :         {
    1386           4 :             return nullptr;
    1387             :         }
    1388          29 :         poOutDS = poNewOutDS.get();
    1389             :     }
    1390             : 
    1391             :     const bool bCloseReportsProgress =
    1392          64 :         bCreateOutput && poOutDS->GetCloseReportsProgress();
    1393             : 
    1394             :     /* -------------------------------------------------------------------- */
    1395             :     /*      Process each layer.                                             */
    1396             :     /* -------------------------------------------------------------------- */
    1397             : 
    1398         119 :     for (int i = 0; i < nLayerCount; i++)
    1399             :     {
    1400             :         OGRLayerH hLayer;
    1401          56 :         if (sOptions.aosLayers.size() > static_cast<size_t>(i))
    1402          28 :             hLayer = GDALDatasetGetLayerByName(hSrcDataset,
    1403          28 :                                                sOptions.aosLayers[i].c_str());
    1404             :         else
    1405          28 :             hLayer = GDALDatasetGetLayer(hSrcDataset, 0);
    1406          56 :         if (hLayer == nullptr)
    1407             :         {
    1408           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1409             :                      "Unable to find layer \"%s\".",
    1410           0 :                      sOptions.aosLayers.size() > static_cast<size_t>(i)
    1411           0 :                          ? sOptions.aosLayers[i].c_str()
    1412             :                          : "0");
    1413           0 :             eErr = CE_Failure;
    1414           1 :             break;
    1415             :         }
    1416             : 
    1417          56 :         if (!sOptions.osWHERE.empty())
    1418             :         {
    1419           1 :             if (OGR_L_SetAttributeFilter(hLayer, sOptions.osWHERE.c_str()) !=
    1420             :                 OGRERR_NONE)
    1421             :             {
    1422           0 :                 eErr = CE_Failure;
    1423           0 :                 break;
    1424             :             }
    1425             :         }
    1426             : 
    1427          56 :         const double dfFactor = bCloseReportsProgress ? 0.5 : 1.0;
    1428             : 
    1429             :         std::unique_ptr<void, decltype(&GDALDestroyScaledProgress)>
    1430             :             pScaledProgressArg(
    1431          56 :                 GDALCreateScaledProgress(dfFactor * i / nLayerCount,
    1432          56 :                                          dfFactor * (i + 1) / nLayerCount,
    1433             :                                          sOptions.pfnProgress,
    1434             :                                          sOptions.pProgressData),
    1435          56 :                 GDALDestroyScaledProgress);
    1436             : 
    1437         168 :         eErr = ProcessLayer(hLayer, !sOptions.oOutputSRS.IsEmpty(), poOutDS,
    1438             :                             sOptions.anBandList, sOptions.adfBurnValues,
    1439          56 :                             sOptions.b3D, sOptions.bInverse,
    1440             :                             sOptions.osBurnAttribute.c_str(),
    1441             :                             sOptions.aosRasterizeOptions, sOptions.aosTO,
    1442          56 :                             GDALScaledProgress, pScaledProgressArg.get());
    1443          56 :         if (eErr != CE_None)
    1444           1 :             break;
    1445             :     }
    1446             : 
    1447          64 :     if (eErr != CE_None)
    1448             :     {
    1449           1 :         return nullptr;
    1450             :     }
    1451             : 
    1452          63 :     if (bCloseReportsProgress)
    1453             :     {
    1454             :         std::unique_ptr<void, decltype(&GDALDestroyScaledProgress)>
    1455             :             pScaledProgressArg(GDALCreateScaledProgress(0.5, 1.0,
    1456             :                                                         sOptions.pfnProgress,
    1457             :                                                         sOptions.pProgressData),
    1458           1 :                                GDALDestroyScaledProgress);
    1459             : 
    1460             :         const bool bCanReopenWithCurrentDescription =
    1461           1 :             poOutDS->CanReopenWithCurrentDescription();
    1462             : 
    1463           1 :         eErr = poOutDS->Close(GDALScaledProgress, pScaledProgressArg.get());
    1464           1 :         poOutDS = nullptr;
    1465           1 :         if (eErr != CE_None)
    1466           0 :             return nullptr;
    1467             : 
    1468           1 :         if (bCanReopenWithCurrentDescription)
    1469             :         {
    1470             :             {
    1471           2 :                 CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
    1472           1 :                 poNewOutDS.reset(
    1473             :                     GDALDataset::Open(pszDest, GDAL_OF_RASTER | GDAL_OF_UPDATE,
    1474             :                                       nullptr, nullptr, nullptr));
    1475             :             }
    1476           1 :             if (!poNewOutDS)
    1477             :             {
    1478           1 :                 poNewOutDS.reset(GDALDataset::Open(
    1479             :                     pszDest, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR, nullptr,
    1480             :                     nullptr, nullptr));
    1481             :             }
    1482             :         }
    1483             :         else
    1484             :         {
    1485             :             struct DummyDataset final : public GDALDataset
    1486             :             {
    1487           0 :                 DummyDataset() = default;
    1488             :             };
    1489             : 
    1490           0 :             poNewOutDS = std::make_unique<DummyDataset>();
    1491             :         }
    1492             :     }
    1493             : 
    1494          63 :     return poNewOutDS ? poNewOutDS.release() : poOutDS;
    1495             : }
    1496             : 
    1497             : /************************************************************************/
    1498             : /*                       ArgIsNumericRasterize()                        */
    1499             : /************************************************************************/
    1500             : 
    1501         411 : static bool ArgIsNumericRasterize(const char *pszArg)
    1502             : 
    1503             : {
    1504         411 :     char *pszEnd = nullptr;
    1505         411 :     CPLStrtod(pszArg, &pszEnd);
    1506         411 :     return pszEnd != nullptr && pszEnd[0] == '\0';
    1507             : }
    1508             : 
    1509             : /************************************************************************/
    1510             : /*                      GDALRasterizeOptionsNew()                       */
    1511             : /************************************************************************/
    1512             : 
    1513             : /**
    1514             :  * Allocates a GDALRasterizeOptions struct.
    1515             :  *
    1516             :  * @param papszArgv NULL terminated list of options (potentially including
    1517             :  * filename and open options too), or NULL. The accepted options are the ones of
    1518             :  * the <a href="/programs/gdal_rasterize.html">gdal_rasterize</a> utility.
    1519             :  * @param psOptionsForBinary (output) may be NULL (and should generally be
    1520             :  * NULL), otherwise (gdal_translate_bin.cpp use case) must be allocated with
    1521             :  *                           GDALRasterizeOptionsForBinaryNew() prior to this
    1522             :  * function. Will be filled with potentially present filename, open options,...
    1523             :  * @return pointer to the allocated GDALRasterizeOptions struct. Must be freed
    1524             :  * with GDALRasterizeOptionsFree().
    1525             :  *
    1526             :  * @since GDAL 2.1
    1527             :  */
    1528             : 
    1529             : GDALRasterizeOptions *
    1530          76 : GDALRasterizeOptionsNew(char **papszArgv,
    1531             :                         GDALRasterizeOptionsForBinary *psOptionsForBinary)
    1532             : {
    1533             : 
    1534         152 :     auto psOptions = std::make_unique<GDALRasterizeOptions>();
    1535             : 
    1536             :     /*-------------------------------------------------------------------- */
    1537             :     /*      Parse arguments.                                               */
    1538             :     /*-------------------------------------------------------------------- */
    1539             : 
    1540         152 :     CPLStringList aosArgv;
    1541             : 
    1542             :     /* -------------------------------------------------------------------- */
    1543             :     /*      Pre-processing for custom syntax that ArgumentParser does not   */
    1544             :     /*      support.                                                        */
    1545             :     /* -------------------------------------------------------------------- */
    1546          76 :     const int argc = CSLCount(papszArgv);
    1547         741 :     for (int i = 0; i < argc && papszArgv != nullptr && papszArgv[i] != nullptr;
    1548             :          i++)
    1549             :     {
    1550             :         // argparser will be confused if the value of a string argument
    1551             :         // starts with a negative sign.
    1552         665 :         if (EQUAL(papszArgv[i], "-a_nodata") && papszArgv[i + 1])
    1553             :         {
    1554           5 :             ++i;
    1555           5 :             psOptions->osNoData = papszArgv[i];
    1556           5 :             psOptions->bCreateOutput = true;
    1557             :         }
    1558             : 
    1559             :         // argparser is confused by arguments that have at_least_one
    1560             :         // cardinality, if they immediately precede positional arguments.
    1561         660 :         else if (EQUAL(papszArgv[i], "-burn") && papszArgv[i + 1])
    1562             :         {
    1563         117 :             if (strchr(papszArgv[i + 1], ' '))
    1564             :             {
    1565             :                 const CPLStringList aosTokens(
    1566           0 :                     CSLTokenizeString(papszArgv[i + 1]));
    1567           0 :                 for (const char *pszToken : aosTokens)
    1568             :                 {
    1569           0 :                     psOptions->adfBurnValues.push_back(CPLAtof(pszToken));
    1570             :                 }
    1571           0 :                 i += 1;
    1572             :             }
    1573             :             else
    1574             :             {
    1575         234 :                 while (i < argc - 1 && ArgIsNumericRasterize(papszArgv[i + 1]))
    1576             :                 {
    1577         117 :                     psOptions->adfBurnValues.push_back(
    1578         117 :                         CPLAtof(papszArgv[i + 1]));
    1579         117 :                     i += 1;
    1580             :                 }
    1581             :             }
    1582             : 
    1583             :             // Dummy value to make argparse happy, as at least one of
    1584             :             // -burn, -a or -3d is required
    1585         117 :             aosArgv.AddString("-burn");
    1586         117 :             aosArgv.AddString("0");
    1587             :         }
    1588         543 :         else if (EQUAL(papszArgv[i], "-init") && papszArgv[i + 1])
    1589             :         {
    1590          27 :             if (strchr(papszArgv[i + 1], ' '))
    1591             :             {
    1592             :                 const CPLStringList aosTokens(
    1593           0 :                     CSLTokenizeString(papszArgv[i + 1]));
    1594           0 :                 for (const char *pszToken : aosTokens)
    1595             :                 {
    1596           0 :                     psOptions->adfInitVals.push_back(CPLAtof(pszToken));
    1597             :                 }
    1598           0 :                 i += 1;
    1599             :             }
    1600             :             else
    1601             :             {
    1602          54 :                 while (i < argc - 1 && ArgIsNumericRasterize(papszArgv[i + 1]))
    1603             :                 {
    1604          27 :                     psOptions->adfInitVals.push_back(CPLAtof(papszArgv[i + 1]));
    1605          27 :                     i += 1;
    1606             :                 }
    1607             :             }
    1608          27 :             psOptions->bCreateOutput = true;
    1609             :         }
    1610         516 :         else if (EQUAL(papszArgv[i], "-b") && papszArgv[i + 1])
    1611             :         {
    1612          66 :             if (strchr(papszArgv[i + 1], ' '))
    1613             :             {
    1614             :                 const CPLStringList aosTokens(
    1615           0 :                     CSLTokenizeString(papszArgv[i + 1]));
    1616           0 :                 for (const char *pszToken : aosTokens)
    1617             :                 {
    1618           0 :                     psOptions->anBandList.push_back(atoi(pszToken));
    1619             :                 }
    1620           0 :                 i += 1;
    1621             :             }
    1622             :             else
    1623             :             {
    1624         132 :                 while (i < argc - 1 && ArgIsNumericRasterize(papszArgv[i + 1]))
    1625             :                 {
    1626          66 :                     psOptions->anBandList.push_back(atoi(papszArgv[i + 1]));
    1627          66 :                     i += 1;
    1628             :                 }
    1629          66 :             }
    1630             :         }
    1631             :         else
    1632             :         {
    1633         450 :             aosArgv.AddString(papszArgv[i]);
    1634             :         }
    1635             :     }
    1636             : 
    1637             :     try
    1638             :     {
    1639             :         auto argParser =
    1640          78 :             GDALRasterizeOptionsGetParser(psOptions.get(), psOptionsForBinary);
    1641          76 :         argParser->parse_args_without_binary_name(aosArgv.List());
    1642             : 
    1643             :         // Check all no store_into args
    1644          77 :         if (auto oTe = argParser->present<std::vector<double>>("-te"))
    1645             :         {
    1646           3 :             psOptions->sEnvelop.MinX = oTe.value()[0];
    1647           3 :             psOptions->sEnvelop.MinY = oTe.value()[1];
    1648           3 :             psOptions->sEnvelop.MaxX = oTe.value()[2];
    1649           3 :             psOptions->sEnvelop.MaxY = oTe.value()[3];
    1650           3 :             psOptions->bCreateOutput = true;
    1651             :         }
    1652             : 
    1653          74 :         if (auto oTr = argParser->present<std::vector<double>>("-tr"))
    1654             :         {
    1655          13 :             psOptions->dfXRes = oTr.value()[0];
    1656          13 :             psOptions->dfYRes = oTr.value()[1];
    1657             : 
    1658          13 :             if (psOptions->dfXRes <= 0 || psOptions->dfYRes <= 0)
    1659             :             {
    1660           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1661             :                          "Wrong value for -tr parameter.");
    1662           0 :                 return nullptr;
    1663             :             }
    1664             : 
    1665          13 :             psOptions->bCreateOutput = true;
    1666             :         }
    1667             : 
    1668          74 :         if (auto oTs = argParser->present<std::vector<double>>("-ts"))
    1669             :         {
    1670          29 :             const int nXSize = static_cast<int>(oTs.value()[0]);
    1671          29 :             const int nYSize = static_cast<int>(oTs.value()[1]);
    1672             : 
    1673             :             // Warn the user if the conversion to int looses precision
    1674          29 :             if (nXSize != oTs.value()[0] || nYSize != oTs.value()[1])
    1675             :             {
    1676           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1677             :                          "-ts values parsed as %d %d.", nXSize, nYSize);
    1678             :             }
    1679             : 
    1680          29 :             psOptions->nXSize = nXSize;
    1681          29 :             psOptions->nYSize = nYSize;
    1682             : 
    1683          29 :             if (!(psOptions->nXSize > 0 || psOptions->nYSize > 0))
    1684             :             {
    1685           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1686             :                          "Wrong value for -ts parameter: at least one of the "
    1687             :                          "arguments must be greater than zero.");
    1688           0 :                 return nullptr;
    1689             :             }
    1690             : 
    1691          29 :             psOptions->bCreateOutput = true;
    1692             :         }
    1693             : 
    1694          74 :         if (psOptions->bCreateOutput)
    1695             :         {
    1696          71 :             if (psOptions->dfXRes == 0 && psOptions->dfYRes == 0 &&
    1697          71 :                 psOptions->nXSize == 0 && psOptions->nYSize == 0)
    1698             :             {
    1699           0 :                 CPLError(CE_Failure, CPLE_NotSupported,
    1700             :                          "'-tr xres yres' or '-ts xsize ysize' is required.");
    1701           0 :                 return nullptr;
    1702             :             }
    1703             : 
    1704          42 :             if (psOptions->bTargetAlignedPixels && psOptions->dfXRes == 0 &&
    1705           0 :                 psOptions->dfYRes == 0)
    1706             :             {
    1707           0 :                 CPLError(CE_Failure, CPLE_NotSupported,
    1708             :                          "-tap option cannot be used without using -tr.");
    1709           0 :                 return nullptr;
    1710             :             }
    1711             : 
    1712          42 :             if (!psOptions->anBandList.empty())
    1713             :             {
    1714           1 :                 CPLError(
    1715             :                     CE_Failure, CPLE_NotSupported,
    1716             :                     "-b option cannot be used when creating a GDAL dataset.");
    1717           1 :                 return nullptr;
    1718             :             }
    1719             : 
    1720          41 :             int nBandCount = 1;
    1721             : 
    1722          41 :             if (!psOptions->adfBurnValues.empty())
    1723          24 :                 nBandCount = static_cast<int>(psOptions->adfBurnValues.size());
    1724             : 
    1725          41 :             if (static_cast<int>(psOptions->adfInitVals.size()) > nBandCount)
    1726           0 :                 nBandCount = static_cast<int>(psOptions->adfInitVals.size());
    1727             : 
    1728          41 :             if (psOptions->adfInitVals.size() == 1)
    1729             :             {
    1730           3 :                 for (int i = 1; i <= nBandCount - 1; i++)
    1731           0 :                     psOptions->adfInitVals.push_back(psOptions->adfInitVals[0]);
    1732             :             }
    1733             : 
    1734         110 :             for (int i = 1; i <= nBandCount; i++)
    1735          69 :                 psOptions->anBandList.push_back(i);
    1736             :         }
    1737             :         else
    1738             :         {
    1739          32 :             if (psOptions->anBandList.empty())
    1740          13 :                 psOptions->anBandList.push_back(1);
    1741             :         }
    1742             : 
    1743          73 :         if (!psOptions->osDialect.empty() && !psOptions->osWHERE.empty() &&
    1744           0 :             !psOptions->osSQL.empty())
    1745             :         {
    1746           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    1747             :                      "-dialect is ignored with -where. Use -sql instead");
    1748             :         }
    1749             : 
    1750          73 :         if (psOptionsForBinary)
    1751             :         {
    1752          11 :             psOptionsForBinary->bCreateOutput = psOptions->bCreateOutput;
    1753          11 :             if (!psOptions->osFormat.empty())
    1754           0 :                 psOptionsForBinary->osFormat = psOptions->osFormat;
    1755             :         }
    1756          83 :         else if (psOptions->adfBurnValues.empty() &&
    1757          83 :                  psOptions->osBurnAttribute.empty() && !psOptions->b3D)
    1758             :         {
    1759          14 :             psOptions->adfBurnValues.push_back(255);
    1760             :         }
    1761             :     }
    1762           2 :     catch (const std::exception &e)
    1763             :     {
    1764           2 :         CPLError(CE_Failure, CPLE_AppDefined, "%s", e.what());
    1765           2 :         return nullptr;
    1766             :     }
    1767             : 
    1768          73 :     return psOptions.release();
    1769             : }
    1770             : 
    1771             : /************************************************************************/
    1772             : /*                      GDALRasterizeOptionsFree()                      */
    1773             : /************************************************************************/
    1774             : 
    1775             : /**
    1776             :  * Frees the GDALRasterizeOptions struct.
    1777             :  *
    1778             :  * @param psOptions the options struct for GDALRasterize().
    1779             :  *
    1780             :  * @since GDAL 2.1
    1781             :  */
    1782             : 
    1783          73 : void GDALRasterizeOptionsFree(GDALRasterizeOptions *psOptions)
    1784             : {
    1785          73 :     delete psOptions;
    1786          73 : }
    1787             : 
    1788             : /************************************************************************/
    1789             : /*                  GDALRasterizeOptionsSetProgress()                   */
    1790             : /************************************************************************/
    1791             : 
    1792             : /**
    1793             :  * Set a progress function.
    1794             :  *
    1795             :  * @param psOptions the options struct for GDALRasterize().
    1796             :  * @param pfnProgress the progress callback.
    1797             :  * @param pProgressData the user data for the progress callback.
    1798             :  *
    1799             :  * @since GDAL 2.1
    1800             :  */
    1801             : 
    1802          47 : void GDALRasterizeOptionsSetProgress(GDALRasterizeOptions *psOptions,
    1803             :                                      GDALProgressFunc pfnProgress,
    1804             :                                      void *pProgressData)
    1805             : {
    1806          47 :     psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
    1807          47 :     psOptions->pProgressData = pProgressData;
    1808          47 : }

Generated by: LCOV version 1.14