示例#1
0
int main(int argc, char* argv[])
{
    const char     *pszFormat = "ESRI Shapefile";
    char           *pszLayerName = NULL;
    const char     *pszSrcFilename = NULL, *pszDstFilename = NULL;
    int             iBand = 1;
    GDALDatasetH    hDS;
    GDALRasterBandH hBand;
    int             nXSize, nYSize;
    int             i, j;
    FILE           *fOut = NULL;
    double         *padfBuffer;
    double          adfGeotransform[6];
    OGRSFDriverH    hOGRDriver;
    OGRDataSourceH  hOGRDS;
    OGRLayerH       hOGRLayer;
    OGRwkbGeometryType eType = wkbPoint25D;
    int             xStep = 1, yStep = 1;

    OGRRegisterAll();
    GDALAllRegister();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if ( EQUAL(argv[i], "-b") && i < argc - 1)
            iBand = atoi(argv[++i]);
        else if ( EQUAL(argv[i], "-f") && i < argc - 1)
            pszFormat = argv[++i];
        else if ( EQUAL(argv[i], "-l") && i < argc - 1)
            pszLayerName = CPLStrdup(argv[++i]);
        else if ( EQUAL(argv[i], "-t") && i < argc - 1)
        {
            i++;
            if (EQUAL(argv[i], "POLYGON"))
                eType = wkbPolygon;
            else if (EQUAL(argv[i], "POINT"))
                eType = wkbPoint;
            else if (EQUAL(argv[i], "POINT25D"))
                eType = wkbPoint25D;
            else
            {
                fprintf(stderr, "unhandled geometry type : %s\n", argv[i]);
            }
        }
        else if ( EQUAL(argv[i], "-step") && i < argc - 1)
            xStep = yStep = atoi(argv[++i]);
        else if ( argv[i][0] == '-')
            Usage();
        else if( pszSrcFilename == NULL )
            pszSrcFilename = argv[i];
        else if(  pszDstFilename == NULL )
            pszDstFilename = argv[i];
        else
            Usage();
    }

    if( pszSrcFilename == NULL || pszDstFilename == NULL)
        Usage();

/* -------------------------------------------------------------------- */
/*      Open GDAL source dataset                                        */
/* -------------------------------------------------------------------- */
    hDS = GDALOpen(pszSrcFilename, GA_ReadOnly);
    if (hDS == NULL)
    {
        fprintf(stderr, "Can't open %s\n", pszSrcFilename);
        exit(1);
    }

    hBand = GDALGetRasterBand(hDS, iBand);
    if (hBand == NULL)
    {
        fprintf(stderr, "Can't get band %d\n", iBand);
        exit(1);
    }

    if (GDALGetGeoTransform(hDS, adfGeotransform) != CE_None)
    {
        fprintf(stderr, "Can't get geotransform\n");
        exit(1);
    }

    nXSize = GDALGetRasterXSize(hDS);
    nYSize = GDALGetRasterYSize(hDS);

/* -------------------------------------------------------------------- */
/*     Create OGR destination dataset                                   */
/* -------------------------------------------------------------------- */
    /* Special case for CSV : we generate the appropriate VRT file in the same time */
    if (EQUAL(pszFormat, "CSV") && EQUAL(CPLGetExtension(pszDstFilename), "CSV"))
    {
        FILE* fOutCSVT;
        FILE* fOutVRT;
        char* pszDstFilenameCSVT;
        char* pszDstFilenameVRT;

        fOut = fopen(pszDstFilename, "wt");
        if (fOut == NULL)
        {
            fprintf(stderr, "Can't open %s for writing\n", pszDstFilename);
            exit(1);
        }
        fprintf(fOut, "x,y,z\n");

        pszDstFilenameCSVT = CPLMalloc(strlen(pszDstFilename) + 2);
        strcpy(pszDstFilenameCSVT, pszDstFilename);
        strcat(pszDstFilenameCSVT, "t");
        fOutCSVT = fopen(pszDstFilenameCSVT, "wt");
        if (fOutCSVT == NULL)
        {
            fprintf(stderr, "Can't open %s for writing\n", pszDstFilenameCSVT);
            exit(1);
        }
        CPLFree(pszDstFilenameCSVT);
        fprintf(fOutCSVT, "Real,Real,Real\n");
        fclose(fOutCSVT);
        fOutCSVT = NULL;

        pszDstFilenameVRT = CPLStrdup(pszDstFilename);
        strcpy(pszDstFilenameVRT + strlen(pszDstFilename) - 3, "vrt");
        fOutVRT = fopen(pszDstFilenameVRT, "wt");
        if (fOutVRT == NULL)
        {
            fprintf(stderr, "Can't open %s for writing\n", pszDstFilenameVRT);
            exit(1);
        }
        CPLFree(pszDstFilenameVRT);
        fprintf(fOutVRT, "<OGRVRTDataSource>\n");
        fprintf(fOutVRT, "  <OGRVRTLayer name=\"%s\">\n", CPLGetBasename(pszDstFilename));
        fprintf(fOutVRT, "    <SrcDataSource>%s</SrcDataSource> \n", pszDstFilename);
        fprintf(fOutVRT, "    <GeometryType>wkbPoint</GeometryType>\n");
        fprintf(fOutVRT, "    <GeometryField encoding=\"PointFromColumns\" x=\"x\" y=\"y\" z=\"z\"/>\n");
        fprintf(fOutVRT, "  </OGRVRTLayer>\n");
        fprintf(fOutVRT, "</OGRVRTDataSource>\n");
        fclose(fOutVRT);
        fOutVRT = NULL;
    }
    else
    {
        OGRSpatialReferenceH hSRS = NULL;
        const char* pszWkt;

        hOGRDriver = OGRGetDriverByName(pszFormat);
        if (hOGRDriver == NULL)
        {
            fprintf(stderr, "Can't find OGR driver %s\n", pszFormat);
            exit(1);
        }

        hOGRDS = OGR_Dr_CreateDataSource(hOGRDriver, pszDstFilename, NULL);
        if (hOGRDS == NULL)
        {
            fprintf(stderr, "Can't create OGR datasource %s\n", pszDstFilename);
            exit(1);
        }

        pszWkt = GDALGetProjectionRef(hDS);
        if (pszWkt && pszWkt[0])
        {
            hSRS = OSRNewSpatialReference(pszWkt);
        }

        if (pszLayerName == NULL)
            pszLayerName = CPLStrdup(CPLGetBasename(pszDstFilename));

        hOGRLayer = OGR_DS_CreateLayer( hOGRDS, pszLayerName,
                                        hSRS, eType, NULL);

        if (hSRS)
            OSRDestroySpatialReference(hSRS);

        if (hOGRLayer == NULL)
        {
            fprintf(stderr, "Can't create layer %s\n", pszLayerName);
            exit(1);
        }

        if (eType != wkbPoint25D)
        {
            OGRFieldDefnH hFieldDefn =  OGR_Fld_Create( "z", OFTReal );
            OGR_L_CreateField(hOGRLayer, hFieldDefn, 0);
            OGR_Fld_Destroy( hFieldDefn );
        }
    }


    padfBuffer = (double*)CPLMalloc(nXSize * sizeof(double));

#define GET_X(j, i) adfGeotransform[0] + (j) * adfGeotransform[1] + (i) * adfGeotransform[2]
#define GET_Y(j, i) adfGeotransform[3] + (j) * adfGeotransform[4] + (i) * adfGeotransform[5]
#define GET_XY(j, i) GET_X(j, i), GET_Y(j, i)

/* -------------------------------------------------------------------- */
/*     "Translate" the source dataset                                   */
/* -------------------------------------------------------------------- */
    for(i=0;i<nYSize;i+=yStep)
    {
        GDALRasterIO( hBand, GF_Read, 0, i, nXSize, 1,
                      padfBuffer, nXSize, 1, GDT_Float64, 0, 0);
        for(j=0;j<nXSize;j+=xStep)
        {
            if (fOut)
            {
                fprintf(fOut, "%f,%f,%f\n",
                        GET_XY(j + .5, i + .5), padfBuffer[j]);
            }
            else
            {
                OGRFeatureH hFeature = OGR_F_Create(OGR_L_GetLayerDefn(hOGRLayer));
                OGRGeometryH hGeometry = OGR_G_CreateGeometry(eType);
                if (eType == wkbPoint25D)
                {
                    OGR_G_SetPoint(hGeometry, 0, GET_XY(j + .5, i + .5),
                                   padfBuffer[j]);
                }
                else if (eType == wkbPoint)
                {
                    OGR_G_SetPoint_2D(hGeometry, 0, GET_XY(j + .5, i + .5));
                    OGR_F_SetFieldDouble(hFeature, 0, padfBuffer[j]);
                }
                else
                {
                    OGRGeometryH hLinearRing = OGR_G_CreateGeometry(wkbLinearRing);
                    OGR_G_SetPoint_2D(hLinearRing, 0, GET_XY(j + 0, i + 0));
                    OGR_G_SetPoint_2D(hLinearRing, 1, GET_XY(j + 1, i + 0));
                    OGR_G_SetPoint_2D(hLinearRing, 2, GET_XY(j + 1, i + 1));
                    OGR_G_SetPoint_2D(hLinearRing, 3, GET_XY(j + 0, i + 1));
                    OGR_G_SetPoint_2D(hLinearRing, 4, GET_XY(j + 0, i + 0));
                    OGR_G_AddGeometryDirectly(hGeometry, hLinearRing);
                    OGR_F_SetFieldDouble(hFeature, 0, padfBuffer[j]);
                }
                OGR_F_SetGeometryDirectly(hFeature, hGeometry);
                OGR_L_CreateFeature(hOGRLayer, hFeature);
                OGR_F_Destroy(hFeature);
            }
        }
    }

/* -------------------------------------------------------------------- */
/*     Cleanup                                                          */
/* -------------------------------------------------------------------- */
    if (fOut)
        fclose(fOut);
    else
        OGR_DS_Destroy(hOGRDS);
    GDALClose(hDS);

    CPLFree(padfBuffer);
    CPLFree(pszLayerName);

    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();
    OGRCleanupAll();
    CSLDestroy( argv );

    return 0;
}
int main( int argc, char ** argv )

{
    int i, b3D = FALSE;
    int bInverse = FALSE;
    const char *pszSrcFilename = NULL;
    const char *pszDstFilename = NULL;
    char **papszLayers = NULL;
    const char *pszSQL = NULL;
    const char *pszBurnAttribute = NULL;
    const char *pszWHERE = NULL;
    std::vector<int> anBandList;
    std::vector<double> adfBurnValues;
    char **papszRasterizeOptions = NULL;
    double dfXRes = 0, dfYRes = 0;
    int bCreateOutput = FALSE;
    const char* pszFormat = "GTiff";
    int bFormatExplicitelySet = FALSE;
    char **papszCreateOptions = NULL;
    GDALDriverH hDriver = NULL;
    GDALDataType eOutputType = GDT_Float64;
    std::vector<double> adfInitVals;
    int bNoDataSet = FALSE;
    double dfNoData = 0;
    OGREnvelope sEnvelop;
    int bGotBounds = FALSE;
    int nXSize = 0, nYSize = 0;
    int bQuiet = FALSE;
    GDALProgressFunc pfnProgress = GDALTermProgress;
    OGRSpatialReferenceH hSRS = NULL;
    int bTargetAlignedPixels = FALSE;
    

    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }

    GDALAllRegister();
    OGRRegisterAll();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") )
        {
            bQuiet = TRUE;
            pfnProgress = GDALDummyProgress;
        }
        else if( EQUAL(argv[i],"-a") && i < argc-1 )
        {
            pszBurnAttribute = argv[++i];
        }
        else if( EQUAL(argv[i],"-b") && i < argc-1 )
        {
            if (strchr(argv[i+1], ' '))
            {
                char** papszTokens = CSLTokenizeString( argv[i+1] );
                char** papszIter = papszTokens;
                while(papszIter && *papszIter)
                {
                    anBandList.push_back(atoi(*papszIter));
                    papszIter ++;
                }
                CSLDestroy(papszTokens);
                i += 1;
            }
            else
            {
                while(i < argc-1 && ArgIsNumeric(argv[i+1]))
                {
                    anBandList.push_back(atoi(argv[i+1]));
                    i += 1;
                }
            }
        }
        else if( EQUAL(argv[i],"-3d")  )
        {
            b3D = TRUE;
            papszRasterizeOptions = 
                CSLSetNameValue( papszRasterizeOptions, "BURN_VALUE_FROM", "Z");
        }
        else if( EQUAL(argv[i],"-i")  )
        {
            bInverse = TRUE;
        }
        else if( EQUAL(argv[i],"-at")  )
        {
            papszRasterizeOptions = 
                CSLSetNameValue( papszRasterizeOptions, "ALL_TOUCHED", "TRUE" );
        }
        else if( EQUAL(argv[i],"-burn") && i < argc-1 )
        {
            if (strchr(argv[i+1], ' '))
            {
                char** papszTokens = CSLTokenizeString( argv[i+1] );
                char** papszIter = papszTokens;
                while(papszIter && *papszIter)
                {
                    adfBurnValues.push_back(atof(*papszIter));
                    papszIter ++;
                }
                CSLDestroy(papszTokens);
                i += 1;
            }
            else
            {
                while(i < argc-1 && ArgIsNumeric(argv[i+1]))
                {
                    adfBurnValues.push_back(atof(argv[i+1]));
                    i += 1;
                }
            }
        }
        else if( EQUAL(argv[i],"-where") && i < argc-1 )
        {
            pszWHERE = argv[++i];
        }
        else if( EQUAL(argv[i],"-l") && i < argc-1 )
        {
            papszLayers = CSLAddString( papszLayers, argv[++i] );
        }
        else if( EQUAL(argv[i],"-sql") && i < argc-1 )
        {
            pszSQL = argv[++i];
        }
        else if( EQUAL(argv[i],"-of") && i < argc-1 )
        {
            pszFormat = argv[++i];
            bFormatExplicitelySet = TRUE;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-init") && i < argc - 1 )
        {
            if (strchr(argv[i+1], ' '))
            {
                char** papszTokens = CSLTokenizeString( argv[i+1] );
                char** papszIter = papszTokens;
                while(papszIter && *papszIter)
                {
                    adfInitVals.push_back(atof(*papszIter));
                    papszIter ++;
                }
                CSLDestroy(papszTokens);
                i += 1;
            }
            else
            {
                while(i < argc-1 && ArgIsNumeric(argv[i+1]))
                {
                    adfInitVals.push_back(atof(argv[i+1]));
                    i += 1;
                }
            }
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-a_nodata") && i < argc - 1 )
        {
            dfNoData = atof(argv[i+1]);
            bNoDataSet = TRUE;
            i += 1;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-a_srs") && i < argc-1 )
        {
            hSRS = OSRNewSpatialReference( NULL );

            if( OSRSetFromUserInput(hSRS, argv[i+1]) != OGRERR_NONE )
            {
                fprintf( stderr, "Failed to process SRS definition: %s\n", 
                         argv[i+1] );
                exit( 1 );
            }

            i++;
            bCreateOutput = TRUE;
        }   

        else if( EQUAL(argv[i],"-te") && i < argc - 4 )
        {
            sEnvelop.MinX = atof(argv[++i]);
            sEnvelop.MinY = atof(argv[++i]);
            sEnvelop.MaxX = atof(argv[++i]);
            sEnvelop.MaxY = atof(argv[++i]);
            bGotBounds = TRUE;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-a_ullr") && i < argc - 4 )
        {
            sEnvelop.MinX = atof(argv[++i]);
            sEnvelop.MaxY = atof(argv[++i]);
            sEnvelop.MaxX = atof(argv[++i]);
            sEnvelop.MinY = atof(argv[++i]);
            bGotBounds = TRUE;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-co") && i < argc-1 )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-ot") && i < argc-1 )
        {
            int	iType;
            
            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName((GDALDataType)iType) != NULL
                    && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
                             argv[i+1]) )
                {
                    eOutputType = (GDALDataType) iType;
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
            }
            i++;
            bCreateOutput = TRUE;
        }
        else if( (EQUAL(argv[i],"-ts") || EQUAL(argv[i],"-outsize")) && i < argc-2 )
        {
            nXSize = atoi(argv[++i]);
            nYSize = atoi(argv[++i]);
            if (nXSize <= 0 || nYSize <= 0)
            {
                printf( "Wrong value for -outsize parameters\n");
                Usage();
            }
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-tr") && i < argc-2 )
        {
            dfXRes = atof(argv[++i]);
            dfYRes = fabs(atof(argv[++i]));
            if( dfXRes == 0 || dfYRes == 0 )
            {
                printf( "Wrong value for -tr parameters\n");
                Usage();
            }
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-tap") )
        {
            bTargetAlignedPixels = TRUE;
            bCreateOutput = TRUE;
        }
        else if( pszSrcFilename == NULL )
        {
            pszSrcFilename = argv[i];
        }
        else if( pszDstFilename == NULL )
        {
            pszDstFilename = argv[i];
        }
        else
            Usage();
    }

    if( pszSrcFilename == NULL || pszDstFilename == NULL )
    {
        fprintf( stderr, "Missing source or destination.\n\n" );
        Usage();
    }

    if( adfBurnValues.size() == 0 && pszBurnAttribute == NULL && !b3D )
    {
        fprintf( stderr, "At least one of -3d, -burn or -a required.\n\n" );
        Usage();
    }

    if( bCreateOutput )
    {
        if( dfXRes == 0 && dfYRes == 0 && nXSize == 0 && nYSize == 0 )
        {
            fprintf( stderr, "'-tr xres yes' or '-ts xsize ysize' is required.\n\n" );
            Usage();
        }
    
        if (bTargetAlignedPixels && dfXRes == 0 && dfYRes == 0)
        {
            fprintf( stderr, "-tap option cannot be used without using -tr\n");
            Usage();
        }

        if( anBandList.size() != 0 )
        {
            fprintf( stderr, "-b option cannot be used when creating a GDAL dataset.\n\n" );
            Usage();
        }

        int nBandCount = 1;

        if (adfBurnValues.size() != 0)
            nBandCount = adfBurnValues.size();

        if ((int)adfInitVals.size() > nBandCount)
            nBandCount = adfInitVals.size();

        if (adfInitVals.size() == 1)
        {
            for(i=1;i<=nBandCount - 1;i++)
                adfInitVals.push_back( adfInitVals[0] );
        }

        int i;
        for(i=1;i<=nBandCount;i++)
            anBandList.push_back( i );
    }
    else
    {
        if( anBandList.size() == 0 )
            anBandList.push_back( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open source vector dataset.                                     */
/* -------------------------------------------------------------------- */
    OGRDataSourceH hSrcDS;

    hSrcDS = OGROpen( pszSrcFilename, FALSE, NULL );
    if( hSrcDS == NULL )
    {
        fprintf( stderr, "Failed to open feature source: %s\n", 
                 pszSrcFilename);
        exit( 1 );
    }

    if( pszSQL == NULL && papszLayers == NULL )
    {
        if( OGR_DS_GetLayerCount(hSrcDS) == 1 )
        {
            papszLayers = CSLAddString(NULL, OGR_L_GetName(OGR_DS_GetLayer(hSrcDS, 0)));
        }
        else
        {
            fprintf( stderr, "At least one of -l or -sql required.\n\n" );
            Usage();
        }
    }

/* -------------------------------------------------------------------- */
/*      Open target raster file.  Eventually we will add optional       */
/*      creation.                                                       */
/* -------------------------------------------------------------------- */
    GDALDatasetH hDstDS = NULL;

    if (bCreateOutput)
    {
/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
        hDriver = GDALGetDriverByName( pszFormat );
        if( hDriver == NULL 
            || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL )
        {
            int	iDr;

            printf( "Output driver `%s' not recognised or does not support\n", 
                    pszFormat );
            printf( "direct output file creation.  The following format drivers are configured\n"
                    "and support direct output:\n" );

            for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
            {
                GDALDriverH hDriver = GDALGetDriver(iDr);

                if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL) != NULL )
                {
                    printf( "  %s: %s\n",
                            GDALGetDriverShortName( hDriver  ),
                            GDALGetDriverLongName( hDriver ) );
                }
            }
            printf( "\n" );
            exit( 1 );
        }

        if (!bQuiet && !bFormatExplicitelySet)
            CheckExtensionConsistency(pszDstFilename, pszFormat);
    }
    else
    {
        hDstDS = GDALOpen( pszDstFilename, GA_Update );
        if( hDstDS == NULL )
            exit( 2 );
    }

/* -------------------------------------------------------------------- */
/*      Process SQL request.                                            */
/* -------------------------------------------------------------------- */
    if( pszSQL != NULL )
    {
        OGRLayerH hLayer;

        hLayer = OGR_DS_ExecuteSQL( hSrcDS, pszSQL, NULL, NULL ); 
        if( hLayer != NULL )
        {
            if (bCreateOutput)
            {
                std::vector<OGRLayerH> ahLayers;
                ahLayers.push_back(hLayer);

                hDstDS = CreateOutputDataset(ahLayers, hSRS,
                                 bGotBounds, sEnvelop,
                                 hDriver, pszDstFilename,
                                 nXSize, nYSize, dfXRes, dfYRes,
                                 bTargetAlignedPixels,
                                 anBandList.size(), eOutputType,
                                 papszCreateOptions, adfInitVals,
                                 bNoDataSet, dfNoData);
            }

            ProcessLayer( hLayer, hSRS != NULL, hDstDS, anBandList, 
                          adfBurnValues, b3D, bInverse, pszBurnAttribute,
                          papszRasterizeOptions, pfnProgress, NULL );

            OGR_DS_ReleaseResultSet( hSrcDS, hLayer );
        }
    }

/* -------------------------------------------------------------------- */
/*      Create output file if necessary.                                */
/* -------------------------------------------------------------------- */
    int nLayerCount = CSLCount(papszLayers);

    if (bCreateOutput && hDstDS == NULL)
    {
        std::vector<OGRLayerH> ahLayers;

        for( i = 0; i < nLayerCount; i++ )
        {
            OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i] );
            if( hLayer == NULL )
            {
                continue;
            }
            ahLayers.push_back(hLayer);
        }

        hDstDS = CreateOutputDataset(ahLayers, hSRS,
                                bGotBounds, sEnvelop,
                                hDriver, pszDstFilename,
                                nXSize, nYSize, dfXRes, dfYRes,
                                bTargetAlignedPixels,
                                anBandList.size(), eOutputType,
                                papszCreateOptions, adfInitVals,
                                bNoDataSet, dfNoData);
    }

/* -------------------------------------------------------------------- */
/*      Process each layer.                                             */
/* -------------------------------------------------------------------- */

    for( i = 0; i < nLayerCount; i++ )
    {
        OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i] );
        if( hLayer == NULL )
        {
            fprintf( stderr, "Unable to find layer %s, skipping.\n", 
                      papszLayers[i] );
            continue;
        }

        if( pszWHERE )
        {
            if( OGR_L_SetAttributeFilter( hLayer, pszWHERE ) != OGRERR_NONE )
                break;
        }

        void *pScaledProgress;
        pScaledProgress =
            GDALCreateScaledProgress( 0.0, 1.0 * (i + 1) / nLayerCount,
                                      pfnProgress, NULL );

        ProcessLayer( hLayer, hSRS != NULL, hDstDS, anBandList, 
                      adfBurnValues, b3D, bInverse, pszBurnAttribute,
                      papszRasterizeOptions, GDALScaledProgress, pScaledProgress );

        GDALDestroyScaledProgress( pScaledProgress );
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */

    OGR_DS_Destroy( hSrcDS );
    GDALClose( hDstDS );

    OSRDestroySpatialReference(hSRS);

    CSLDestroy( argv );
    CSLDestroy( papszRasterizeOptions );
    CSLDestroy( papszLayers );
    CSLDestroy( papszCreateOptions );
    
    GDALDestroyDriverManager();
    OGRCleanupAll();

    return 0;
}
示例#3
0
void TIndexReader::initialize()
{
    if (!m_bounds.empty())
        m_wkt = m_bounds.toWKT();
    m_out_ref.reset(new gdal::SpatialRef());

    log()->get(LogLevel::Debug) << "Opening file " << m_filename <<
        std::endl;

    gdal::registerDrivers();
    m_dataset = OGROpen(m_filename.c_str(), FALSE, NULL);
    if (!m_dataset)
        throwError("Unable to datasource '" + m_filename + "'");

    OGRGeometryH geometry(0);
    if (m_sql.size())
    {
        m_layer = OGR_DS_ExecuteSQL(m_dataset, m_sql.c_str(), geometry,
            m_dialect.c_str());
    }
    else
    {
        m_layer = OGR_DS_GetLayerByName(m_dataset, m_layerName.c_str());
    }
    if (!m_layer)
        throwError("Unable to open layer '" + m_layerName +
            "' from OGR datasource '" + m_filename + "'");

    m_out_ref->setFromLayer(m_layer);

    // Override the SRS if the user set one, otherwise, take it
    // from the layer
    if (m_tgtSrsString.size())
        m_out_ref.reset(new gdal::SpatialRef(m_tgtSrsString));
    else
        m_out_ref.reset(new gdal::SpatialRef(m_out_ref->wkt()));

    setSpatialReference(SpatialReference(m_out_ref->wkt()));

    std::unique_ptr<gdal::Geometry> wkt_g;

    // If the user set either explicit 'polygon' or 'boundary' options
    // we will filter by that geometry. The user can set a 'filter_srs'
    // option to override the SRS of the input geometry and we will
    // reproject to the output projection as needed.
    if (m_wkt.size())
    {
        // Reproject the given wkt to the output SRS so
        // filtering/cropping works
        gdal::SpatialRef assign(m_filterSRS);
        gdal::Geometry before(m_wkt, assign);
        before.transform(*m_out_ref);

        wkt_g.reset (new gdal::Geometry(before.wkt(), *m_out_ref));

        geometry = wkt_g->get();
        m_wkt = wkt_g->wkt();
        OGR_L_SetSpatialFilter(m_layer, geometry);
    }

    if (m_attributeFilter.size())
    {
        OGRErr err = OGR_L_SetAttributeFilter(m_layer,
            m_attributeFilter.c_str());
        if (err != OGRERR_NONE)
            throwError("Unable to set attribute filter '" + m_attributeFilter +
                "' for OGR datasource '" + m_filename + "'");
    }

    Options cropOptions;
    if (m_wkt.size())
        cropOptions.add("polygon", m_wkt);

    for (auto f : getFiles())
    {
        log()->get(LogLevel::Debug) << "Adding file " << f.m_filename <<
            " to merge filter" << std::endl;

        std::string driver = m_factory.inferReaderDriver(f.m_filename);
        Stage *reader = m_factory.createStage(driver);
        if (!reader)
            throwError("Unable to create reader for file '" + f.m_filename +
                "'.");
        Options readerOptions;
        readerOptions.add("filename", f.m_filename);
        reader->setOptions(readerOptions);
        Stage *premerge = reader;

        if (m_tgtSrsString != f.m_srs &&
            (m_tgtSrsString.size() && f.m_srs.size()))
        {
            Stage *repro = m_factory.createStage("filters.reprojection");
            repro->setInput(*reader);
            Options reproOptions;
            reproOptions.add("out_srs", m_tgtSrsString);
            reproOptions.add("in_srs", f.m_srs);
            log()->get(LogLevel::Debug2) << "Repro = "
                                         << m_tgtSrsString << "/"
                                         << f.m_srs << "!\n";
            repro->setOptions(reproOptions);
            premerge = repro;
        }

        // WKT is set even if we're using a bounding box for filtering, so
        // can be used as a test here.
        if (!m_wkt.empty())
        {
            Stage *crop = m_factory.createStage("filters.crop");
            crop->setOptions(cropOptions);
            crop->setInput(*premerge);
            log()->get(LogLevel::Debug3) << "Cropping data with wkt '"
                                         << m_wkt << "'" << std::endl;
            premerge = crop;
        }

        m_merge.setInput(*premerge);
    }

    if (m_sql.size())
    {
        // We were created with OGR_DS_ExecuteSQL which needs to have
        // its layer explicitly released
        OGR_DS_ReleaseResultSet(m_dataset, m_layer);
    }
    else
    {
        OGR_DS_Destroy(m_dataset);
    }
    m_layer = 0;
    m_dataset = 0;
}
示例#4
0
int OGRCDump(const char *pszFname)
{
    OGRDataSourceH datasource;
    int i, numLayers;

    /* Register all OGR drivers */
    OGRRegisterAll();

    /* Open data source */
    datasource = OGROpen(pszFname, 0 /* bUpdate */, NULL);

    if (datasource == NULL)
    {
        printf("Unable to open %s\n", pszFname);
        return -1;
    }

    /* Loop through layers and dump their contents */

    numLayers = OGR_DS_GetLayerCount(datasource);
    for(i=0; i<numLayers; i++)
    {
        OGRLayerH layer;
        int j, numFields;
        OGRFeatureH feature;
        OGRFeatureDefnH layerDefn;

        layer = OGR_DS_GetLayer( datasource, i );

        /* Dump info about this layer */
        layerDefn = OGR_L_GetLayerDefn( layer );
        numFields = OGR_FD_GetFieldCount( layerDefn );

        printf("\n===================\n");
        printf("Layer %d: '%s'\n\n", i, OGR_FD_GetName(layerDefn));

        for(j=0; j<numFields; j++)
        {
            OGRFieldDefnH fieldDefn;

            fieldDefn = OGR_FD_GetFieldDefn( layerDefn, j );
            printf(" Field %d: %s (%s)\n", 
                   j, OGR_Fld_GetNameRef(fieldDefn), 
                   OGR_GetFieldTypeName(OGR_Fld_GetType(fieldDefn)) );
        }
        printf("\n");

        /* And dump each feature individually */
        while( (feature = OGR_L_GetNextFeature( layer )) != NULL )
        {
            OGR_F_DumpReadable( feature, stdout );
            OGR_F_Destroy( feature );
        }

        /* No need to free layer handle, it belongs to the datasource */
    }

    /* Close data source */
    OGR_DS_Destroy( datasource );

    return 0;
}
示例#5
0
  int tindex(maps*& conf, maps*& inputs,maps*& outputs)
  {
    char *index_filename = NULL;
    const char *tile_index = "location";
    int		i_arg, ti_field;
    OGRDataSourceH hTileIndexDS;
    OGRLayerH hLayer = NULL;
    OGRFeatureDefnH hFDefn;
    int write_absolute_path = FALSE;
    char* current_path = NULL;
    int i;
    int nExistingFiles;
    int skip_different_projection = FALSE;
    char** existingFilesTab = NULL;
    int alreadyExistingProjectionRefValid = FALSE;
    char* alreadyExistingProjectionRef = NULL;
    char* index_filename_mod;
    int bExists;
    VSIStatBuf sStatBuf;

    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
      {
	char tmp[1024];
        sprintf(tmp, "At least, GDAL >= 1.4.0 is required for this version of"
		"tindex, which was compiled against GDAL %s\n", GDAL_RELEASE_NAME);
        return SERVICE_FAILED;
      }

    GDALAllRegister();
    OGRRegisterAll();


    /* -------------------------------------------------------------------- */
    /*      Get the directory name to search for raster file to index.      */
    /* -------------------------------------------------------------------- */
    char *tmpDataDir;
    char *pszDataDir;
    map* tmpMap=getMapFromMaps(conf,"main","isTrial");      
    map* tmpMap1=getMapFromMaps(conf,"main","dataPath");
    map* tmpInputMap=getMapFromMaps(inputs,"dir","value");
    if(tmpMap!=NULL && strcasecmp(tmpMap->value,"true")==0){
      pszDataDir=(char*) malloc((strlen(tmpInputMap->value)+strlen(tmpMap1->value)+5+1)*sizeof(char));
      sprintf(pszDataDir,"%s/ftp/%s",tmpMap1->value,tmpInputMap->value);
    }else{
      pszDataDir=(char*) malloc(((strlen(tmpInputMap->value)+1)*sizeof(char)));
      sprintf(pszDataDir,"%s",tmpInputMap->value);
    }
    
    tmpMap=getMapFromMaps(inputs,"iname","value");
    tmpMap1=getMapFromMaps(inputs,"idir","value");
    map* tmpMap2=getMapFromMaps(conf,"main","dataPath");
    if(tmpMap!=NULL && tmpMap1!=NULL && tmpMap2!=NULL){
      index_filename = (char*) malloc((strlen(tmpMap->value)+strlen(tmpMap1->value)+strlen(tmpMap2->value)+12)*sizeof(char));
      sprintf(index_filename,"%s/dirs/%s/%s.shp",tmpMap2->value,tmpMap1->value,tmpMap->value);
    }
    fprintf(stderr,"Filename %s\n",index_filename);
    /* -------------------------------------------------------------------- */
    /*      Open or create the target shapefile and DBF file.               */
    /* -------------------------------------------------------------------- */
    index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "shp"));

    bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0);
    if (!bExists)
      {
        CPLFree(index_filename_mod);
        index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "SHP"));
        bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0);
      }
    CPLFree(index_filename_mod);

    if (bExists)
      {
        hTileIndexDS = OGROpen( index_filename, TRUE, NULL );
        if (hTileIndexDS != NULL)
	  {
            hLayer = OGR_DS_GetLayer(hTileIndexDS, 0);
	  }
      }
    else
      {
        OGRSFDriverH hDriver;
        const char* pszDriverName = "ESRI Shapefile";

        fprintf( stderr,"Creating new index file...\n" );
        hDriver = OGRGetDriverByName( pszDriverName );
        if( hDriver == NULL )
	  {
	    char msg[1024];
            sprintf( msg, "%s driver not available.", pszDriverName );
	    setMapInMaps(conf,"lenv","message",msg);
	    return SERVICE_FAILED;
	  }

        hTileIndexDS = OGR_Dr_CreateDataSource( hDriver, index_filename, NULL );
        if (hTileIndexDS)
	  {
            char* pszLayerName = CPLStrdup(CPLGetBasename(index_filename));
            OGRSpatialReferenceH hSpatialRef = NULL;
            GDALDatasetH hDS = GDALOpen( index_filename, GA_ReadOnly );
            if (hDS)
	      {
                const char* pszWKT = GDALGetProjectionRef(hDS);
                if (pszWKT != NULL && pszWKT[0] != '\0')
		  {
                    hSpatialRef = OSRNewSpatialReference(pszWKT);
		  }
                GDALClose(hDS);
	      }

	    DIR *dirp = opendir(pszDataDir);
	    if(dirp==NULL){
	      char tmp1[1024];
	      sprintf(tmp1,_ss("The specified path %s doesn't exist."),pszDataDir);
	      setMapInMaps(conf,"lenv","message",tmp1);
	      return SERVICE_FAILED;
	    }
	    char *res=NULL;
	    struct dirent *dp;
	    tmpMap=getMapFromMaps(inputs,"ext","value");
	    char *ext;
	    if(tmpMap!=NULL)
	      ext=tmpMap->value;
	    while ((dp = readdir(dirp)) != NULL){
	      if(strncmp(dp->d_name,".",1)!=0&&strncmp(dp->d_name,"..",2)!=0){
		char* argv=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+2)*sizeof(char));
		sprintf(argv,"%s/%s",pszDataDir,dp->d_name);
		GDALDatasetH hDS0 = GDALOpen( argv, GA_ReadOnly );
		if (hDS0)
		  {
		    const char* pszWKT = GDALGetProjectionRef(hDS0);
		    fprintf(stderr,"SRS %s \n",pszWKT);
		    if (pszWKT != NULL && pszWKT[0] != '\0')
		      {
			if (hSpatialRef)
			  OSRRelease(hSpatialRef);
			hSpatialRef = OSRNewSpatialReference(pszWKT);
		      }
		    GDALClose(hDS);
		  }
		break;
	      }
	    }
	    closedir(dirp);
            hLayer = OGR_DS_CreateLayer( hTileIndexDS, pszLayerName, hSpatialRef, wkbPolygon, NULL );
            CPLFree(pszLayerName);
            if (hSpatialRef)
	      OSRRelease(hSpatialRef);

            if (hLayer)
	      {
                OGRFieldDefnH hFieldDefn = OGR_Fld_Create( tile_index, OFTString );
                OGR_Fld_SetWidth( hFieldDefn, 255);
                OGR_L_CreateField( hLayer, hFieldDefn, TRUE );
                OGR_Fld_Destroy(hFieldDefn);
	      }
	  }
      }

    if( hTileIndexDS == NULL || hLayer == NULL )
      {
	char msg[1024];
        sprintf( msg, "Unable to open/create shapefile `%s'.", 
                 index_filename );
	setMapInMaps(conf,"lenv","message",msg);
      }

    hFDefn = OGR_L_GetLayerDefn(hLayer);

    for( ti_field = 0; ti_field < OGR_FD_GetFieldCount(hFDefn); ti_field++ )
      {
        OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( hFDefn, ti_field );
        if( strcmp(OGR_Fld_GetNameRef(hFieldDefn), tile_index) == 0 )
	  break;
      }

    if( ti_field == OGR_FD_GetFieldCount(hFDefn) )
      {
	char msg[1024];
        sprintf( msg, "Unable to find field `%s' in DBF file `%s'.\n", 
                 tile_index, index_filename );
	setMapInMaps(conf,"lenv","message",msg);
	return SERVICE_FAILED;
      }

    /* Load in memory existing file names in SHP */
    nExistingFiles = OGR_L_GetFeatureCount(hLayer, FALSE);
    if (nExistingFiles)
      {
        OGRFeatureH hFeature;
        existingFilesTab = (char**)CPLMalloc(nExistingFiles * sizeof(char*));
        for(i=0;i<nExistingFiles;i++)
	  {
            hFeature = OGR_L_GetNextFeature(hLayer);
            existingFilesTab[i] = CPLStrdup(OGR_F_GetFieldAsString( hFeature, ti_field ));
            if (i == 0)
	      {
                GDALDatasetH hDS = GDALOpen(existingFilesTab[i], GA_ReadOnly );
                if (hDS)
		  {
                    alreadyExistingProjectionRefValid = TRUE;
                    alreadyExistingProjectionRef = CPLStrdup(GDALGetProjectionRef(hDS));
                    GDALClose(hDS);
		  }
	      }
            OGR_F_Destroy( hFeature );
	  }
      }

    if (write_absolute_path)
      {
        current_path = CPLGetCurrentDir();
        if (current_path == NULL)
	  {
            fprintf( stderr, "This system does not support the CPLGetCurrentDir call. "
		     "The option -write_absolute_path will have no effect\n");
            write_absolute_path = FALSE;
	  }
      }

      
    /* -------------------------------------------------------------------- */
    /*      loop over GDAL files, processing.                               */
    /* -------------------------------------------------------------------- */
    DIR *dirp = opendir(pszDataDir);
    if(dirp==NULL){
      char tmp1[1024];
      sprintf(tmp1,_ss("The specified path %s doesn't exist."),pszDataDir);
      setMapInMaps(conf,"lenv","message",tmp1);
      return SERVICE_FAILED;
    }
    char *res=NULL;
    struct dirent *dp;
    tmpMap=getMapFromMaps(inputs,"ext","value");
    char *ext;
    if(tmpMap!=NULL)
      ext=tmpMap->value;
    while ((dp = readdir(dirp)) != NULL){
      
      if(strlen(dp->d_name)>2 && strstr(dp->d_name,".")!=0 && strstr(dp->d_name,ext)>0){
	char* argv=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+2)*sizeof(char));
	sprintf(argv,"%s/%s",pszDataDir,dp->d_name);


        GDALDatasetH	hDS;
        double	        adfGeoTransform[6];
        double		adfX[5], adfY[5];
        int		nXSize, nYSize;
        char* fileNameToWrite;
        const char* projectionRef;
        VSIStatBuf sStatBuf;
        int k;
        OGRFeatureH hFeature;
        OGRGeometryH hPoly, hRing;

        /* Make sure it is a file before building absolute path name */
        if (write_absolute_path && CPLIsFilenameRelative( argv ) &&
            VSIStat( argv, &sStatBuf ) == 0)
	  {
            fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv));
	  }
        else
	  {
            fileNameToWrite = CPLStrdup(argv);
	  }

        /* Checks that file is not already in tileindex */
        for(i=0;i<nExistingFiles;i++)
	  {
            if (EQUAL(fileNameToWrite, existingFilesTab[i]))
	      {
                fprintf(stderr, "File %s is already in tileindex. Skipping it.\n",
                        fileNameToWrite);
                break;
	      }
	  }
        if (i != nExistingFiles)
	  {
            CPLFree(fileNameToWrite);
            continue;
	  }

        hDS = GDALOpen( argv, GA_ReadOnly );
        if( hDS == NULL )
	  {
            fprintf( stderr, "Unable to open %s, skipping.\n", 
                     argv );
            CPLFree(fileNameToWrite);
	    continue;
	  }

        GDALGetGeoTransform( hDS, adfGeoTransform );
        if( adfGeoTransform[0] == 0.0 
            && adfGeoTransform[1] == 1.0
            && adfGeoTransform[3] == 0.0
            && ABS(adfGeoTransform[5]) == 1.0 )
	  {
            fprintf( stderr, 
                     "It appears no georeferencing is available for\n"
                     "`%s', skipping.\n", 
                     argv );
            GDALClose( hDS );
            CPLFree(fileNameToWrite);
            continue;
	  }

        projectionRef = GDALGetProjectionRef(hDS);
        if (alreadyExistingProjectionRefValid)
	  {
            int projectionRefNotNull, alreadyExistingProjectionRefNotNull;
            projectionRefNotNull = projectionRef && projectionRef[0];
            alreadyExistingProjectionRefNotNull = alreadyExistingProjectionRef && alreadyExistingProjectionRef[0];
            if ((projectionRefNotNull &&
                 alreadyExistingProjectionRefNotNull &&
                 EQUAL(projectionRef, alreadyExistingProjectionRef) == 0) ||
                (projectionRefNotNull != alreadyExistingProjectionRefNotNull))
	      {
                fprintf(stderr, "Warning : %s is not using the same projection system as "
			"other files in the tileindex. This may cause problems when "
			"using it in MapServer for example.%s\n", argv,
			(skip_different_projection) ? " Skipping it" : "");
                if (skip_different_projection)
		  {
                    CPLFree(fileNameToWrite);
                    GDALClose( hDS );
                    continue;
		  }
	      }
	  }
        else
	  {
            alreadyExistingProjectionRefValid = TRUE;
            alreadyExistingProjectionRef = CPLStrdup(projectionRef);
	  }

        nXSize = GDALGetRasterXSize( hDS );
        nYSize = GDALGetRasterYSize( hDS );
        
        adfX[0] = adfGeoTransform[0] 
	  + 0 * adfGeoTransform[1] 
	  + 0 * adfGeoTransform[2];
        adfY[0] = adfGeoTransform[3] 
	  + 0 * adfGeoTransform[4] 
	  + 0 * adfGeoTransform[5];
        
        adfX[1] = adfGeoTransform[0] 
	  + nXSize * adfGeoTransform[1] 
	  + 0 * adfGeoTransform[2];
        adfY[1] = adfGeoTransform[3] 
	  + nXSize * adfGeoTransform[4] 
	  + 0 * adfGeoTransform[5];
        
        adfX[2] = adfGeoTransform[0] 
	  + nXSize * adfGeoTransform[1] 
	  + nYSize * adfGeoTransform[2];
        adfY[2] = adfGeoTransform[3] 
	  + nXSize * adfGeoTransform[4] 
	  + nYSize * adfGeoTransform[5];
        
        adfX[3] = adfGeoTransform[0] 
	  + 0 * adfGeoTransform[1] 
	  + nYSize * adfGeoTransform[2];
        adfY[3] = adfGeoTransform[3] 
	  + 0 * adfGeoTransform[4] 
	  + nYSize * adfGeoTransform[5];
        
        adfX[4] = adfGeoTransform[0] 
	  + 0 * adfGeoTransform[1] 
	  + 0 * adfGeoTransform[2];
        adfY[4] = adfGeoTransform[3] 
	  + 0 * adfGeoTransform[4] 
	  + 0 * adfGeoTransform[5];

        hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );
        OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite );

        hPoly = OGR_G_CreateGeometry(wkbPolygon);
        hRing = OGR_G_CreateGeometry(wkbLinearRing);
        for(k=0;k<5;k++)
	  OGR_G_SetPoint_2D(hRing, k, adfX[k], adfY[k]);
        OGR_G_AddGeometryDirectly( hPoly, hRing );
        OGR_F_SetGeometryDirectly( hFeature, hPoly );

        if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE )
	  {
	    fprintf( stderr, "Failed to create feature in shapefile.\n" );
	    break;
	  }

        OGR_F_Destroy( hFeature );

        
        CPLFree(fileNameToWrite);

        GDALClose( hDS );
      }
    }
    
    CPLFree(current_path);
    
    if (nExistingFiles)
      {
        for(i=0;i<nExistingFiles;i++)
	  {
            CPLFree(existingFilesTab[i]);
	  }
        CPLFree(existingFilesTab);
      }
    CPLFree(alreadyExistingProjectionRef);

    OGR_DS_Destroy( hTileIndexDS );
    
    GDALDestroyDriverManager();
    OGRCleanupAll();
    setMapInMaps(outputs,"Result","value","Tile index successfully created.");
    //CSLDestroy(argv);
    
    return SERVICE_SUCCEEDED;
  } 
示例#6
0
/**
 * Check the validity of the csv file named pszFilename.  If it is valid, return
 * the format version of the data.
 *
 * 1 -> original windninja format, in use until 3.2.0 (TODO(kyle):update
 * version)
 * 2 -> format after implemententing the station fetch functionality.
 *
 * 3 -> csv that stores the actual timeseries files (all format 2)
 *
 * 4 -> csv that stores the actual current data files (all format 2)
 *
 * If the header is not valid, return -1;
 *
 * \param pszFilename the path of the file to test
 *
 * \return -1 if the file is invalid in anyway, or the version of the file(1 or
 * 2,3,4).
 */
int wxStation::GetHeaderVersion(const char *pszFilename)
{
    OGRDataSourceH hDS = NULL;
    hDS = OGROpen(pszFilename, FALSE, NULL);
    int rc = 0;
    if (hDS == NULL) {
        return -1;
    }
    OGRLayerH hLayer = NULL;
    hLayer = OGR_DS_GetLayer(hDS, 0);
    if (hLayer == NULL) {
        rc = -1;
    }
    OGRFeatureDefnH hDefn = NULL;
    hDefn = OGR_L_GetLayerDefn(hLayer);
    if (hDefn == NULL) {
        rc = -1;
    }
    // If we failed to open or get metadata, bail
    if (rc == -1) {
        OGR_DS_Destroy(hDS);
        return -1;
    }
    
    OGRFieldDefnH hFldDefo = NULL;
    hFldDefo = OGR_FD_GetFieldDefn(hDefn, 0);
    if(EQUAL(OGR_Fld_GetNameRef(hFldDefo),"Station_File_List")){
        return 3; //List of station files with time data
    }
    OGRFieldDefnH hFldDefp = NULL;
    hFldDefp = OGR_FD_GetFieldDefn(hDefn, 0);
    if(EQUAL(OGR_Fld_GetNameRef(hFldDefp),"Recent_Station_File_List")){
        return 4; //list of station files with no time data, but datetimecolumn
    }
    
    /*
    ** Iterate through the expected columns.  If the layer doesn't runs out of
    ** fields before we get to the end of the expected header, GetFieldDefn() will
    ** return NULL, so there is no explicit count check needed.
    */
    const char *oldSpeedHeadStr="Speed_Units(mph,kph,mps)";
    int n = CSLCount((char **)apszValidHeader1); //Number of fields in old header
    int n2 = CSLCount((char **)apszValidHeader2); //Number of fields in new header
    int xt = OGR_FD_GetFieldCount(hDefn); //Number of fields in File of Interest

    //Check the number of fields in the file
    //if the number of fields isn't even equal, kill it before we check
    if (xt!=n) //If it doesn't equal the old header...
    { //Check the new header...
        if(xt!=n2) //if it doesn't equal the new header size....
        { //kill it
            return -1;
        }
    }

    /* We'll use our index later to check for more fields */
    int i = 0;
    assert(rc == 0);
    OGRFieldDefnH hFldDefn = NULL;
    for (i = 0; i < n; i++) {
        hFldDefn = OGR_FD_GetFieldDefn(hDefn, i);
        if (hFldDefn == NULL) {
            rc = -1;
        }
        if (!EQUAL(OGR_Fld_GetNameRef(hFldDefn), apszValidHeader1[i])) {
            if(!EQUAL(OGR_Fld_GetNameRef(hFldDefn), oldSpeedHeadStr))
            {
                rc = -1;
            }
        }
    }
    // If we failed to get version 1 columns, bail
    if (rc == -1) {
        OGR_DS_Destroy(hDS);
        return -1;
    }
    /*
    ** Now we have a valid header for version 1.  If there are more fields, we
    ** check them.  If not, we are done.
    **
    ** TODO(kyle): should we accept a version 1 file with extra non-valid fields?
    */
    rc = 1;
    if (OGR_FD_GetFieldCount(hDefn) > n) {
        if (!EQUAL(OGR_Fld_GetNameRef(hFldDefn), apszValidHeader2[i])) {
            /* If we silently except version 1 files, return 1 here. */
            rc = -1;
        }
        rc = 2;
    }
    OGR_DS_Destroy(hDS);
    return rc;
}
示例#7
0
  int Gdal_Contour(maps*& conf,maps*& inputs,maps*& outputs)
#endif
{
    fprintf(stderr,"DEBUG HELLO %f %d\n",__FILE__,__LINE__);
    fflush(stderr);
    GDALDatasetH	hSrcDS;
    int i, b3D = FALSE, bNoDataSet = FALSE, bIgnoreNoData = FALSE;
    int nBandIn = 1;
    double dfInterval = 0.0, dfNoData = 0.0, dfOffset = 0.0;
    const char *pszSrcFilename = NULL;
    const char *pszDstFilename = NULL;
    const char *pszElevAttrib = NULL;
    const char *pszFormat = "ESRI Shapefile";
    char        **papszDSCO = NULL, **papszLCO = NULL;
    double adfFixedLevels[1000];
    int    nFixedLevelCount = 0;
    const char *pszNewLayerName = "contour";
    int bQuiet = FALSE;
    GDALProgressFunc pfnProgress = NULL;
    fprintf(stderr,"DEBUG HELLO %f %d\n",__FILE__,__LINE__);
    fflush(stderr);
#ifndef ZOO_SERVICE
    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }
#endif
    GDALAllRegister();
    OGRRegisterAll();

#ifndef ZOO_SERVICE
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i], "--help") )
            Usage();
        else if( EQUAL(argv[i],"-a") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszElevAttrib = argv[++i];
        }
        else if( EQUAL(argv[i],"-off") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            dfOffset = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-i") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            dfInterval = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-fl") )
        {
            if( i >= argc-1 )
                Usage(CPLSPrintf("%s option requires at least 1 argument", argv[i]));
            while( i < argc-1 
                   && nFixedLevelCount 
                             < (int)(sizeof(adfFixedLevels)/sizeof(double))
                   && ArgIsNumeric(argv[i+1]) )
                adfFixedLevels[nFixedLevelCount++] = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-b") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            nBandIn = atoi(argv[++i]);
        }
        else if( EQUAL(argv[i],"-f") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszFormat = argv[++i];
        }
        else if( EQUAL(argv[i],"-dsco") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszDSCO = CSLAddString(papszDSCO, argv[++i] );
        }
        else if( EQUAL(argv[i],"-lco") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszLCO = CSLAddString(papszLCO, argv[++i] );
        }
        else if( EQUAL(argv[i],"-3d")  )
        {
            b3D = TRUE;
        }
        else if( EQUAL(argv[i],"-snodata") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            bNoDataSet = TRUE;
            dfNoData = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-nln") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszNewLayerName = argv[++i];
        }
        else if( EQUAL(argv[i],"-inodata") )
        {
            bIgnoreNoData = TRUE;
        }
        else if ( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") )
        {
            bQuiet = TRUE;
        }
        else if( pszSrcFilename == NULL )
        {
            pszSrcFilename = argv[i];
        }
        else if( pszDstFilename == NULL )
        {
            pszDstFilename = argv[i];
        }
        else
            Usage("Too many command options.");
    }
#else
    bQuiet = TRUE;
    bIgnoreNoData = TRUE;
    map* tmpMap=NULL;
    tmpMap=NULL;
    tmpMap=getMapFromMaps(inputs,"a","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      pszElevAttrib = strdup(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"off","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      dfOffset = atof(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"i","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      dfInterval = atof(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"b","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      nBandIn = atoi(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"InputDSN","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      pszSrcFilename = strdup(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"OutputDSN","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      pszDstFilename = strdup(tmpMap->value);
    }
#endif
    if( dfInterval == 0.0 && nFixedLevelCount == 0 )
    {
        Usage("Neither -i nor -fl are specified.");
    }

    if (pszSrcFilename == NULL)
    {
        Usage("Missing source filename.");
    }

    if (pszDstFilename == NULL)
    {
        Usage("Missing destination filename.");
    }
    
    if (!bQuiet)
        pfnProgress = GDALTermProgress;

/* -------------------------------------------------------------------- */
/*      Open source raster file.                                        */
/* -------------------------------------------------------------------- */
    GDALRasterBandH hBand;

    hSrcDS = GDALOpen( pszSrcFilename, GA_ReadOnly );
    if( hSrcDS == NULL ){
#ifndef ZOO_SERVICE
        exit( 2 );
#else
	setMapInMaps(conf,"lenv","message","Unable to open the file");
#endif
    }
    hBand = GDALGetRasterBand( hSrcDS, nBandIn );
    if( hBand == NULL )
    {
#ifndef ZOO_SERVICE
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Band %d does not exist on dataset.", 
                  nBandIn );
        exit(2);
#else
	char tmp[1024];
	sprintf(tmp,"Band %d does not exist on dataset.",nBandIn);
	setMapInMaps(conf,"lenv","message",tmp);
	return SERVICE_FAILED;
#endif
    }

    if( !bNoDataSet && !bIgnoreNoData )
        dfNoData = GDALGetRasterNoDataValue( hBand, &bNoDataSet );

/* -------------------------------------------------------------------- */
/*      Try to get a coordinate system from the raster.                 */
/* -------------------------------------------------------------------- */
    OGRSpatialReferenceH hSRS = NULL;

    const char *pszWKT = GDALGetProjectionRef( hSrcDS );

    if( pszWKT != NULL && strlen(pszWKT) != 0 )
        hSRS = OSRNewSpatialReference( pszWKT );

/* -------------------------------------------------------------------- */
/*      Create the outputfile.                                          */
/* -------------------------------------------------------------------- */
    OGRDataSourceH hDS;
    OGRSFDriverH hDriver = OGRGetDriverByName( pszFormat );
    OGRFieldDefnH hFld;
    OGRLayerH hLayer;

    if( hDriver == NULL )
    {
#ifndef ZOO_SERVICE
        fprintf( stderr, "Unable to find format driver named %s.\n", 
                 pszFormat );
        exit( 10 );
#else
	char tmp[1024];
        sprintf( tmp, "Unable to find format driver named %s.\n", pszFormat );	
	setMapInMaps(conf,"lenv","message",tmp);
	return SERVICE_FAILED;
#endif
    }

    hDS = OGR_Dr_CreateDataSource( hDriver, pszDstFilename, papszDSCO );
    if( hDS == NULL ){
#ifndef ZOO_SERVICE
        exit( 1 );
#else
	setMapInMaps(conf,"lenv","message","Unable to create the file");
	return SERVICE_FAILED;
#endif
    }

    hLayer = OGR_DS_CreateLayer( hDS, pszNewLayerName, hSRS, 
                                 b3D ? wkbLineString25D : wkbLineString,
                                 papszLCO );
    if( hLayer == NULL )
        exit( 1 );

    hFld = OGR_Fld_Create( "ID", OFTInteger );
    OGR_Fld_SetWidth( hFld, 8 );
    OGR_L_CreateField( hLayer, hFld, FALSE );
    OGR_Fld_Destroy( hFld );

    if( pszElevAttrib )
    {
        hFld = OGR_Fld_Create( pszElevAttrib, OFTReal );
        OGR_Fld_SetWidth( hFld, 12 );
        OGR_Fld_SetPrecision( hFld, 3 );
        OGR_L_CreateField( hLayer, hFld, FALSE );
        OGR_Fld_Destroy( hFld );
    }

/* -------------------------------------------------------------------- */
/*      Invoke.                                                         */
/* -------------------------------------------------------------------- */
    CPLErr eErr;
    
    eErr = GDALContourGenerate( hBand, dfInterval, dfOffset, 
                         nFixedLevelCount, adfFixedLevels,
                         bNoDataSet, dfNoData, hLayer, 
                         OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), 
                                               "ID" ), 
                         (pszElevAttrib == NULL) ? -1 :
                                 OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), 
                                                       pszElevAttrib ), 
                         pfnProgress, NULL );

    OGR_DS_Destroy( hDS );
    GDALClose( hSrcDS );

    if (hSRS)
        OSRDestroySpatialReference( hSRS );

#ifndef ZOO_SERVICE
    CSLDestroy( argv );
    CSLDestroy( papszDSCO );
    CSLDestroy( papszLCO );
    GDALDestroyDriverManager();
    OGRCleanupAll();
    return 0;
#else
    GDALDestroyDriverManager();
    OGRCleanupAll();
    char tmp[1024];
    sprintf(tmp,"File %s successfully created.",pszDstFilename);
    setMapInMaps(outputs,"Result","value",tmp);
    return SERVICE_SUCCEEDED;
#endif
}
示例#8
0
文件: nitfdump.c 项目: Mavrx-inc/gdal
int main( int nArgc, char ** papszArgv )

{
    NITFFile	*psFile;
    int          iSegment, iFile;
    char         szTemp[100];
    int          bDisplayTRE = FALSE;
    int          bExtractSHP = FALSE, bExtractSHPInMem = FALSE;

    if( nArgc < 2 )
    {
        printf( "Usage: nitfdump [-tre] [-extractshp | -extractshpinmem] <nitf_filename>*\n" );
        exit( 1 );
    }

    for( iFile = 1; iFile < nArgc; iFile++ )
    {
        if ( EQUAL(papszArgv[iFile], "-tre") )
            bDisplayTRE = TRUE;
        else if ( EQUAL(papszArgv[iFile], "-extractshp") )
            bExtractSHP = TRUE;
        else if ( EQUAL(papszArgv[iFile], "-extractshpinmem") )
        {
            bExtractSHP = TRUE;
            bExtractSHPInMem = TRUE;
        }
    }

/* ==================================================================== */
/*      Loop over all files.                                            */
/* ==================================================================== */
    for( iFile = 1; iFile < nArgc; iFile++ )
    {
        int bHasFoundLocationTable = FALSE;

        if ( EQUAL(papszArgv[iFile], "-tre") )
            continue;
        if ( EQUAL(papszArgv[iFile], "-extractshp") )
            continue;
        if ( EQUAL(papszArgv[iFile], "-extractshpinmem") )
            continue;

/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
        psFile = NITFOpen( papszArgv[iFile], FALSE );
        if( psFile == NULL )
            exit( 2 );

        printf( "Dump for %s\n", papszArgv[iFile] );

/* -------------------------------------------------------------------- */
/*      Dump first TRE list.                                            */
/* -------------------------------------------------------------------- */
        if( psFile->pachTRE != NULL )
        {
            int nTREBytes = psFile->nTREBytes;
            const char *pszTREData = psFile->pachTRE;


            printf( "File TREs:" );

            while( nTREBytes > 10 )
            {
                int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 ));
                if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11)
                {
                    NITFGetField(szTemp, pszTREData, 0, 6 );
                    printf(" Invalid size (%d) for TRE %s", nThisTRESize, szTemp);
                    break;
                }

                printf( " %6.6s(%d)", pszTREData, nThisTRESize );
                pszTREData += nThisTRESize + 11;
                nTREBytes -= (nThisTRESize + 11);
            }
            printf( "\n" );

            if (bDisplayTRE)
            {
                nTREBytes = psFile->nTREBytes;
                pszTREData = psFile->pachTRE;

                while( nTREBytes > 10 )
                {
                    char *pszEscaped;
                    int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 ));
                    if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11)
                    {
                        break;
                    }

                    pszEscaped = CPLEscapeString( pszTREData + 11, nThisTRESize,
                                                       CPLES_BackslashQuotable );
                    printf( "TRE '%6.6s' : %s\n", pszTREData, pszEscaped);
                    CPLFree(pszEscaped);

                    pszTREData += nThisTRESize + 11;
                    nTREBytes -= (nThisTRESize + 11);
                }
            }
        }

/* -------------------------------------------------------------------- */
/*      Dump Metadata                                                   */
/* -------------------------------------------------------------------- */
        DumpMetadata( "File Metadata:", "  ", psFile->papszMetadata );

/* -------------------------------------------------------------------- */
/*      Dump general info about segments.                               */
/* -------------------------------------------------------------------- */
        NITFCollectAttachments( psFile );
        NITFReconcileAttachments( psFile );

        for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ )
        {
            NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment;

            printf( "Segment %d (Type=%s):\n",
                    iSegment + 1, psSegInfo->szSegmentType );

            printf( "  HeaderStart=" CPL_FRMT_GUIB ", HeaderSize=%u, DataStart=" CPL_FRMT_GUIB ", DataSize=" CPL_FRMT_GUIB "\n",
                    psSegInfo->nSegmentHeaderStart,
                    psSegInfo->nSegmentHeaderSize,
                    psSegInfo->nSegmentStart,
                    psSegInfo->nSegmentSize );
            printf( "  DLVL=%d, ALVL=%d, LOC=C%d,R%d, CCS=C%d,R%d\n",
                    psSegInfo->nDLVL,
                    psSegInfo->nALVL,
                    psSegInfo->nLOC_C,
                    psSegInfo->nLOC_R,
                    psSegInfo->nCCS_C,
                    psSegInfo->nCCS_R );
            printf( "\n" );
        }

/* -------------------------------------------------------------------- */
/*      Report details of images.                                       */
/* -------------------------------------------------------------------- */
        for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ )
        {
            NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment;
            NITFImage *psImage;
            NITFRPC00BInfo sRPCInfo;
            int iBand;
            char **papszMD;

            if( !EQUAL(psSegInfo->szSegmentType,"IM") )
                continue;

            psImage = NITFImageAccess( psFile, iSegment );
            if( psImage == NULL )
            {
                printf( "NITFAccessImage(%d) failed!\n", iSegment );
                continue;
            }

            printf( "Image Segment %d, %dPx%dLx%dB x %dbits:\n",
                    iSegment + 1, psImage->nCols, psImage->nRows,
                    psImage->nBands, psImage->nBitsPerSample );
            printf( "  PVTYPE=%s, IREP=%s, ICAT=%s, IMODE=%c, IC=%s, COMRAT=%s, ICORDS=%c\n",
                    psImage->szPVType, psImage->szIREP, psImage->szICAT,
                    psImage->chIMODE, psImage->szIC, psImage->szCOMRAT,
                    psImage->chICORDS );
            if( psImage->chICORDS != ' ' )
            {
                printf( "  UL=(%.15g,%.15g), UR=(%.15g,%.15g) Center=%d\n  LL=(%.15g,%.15g), LR=(%.15g,%.15g)\n",
                        psImage->dfULX, psImage->dfULY,
                        psImage->dfURX, psImage->dfURY,
                        psImage->bIsBoxCenterOfPixel,
                        psImage->dfLLX, psImage->dfLLY,
                        psImage->dfLRX, psImage->dfLRY );
            }

            printf( "  IDLVL=%d, IALVL=%d, ILOC R=%d,C=%d, IMAG=%s\n",
                    psImage->nIDLVL, psImage->nIALVL,
                    psImage->nILOCRow, psImage->nILOCColumn,
                    psImage->szIMAG );

            printf( "  %d x %d blocks of size %d x %d\n",
                    psImage->nBlocksPerRow, psImage->nBlocksPerColumn,
                    psImage->nBlockWidth, psImage->nBlockHeight );

            if( psImage->pachTRE != NULL )
            {
                int nTREBytes = psImage->nTREBytes;
                const char *pszTREData = psImage->pachTRE;

                printf( "  Image TREs:" );

                while( nTREBytes > 10 )
                {
                    int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 ));
                    if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11)
                    {
                        NITFGetField(szTemp, pszTREData, 0, 6 );
                        printf(" Invalid size (%d) for TRE %s", nThisTRESize, szTemp);
                        break;
                    }

                    printf( " %6.6s(%d)", pszTREData, nThisTRESize );
                    pszTREData += nThisTRESize + 11;
                    nTREBytes -= (nThisTRESize + 11);
                }
                printf( "\n" );

                if (bDisplayTRE)
                {
                    nTREBytes = psImage->nTREBytes;
                    pszTREData = psImage->pachTRE;

                    while( nTREBytes > 10 )
                    {
                        char *pszEscaped;
                        int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 ));
                        if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11)
                        {
                            break;
                        }

                        pszEscaped = CPLEscapeString( pszTREData + 11, nThisTRESize,
                                                        CPLES_BackslashQuotable );
                        printf( "  TRE '%6.6s' : %s\n", pszTREData, pszEscaped);
                        CPLFree(pszEscaped);

                        pszTREData += nThisTRESize + 11;
                        nTREBytes -= (nThisTRESize + 11);
                    }
                }
            }

            /* Report info from location table, if found.                  */
            if( psImage->nLocCount > 0 )
            {
                int i;
                bHasFoundLocationTable = TRUE;
                printf( "  Location Table\n" );
                for( i = 0; i < psImage->nLocCount; i++ )
                {
                    printf( "    LocName=%s, LocId=%d, Offset=%u, Size=%u\n",
                            GetLocationNameFromId(psImage->pasLocations[i].nLocId),
                            psImage->pasLocations[i].nLocId,
                            psImage->pasLocations[i].nLocOffset,
                            psImage->pasLocations[i].nLocSize );
                }
                printf( "\n" );
            }

            if( strlen(psImage->pszComments) > 0 )
                printf( "  Comments:\n%s\n", psImage->pszComments );

            for( iBand = 0; iBand < psImage->nBands; iBand++ )
            {
                NITFBandInfo *psBandInfo = psImage->pasBandInfo + iBand;

                printf( "  Band %d: IREPBAND=%s, ISUBCAT=%s, %d LUT entries.\n",
                        iBand + 1, psBandInfo->szIREPBAND, psBandInfo->szISUBCAT,
                        psBandInfo->nSignificantLUTEntries );
            }

            if( NITFReadRPC00B( psImage, &sRPCInfo ) )
            {
                DumpRPC( psImage, &sRPCInfo );
            }

            papszMD = NITFReadUSE00A( psImage );
            if( papszMD != NULL )
            {
                DumpMetadata( "  USE00A TRE:", "    ", papszMD );
                CSLDestroy( papszMD );
            }

            papszMD = NITFReadBLOCKA( psImage );
            if( papszMD != NULL )
            {
                DumpMetadata( "  BLOCKA TRE:", "    ", papszMD );
                CSLDestroy( papszMD );
            }

            papszMD = NITFReadSTDIDC( psImage );
            if( papszMD != NULL )
            {
                DumpMetadata( "  STDIDC TRE:", "    ", papszMD );
                CSLDestroy( papszMD );
            }

            DumpMetadata( "  Image Metadata:", "    ", psImage->papszMetadata );
            printf("\n");
        }

/* ==================================================================== */
/*      Report details of graphic segments.                             */
/* ==================================================================== */
        for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ )
        {
            NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment;
            char achSubheader[298];
            int  nSTYPEOffset;

            if( !EQUAL(psSegInfo->szSegmentType,"GR")
                && !EQUAL(psSegInfo->szSegmentType,"SY") )
                continue;

/* -------------------------------------------------------------------- */
/*      Load the graphic subheader.                                     */
/* -------------------------------------------------------------------- */
            if( VSIFSeekL( psFile->fp, psSegInfo->nSegmentHeaderStart,
                           SEEK_SET ) != 0
                || VSIFReadL( achSubheader, 1, sizeof(achSubheader),
                              psFile->fp ) < 258 )
            {
                CPLError( CE_Warning, CPLE_FileIO,
                          "Failed to read graphic subheader at " CPL_FRMT_GUIB ".",
                          psSegInfo->nSegmentHeaderStart );
                continue;
            }

            // NITF 2.0. (also works for NITF 2.1)
            nSTYPEOffset = 200;
            if( STARTS_WITH_CI(achSubheader+193, "999998") )
                nSTYPEOffset += 40;

/* -------------------------------------------------------------------- */
/*      Report some standard info.                                      */
/* -------------------------------------------------------------------- */
            printf( "Graphic Segment %d, type=%2.2s, sfmt=%c, sid=%10.10s\n",
                    iSegment + 1,
                    achSubheader + 0,
                    achSubheader[nSTYPEOffset],
                    achSubheader + 2 );

            printf( "  sname=%20.20s\n", achSubheader + 12 );
            printf("\n");
        }

/* ==================================================================== */
/*      Report details of text segments.                                */
/* ==================================================================== */
        for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ )
        {
            char *pabyHeaderData;
            char *pabyTextData;

            NITFSegmentInfo *psSegment = psFile->pasSegmentInfo + iSegment;

            if( !EQUAL(psSegment->szSegmentType,"TX") )
                continue;

            printf( "Text Segment %d\n", iSegment + 1);

/* -------------------------------------------------------------------- */
/*      Load the text header                                            */
/* -------------------------------------------------------------------- */

            /* Allocate one extra byte for the NULL terminating character */
            pabyHeaderData = (char *) CPLCalloc(1,
                    (size_t) psSegment->nSegmentHeaderSize + 1);
            if (VSIFSeekL(psFile->fp, psSegment->nSegmentHeaderStart,
                        SEEK_SET) != 0 ||
                VSIFReadL(pabyHeaderData, 1, (size_t) psSegment->nSegmentHeaderSize,
                        psFile->fp) != psSegment->nSegmentHeaderSize)
            {
                CPLError( CE_Warning, CPLE_FileIO,
                        "Failed to read %d bytes of text header data at " CPL_FRMT_GUIB ".",
                        psSegment->nSegmentHeaderSize,
                        psSegment->nSegmentHeaderStart);
                CPLFree(pabyHeaderData);
                continue;
            }

            printf("  Header : %s\n", pabyHeaderData);
            CPLFree(pabyHeaderData);

/* -------------------------------------------------------------------- */
/*      Load the raw TEXT data itself.                                  */
/* -------------------------------------------------------------------- */


            /* Allocate one extra byte for the NULL terminating character */
            pabyTextData = (char *) CPLCalloc(1,(size_t)psSegment->nSegmentSize+1);
            if( VSIFSeekL( psFile->fp, psSegment->nSegmentStart,
                        SEEK_SET ) != 0
                || VSIFReadL( pabyTextData, 1, (size_t)psSegment->nSegmentSize,
                            psFile->fp ) != psSegment->nSegmentSize )
            {
                CPLError( CE_Warning, CPLE_FileIO,
                        "Failed to read " CPL_FRMT_GUIB " bytes of text data at " CPL_FRMT_GUIB ".",
                        psSegment->nSegmentSize,
                        psSegment->nSegmentStart );
                CPLFree( pabyTextData );
                continue;
            }

            printf("  Data  : %s\n", pabyTextData);
            printf("\n");
            CPLFree( pabyTextData );

        }

/* -------------------------------------------------------------------- */
/*      Report details of DES.                                          */
/* -------------------------------------------------------------------- */
        for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ )
        {
            NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment;
            NITFDES *psDES;
            int nOffset = 0;
            char szTREName[7];
            int nThisTRESize;
            int nRPFDESOffset = -1;

            if( !EQUAL(psSegInfo->szSegmentType,"DE") )
                continue;

            psDES = NITFDESAccess( psFile, iSegment );
            if( psDES == NULL )
            {
                printf( "NITFDESAccess(%d) failed!\n", iSegment );
                continue;
            }

            printf( "DE Segment %d:\n", iSegment + 1 );

            printf( "  Segment TREs:" );
            nOffset = 0;
            while (NITFDESGetTRE( psDES, nOffset, szTREName, NULL, &nThisTRESize))
            {
                printf( " %6.6s(%d)", szTREName, nThisTRESize );
                if (strcmp(szTREName, "RPFDES") == 0)
                    nRPFDESOffset = nOffset + 11;
                nOffset += 11 + nThisTRESize;
            }
            printf( "\n" );

            if (bDisplayTRE)
            {
                char* pabyTREData = NULL;
                nOffset = 0;
                while (NITFDESGetTRE( psDES, nOffset, szTREName, &pabyTREData, &nThisTRESize))
                {
                    char* pszEscaped = CPLEscapeString( pabyTREData, nThisTRESize,
                                                        CPLES_BackslashQuotable );
                    printf( "  TRE '%6.6s' : %s\n", szTREName, pszEscaped);
                    CPLFree(pszEscaped);

                    nOffset += 11 + nThisTRESize;

                    NITFDESFreeTREData(pabyTREData);
                }
            }

            /* Report info from location table, if found. */
            if( !bHasFoundLocationTable && nRPFDESOffset >= 0 )
            {
                int i;
                int nLocCount = 0;
                NITFLocation* pasLocations;

                VSIFSeekL(psFile->fp, psSegInfo->nSegmentStart + nRPFDESOffset, SEEK_SET);
                pasLocations = NITFReadRPFLocationTable(psFile->fp, &nLocCount);
                if (pasLocations)
                {
                    printf( "  Location Table\n" );
                    for( i = 0; i < nLocCount; i++ )
                    {
                        printf( "    LocName=%s, LocId=%d, Offset=%u, Size=%u\n",
                                GetLocationNameFromId(pasLocations[i].nLocId),
                                pasLocations[i].nLocId,
                                pasLocations[i].nLocOffset,
                                pasLocations[i].nLocSize );
                    }

                    CPLFree(pasLocations);
                    printf( "\n" );
                }
            }

            DumpMetadata( "  DES Metadata:", "    ", psDES->papszMetadata );

            if ( bExtractSHP && CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE_USE") != NULL )
            {
                char szFilename[32];
                char szRadix[32];
                if (bExtractSHPInMem)
                    snprintf(szRadix, sizeof(szRadix), "/vsimem/nitf_segment_%d", iSegment + 1);
                else
                    snprintf(szRadix, sizeof(szRadix), "nitf_segment_%d", iSegment + 1);

                if (NITFDESExtractShapefile(psDES, szRadix))
                {
                    OGRDataSourceH hDS;
                    OGRRegisterAll();
                    snprintf(szFilename, sizeof(szFilename), "%s.SHP", szRadix);
                    hDS = OGROpen(szFilename, FALSE, NULL);
                    if (hDS)
                    {
                        int nGeom = 0;
                        OGRLayerH hLayer = OGR_DS_GetLayer(hDS, 0);
                        if (hLayer)
                        {
                            OGRFeatureH hFeat;
                            printf("\n");
                            while ( (hFeat = OGR_L_GetNextFeature(hLayer)) != NULL )
                            {
                                OGRGeometryH hGeom = OGR_F_GetGeometryRef(hFeat);
                                if (hGeom)
                                {
                                    char* pszWKT = NULL;
                                    OGR_G_ExportToWkt(hGeom, &pszWKT);
                                    if (pszWKT)
                                        printf("    Geometry %d : %s\n", nGeom ++, pszWKT);
                                    CPLFree(pszWKT);
                                }
                                OGR_F_Destroy(hFeat);
                            }
                        }
                        OGR_DS_Destroy(hDS);
                    }
                }

                if (bExtractSHPInMem)
                {
                    snprintf(szFilename, sizeof(szFilename), "%s.SHP", szRadix);
                    VSIUnlink(szFilename);
                    snprintf(szFilename, sizeof(szFilename), "%s.SHX", szRadix);
                    VSIUnlink(szFilename);
                    snprintf(szFilename, sizeof(szFilename), "%s.DBF", szRadix);
                    VSIUnlink(szFilename);
                }
            }
        }

/* -------------------------------------------------------------------- */
/*      Close.                                                          */
/* -------------------------------------------------------------------- */
        NITFClose( psFile );
    }

    CPLFinderClean();
    CPLCleanupTLS();
    VSICleanupFileManager();
    OGRCleanupAll();

    exit( 0 );
}
示例#9
0
QgsShapeFile::~QgsShapeFile()
{
  OGR_DS_Destroy( ogrDataSource );
}
示例#10
0
void VectorClose( OGRDataSource * poDS )
{
	OGR_DS_Destroy(poDS);
}
示例#11
0
QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& userStyleElem, QgsRasterLayer* rasterLayer ) const
{
  QgsDebugMsg( "Entering." );

  if ( !rasterLayer )
  {
    return nullptr;
  }

  //get <ContourSymbolizer> element
  QDomNodeList contourNodeList = userStyleElem.elementsByTagName( QStringLiteral( "ContourSymbolizer" ) );
  if ( contourNodeList.size() < 1 )
  {
    return nullptr;
  }

  QDomElement contourSymbolizerElem = contourNodeList.item( 0 ).toElement();
  if ( contourSymbolizerElem.isNull() )
  {
    return nullptr;
  }

  double equidistance, minValue, maxValue, offset;
  QString propertyName;

  equidistance = contourSymbolizerElem.attribute( QStringLiteral( "equidistance" ) ).toDouble();
  minValue = contourSymbolizerElem.attribute( QStringLiteral( "minValue" ) ).toDouble();
  maxValue = contourSymbolizerElem.attribute( QStringLiteral( "maxValue" ) ).toDouble();
  offset = contourSymbolizerElem.attribute( QStringLiteral( "offset" ) ).toDouble();
  propertyName = contourSymbolizerElem.attribute( QStringLiteral( "propertyName" ) );

  if ( equidistance <= 0.0 )
  {
    return nullptr;
  }

  QTemporaryFile* tmpFile1 = new QTemporaryFile();
  tmpFile1->open();
  mFilesToRemove.push_back( tmpFile1 );
  QString tmpBaseName = tmpFile1->fileName();
  QString tmpFileName = tmpBaseName + ".shp";

  //hack: use gdal_contour first to write into a temporary file
  /* todo: use GDALContourGenerate( hBand, dfInterval, dfOffset,
                                nFixedLevelCount, adfFixedLevels,
                                bNoDataSet, dfNoData,
                                hLayer, 0, nElevField,
                                GDALTermProgress, nullptr );*/


  //do the stuff that is also done in the main method of gdal_contour...
  /* -------------------------------------------------------------------- */
  /*      Open source raster file.                                        */
  /* -------------------------------------------------------------------- */
  GDALRasterBandH hBand;
  GDALDatasetH hSrcDS;

  int numberOfLevels = 0;
  double currentLevel = 0.0;

  if ( maxValue > minValue )
  {
    //find first level
    currentLevel = ( int )(( minValue - offset ) / equidistance + 0.5 ) * equidistance + offset;
    while ( currentLevel <= maxValue )
    {
      ++numberOfLevels;
      currentLevel += equidistance;
    }
  }

  double *adfFixedLevels = new double[numberOfLevels];
  int    nFixedLevelCount = numberOfLevels;
  currentLevel = ( int )(( minValue - offset ) / equidistance + 0.5 ) * equidistance + offset;
  for ( int i = 0; i < numberOfLevels; ++i )
  {
    adfFixedLevels[i] = currentLevel;
    currentLevel += equidistance;
  }
  int nBandIn = 1;
  double dfInterval = equidistance, dfNoData = 0.0, dfOffset = offset;

  int /* b3D = FALSE, */ bNoDataSet = FALSE, bIgnoreNoData = FALSE;

  hSrcDS = GDALOpen( rasterLayer->source().toUtf8().constData(), GA_ReadOnly );
  if ( !hSrcDS )
  {
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) );
  }

  hBand = GDALGetRasterBand( hSrcDS, nBandIn );
  if ( !hBand )
  {
    CPLError( CE_Failure, CPLE_AppDefined,
              "Band %d does not exist on dataset.",
              nBandIn );
  }

  if ( !bNoDataSet && !bIgnoreNoData )
    dfNoData = GDALGetRasterNoDataValue( hBand, &bNoDataSet );

  /* -------------------------------------------------------------------- */
  /*      Try to get a coordinate system from the raster.                 */
  /* -------------------------------------------------------------------- */
  OGRSpatialReferenceH hSRS = nullptr;

  const char *pszWKT = GDALGetProjectionRef( hBand );

  if ( pszWKT && strlen( pszWKT ) != 0 )
    hSRS = OSRNewSpatialReference( pszWKT );

  /* -------------------------------------------------------------------- */
  /*      Create the outputfile.                                          */
  /* -------------------------------------------------------------------- */
  OGRDataSourceH hDS;
  OGRSFDriverH hDriver = OGRGetDriverByName( "ESRI Shapefile" );
  OGRFieldDefnH hFld;
  OGRLayerH hLayer;
  int nElevField = -1;

  if ( !hDriver )
  {
    //fprintf( FCGI_stderr, "Unable to find format driver named 'ESRI Shapefile'.\n" );
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) );
  }

  hDS = OGR_Dr_CreateDataSource( hDriver, tmpFileName.toUtf8().constData(), nullptr );
  if ( !hDS )
  {
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request cannot create data source." ) );
  }

  hLayer = OGR_DS_CreateLayer( hDS, "contour", hSRS,
                               /* b3D ? wkbLineString25D : */ wkbLineString,
                               nullptr );
  if ( !hLayer )
  {
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request could not create contour file." ) );
  }

  hFld = OGR_Fld_Create( "ID", OFTInteger );
  OGR_Fld_SetWidth( hFld, 8 );
  OGR_L_CreateField( hLayer, hFld, FALSE );
  OGR_Fld_Destroy( hFld );

  if ( !propertyName.isEmpty() )
  {
    hFld = OGR_Fld_Create( propertyName.toUtf8().constData(), OFTReal );
    OGR_Fld_SetWidth( hFld, 12 );
    OGR_Fld_SetPrecision( hFld, 3 );
    OGR_L_CreateField( hLayer, hFld, FALSE );
    OGR_Fld_Destroy( hFld );
    nElevField = 1;
  }

  /* -------------------------------------------------------------------- */
  /*      Invoke.                                                         */
  /* -------------------------------------------------------------------- */
  GDALContourGenerate( hBand, dfInterval, dfOffset,
                       nFixedLevelCount, adfFixedLevels,
                       bNoDataSet, dfNoData,
                       hLayer, 0, nElevField,
                       GDALTermProgress, nullptr );

  delete [] adfFixedLevels;

  OGR_DS_Destroy( hDS );
  GDALClose( hSrcDS );

  //todo: store those three files elsewhere...
  //mark shp, dbf and shx to delete after the request
  mFilePathsToRemove.push_back( tmpBaseName + ".shp" );
  mFilePathsToRemove.push_back( tmpBaseName + ".dbf" );
  mFilePathsToRemove.push_back( tmpBaseName + ".shx" );

  QgsVectorLayer* contourLayer = new QgsVectorLayer( tmpFileName, QStringLiteral( "layer" ), QStringLiteral( "ogr" ) );

  //create renderer
  QgsFeatureRenderer* theRenderer = rendererFromUserStyle( userStyleElem, contourLayer );
  contourLayer->setRenderer( theRenderer );

  //add labeling if requested
  labelSettingsFromUserStyle( userStyleElem, contourLayer );

  QgsDebugMsg( "Returning the contour layer" );
  return contourLayer;
}
示例#12
0
int main(int argc, char *argv[])
{
    const char* pszIndexLayerName = NULL;
    const char *index_filename = NULL;
    const char *tile_index = "location";
    const char* pszDriverName = "ESRI Shapefile";
    size_t nMaxFieldSize = 254;
    int		i_arg, ti_field;
    OGRDataSourceH hTileIndexDS;
    OGRLayerH hLayer = NULL;
    OGRFeatureDefnH hFDefn;
    int write_absolute_path = FALSE;
    char* current_path = NULL;
    int i;
    int nExistingFiles;
    int skip_different_projection = FALSE;
    char** existingFilesTab = NULL;
    int alreadyExistingProjectionRefValid = FALSE;
    char* alreadyExistingProjectionRef = NULL;
    const char *pszTargetSRS = "";
    int bSetTargetSRS = FALSE;
    OGRSpatialReferenceH hTargetSRS = NULL;
    const char* pszSrcSRSName = NULL;
    int i_SrcSRSName = -1;
    int bSrcSRSFormatSpecified = FALSE;
    SrcSRSFormat eSrcSRSFormat = FORMAT_AUTO;

    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }

    GDALAllRegister();
    OGRRegisterAll();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Get commandline arguments other than the GDAL raster filenames. */
/* -------------------------------------------------------------------- */
    for( i_arg = 1; i_arg < argc; i_arg++ )
    {
        if( EQUAL(argv[i_arg], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i_arg],"--help") )
            Usage(NULL);
        else if( strcmp(argv[i_arg],"-f") == 0 )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszDriverName = argv[++i_arg];
            if( !EQUAL(pszDriverName, "ESRI Shapefile") )
                nMaxFieldSize = 0;
        }
        else if( strcmp(argv[i_arg],"-lyr_name") == 0 )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszIndexLayerName = argv[++i_arg];
        }
        else if( strcmp(argv[i_arg],"-tileindex") == 0 )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            tile_index = argv[++i_arg];
        }
        else if( strcmp(argv[i_arg],"-t_srs") == 0 )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszTargetSRS = argv[++i_arg];
            bSetTargetSRS = TRUE;
        }
        else if ( strcmp(argv[i_arg],"-write_absolute_path") == 0 )
        {
            write_absolute_path = TRUE;
        }
        else if ( strcmp(argv[i_arg],"-skip_different_projection") == 0 )
        {
            skip_different_projection = TRUE;
        }
        else if( strcmp(argv[i_arg], "-src_srs_name") == 0 )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszSrcSRSName = argv[++i_arg];
        }
        else if( strcmp(argv[i_arg], "-src_srs_format") == 0 )
        {
            const char* pszFormat;
            bSrcSRSFormatSpecified = TRUE;
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszFormat = argv[++i_arg];
            if( EQUAL(pszFormat, "AUTO") )
                eSrcSRSFormat = FORMAT_AUTO;
            else if( EQUAL(pszFormat, "WKT") )
                eSrcSRSFormat = FORMAT_WKT;
            else if( EQUAL(pszFormat, "EPSG") )
                eSrcSRSFormat = FORMAT_EPSG;
            else if( EQUAL(pszFormat, "PROJ") )
                eSrcSRSFormat = FORMAT_PROJ;
        }
        else if( argv[i_arg][0] == '-' )
            Usage(CPLSPrintf("Unknown option name '%s'", argv[i_arg]));
        else if( index_filename == NULL )
        {
            index_filename = argv[i_arg];
            i_arg++;
            break;
        }
    }
 
    if( index_filename == NULL )
        Usage("No index filename specified.");
    if( i_arg == argc )
        Usage("No file to index specified.");
    if( bSrcSRSFormatSpecified && pszSrcSRSName == NULL )
        Usage("-src_srs_name must be specified when -src_srs_format is specified.");

/* -------------------------------------------------------------------- */
/*      Create and validate target SRS if given.                        */
/* -------------------------------------------------------------------- */
   if( bSetTargetSRS )
   {  
       if ( skip_different_projection )
       {
           fprintf( stderr, 
                    "Warning : -skip_different_projection does not apply "
                    "when -t_srs is requested.\n" );
       }
       hTargetSRS = OSRNewSpatialReference("");
       if( OSRSetFromUserInput( hTargetSRS, pszTargetSRS ) != CE_None )
       {
           OSRDestroySpatialReference( hTargetSRS );
           fprintf( stderr, "Invalid target SRS `%s'.\n", 
                    pszTargetSRS );
           exit(1);
       }
   }

/* -------------------------------------------------------------------- */
/*      Open or create the target datasource                            */
/* -------------------------------------------------------------------- */
    hTileIndexDS = OGROpen( index_filename, TRUE, NULL );
    if (hTileIndexDS != NULL)
    {
        if( OGR_DS_GetLayerCount(hTileIndexDS) == 1 )
            hLayer = OGR_DS_GetLayer(hTileIndexDS, 0);
        else
        {
            if( pszIndexLayerName == NULL )
            {
                printf( "-lyr_name must be specified.\n" );
                exit( 1 );
            }
            CPLPushErrorHandler(CPLQuietErrorHandler);
            hLayer = OGR_DS_GetLayerByName(hTileIndexDS, pszIndexLayerName);
            CPLPopErrorHandler();
        }
    }
    else
    {
        OGRSFDriverH hDriver;

        printf( "Creating new index file...\n" );
        hDriver = OGRGetDriverByName( pszDriverName );
        if( hDriver == NULL )
        {
            printf( "%s driver not available.\n", pszDriverName );
            exit( 1 );
        }

        hTileIndexDS = OGR_Dr_CreateDataSource( hDriver, index_filename, NULL );
    }

    if( hTileIndexDS != NULL && hLayer == NULL )
    {
        OGRSpatialReferenceH hSpatialRef = NULL;
        char* pszLayerName;
        if( pszIndexLayerName == NULL )
        {
            VSIStatBuf sStat;
            if( EQUAL(pszDriverName, "ESRI Shapefile") ||
                VSIStat(index_filename, &sStat) == 0 )
                pszLayerName = CPLStrdup(CPLGetBasename(index_filename));
            else
            {
                printf( "-lyr_name must be specified.\n" );
                exit( 1 );
            }
        }
        else
            pszLayerName = CPLStrdup(pszIndexLayerName);

        /* get spatial reference for output file from target SRS (if set) */
        /* or from first input file */
        if( bSetTargetSRS )
        {
            hSpatialRef = OSRClone( hTargetSRS );
        }
        else
        {
            GDALDatasetH hDS = GDALOpen( argv[i_arg], GA_ReadOnly );
            if (hDS)
            {
                const char* pszWKT = GDALGetProjectionRef(hDS);
                if (pszWKT != NULL && pszWKT[0] != '\0')
                {
                    hSpatialRef = OSRNewSpatialReference(pszWKT);
                }
                GDALClose(hDS);
            }
        }

        hLayer = OGR_DS_CreateLayer( hTileIndexDS, pszLayerName, hSpatialRef, wkbPolygon, NULL );
        CPLFree(pszLayerName);
        if (hSpatialRef)
            OSRRelease(hSpatialRef);

        if (hLayer)
        {
            OGRFieldDefnH hFieldDefn = OGR_Fld_Create( tile_index, OFTString );
            if( nMaxFieldSize )
                OGR_Fld_SetWidth( hFieldDefn, nMaxFieldSize);
            OGR_L_CreateField( hLayer, hFieldDefn, TRUE );
            OGR_Fld_Destroy(hFieldDefn);
            if( pszSrcSRSName != NULL )
            {
                hFieldDefn = OGR_Fld_Create( pszSrcSRSName, OFTString );
                if( nMaxFieldSize )
                    OGR_Fld_SetWidth( hFieldDefn, nMaxFieldSize);
                OGR_L_CreateField( hLayer, hFieldDefn, TRUE );
                OGR_Fld_Destroy(hFieldDefn);
            }
        }
    }

    if( hTileIndexDS == NULL || hLayer == NULL )
    {
        fprintf( stderr, "Unable to open/create shapefile `%s'.\n", 
                 index_filename );
        exit(2);
    }

    hFDefn = OGR_L_GetLayerDefn(hLayer);

    ti_field = OGR_FD_GetFieldIndex( hFDefn, tile_index );
    if( ti_field < 0 )
    {
        fprintf( stderr, "Unable to find field `%s' in file `%s'.\n", 
                 tile_index, index_filename );
        exit(2);
    }
    
    if( pszSrcSRSName != NULL )
        i_SrcSRSName = OGR_FD_GetFieldIndex( hFDefn, pszSrcSRSName );

    /* Load in memory existing file names in SHP */
    nExistingFiles = (int)OGR_L_GetFeatureCount(hLayer, FALSE);
    if( nExistingFiles < 0)
        nExistingFiles = 0;
    if (nExistingFiles > 0)
    {
        OGRFeatureH hFeature;
        existingFilesTab = (char**)CPLMalloc(nExistingFiles * sizeof(char*));
        for(i=0;i<nExistingFiles;i++)
        {
            hFeature = OGR_L_GetNextFeature(hLayer);
            existingFilesTab[i] = CPLStrdup(OGR_F_GetFieldAsString( hFeature, ti_field ));
            if (i == 0)
            {
                GDALDatasetH hDS = GDALOpen(existingFilesTab[i], GA_ReadOnly );
                if (hDS)
                {
                    alreadyExistingProjectionRefValid = TRUE;
                    alreadyExistingProjectionRef = CPLStrdup(GDALGetProjectionRef(hDS));
                    GDALClose(hDS);
                }
            }
            OGR_F_Destroy( hFeature );
        }
    }

    if (write_absolute_path)
    {
        current_path = CPLGetCurrentDir();
        if (current_path == NULL)
        {
            fprintf( stderr, "This system does not support the CPLGetCurrentDir call. "
                             "The option -write_absolute_path will have no effect\n");
            write_absolute_path = FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      loop over GDAL files, processing.                               */
/* -------------------------------------------------------------------- */
    for( ; i_arg < argc; i_arg++ )
    {
        GDALDatasetH	hDS;
        double	        adfGeoTransform[6];
        double		adfX[5], adfY[5];
        int		nXSize, nYSize;
        char* fileNameToWrite;
        const char* projectionRef;
        VSIStatBuf sStatBuf;
        int k;
        OGRFeatureH hFeature;
        OGRGeometryH hPoly, hRing;
        OGRSpatialReferenceH hSourceSRS = NULL;

        /* Make sure it is a file before building absolute path name */
        if (write_absolute_path && CPLIsFilenameRelative( argv[i_arg] ) &&
            VSIStat( argv[i_arg], &sStatBuf ) == 0)
        {
            fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv[i_arg]));
        }
        else
        {
            fileNameToWrite = CPLStrdup(argv[i_arg]);
        }

        /* Checks that file is not already in tileindex */
        for(i=0;i<nExistingFiles;i++)
        {
            if (EQUAL(fileNameToWrite, existingFilesTab[i]))
            {
                fprintf(stderr, "File %s is already in tileindex. Skipping it.\n",
                        fileNameToWrite);
                break;
            }
        }
        if (i != nExistingFiles)
        {
            CPLFree(fileNameToWrite);
            continue;
        }

        hDS = GDALOpen( argv[i_arg], GA_ReadOnly );
        if( hDS == NULL )
        {
            fprintf( stderr, "Unable to open %s, skipping.\n", 
                     argv[i_arg] );
            CPLFree(fileNameToWrite);
            continue;
        }

        GDALGetGeoTransform( hDS, adfGeoTransform );
        if( adfGeoTransform[0] == 0.0 
            && adfGeoTransform[1] == 1.0
            && adfGeoTransform[3] == 0.0
            && ABS(adfGeoTransform[5]) == 1.0 )
        {
            fprintf( stderr, 
                     "It appears no georeferencing is available for\n"
                     "`%s', skipping.\n", 
                     argv[i_arg] );
            GDALClose( hDS );
            CPLFree(fileNameToWrite);
            continue;
        }

        projectionRef = GDALGetProjectionRef(hDS);

        /* if not set target srs, test that the current file uses same projection as others */
        if( !bSetTargetSRS )
        { 
            if (alreadyExistingProjectionRefValid)
            {
                int projectionRefNotNull, alreadyExistingProjectionRefNotNull;
                projectionRefNotNull = projectionRef && projectionRef[0];
                alreadyExistingProjectionRefNotNull = alreadyExistingProjectionRef && alreadyExistingProjectionRef[0];
                if ((projectionRefNotNull &&
                     alreadyExistingProjectionRefNotNull &&
                     EQUAL(projectionRef, alreadyExistingProjectionRef) == 0) ||
                    (projectionRefNotNull != alreadyExistingProjectionRefNotNull))
                {
                    fprintf(stderr, "Warning : %s is not using the same projection system as "
                            "other files in the tileindex.\n"
			    "This may cause problems when using it in MapServer for example.\n"
                            "Use -t_srs option to set target projection system (not supported by MapServer).\n"
                            "%s\n", argv[i_arg],
                            (skip_different_projection) ? "Skipping this file." : "");
                    if (skip_different_projection)
                    {
                        CPLFree(fileNameToWrite);
                        GDALClose( hDS );
                        continue;
                    }
                }
            }
            else
            {
                alreadyExistingProjectionRefValid = TRUE;
                alreadyExistingProjectionRef = CPLStrdup(projectionRef);
            }
        }

        nXSize = GDALGetRasterXSize( hDS );
        nYSize = GDALGetRasterYSize( hDS );
        
        adfX[0] = adfGeoTransform[0] 
            + 0 * adfGeoTransform[1] 
            + 0 * adfGeoTransform[2];
        adfY[0] = adfGeoTransform[3] 
            + 0 * adfGeoTransform[4] 
            + 0 * adfGeoTransform[5];
        
        adfX[1] = adfGeoTransform[0] 
            + nXSize * adfGeoTransform[1] 
            + 0 * adfGeoTransform[2];
        adfY[1] = adfGeoTransform[3] 
            + nXSize * adfGeoTransform[4] 
            + 0 * adfGeoTransform[5];
        
        adfX[2] = adfGeoTransform[0] 
            + nXSize * adfGeoTransform[1] 
            + nYSize * adfGeoTransform[2];
        adfY[2] = adfGeoTransform[3] 
            + nXSize * adfGeoTransform[4] 
            + nYSize * adfGeoTransform[5];
        
        adfX[3] = adfGeoTransform[0] 
            + 0 * adfGeoTransform[1] 
            + nYSize * adfGeoTransform[2];
        adfY[3] = adfGeoTransform[3] 
            + 0 * adfGeoTransform[4] 
            + nYSize * adfGeoTransform[5];
        
        adfX[4] = adfGeoTransform[0] 
            + 0 * adfGeoTransform[1] 
            + 0 * adfGeoTransform[2];
        adfY[4] = adfGeoTransform[3] 
            + 0 * adfGeoTransform[4] 
            + 0 * adfGeoTransform[5];

        if( (bSetTargetSRS || i_SrcSRSName >= 0) && projectionRef != NULL && projectionRef[0] != '\0' )
            hSourceSRS = OSRNewSpatialReference( projectionRef );

        /* if set target srs, do the forward transformation of all points */
        if( bSetTargetSRS && projectionRef != NULL && projectionRef[0] != '\0' )
        {
            OGRCoordinateTransformationH hCT = NULL;
            if( hSourceSRS && !OSRIsSame( hSourceSRS, hTargetSRS ) )
            {
                hCT = OCTNewCoordinateTransformation( hSourceSRS, hTargetSRS );
                if( hCT == NULL || !OCTTransform( hCT, 5, adfX, adfY, NULL ) )
                {
                    fprintf( stderr, 
                             "Warning : unable to transform points from source SRS `%s' to target SRS `%s'\n"
                             "for file `%s' - file skipped\n", 
                             projectionRef, pszTargetSRS, fileNameToWrite );
                    if ( hCT ) 
                        OCTDestroyCoordinateTransformation( hCT );
                    if ( hSourceSRS )
                        OSRDestroySpatialReference( hSourceSRS );
                    continue;
                }
                if ( hCT ) 
                    OCTDestroyCoordinateTransformation( hCT );
            }
        }

        hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );
        OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite );

        if( i_SrcSRSName >= 0 && hSourceSRS != NULL )
        {
            const char* pszAuthorityCode = OSRGetAuthorityCode(hSourceSRS, NULL);
            const char* pszAuthorityName = OSRGetAuthorityName(hSourceSRS, NULL);
            if( eSrcSRSFormat == FORMAT_AUTO )
            {
                if( pszAuthorityName != NULL && pszAuthorityCode != NULL )
                    OGR_F_SetFieldString( hFeature, i_SrcSRSName,
                                        CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) );
                else if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize )
                    OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef );
                else
                {
                    char* pszProj4 = NULL;
                    if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE )
                    {
                        OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 );
                        CPLFree(pszProj4);
                    }
                    else
                        OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef );
                }
            }
            else if( eSrcSRSFormat == FORMAT_WKT )
            {
                if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize )
                    OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef );
            }
            else if( eSrcSRSFormat == FORMAT_PROJ )
            {
                char* pszProj4 = NULL;
                if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE )
                {
                    OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 );
                    CPLFree(pszProj4);
                }
            }
            else if( eSrcSRSFormat == FORMAT_EPSG )
            {
                if( pszAuthorityName != NULL && pszAuthorityCode != NULL )
                    OGR_F_SetFieldString( hFeature, i_SrcSRSName,
                                        CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) );
            }
        }
        if( hSourceSRS )
            OSRDestroySpatialReference( hSourceSRS );

        hPoly = OGR_G_CreateGeometry(wkbPolygon);
        hRing = OGR_G_CreateGeometry(wkbLinearRing);
        for(k=0;k<5;k++)
            OGR_G_SetPoint_2D(hRing, k, adfX[k], adfY[k]);
        OGR_G_AddGeometryDirectly( hPoly, hRing );
        OGR_F_SetGeometryDirectly( hFeature, hPoly );

        if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE )
        {
           printf( "Failed to create feature in shapefile.\n" );
           break;
        }

        OGR_F_Destroy( hFeature );

        
        CPLFree(fileNameToWrite);

        GDALClose( hDS );
    }
    
    CPLFree(current_path);
    
    if (nExistingFiles)
    {
        for(i=0;i<nExistingFiles;i++)
        {
            CPLFree(existingFilesTab[i]);
        }
        CPLFree(existingFilesTab);
    }
    CPLFree(alreadyExistingProjectionRef);

    if ( hTargetSRS )
        OSRDestroySpatialReference( hTargetSRS );

    OGR_DS_Destroy( hTileIndexDS );
    
    GDALDestroyDriverManager();
    OGRCleanupAll();
    CSLDestroy(argv);
    
    exit( 0 );
} 
示例#13
0
文件: field.c 项目: caomw/grass
/* return -1 on error */
static int read_dblinks_ogr(struct Map_info *Map)
{
    struct dblinks *dbl;
    
    dbl = Map->dblnk;
    G_debug(3, "Searching for FID column in OGR DB");
#ifndef HAVE_OGR
    G_warning(_("GRASS is not compiled with OGR support"));
#else
#if GDAL_VERSION_NUM > 1320 && HAVE_OGR /* seems to be fixed after 1320 release */
    int nLayers;
    char *ogr_fid_col;
    
    G_debug(3, "GDAL_VERSION_NUM: %d", GDAL_VERSION_NUM);
    
    if (Map->fInfo.ogr.ds == NULL) {
	/* open the connection to fetch the FID column name */
	OGRRegisterAll();
	
	/* data source handle */
	Map->fInfo.ogr.ds = OGROpen(Map->fInfo.ogr.dsn, FALSE, NULL);
	if (Map->fInfo.ogr.ds == NULL) {
            G_warning(_("Unable to open OGR data source '%s'"),
                      Map->fInfo.ogr.dsn);
            return -1;
        }
    }
    if (Map->fInfo.ogr.layer == NULL) {
	/* get layer number */
	nLayers = OGR_DS_GetLayerCount(Map->fInfo.ogr.ds);	/* Layers = Maps in OGR DB */
	
	G_debug(3, "%d layers (maps) found in data source", nLayers);
	
	G_debug(3, "Trying to open OGR layer: %s", Map->fInfo.ogr.layer_name);
	if (Map->fInfo.ogr.layer_name) {
	    Map->fInfo.ogr.layer = OGR_DS_GetLayerByName(Map->fInfo.ogr.ds, Map->fInfo.ogr.layer_name);
	    if (Map->fInfo.ogr.layer == NULL) {
		OGR_DS_Destroy(Map->fInfo.ogr.ds);
		Map->fInfo.ogr.ds = NULL;
		G_warning(_("Unable to open OGR layer <%s>"),
                          Map->fInfo.ogr.layer_name);
                return -1;
	    }
	}
    }
    
    /* get fid column */
    ogr_fid_col = G_store(OGR_L_GetFIDColumn(Map->fInfo.ogr.layer));
    G_debug(3, "Using FID column <%s> in OGR DB", ogr_fid_col);
    Vect_add_dblink(dbl, 1,  Map->fInfo.ogr.layer_name,
		    Map->fInfo.ogr.layer_name, ogr_fid_col,
		    Map->fInfo.ogr.dsn, "ogr");
#else
	dbDriver *driver;
	dbCursor cursor;
	dbString sql;
	int FID = 0, OGC_FID = 0, OGR_FID = 0, GID = 0;

	G_debug(3, "GDAL_VERSION_NUM: %d", GDAL_VERSION_NUM);

	/* FID is not available for all OGR drivers */
	db_init_string(&sql);

	driver = db_start_driver_open_database("ogr", Map->fInfo.ogr.dsn);

	if (driver == NULL) {
	    G_warning(_("Unable to open OGR DBMI driver"));
	    return -1;
	}

	/* this is a bit stupid, but above FID auto-detection doesn't work yet...: */
	db_auto_print_errors(0);
	sprintf(buf, "select FID from %s where FID > 0",
		Map->fInfo.ogr.layer_name);
	db_set_string(&sql, buf);

	if (db_open_select_cursor(driver, &sql, &cursor, DB_SEQUENTIAL) !=
	    DB_OK) {
	    /* FID not available, so we try ogc_fid */
	    G_debug(3, "Failed. Now searching for ogc_fid column in OGR DB");
	    sprintf(buf, "select ogc_fid from %s where ogc_fid > 0",
		    Map->fInfo.ogr.layer_name);
	    db_set_string(&sql, buf);

	    if (db_open_select_cursor(driver, &sql, &cursor, DB_SEQUENTIAL) !=
		DB_OK) {
		/* Neither FID nor ogc_fid available, so we try ogr_fid */
		G_debug(3,
			"Failed. Now searching for ogr_fid column in OGR DB");
		sprintf(buf, "select ogr_fid from %s where ogr_fid > 0",
			Map->fInfo.ogr.layer_name);
		db_set_string(&sql, buf);

		if (db_open_select_cursor
		    (driver, &sql, &cursor, DB_SEQUENTIAL) != DB_OK) {
		    /* Neither FID nor ogc_fid available, so we try gid */
		    G_debug(3,
			    "Failed. Now searching for gid column in OGR DB");
		    sprintf(buf, "select gid from %s where gid > 0",
			    Map->fInfo.ogr.layer_name);
		    db_set_string(&sql, buf);

		    if (db_open_select_cursor
			(driver, &sql, &cursor, DB_SEQUENTIAL) != DB_OK) {
			/* neither FID nor ogc_fid nor ogr_fid nor gid available */
			G_warning(_("All FID tests failed. Neither 'FID' nor 'ogc_fid' "
				   "nor 'ogr_fid' nor 'gid' available in OGR DB table"));
			db_close_database_shutdown_driver(driver);
			return 0;
		    }
		    else
			GID = 1;
		}
		else
		    OGR_FID = 1;
	    }
	    else
		OGC_FID = 1;
	}
	else
	    FID = 1;

	G_debug(3, "FID: %d, OGC_FID: %d, OGR_FID: %d, GID: %d", FID, OGC_FID,
		OGR_FID, GID);

	db_close_cursor(&cursor);
	db_close_database_shutdown_driver(driver);
	db_auto_print_errors(1);

	if (FID) {
	    G_debug(3, "Using FID column in OGR DB");
	    Vect_add_dblink(dbl, 1, Map->fInfo.ogr.layer_name, Map->fInfo.ogr.layer_name, "FID",
			    Map->fInfo.ogr.dsn, "ogr");
	}
	else {
	    if (OGC_FID) {
		G_debug(3, "Using ogc_fid column in OGR DB");
		Vect_add_dblink(dbl, 1, Map->fInfo.ogr.layer_name, Map->fInfo.ogr.layer_name,
				"ogc_fid", Map->fInfo.ogr.dsn, "ogr");
	    }
	    else {
		if (OGR_FID) {
		    G_debug(3, "Using ogr_fid column in OGR DB");
		    Vect_add_dblink(dbl, 1, Map->fInfo.ogr.layer_name, Map->fInfo.ogr.layer_name,
				    "ogr_fid", Map->fInfo.ogr.dsn, "ogr");
		}
		else {
		    if (GID) {
			G_debug(3, "Using gid column in OGR DB");
			Vect_add_dblink(dbl, 1, Map->fInfo.ogr.layer_name,
					Map->fInfo.ogr.layer_name, "gid",
					Map->fInfo.ogr.dsn, "ogr");
		    }
		}
	    }
	}
#endif /* GDAL_VERSION_NUM > 1320 && HAVE_OGR */
	return 1;
#endif	/* HAVE_GDAL */
}
示例#14
0
    void object::test<3>()
    {
        OGRErr err = OGRERR_NONE;

        OGRDataSourceH ds = NULL;
        ds = OGR_Dr_CreateDataSource(drv_, data_tmp_.c_str(), NULL);
        ensure("Can't open or create data source", NULL != ds);

        // Create memory Layer
        OGRLayerH lyr = NULL;
        lyr = OGR_DS_CreateLayer(ds, "tpoly", NULL, wkbPolygon, NULL);
        ensure("Can't create layer", NULL != lyr);

        // Create schema
        OGRFieldDefnH fld = NULL;

        fld = OGR_Fld_Create("AREA", OFTReal);
        err = OGR_L_CreateField(lyr, fld, true);
        OGR_Fld_Destroy(fld);
        ensure_equals("Can't create field", OGRERR_NONE, err);

        fld = OGR_Fld_Create("EAS_ID", OFTInteger);
        err = OGR_L_CreateField(lyr, fld, true);
        OGR_Fld_Destroy(fld);
        ensure_equals("Can't create field", OGRERR_NONE, err);

        fld = OGR_Fld_Create("PRFEDEA", OFTString);
        err = OGR_L_CreateField(lyr, fld, true);
        OGR_Fld_Destroy(fld);
        ensure_equals("Can't create field", OGRERR_NONE, err);

        // Check schema
        OGRFeatureDefnH featDefn = OGR_L_GetLayerDefn(lyr);
        ensure("Layer schema is NULL", NULL != featDefn);
        ensure_equals("Fields creation failed", 3, OGR_FD_GetFieldCount(featDefn));

        // Copy ogr/poly.shp to temporary layer
        OGRFeatureH featDst = OGR_F_Create(featDefn);
        ensure("Can't create empty feature", NULL != featDst);

        std::string source(data_);
        source += SEP;
        source += "poly.shp";
        OGRDataSourceH dsSrc = OGR_Dr_Open(drv_, source.c_str(), false);
        ensure("Can't open source layer", NULL != dsSrc);

        OGRLayerH lyrSrc = OGR_DS_GetLayer(dsSrc, 0);
        ensure("Can't get source layer", NULL != lyrSrc);

        OGRFeatureH featSrc = NULL;
        while (NULL != (featSrc = OGR_L_GetNextFeature(lyrSrc)))
        {
            err = OGR_F_SetFrom(featDst, featSrc, true);
            ensure_equals("Can't set festure from source", OGRERR_NONE, err);

            err = OGR_L_CreateFeature(lyr, featDst);
            ensure_equals("Can't write feature to layer", OGRERR_NONE, err);

            OGR_F_Destroy(featSrc);
        }

        // Release and close resources
        OGR_F_Destroy(featDst);
        OGR_DS_Destroy(dsSrc);
        OGR_DS_Destroy(ds);
    }
示例#15
0
  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":20
 *     def __init__(self, path):
 *         self.path = path
 *         self._collections = None             # <<<<<<<<<<<<<< 
 * 
 *     def _read_collections(self):
 */
  Py_INCREF(Py_None);
  Py_DECREF(((struct __pyx_obj_4mill_9workspace_Workspace *)__pyx_v_self)->_collections);
  ((struct __pyx_obj_4mill_9workspace_Workspace *)__pyx_v_self)->_collections = Py_None;

  __pyx_r = 0;
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_path);
  return __pyx_r;
}

static PyObject *__pyx_n_range;

static PyObject *__pyx_builtin_range;

static PyObject *__pyx_pf_4mill_9workspace_9Workspace__read_collections(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static PyObject *__pyx_pf_4mill_9workspace_9Workspace__read_collections(PyObject *__pyx_v_self, PyObject *unused) {
  void *__pyx_v_cogr_ds;
  void *__pyx_v_cogr_layer;
  void *__pyx_v_cogr_layerdefn;
  PyObject *__pyx_v_collections;
  PyObject *__pyx_v_n;
  PyObject *__pyx_v_i;
  PyObject *__pyx_v_layer_name;
  PyObject *__pyx_v_collection;
  PyObject *__pyx_r;
  PyObject *__pyx_1 = 0;
  char *__pyx_2;
  Py_ssize_t __pyx_3;
  PyObject *__pyx_4 = 0;
  int __pyx_5;
  PyObject *__pyx_6 = 0;
  PyObject *__pyx_7 = 0;
  Py_INCREF(__pyx_v_self);
  __pyx_v_collections = Py_None; Py_INCREF(Py_None);
  __pyx_v_n = Py_None; Py_INCREF(Py_None);
  __pyx_v_i = Py_None; Py_INCREF(Py_None);
  __pyx_v_layer_name = Py_None; Py_INCREF(Py_None);
  __pyx_v_collection = Py_None; Py_INCREF(Py_None);

  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":26
 *         cdef void * cogr_layer
 *         cdef void * cogr_layerdefn
 *         collections = {}             # <<<<<<<<<<<<<< 
 * 
 *         # start session
 */
  __pyx_1 = PyDict_New(); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; goto __pyx_L1;}
  Py_DECREF(__pyx_v_collections);
  __pyx_v_collections = __pyx_1;
  __pyx_1 = 0;

  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":29
 * 
 *         # start session
 *         cogr_ds = ograpi.OGROpen(self.path, 0, NULL)             # <<<<<<<<<<<<<< 
 * 
 *         n = ograpi.OGR_DS_GetLayerCount(cogr_ds)
 */
  __pyx_2 = PyString_AsString(((struct __pyx_obj_4mill_9workspace_Workspace *)__pyx_v_self)->path); if (unlikely((!__pyx_2) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; goto __pyx_L1;}
  __pyx_v_cogr_ds = OGROpen(__pyx_2,0,NULL);

  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":31
 *         cogr_ds = ograpi.OGROpen(self.path, 0, NULL)
 * 
 *         n = ograpi.OGR_DS_GetLayerCount(cogr_ds)             # <<<<<<<<<<<<<< 
 *         for i in range(n):
 *             cogr_layer = ograpi.OGR_DS_GetLayer(cogr_ds, i)
 */
  __pyx_1 = PyInt_FromLong(OGR_DS_GetLayerCount(__pyx_v_cogr_ds)); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; goto __pyx_L1;}
  Py_DECREF(__pyx_v_n);
  __pyx_v_n = __pyx_1;
  __pyx_1 = 0;

  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":32
 * 
 *         n = ograpi.OGR_DS_GetLayerCount(cogr_ds)
 *         for i in range(n):             # <<<<<<<<<<<<<< 
 *             cogr_layer = ograpi.OGR_DS_GetLayer(cogr_ds, i)
 *             cogr_layerdefn = ograpi.OGR_L_GetLayerDefn(cogr_layer)
 */
  __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;}
  Py_INCREF(__pyx_v_n);
  PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_n);
  __pyx_4 = PyObject_CallObject(__pyx_builtin_range, __pyx_1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  if (PyList_CheckExact(__pyx_4)) { __pyx_3 = 0; __pyx_1 = __pyx_4; Py_INCREF(__pyx_1); }
  else { __pyx_1 = PyObject_GetIter(__pyx_4); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; goto __pyx_L1;} }
  Py_DECREF(__pyx_4); __pyx_4 = 0;
  for (;;) {
    if (PyList_CheckExact(__pyx_1)) { if (__pyx_3 >= PyList_GET_SIZE(__pyx_1)) break; __pyx_4 = PyList_GET_ITEM(__pyx_1, __pyx_3++); Py_INCREF(__pyx_4); }
    else {
      __pyx_4 = PyIter_Next(__pyx_1);
      if (!__pyx_4) {
        break;
      }
    }
    Py_DECREF(__pyx_v_i);
    __pyx_v_i = __pyx_4;
    __pyx_4 = 0;

    /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":33
 *         n = ograpi.OGR_DS_GetLayerCount(cogr_ds)
 *         for i in range(n):
 *             cogr_layer = ograpi.OGR_DS_GetLayer(cogr_ds, i)             # <<<<<<<<<<<<<< 
 *             cogr_layerdefn = ograpi.OGR_L_GetLayerDefn(cogr_layer)
 *             layer_name = ograpi.OGR_FD_GetName(cogr_layerdefn)
 */
    __pyx_5 = PyInt_AsLong(__pyx_v_i); if (unlikely((__pyx_5 == -1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; goto __pyx_L1;}
    __pyx_v_cogr_layer = OGR_DS_GetLayer(__pyx_v_cogr_ds,__pyx_5);

    /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":34
 *         for i in range(n):
 *             cogr_layer = ograpi.OGR_DS_GetLayer(cogr_ds, i)
 *             cogr_layerdefn = ograpi.OGR_L_GetLayerDefn(cogr_layer)             # <<<<<<<<<<<<<< 
 *             layer_name = ograpi.OGR_FD_GetName(cogr_layerdefn)
 *             collection = Collection(layer_name, self)
 */
    __pyx_v_cogr_layerdefn = OGR_L_GetLayerDefn(__pyx_v_cogr_layer);

    /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":35
 *             cogr_layer = ograpi.OGR_DS_GetLayer(cogr_ds, i)
 *             cogr_layerdefn = ograpi.OGR_L_GetLayerDefn(cogr_layer)
 *             layer_name = ograpi.OGR_FD_GetName(cogr_layerdefn)             # <<<<<<<<<<<<<< 
 *             collection = Collection(layer_name, self)
 *             collections[layer_name] = collection
 */
    __pyx_4 = PyString_FromString(OGR_FD_GetName(__pyx_v_cogr_layerdefn)); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; goto __pyx_L1;}
    Py_DECREF(__pyx_v_layer_name);
    __pyx_v_layer_name = __pyx_4;
    __pyx_4 = 0;

    /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":36
 *             cogr_layerdefn = ograpi.OGR_L_GetLayerDefn(cogr_layer)
 *             layer_name = ograpi.OGR_FD_GetName(cogr_layerdefn)
 *             collection = Collection(layer_name, self)             # <<<<<<<<<<<<<< 
 *             collections[layer_name] = collection
 *         
 */
    __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_Collection); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    __pyx_6 = PyTuple_New(2); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    Py_INCREF(__pyx_v_layer_name);
    PyTuple_SET_ITEM(__pyx_6, 0, __pyx_v_layer_name);
    Py_INCREF(__pyx_v_self);
    PyTuple_SET_ITEM(__pyx_6, 1, __pyx_v_self);
    __pyx_7 = PyObject_CallObject(__pyx_4, __pyx_6); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;}
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    Py_DECREF(__pyx_6); __pyx_6 = 0;
    Py_DECREF(__pyx_v_collection);
    __pyx_v_collection = __pyx_7;
    __pyx_7 = 0;

    /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":37
 *             layer_name = ograpi.OGR_FD_GetName(cogr_layerdefn)
 *             collection = Collection(layer_name, self)
 *             collections[layer_name] = collection             # <<<<<<<<<<<<<< 
 *         
 *         # end session
 */
    if (PyObject_SetItem(__pyx_v_collections, __pyx_v_layer_name, __pyx_v_collection) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;}
  }
  Py_DECREF(__pyx_1); __pyx_1 = 0;

  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":40
 *         
 *         # end session
 *         ograpi.OGR_DS_Destroy(cogr_ds)             # <<<<<<<<<<<<<< 
 *         
 *         return collections
 */
  OGR_DS_Destroy(__pyx_v_cogr_ds);

  /* "/home/sean/Projects/WorldMill/src/mill/workspace.pyx":42
 *         ograpi.OGR_DS_Destroy(cogr_ds)
 *         
 *         return collections             # <<<<<<<<<<<<<< 
 * 
 *     property collections:
 */
  Py_INCREF(__pyx_v_collections);
  __pyx_r = __pyx_v_collections;
  goto __pyx_L0;

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_6);
  Py_XDECREF(__pyx_7);
  __Pyx_AddTraceback("mill.workspace.Workspace._read_collections");
  __pyx_r = NULL;
  __pyx_L0:;
  Py_DECREF(__pyx_v_collections);
  Py_DECREF(__pyx_v_n);
  Py_DECREF(__pyx_v_i);
  Py_DECREF(__pyx_v_layer_name);
  Py_DECREF(__pyx_v_collection);
  Py_DECREF(__pyx_v_self);
  return __pyx_r;
}
示例#16
0
文件: OGR.hpp 项目: jorgkv/hexer
    inline bool close() 
    { 
		OGR_DS_Destroy(m_ds);
		m_ds = 0;
        return true; 
    }
bool QgsNewGeoPackageLayerDialog::apply()
{
  QString fileName( mDatabaseEdit->text() );
  bool createNewDb = false;
  if ( QFile( fileName ).exists( fileName ) )
  {
    QMessageBox msgBox;
    msgBox.setIcon( QMessageBox::Question );
    msgBox.setWindowTitle( tr( "The file already exists." ) );
    msgBox.setText( tr( "Do you want to overwrite the existing file with a new database or add a new layer to it ?" ) );
    QPushButton *overwriteButton = msgBox.addButton( tr( "Overwrite" ), QMessageBox::ActionRole );
    QPushButton *addNewLayerButton = msgBox.addButton( tr( "Add new layer" ), QMessageBox::ActionRole );
    msgBox.setStandardButtons( QMessageBox::Cancel );
    msgBox.setDefaultButton( addNewLayerButton );
    bool overwrite = false;
    bool cancel = false;
    if ( property( "hideDialogs" ).toBool() )
    {
      overwrite = property( "question_existing_db_answer_overwrite" ).toBool();
      if ( !overwrite )
        cancel = !property( "question_existing_db_answer_add_new_layer" ).toBool();
    }
    else
    {
      int ret = msgBox.exec();
      if ( ret == QMessageBox::Cancel )
        cancel = true;
      if ( msgBox.clickedButton() == overwriteButton )
        overwrite = true;
    }
    if ( cancel )
    {
      return false;
    }
    if ( overwrite )
    {
      QFile( fileName ).remove();
      createNewDb = true;
    }
  }
  else
  {
    createNewDb = true;
  }

  OGRSFDriverH hGpkgDriver = OGRGetDriverByName( "GPKG" );
  if ( !hGpkgDriver )
  {
    if ( !property( "hideDialogs" ).toBool() )
      QMessageBox::critical( this, tr( "Layer creation failed" ),
                             tr( "GeoPackage driver not found" ) );
    return false;
  }

  OGRDataSourceH hDS = nullptr;
  if ( createNewDb )
  {
    hDS = OGR_Dr_CreateDataSource( hGpkgDriver, fileName.toUtf8().constData(), nullptr );
    if ( !hDS )
    {
      QString msg( tr( "Creation of database failed (OGR error:%1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
      if ( !property( "hideDialogs" ).toBool() )
        QMessageBox::critical( this, tr( "Layer creation failed" ), msg );
      return false;
    }
  }
  else
  {
    OGRSFDriverH hDriver = nullptr;
    hDS = OGROpen( fileName.toUtf8().constData(), true, &hDriver );
    if ( !hDS )
    {
      QString msg( tr( "Opening of database failed (OGR error:%1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
      if ( !property( "hideDialogs" ).toBool() )
        QMessageBox::critical( this, tr( "Layer creation failed" ), msg );
      return false;
    }
    if ( hDriver != hGpkgDriver )
    {
      QString msg( tr( "Opening of file succeeded, but this is not a GeoPackage database" ) );
      if ( !property( "hideDialogs" ).toBool() )
        QMessageBox::critical( this, tr( "Layer creation failed" ), msg );
      OGR_DS_Destroy( hDS );
      return false;
    }
  }

  QString tableName( mTableNameEdit->text() );

  bool overwriteTable = false;
  if ( OGR_DS_GetLayerByName( hDS, tableName.toUtf8().constData() ) != nullptr )
  {
    if ( property( "hideDialogs" ).toBool() )
    {
      overwriteTable = property( "question_existing_layer_answer_overwrite" ).toBool();
    }
    else if ( QMessageBox::question( this, tr( "Existing layer" ),
                                     tr( "A table with the same name already exists. Do you want to overwrite it ?" ),
                                     QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
    {
      overwriteTable = true;
    }

    if ( !overwriteTable )
    {
      OGR_DS_Destroy( hDS );
      return false;
    }
  }

  QString layerIdentifier( mLayerIdentifierEdit->text() );
  QString layerDescription( mLayerDescriptionEdit->text() );

  OGRwkbGeometryType wkbType = static_cast<OGRwkbGeometryType>
                               ( mGeometryTypeBox->itemData( mGeometryTypeBox->currentIndex(), Qt::UserRole ).toInt() );

  OGRSpatialReferenceH hSRS = nullptr;
  // consider spatial reference system of the layer
  int crsId = mCrsSelector->crs().srsid();
  if ( wkbType != wkbNone && crsId > 0 )
  {
    QgsCoordinateReferenceSystem srs( crsId, QgsCoordinateReferenceSystem::InternalCrsId );
    QString srsWkt = srs.toWkt();
    hSRS = OSRNewSpatialReference( srsWkt.toLocal8Bit().data() );
  }

  // Set options
  char **options = nullptr;

  if ( overwriteTable )
    options = CSLSetNameValue( options, "OVERWRITE", "YES" );
  if ( !layerIdentifier.isEmpty() )
    options = CSLSetNameValue( options, "IDENTIFIER", layerIdentifier.toUtf8().constData() );
  if ( !layerDescription.isEmpty() )
    options = CSLSetNameValue( options, "DESCRIPTION", layerDescription.toUtf8().constData() );

  QString featureId( mFeatureIdColumnEdit->text() );
  if ( !featureId.isEmpty() )
    options = CSLSetNameValue( options, "FID", featureId.toUtf8().constData() );

  QString geometryColumn( mGeometryColumnEdit->text() );
  if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
    options = CSLSetNameValue( options, "GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );

#ifdef SUPPORT_SPATIAL_INDEX
  if ( wkbType != wkbNone )
    options = CSLSetNameValue( options, "SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ? "YES" : "NO" );
#endif

  OGRLayerH hLayer = OGR_DS_CreateLayer( hDS, tableName.toUtf8().constData(), hSRS, wkbType, options );
  CSLDestroy( options );
  if ( hSRS != nullptr )
    OSRRelease( hSRS );
  if ( hLayer == nullptr )
  {
    QString msg( tr( "Creation of layer failed (OGR error:%1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
    if ( !property( "hideDialogs" ).toBool() )
      QMessageBox::critical( this, tr( "Layer creation failed" ), msg );
    OGR_DS_Destroy( hDS );
    return false;
  }

  QTreeWidgetItemIterator it( mAttributeView );
  while ( *it )
  {
    QString fieldName(( *it )->text( 0 ) );
    QString fieldType(( *it )->text( 1 ) );
    QString fieldWidth(( *it )->text( 2 ) );

    OGRFieldType ogrType( OFTString );
    if ( fieldType == "text" )
      ogrType = OFTString;
    else if ( fieldType == "integer" )
      ogrType = OFTInteger;
#ifdef SUPPORT_INTEGER64
    else if ( fieldType == "integer64" )
      ogrType = OFTInteger64;
#endif
    else if ( fieldType == "real" )
      ogrType = OFTReal;
    else if ( fieldType == "date" )
      ogrType = OFTDate;
    else if ( fieldType == "datetime" )
      ogrType = OFTDateTime;

    int ogrWidth = fieldWidth.toInt();

    OGRFieldDefnH fld = OGR_Fld_Create( fieldName.toUtf8().constData(), ogrType );
    OGR_Fld_SetWidth( fld, ogrWidth );

    if ( OGR_L_CreateField( hLayer, fld, true ) != OGRERR_NONE )
    {
      if ( !property( "hideDialogs" ).toBool() )
      {
        QMessageBox::critical( this, tr( "Layer creation failed" ),
                               tr( "Creation of field %1 failed (OGR error: %2)" )
                               .arg( fieldName, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
      }
      OGR_Fld_Destroy( fld );
      OGR_DS_Destroy( hDS );
      return false;
    }
    OGR_Fld_Destroy( fld );

    ++it;
  }

  // In GDAL >= 2.0, the driver implements a defered creation strategy, so
  // issue a command that will force table creation
  CPLErrorReset();
  OGR_L_ResetReading( hLayer );
  if ( CPLGetLastErrorType() != CE_None )
  {
    QString msg( tr( "Creation of layer failed (OGR error:%1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
    if ( !property( "hideDialogs" ).toBool() )
      QMessageBox::critical( this, tr( "Layer creation failed" ), msg );
    OGR_DS_Destroy( hDS );
    return false;
  }

  OGR_DS_Destroy( hDS );

  QString uri( QString( "%1|layername=%2" ).arg( mDatabaseEdit->text() ).arg( tableName ) );
  QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier );
  QgsVectorLayer *layer = new QgsVectorLayer( uri, userVisiblelayerName, "ogr" );
  if ( layer->isValid() )
  {
    // register this layer with the central layers registry
    QList<QgsMapLayer *> myList;
    myList << layer;
    //addMapLayers returns a list of all successfully added layers
    //so we compare that to our original list.
    if ( myList == QgsMapLayerRegistry::instance()->addMapLayers( myList ) )
      return true;
  }
  else
  {
    if ( !property( "hideDialogs" ).toBool() )
      QMessageBox::critical( this, tr( "Invalid Layer" ), tr( "%1 is an invalid layer and cannot be loaded." ).arg( tableName ) );
    delete layer;
  }

  return false;
}
示例#18
0
int OGRCCreate(const char *pszFname)
{
    OGRSFDriverH    driver;
    int             i, numDrivers;
    OGRDataSourceH  datasource;
    OGRLayerH       layer;
    OGRFeatureDefnH layerDefn;
    OGRFieldDefnH   fieldDefn;
    OGRFeatureH     feature;
    OGRGeometryH    geometry, ring;

    /* Register all OGR drivers */
    OGRRegisterAll();

    /* Fetch MITAB driver - we want to create a TAB file */
    numDrivers = OGRGetDriverCount();
    for(i=0; i<numDrivers; i++)
    {
        driver = OGRGetDriver(i);
        if (EQUAL("MapInfo File", OGR_Dr_GetName(driver)))
            break;  /* Found it! */
        driver = NULL;
    }

    if (!driver)
    {
        printf("Driver not found!\n");
        return -1;
    }

    /* Create new file using this driver */
    datasource = OGR_Dr_CreateDataSource(driver, pszFname, NULL);

    if (datasource == NULL)
    {
        printf("Unable to create %s\n", pszFname);
        return -1;
    }

    /* MapInfo data sources are created with one empty layer.
       Fetch the layer handle */
    layer = OGR_DS_GetLayer(datasource, 0);

    if (layer == NULL)
    {
        printf("Unable to create new layer in %s\n", pszFname);
        return -1;
    }

    /* Add a few fields to the layer defn */
    fieldDefn = OGR_Fld_Create( "id", OFTInteger );
    OGR_L_CreateField(layer, fieldDefn, 0);

    fieldDefn = OGR_Fld_Create( "area", OFTReal );
    OGR_L_CreateField(layer, fieldDefn, 0);

    fieldDefn = OGR_Fld_Create( "name", OFTString );
    OGR_L_CreateField(layer, fieldDefn, 0);

    /* We'll need the layerDefn handle to create new features in this layer */
    layerDefn = OGR_L_GetLayerDefn( layer );

    /* Create a new point */
    feature = OGR_F_Create( layerDefn );
    OGR_F_SetFieldInteger( feature, 0, 1);
    OGR_F_SetFieldDouble( feature, 1, 123.45);
    OGR_F_SetFieldString( feature, 2, "Feature #1");

    geometry = OGR_G_CreateGeometry( wkbPoint );
    OGR_G_SetPoint(geometry, 0, 123.45, 456.78, 0);

    OGR_F_SetGeometryDirectly(feature, geometry);

    OGR_L_CreateFeature( layer, feature );

    /* Create a new line */
    feature = OGR_F_Create( layerDefn );
    OGR_F_SetFieldInteger( feature, 0, 2);
    OGR_F_SetFieldDouble( feature, 1, 42.45);
    OGR_F_SetFieldString( feature, 2, "Feature #2");

    geometry = OGR_G_CreateGeometry( wkbLineString );
    OGR_G_AddPoint(geometry, 123.45, 456.78, 0);
    OGR_G_AddPoint(geometry, 12.34,  45.67, 0);

    OGR_F_SetGeometryDirectly(feature, geometry);
 
    OGR_L_CreateFeature( layer, feature );

    /* Create a new polygon (square) */
    feature = OGR_F_Create( layerDefn );
    OGR_F_SetFieldInteger( feature, 0, 3);
    OGR_F_SetFieldDouble( feature, 1, 49.71);
    OGR_F_SetFieldString( feature, 2, "Feature #3");

    geometry = OGR_G_CreateGeometry( wkbPolygon );
    ring = OGR_G_CreateGeometry( wkbLinearRing );
    OGR_G_AddPoint(ring, 123.45, 456.78, 0);
    OGR_G_AddPoint(ring, 12.34,  456.78, 0);
    OGR_G_AddPoint(ring, 12.34,  45.67, 0);
    OGR_G_AddPoint(ring, 123.45, 45.67, 0);
    OGR_G_AddPoint(ring, 123.45, 456.78, 0);
    OGR_G_AddGeometryDirectly(geometry, ring);

    OGR_F_SetGeometryDirectly(feature, geometry);
 
    OGR_L_CreateFeature( layer, feature );

    /* Close data source */
    OGR_DS_Destroy( datasource );

    return 0;
}
示例#19
0
  int Delaunay(maps*& conf,maps*& inputs,maps*& outputs){
#ifdef DEBUG
    fprintf(stderr,"\nService internal print\nStarting\n");
#endif
    maps* cursor=inputs;
    OGRGeometryH geometry,res;
    int bufferDistance;
    map* tmpm=NULL;
    OGRRegisterAll();

    std::vector<Point> points;
    if(int res=parseInput(conf,inputs,&points,"/vsimem/tmp")!=SERVICE_SUCCEEDED)
      return res;

    DelaunayT T;
    T.insert(points.begin(), points.end());

    /* -------------------------------------------------------------------- */
    /*      Try opening the output datasource as an existing, writable      */
    /* -------------------------------------------------------------------- */
#if GDAL_VERSION_MAJOR >= 2
    GDALDataset *poODS;
    GDALDriverManager* poR=GetGDALDriverManager();
    GDALDriver          *poDriver = NULL;
#else
    OGRDataSource       *poODS;    
    OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
    OGRSFDriver          *poDriver = NULL;
#endif
    int                  iDriver;
    map *tmpMap=getMapFromMaps(outputs,"Result","mimeType");
    const char *oDriver;
    oDriver="GeoJSON";
    if(tmpMap!=NULL){
      if(strcmp(tmpMap->value,"text/xml")==0){
	oDriver="GML";
      }
    }
    
    for( iDriver = 0;
	 iDriver < poR->GetDriverCount() && poDriver == NULL;
	 iDriver++ )
      {
#ifdef DEBUG
#if GDAL_VERSION_MAJOR >= 2
	fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetDescription());
#else
	fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetName());
#endif
#endif
	if( EQUAL(
#if GDAL_VERSION_MAJOR >= 2
		  poR->GetDriver(iDriver)->GetDescription()
#else
		  poR->GetDriver(iDriver)->GetName()
#endif
		  ,
		  oDriver) )
	  {
	    poDriver = poR->GetDriver(iDriver);
	  }
      }

    if( poDriver == NULL )
      {
	char emessage[8192];
	sprintf( emessage, "Unable to find driver `%s'.\n", oDriver );
	sprintf( emessage,  "%sThe following drivers are available:\n",emessage );
        
	for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
	  {
#if GDAL_VERSION_MAJOR >= 2
	    sprintf( emessage,  "%s  -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetDescription() );
#else
	    sprintf( emessage,  "%s  -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetName() );
#endif
	  }

	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;

      }

#if GDAL_VERSION_MAJOR >=2
    if( !CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) )
#else
    if( !poDriver->TestCapability( ODrCCreateDataSource ) )
#endif
      {
	char emessage[1024];
	sprintf( emessage,  "%s driver does not support data source creation.\n",
		 "json" );
	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;
      }

    /* -------------------------------------------------------------------- */
    /*      Create the output data source.                                  */
    /* -------------------------------------------------------------------- */
    char *pszDestDataSource=(char*)malloc(100);
    char **papszDSCO=NULL;
    sprintf(pszDestDataSource,"/vsimem/result_%d",getpid());
#if GDAL_VERSION_MAJOR >=2
    poODS = poDriver->Create( pszDestDataSource, 0, 0, 0, GDT_Unknown, papszDSCO );
#else
    poODS = poDriver->CreateDataSource( pszDestDataSource, papszDSCO );
#endif
    if( poODS == NULL ){
      char emessage[1024];      
      sprintf( emessage,  "%s driver failed to create %s\n", 
	       "json", pszDestDataSource );
      setMapInMaps(conf,"lenv","message",emessage);
      return SERVICE_FAILED;
    }

    /* -------------------------------------------------------------------- */
    /*      Create the layer.                                               */
    /* -------------------------------------------------------------------- */
    if( !poODS->TestCapability( ODsCCreateLayer ) )
      {
	char emessage[1024];
	sprintf( emessage, 
		 "Layer %s not found, and CreateLayer not supported by driver.", 
		 "Result" );
	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;
      }
    
    CPLErrorReset();
    
    OGRLayer *poDstLayer = poODS->CreateLayer( "Result", NULL,wkbPolygon,NULL);
    if( poDstLayer == NULL ){
      setMapInMaps(conf,"lenv","message","Layer creation failed.\n");
      return SERVICE_FAILED;
    }


    for(DelaunayT::Finite_faces_iterator fit = T.finite_faces_begin();
	fit != T.finite_faces_end(); ++fit) {
      DelaunayT::Face_handle face = fit;
      OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( poDstLayer ) );
      OGRGeometryH hCollection = OGR_G_CreateGeometry( wkbGeometryCollection );
      OGRGeometryH currLine=OGR_G_CreateGeometry(wkbLinearRing);
      OGRGeometryH currPoly=OGR_G_CreateGeometry(wkbPolygon);
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[1].x(),T.triangle(face)[1].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[2].x(),T.triangle(face)[2].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y());
      OGR_G_AddGeometryDirectly( currPoly, currLine ); 
      OGR_G_AddGeometryDirectly( hCollection, currPoly ); 
      OGR_F_SetGeometry( hFeature, hCollection ); 
      OGR_G_DestroyGeometry(hCollection);
      if( OGR_L_CreateFeature( poDstLayer, hFeature ) != OGRERR_NONE ){
	setMapInMaps(conf,"lenv","message","Failed to create feature in file.\n");
	return SERVICE_FAILED;
      }
      OGR_F_Destroy( hFeature );
    }
    OGR_DS_Destroy( poODS );

#ifdef DEBUG
    std::cerr << "The Voronoi diagram has " << ns << " finite edges "
	      << " and " << nr << " rays" << std::endl;
#endif

    char *res1=readVSIFile(conf,pszDestDataSource);
    if(res1==NULL)
      return SERVICE_FAILED;

    setMapInMaps(outputs,"Result","value",res1);
    free(res1);

    if(strcmp(oDriver,"GML")==0)
      setMapInMaps(outputs,"Result","mimeType","text/xml");
    else
      setMapInMaps(outputs,"Result","mimeType","application/json");

    setMapInMaps(outputs,"Result","encoding","UTF-8");
    OGRCleanupAll();
    
    return SERVICE_SUCCEEDED;
  }
示例#20
0
/*!
   \brief Open existing OGR layer on non-topological level

   Note: Map->name, Map->mapset, Map->fInfo.ogr.dsn and
   Map->fInfo.ogr.layer_name must be set before.

   \param[in,out] Map pointer to Map_info structure
   \param update TRUE for write mode, otherwise read-only
   
   \return 0 success
   \return -1 error
*/
int V1_open_old_ogr(struct Map_info *Map, int update)
{
#ifdef HAVE_OGR
    int i, layer, nLayers;

    struct Format_info_ogr *ogr_info;
    
    OGRDataSourceH Ogr_ds;
    OGRLayerH Ogr_layer;
    OGRFeatureDefnH Ogr_featuredefn;
    OGRwkbGeometryType Ogr_geom_type;
    
    Ogr_layer = NULL;
    Ogr_geom_type = wkbUnknown;

    ogr_info = &(Map->fInfo.ogr);
    if (!ogr_info->dsn) {
	G_fatal_error(_("OGR datasource not defined"));
	return -1;
    }
    
    if (!ogr_info->layer_name) {
	G_fatal_error(_("OGR layer not defined"));
	return -1;
    }
    
    G_debug(2, "V1_open_old_ogr(): dsn = %s layer = %s", ogr_info->dsn,
	    ogr_info->layer_name);

    OGRRegisterAll();

    /* open data source handle */
    Ogr_ds = OGROpen(ogr_info->dsn, FALSE, NULL);
    if (Ogr_ds == NULL)
	G_fatal_error(_("Unable to open OGR data source '%s'"),
		      ogr_info->dsn);
    ogr_info->ds = Ogr_ds;

    /* get layer number */
    layer = -1;
    nLayers = OGR_DS_GetLayerCount(Ogr_ds);
    G_debug(2, "%d layers found in data source", nLayers);

    for (i = 0; i < nLayers; i++) {
	Ogr_layer = OGR_DS_GetLayer(Ogr_ds, i);	
	Ogr_featuredefn = OGR_L_GetLayerDefn(Ogr_layer);
	if (strcmp(OGR_FD_GetName(Ogr_featuredefn), ogr_info->layer_name) == 0) {
	    Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn);
	    layer = i;
	    break;
	}
    }
    if (layer == -1) {
	OGR_DS_Destroy(Ogr_ds);
	G_fatal_error(_("OGR layer <%s> not found"),
		      ogr_info->layer_name);
    }
    G_debug(2, "OGR layer %d opened", layer);

    ogr_info->layer = Ogr_layer;
    if (update && OGR_L_TestCapability(ogr_info->layer, OLCTransactions))
	OGR_L_StartTransaction(ogr_info->layer);
    
    switch(Ogr_geom_type) {
    case wkbPoint25D: case wkbLineString25D: case wkbPolygon25D:
    case wkbMultiPoint25D: case wkbMultiLineString25D: case wkbMultiPolygon25D:
    case wkbGeometryCollection25D:
	Map->head.with_z = WITH_Z;
	break;
    default:
	Map->head.with_z = WITHOUT_Z;
	break;
    }
    
    ogr_info->cache.fid = -1;	/* FID >= 0 */
    
    return 0;
#else
    G_fatal_error(_("GRASS is not compiled with OGR support"));
    return -1;
#endif
}