Exemplo n.º 1
0
void SaveGeometry(const CPLString &path, const OGRPolygon &polygon, const OGRSpatialReference &spaRef)
{
    const char *pszDriverName = "ESRI Shapefile";
    GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName );
    if( poDriver == NULL )
    {
        printf( "%s driver not available.\n", pszDriverName );
        exit( 1 );
    }

    GDALDataset *poDS = poDriver->Create( path, 0, 0, 0, GDT_Unknown, NULL );
    if( poDS == NULL )
    {
        printf( "Creation of output file failed.\n" );
        exit( 1 );
    }

    const char* pszLayerName = CPLGetBasename(path);

    OGRLayer *poLayer = poDS->CreateLayer( pszLayerName, spaRef.Clone(), wkbPolygon, NULL );
    if( poLayer == NULL )
    {
        printf( "Layer creation failed.\n" );
        exit( 1 );
    }

    OGRFieldDefn oField( "Name", OFTString );
    oField.SetWidth(32);
    if( poLayer->CreateField( &oField ) != OGRERR_NONE )
    {
        printf( "Creating Name field failed.\n" );
        exit( 1 );
    }

    OGRFeature *poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() );
    //poFeature->SetField( "Name", szName );

    poFeature->SetGeometry( polygon.clone() );
    if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
    {
        printf( "Failed to create feature in shapefile.\n" );
        exit( 1 );
    }
    OGRFeature::DestroyFeature( poFeature );
    GDALClose( poDS );
}
Exemplo n.º 2
0
int main( int nArgc, char ** papszArgv )

{
    int   nFirstSourceDataset = -1, bLayersWildcarded = TRUE, iArg;
    const char *pszFormat = "ESRI Shapefile";
    const char *pszTileIndexField = "LOCATION";
    const char *pszOutputName = NULL;
    int write_absolute_path = FALSE;
    int skip_different_projection = FALSE;
    char* current_path = NULL;
    int accept_different_schemas = FALSE;
    int bFirstWarningForNonMatchingAttributes = TRUE;
    
    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(papszArgv[0]))
        exit(1);
/* -------------------------------------------------------------------- */
/*      Register format(s).                                             */
/* -------------------------------------------------------------------- */
    OGRRegisterAll();
    
/* -------------------------------------------------------------------- */
/*      Processing command line arguments.                              */
/* -------------------------------------------------------------------- */
    for( iArg = 1; iArg < nArgc; iArg++ )
    {
        if( EQUAL(papszArgv[iArg], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 )
        {
            pszFormat = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-write_absolute_path"))
        {
            write_absolute_path = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-skip_different_projection"))
        {
            skip_different_projection = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-accept_different_schemas"))
        {
            accept_different_schemas = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-tileindex") && iArg < nArgc-1 )
        {
            pszTileIndexField = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-lnum") 
                 || EQUAL(papszArgv[iArg],"-lname") )
        {
            iArg++;
            bLayersWildcarded = FALSE;
        }
        else if( papszArgv[iArg][0] == '-' )
            Usage();
        else if( pszOutputName == NULL )
            pszOutputName = papszArgv[iArg];
        else if( nFirstSourceDataset == -1 )
            nFirstSourceDataset = iArg;
    }

    if( pszOutputName == NULL || nFirstSourceDataset == -1 )
        Usage();

/* -------------------------------------------------------------------- */
/*      Try to open as an existing dataset for update access.           */
/* -------------------------------------------------------------------- */
    GDALDataset *poDstDS;
    OGRLayer *poDstLayer = NULL;

    poDstDS = (GDALDataset*) OGROpen( pszOutputName, TRUE, NULL );

/* -------------------------------------------------------------------- */
/*      If that failed, find the driver so we can create the tile index.*/
/* -------------------------------------------------------------------- */
    if( poDstDS == NULL )
    {
        OGRSFDriverRegistrar     *poR = OGRSFDriverRegistrar::GetRegistrar();
        GDALDriver              *poDriver = NULL;
        int                      iDriver;

        for( iDriver = 0;
             iDriver < poR->GetDriverCount() && poDriver == NULL;
             iDriver++ )
        {
            if( EQUAL(poR->GetDriver(iDriver)->GetDescription(),pszFormat) )
            {
                poDriver = poR->GetDriver(iDriver);
            }
        }

        if( poDriver == NULL )
        {
            fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat );
            fprintf( stderr, "The following drivers are available:\n" );
        
            for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
            {
                fprintf( stderr, "  -> `%s'\n", poR->GetDriver(iDriver)->GetDescription() );
            }
            exit( 1 );
        }

        if( !CSLTestBoolean( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) )
        {
            fprintf( stderr, "%s driver does not support data source creation.\n",
                    pszFormat );
            exit( 1 );
        }

/* -------------------------------------------------------------------- */
/*      Now create it.                                                  */
/* -------------------------------------------------------------------- */
        
        poDstDS = poDriver->Create( pszOutputName, 0, 0, 0, GDT_Unknown, NULL );
        if( poDstDS == NULL )
        {
            fprintf( stderr, "%s driver failed to create %s\n", 
                    pszFormat, pszOutputName );
            exit( 1 );
        }

        if( poDstDS->GetLayerCount() == 0 )
        {
            OGRFieldDefn oLocation( pszTileIndexField, OFTString );
            
            oLocation.SetWidth( 200 );
            
            if( nFirstSourceDataset < nArgc && papszArgv[nFirstSourceDataset][0] == '-' )
            {
                nFirstSourceDataset++;
            }
            
            OGRSpatialReference* poSrcSpatialRef = NULL;
            
            /* Fetches the SRS of the first layer and use it when creating the tileindex layer */
            if (nFirstSourceDataset < nArgc)
            {
                GDALDataset* poDS = (GDALDataset*) OGROpen(papszArgv[nFirstSourceDataset], FALSE, NULL);
                if (poDS)
                {
                    int iLayer;

                    for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
                    {
                        int bRequested = bLayersWildcarded;
                        OGRLayer *poLayer = poDS->GetLayer(iLayer);

                        for( iArg = 1; iArg < nArgc && !bRequested; iArg++ )
                        {
                            if( EQUAL(papszArgv[iArg],"-lnum") 
                                && atoi(papszArgv[iArg+1]) == iLayer )
                                bRequested = TRUE;
                            else if( EQUAL(papszArgv[iArg],"-lname") 
                                     && EQUAL(papszArgv[iArg+1],
                                              poLayer->GetLayerDefn()->GetName()) )
                                bRequested = TRUE;
                        }

                        if( !bRequested )
                            continue;
                            
                        if ( poLayer->GetSpatialRef() )
                            poSrcSpatialRef = poLayer->GetSpatialRef()->Clone();
                        break;
                    }
                }
                
                GDALClose( (GDALDatasetH)poDS );
            }

            poDstLayer = poDstDS->CreateLayer( "tileindex", poSrcSpatialRef );
            poDstLayer->CreateField( &oLocation, OFTString );
            
            OGRSpatialReference::DestroySpatialReference( poSrcSpatialRef );
        }
    }

/* -------------------------------------------------------------------- */
/*      Identify target layer and field.                                */
/* -------------------------------------------------------------------- */
    int   iTileIndexField;

    poDstLayer = poDstDS->GetLayer(0);
    if( poDstLayer == NULL )
    {
        fprintf( stderr, "Can't find any layer in output tileindex!\n" );
        exit( 1 );
    }

    iTileIndexField = 
        poDstLayer->GetLayerDefn()->GetFieldIndex( pszTileIndexField );
    if( iTileIndexField == -1 )
    {
        fprintf( stderr, "Can't find %s field in tile index dataset.\n", 
                pszTileIndexField );
        exit( 1 );
    }

    OGRFeatureDefn* poFeatureDefn = NULL;

    /* Load in memory existing file names in SHP */
    int nExistingLayers = 0;
    char** existingLayersTab = NULL;
    OGRSpatialReference* alreadyExistingSpatialRef = NULL;
    int alreadyExistingSpatialRefValid = FALSE;
    nExistingLayers = (int)poDstLayer->GetFeatureCount();
    if (nExistingLayers)
    {
        int i;
        existingLayersTab = (char**)CPLMalloc(nExistingLayers * sizeof(char*));
        for(i=0;i<nExistingLayers;i++)
        {
            OGRFeature* feature = poDstLayer->GetNextFeature();
            existingLayersTab[i] = CPLStrdup(feature->GetFieldAsString( iTileIndexField));
            if (i == 0)
            {
                GDALDataset       *poDS;
                char* filename = CPLStrdup(existingLayersTab[i]);
                int j;
                for(j=strlen(filename)-1;j>=0;j--)
                {
                    if (filename[j] == ',')
                        break;
                }
                if (j >= 0)
                {
                    int iLayer = atoi(filename + j + 1);
                    filename[j] = 0;
                    poDS = (GDALDataset*) OGROpen(filename, FALSE, NULL);
                    if (poDS)
                    {
                        OGRLayer *poLayer = poDS->GetLayer(iLayer);
                        if (poLayer)
                        {
                            alreadyExistingSpatialRefValid = TRUE;
                            alreadyExistingSpatialRef =
                                    (poLayer->GetSpatialRef()) ? poLayer->GetSpatialRef()->Clone() : NULL;
                                    
                            if (poFeatureDefn == NULL)
                                poFeatureDefn = poLayer->GetLayerDefn()->Clone();
                        }
                        GDALClose( (GDALDatasetH)poDS );
                    }
                }
            }
        }
    }


    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;
        }
    }
/* ==================================================================== */
/*      Process each input datasource in turn.                          */
/* ==================================================================== */

	for(; nFirstSourceDataset < nArgc; nFirstSourceDataset++ )
    {
        int i;
        GDALDataset       *poDS;

        if( papszArgv[nFirstSourceDataset][0] == '-' )
        {
            nFirstSourceDataset++;
            continue;
        }
        
        char* fileNameToWrite;
        VSIStatBuf sStatBuf;

        if (write_absolute_path && CPLIsFilenameRelative( papszArgv[nFirstSourceDataset] ) &&
            VSIStat( papszArgv[nFirstSourceDataset], &sStatBuf ) == 0)
        {
            fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,papszArgv[nFirstSourceDataset]));
        }
        else
        {
            fileNameToWrite = CPLStrdup(papszArgv[nFirstSourceDataset]);
        }

        poDS = (GDALDataset*) OGROpen( papszArgv[nFirstSourceDataset], FALSE, NULL );

        if( poDS == NULL )
        {
            fprintf( stderr, "Failed to open dataset %s, skipping.\n", 
                    papszArgv[nFirstSourceDataset] );
            CPLFree(fileNameToWrite);
            continue;
        }

/* -------------------------------------------------------------------- */
/*      Check all layers, and see if they match requests.               */
/* -------------------------------------------------------------------- */
        int iLayer;

        for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
        {
            int bRequested = bLayersWildcarded;
            OGRLayer *poLayer = poDS->GetLayer(iLayer);

            for( iArg = 1; iArg < nArgc && !bRequested; iArg++ )
            {
                if( EQUAL(papszArgv[iArg],"-lnum") 
                    && atoi(papszArgv[iArg+1]) == iLayer )
                    bRequested = TRUE;
                else if( EQUAL(papszArgv[iArg],"-lname") 
                         && EQUAL(papszArgv[iArg+1],
                                  poLayer->GetLayerDefn()->GetName()) )
                    bRequested = TRUE;
            }

            if( !bRequested )
                continue;

            /* Checks that the layer is not already in tileindex */
            for(i=0;i<nExistingLayers;i++)
            {
                char        szLocation[5000];
                sprintf( szLocation, "%s,%d", 
                        fileNameToWrite, iLayer );
                if (EQUAL(szLocation, existingLayersTab[i]))
                {
                    fprintf(stderr, "Layer %d of %s is already in tileindex. Skipping it.\n",
                            iLayer, papszArgv[nFirstSourceDataset]);
                    break;
                }
            }
            if (i != nExistingLayers)
            {
                continue;
            }

            OGRSpatialReference* spatialRef = poLayer->GetSpatialRef();
            if (alreadyExistingSpatialRefValid)
            {
                if ((spatialRef != NULL && alreadyExistingSpatialRef != NULL &&
                     spatialRef->IsSame(alreadyExistingSpatialRef) == FALSE) ||
                    ((spatialRef != NULL) != (alreadyExistingSpatialRef != NULL)))
                {
                    fprintf(stderr, "Warning : layer %d of %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", iLayer, papszArgv[nFirstSourceDataset],
                                (skip_different_projection) ? " Skipping it" : "");
                    if (skip_different_projection)
                    {
                        continue;
                    }
                }
            }
            else
            {
                alreadyExistingSpatialRefValid = TRUE;
                alreadyExistingSpatialRef = (spatialRef) ? spatialRef->Clone() : NULL;
            }

/* -------------------------------------------------------------------- */
/*		Check if all layers in dataset have the same attributes	schema. */
/* -------------------------------------------------------------------- */
			if( poFeatureDefn == NULL )
			{
				poFeatureDefn = poLayer->GetLayerDefn()->Clone();
			}
			else if ( !accept_different_schemas )
			{
				OGRFeatureDefn* poFeatureDefnCur = poLayer->GetLayerDefn();
				assert(NULL != poFeatureDefnCur);

				int fieldCount = poFeatureDefnCur->GetFieldCount();

				if( fieldCount != poFeatureDefn->GetFieldCount())
				{
					fprintf( stderr, "Number of attributes of layer %s of %s does not match ... skipping it.\n",
                             poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]);
                    if (bFirstWarningForNonMatchingAttributes)
                    {
                        fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n"
                                         "but this may result in a tileindex incompatible with MapServer\n");
                        bFirstWarningForNonMatchingAttributes = FALSE;
                    }
					continue;
				}
				
                int bSkip = FALSE;
				for( int fn = 0; fn < poFeatureDefnCur->GetFieldCount(); fn++ )
				{
 					OGRFieldDefn* poField = poFeatureDefn->GetFieldDefn(fn);
 					OGRFieldDefn* poFieldCur = poFeatureDefnCur->GetFieldDefn(fn);

					/* XXX - Should those pointers be checked against NULL? */ 
					assert(NULL != poField);
					assert(NULL != poFieldCur);

					if( poField->GetType() != poFieldCur->GetType() 
						|| poField->GetWidth() != poFieldCur->GetWidth() 
						|| poField->GetPrecision() != poFieldCur->GetPrecision() 
						|| !EQUAL( poField->GetNameRef(), poFieldCur->GetNameRef() ) )
					{
						fprintf( stderr, "Schema of attributes of layer %s of %s does not match ... skipping it.\n",
                                 poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]);
                        if (bFirstWarningForNonMatchingAttributes)
                        {
                            fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n"
                                             "but this may result in a tileindex incompatible with MapServer\n");
                            bFirstWarningForNonMatchingAttributes = FALSE;
                        }
                        bSkip = TRUE; 
                        break;
					}
				}
                
                if (bSkip)
                    continue;
			}


/* -------------------------------------------------------------------- */
/*      Get layer extents, and create a corresponding polygon           */
/*      geometry.                                                       */
/* -------------------------------------------------------------------- */
            OGREnvelope sExtents;
            OGRPolygon oRegion;
            OGRLinearRing oRing;

            if( poLayer->GetExtent( &sExtents, TRUE ) != OGRERR_NONE )
            {
                fprintf( stderr, "GetExtent() failed on layer %s of %s, skipping.\n", 
                        poLayer->GetLayerDefn()->GetName(), 
                        papszArgv[nFirstSourceDataset] );
                continue;
            }
            
            oRing.addPoint( sExtents.MinX, sExtents.MinY );
            oRing.addPoint( sExtents.MinX, sExtents.MaxY );
            oRing.addPoint( sExtents.MaxX, sExtents.MaxY );
            oRing.addPoint( sExtents.MaxX, sExtents.MinY );
            oRing.addPoint( sExtents.MinX, sExtents.MinY );

            oRegion.addRing( &oRing );

/* -------------------------------------------------------------------- */
/*      Add layer to tileindex.                                         */
/* -------------------------------------------------------------------- */
            char        szLocation[5000];
            OGRFeature  oTileFeat( poDstLayer->GetLayerDefn() );

            sprintf( szLocation, "%s,%d", 
                     fileNameToWrite, iLayer );
            oTileFeat.SetGeometry( &oRegion );
            oTileFeat.SetField( iTileIndexField, szLocation );

            if( poDstLayer->CreateFeature( &oTileFeat ) != OGRERR_NONE )
            {
                fprintf( stderr, "Failed to create feature on tile index ... terminating." );
                GDALClose( (GDALDatasetH) poDstDS );
                exit( 1 );
            }
        }

/* -------------------------------------------------------------------- */
/*      Cleanup this data source.                                       */
/* -------------------------------------------------------------------- */
        CPLFree(fileNameToWrite);
        GDALClose( (GDALDatasetH)poDS );
    }

/* -------------------------------------------------------------------- */
/*      Close tile index and clear buffers.                             */
/* -------------------------------------------------------------------- */
    GDALClose( (GDALDatasetH) poDstDS );
	OGRFeatureDefn::DestroyFeatureDefn( poFeatureDefn );
  
    if (alreadyExistingSpatialRef != NULL)
        OGRSpatialReference::DestroySpatialReference( alreadyExistingSpatialRef );
  
    CPLFree(current_path);
    
    if (nExistingLayers)
    {
        int i;
        for(i=0;i<nExistingLayers;i++)
        {
            CPLFree(existingLayersTab[i]);
        }
        CPLFree(existingLayersTab);
    }

    OGRCleanupAll();

    return 0;
}
Exemplo n.º 3
0
OGRLayer *GNMGenericNetwork::GetPath(GNMGFID nStartFID, GNMGFID nEndFID,
                          GNMGraphAlgorithmType eAlgorithm, char **papszOptions)
{

    if(!m_bIsGraphLoaded && LoadGraph() != CE_None)
    {
        return NULL;
    }

    GDALDriver* poMEMDrv =
            OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("Memory");
    if (poMEMDrv == NULL)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot load 'Memory' driver");
        return NULL;
    }

    GDALDataset* poMEMDS =
            poMEMDrv->Create("dummy_name", 0, 0, 0, GDT_Unknown, NULL);
    OGRSpatialReference oDstSpaRef(GetProjectionRef());
    OGRLayer* poMEMLayer = poMEMDS->CreateLayer(GetAlgorithmName(eAlgorithm,
                               true), &oDstSpaRef, wkbGeometryCollection, NULL);

    OGRGNMWrappedResultLayer* poResLayer =
                              new OGRGNMWrappedResultLayer(poMEMDS, poMEMLayer);

    const bool bReturnEdges = CPLFetchBool(papszOptions, GNM_MD_FETCHEDGES, true);
    const bool bReturnVertices = CPLFetchBool(papszOptions, GNM_MD_FETCHVERTEX, true);

    switch (eAlgorithm)
    {
    case GATDijkstraShortestPath:
        {
            GNMPATH path = m_oGraph.DijkstraShortestPath(nStartFID, nEndFID);

            // fill features in result layer
            FillResultLayer(poResLayer, path, 1, bReturnVertices, bReturnEdges);
        }
        break;
    case GATKShortestPath:
        {
            int nK = atoi(CSLFetchNameValueDef(papszOptions, GNM_MD_NUM_PATHS,
                                               "1"));

            CPLDebug("GNM", "Search %d path(s)", nK);

            std::vector<GNMPATH> paths = m_oGraph.KShortestPaths(nStartFID,
                                                                 nEndFID, nK);

            // fill features in result layer
            for(size_t i = 0; i < paths.size(); ++i)
            {
                FillResultLayer(poResLayer, paths[i], static_cast<int>(i + 1), bReturnVertices,
                                bReturnEdges);
            }
        }
        break;
    case GATConnectedComponents:
        {
            GNMVECTOR anEmitters;
            if(NULL != papszOptions)
            {
                char** papszEmitter = CSLFetchNameValueMultiple(papszOptions, GNM_MD_EMITTER);
                for(int i = 0; papszEmitter[i] != NULL; ++i)
                {
                    GNMGFID nEmitter = atol(papszEmitter[i]);
                    anEmitters.push_back(nEmitter);
                }
                CSLDestroy(papszEmitter);
            }

            if(nStartFID != -1)
            {
                anEmitters.push_back(nStartFID);
            }

            if(nStartFID != -1)
            {
                anEmitters.push_back(nEndFID);
            }

            GNMPATH path = m_oGraph.ConnectedComponents(anEmitters);

            // fill features in result layer
            FillResultLayer(poResLayer, path, 1, bReturnVertices, bReturnEdges);
        }
        break;
    }

    return poResLayer;
}
Exemplo n.º 4
0
OGRLayer *GNMFileNetwork::ICreateLayer(const char *pszName,
                                CPL_UNUSED OGRSpatialReference *poSpatialRef,
                                OGRwkbGeometryType eGType, char **papszOptions)
{
    if(NULL == m_poLayerDriver)
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "The network storage format driver is not defined." );
        return NULL;
    }

    //check if layer with such name exist
    for(int i = 0; i < GetLayerCount(); ++i)
    {
        OGRLayer* pLayer = GetLayer(i);
        if(NULL == pLayer)
            continue;
        if(EQUAL(pLayer->GetName(), pszName))
        {
            CPLError( CE_Failure, CPLE_IllegalArg,
                      "The network layer '%s' already exist.", pszName );
            return NULL;
        }
    }

    //form path
    const char* pszExt = m_poLayerDriver->GetMetadataItem(GDAL_DMD_EXTENSION);
    CPLString soPath = CPLFormFilename(m_soNetworkFullName, pszName ,pszExt);

    GDALDataset *poDS = m_poLayerDriver->Create( soPath, 0, 0, 0, GDT_Unknown,
                                                 papszOptions );
    if( poDS == NULL )
    {
        CPLError( CE_Failure, CPLE_FileIO, "Creation of output file failed." );
        return NULL;
    }

    OGRSpatialReference oSpaRef(m_soSRS);

    OGRLayer *poLayer = poDS->CreateLayer( pszName, &oSpaRef, eGType, papszOptions );
    if( poLayer == NULL )
    {
        CPLError( CE_Failure, CPLE_FileIO, "Layer creation failed." );
        GDALClose(poDS);
        return NULL;
    }

    OGRFieldDefn oField( GNM_SYSFIELD_GFID, GNMGFIDInt );
    if( poLayer->CreateField( &oField ) != OGRERR_NONE )
    {
        CPLError( CE_Failure, CPLE_FileIO, "Creating global identificator field failed." );
        GDALClose(poDS);
        return NULL;
    }


    OGRFieldDefn oFieldBlock(GNM_SYSFIELD_BLOCKED, OFTInteger);
    if( poLayer->CreateField( &oFieldBlock ) != OGRERR_NONE )
    {
        CPLError( CE_Failure, CPLE_FileIO, "Creating is blocking field failed." );
        GDALClose(poDS);
        return NULL;
    }

    GNMGenericLayer* pGNMLayer = new GNMGenericLayer(poLayer, this);
    m_apoLayers.push_back(pGNMLayer);
    m_mpLayerDatasetMap[pGNMLayer] = poDS;
    return pGNMLayer;
}
Exemplo n.º 5
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;
  }
Exemplo n.º 6
0
// This function does NOT work for now
bool GdaCache::CacheLayer(std::string ext_ds_name, 
						  OGRLayerProxy* ext_layer_proxy)
{
	OGRLayer* poSrcLayer = ext_layer_proxy->layer;
	
	// get information from current layer: geomtype, layer_name
    // (NOTE: we don't consider coodinator system and translation here)
    OGRFeatureDefn *poSrcFDefn = poSrcLayer->GetLayerDefn();
    int eGType = poSrcFDefn->GetGeomType();
    const char* pszNewLayerName = poSrcLayer->GetName();
    int bForceToPolygon = FALSE;
    int bForceToMultiPolygon = FALSE;
    int bForceToMultiLineString = FALSE;
	
    if( wkbFlatten(eGType) == wkbPolygon )
        bForceToPolygon = TRUE;
    else if( wkbFlatten(eGType) == wkbMultiPolygon )
        bForceToMultiPolygon = TRUE;
    else if( wkbFlatten(eGType) == wkbMultiLineString )
        bForceToMultiLineString = TRUE;
	
	//Setup coordinate transformation if we need it.
	OGRCoordinateTransformation *poCT = NULL;
	bool bTransform                   = FALSE;
	OGRSpatialReference *poSourceSRS = NULL;
	// todo
	OGRSpatialReference *poOutputSRS = new OGRSpatialReference("EPSG:4326");

	// Cache
	char *papszLCO[] = {"OVERWRITE=yes","FORMAT=Spatialite"};
	std::string cache_layer_name = ext_ds_name + "_"+ext_layer_proxy->name;
	GDALDataset *poDstDS = cach_ds_proxy->ds;
	OGRLayer *poDstLayer = poDstDS->CreateLayer(cache_layer_name.c_str(), 
												poOutputSRS, 
												(OGRwkbGeometryType)eGType, 
												papszLCO);
	if (poDstLayer == NULL) {
		// raise create cache failed.
		return false;
	}
    // Process Layer style table
    poDstLayer->SetStyleTable( poSrcLayer->GetStyleTable () );
	
    // Add fields. here to copy all field.
    int nSrcFieldCount = poSrcFDefn->GetFieldCount();
    int iField;
    OGRFeatureDefn *poDstFDefn = poDstLayer->GetLayerDefn();
	
    for( iField = 0; iField < nSrcFieldCount; iField++ )
    {    
        OGRFieldDefn* poSrcFieldDefn = poSrcFDefn->GetFieldDefn(iField);
        OGRFieldDefn oFieldDefn( poSrcFieldDefn );
		
        // The field may have been already created at layer creation 
		if (poDstLayer->CreateField( &oFieldDefn ) == OGRERR_NONE)
        {    
            // now that we've created a field, GetLayerDefn() won't return NULL
            if (poDstFDefn == NULL)
                poDstFDefn = poDstLayer->GetLayerDefn();
        }    
    }    
	
    // Transfer feature from Source Layer to Dest Layer
    OGRFeature  *poFeature;
    GIntBig      nFeaturesWritten = 0;
    poSrcLayer->ResetReading();
	
    while (poFeature = poSrcLayer->GetNextFeature())
    {
        OGRFeature *poDstFeature = OGRFeature::CreateFeature(
										poDstLayer->GetLayerDefn() );
        poDstFeature->SetFrom(poFeature);
		
        OGRGeometry *poDstGeometry = poDstFeature->GetGeometryRef();
        if (poDstGeometry != NULL)
        {
            if( bForceToPolygon )
            {
                poDstFeature->SetGeometryDirectly(
					OGRGeometryFactory::forceToPolygon(
						poDstFeature->StealGeometry()));
            }
            else if( bForceToMultiPolygon )
            {
                poDstFeature->SetGeometryDirectly(
					OGRGeometryFactory::forceToMultiPolygon(
					    poDstFeature->StealGeometry() ) );
            }
            else if ( bForceToMultiLineString )
            {
                poDstFeature->SetGeometryDirectly(
					OGRGeometryFactory::forceToMultiLineString(
						poDstFeature->StealGeometry() ) );
            }
        }
        if( poDstLayer->CreateFeature( poDstFeature ) == OGRERR_NONE )
        {
            nFeaturesWritten ++;
        }            
        OGRFeature::DestroyFeature( poDstFeature );
        OGRFeature::DestroyFeature( poFeature );
    }
    //OGRDataSource::DestroyDataSource(poDstDS);
	GDALClose(poDstDS);
    // XXX
    // delete poDstLayer;
	return true;
}
Exemplo n.º 7
0
	bool Shape::save(const std::string& filename) {
		if (shapeType == -1) {
			std::cout << "Shape type is not set." << std::endl;
			return false;
		}

		if (shapeObjects.size() == 0) {
			std::cout << "No shape exists." << std::endl;
			return false;
		}

		const char *pszDriverName = "ESRI Shapefile";
		GDALDriver *poDriver;
		GDALAllRegister();

		poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName);
		if (poDriver == NULL) {
			printf("%s driver not available.\n", pszDriverName);
			return false;
		}

		GDALDataset *poDS;
		poDS = poDriver->Create(filename.c_str(), 0, 0, 0, GDT_Unknown, NULL);
		if (poDS == NULL) {
			printf("Creation of output file failed.\n");
			return false;
		}

		OGRLayer *poLayer;
		if (shapeType == wkbPoint) {
			poLayer = poDS->CreateLayer("point_out", NULL, wkbPoint, NULL);
		}
		else if (shapeType == wkbLineString) {
			poLayer = poDS->CreateLayer("point_out", NULL, wkbLineString, NULL);
		}
		else if (shapeType == wkbPolygon) {
			poLayer = poDS->CreateLayer("point_out", NULL, wkbPolygon, NULL);
		}
		if (poLayer == NULL) {
			printf("Layer creation failed.\n");
			return false;
		}

		for (auto it = shapeObjects[0].attributes.begin(); it != shapeObjects[0].attributes.end(); ++it) {
			OGRFieldDefn oField(it->first.c_str(), static_cast<OGRFieldType>(it->second.type));
			if (it->second.type == OFTString) {
				oField.SetWidth(it->second.stringValue().size());
			}
			if (poLayer->CreateField(&oField) != OGRERR_NONE) {
				printf("Creating Name field failed.\n");
				return false;
			}
		}
				
		for (int i = 0; i < shapeObjects.size(); ++i) {
			if (shapeObjects[i].parts.size() == 0) continue;
			
			OGRFeature *poFeature;
			poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());

			// 属性をセット
			for (auto it = shapeObjects[i].attributes.begin(); it != shapeObjects[i].attributes.end(); ++it) {
				poFeature->SetField(it->first.c_str(), it->second.stringValue().c_str());
			}

			// ジオメトリ情報をセット
			if (shapeType == wkbPoint) {
				OGRPoint point;
				point.setX(shapeObjects[i].parts[0].points[0].x);
				point.setY(shapeObjects[i].parts[0].points[0].y);
				point.setZ(shapeObjects[i].parts[0].points[0].z);
				poFeature->SetGeometry(&point);
			}
			else if (shapeType == wkbLineString) {
				OGRLineString lineString;
				for (int k = 0; k < shapeObjects[i].parts[0].points.size(); ++k) {
					lineString.addPoint(shapeObjects[i].parts[0].points[k].x, shapeObjects[i].parts[0].points[k].y, shapeObjects[i].parts[0].points[k].z);
				}
				poFeature->SetGeometry(&lineString);
			}
			else if (shapeType == wkbPolygon) {
				OGRPolygon polygon;
				for (int j = 0; j < shapeObjects[i].parts.size(); ++j) {
					OGRLinearRing linearRing;
					for (int k = 0; k < shapeObjects[i].parts[j].points.size(); ++k) {
						linearRing.addPoint(shapeObjects[i].parts[j].points[k].x, shapeObjects[i].parts[j].points[k].y, shapeObjects[i].parts[j].points[k].z);
					}
					polygon.addRing(&linearRing);
				}
				poFeature->SetGeometry(&polygon);
			}
			
			if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) {
				printf("Failed to create feature in shapefile.\n");
				return false;
			}
			OGRFeature::DestroyFeature(poFeature);
		}

		GDALClose(poDS);

		return true;
	}
Exemplo n.º 8
0
void SavePolygons( const std::vector< std::string > InFilenames,
                   const char *OutFilename,
                   const cv::Mat klabels,
                   const std::vector< cv::Mat > raster,
                   const std::vector< u_int32_t > labelpixels,
                   const std::vector< std::vector <double> > sumCH,
                   const std::vector< std::vector <double> > avgCH,
                   const std::vector< std::vector <double> > stdCH,
                   std::vector< std::vector< LINE > >& linelists )
{

  CPLLocaleC oLocaleCForcer();
  CPLErrorReset();

  const char *pszDriverName = "ESRI Shapefile";
  GDALDriver *liDriver;

  liDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName );
  if( liDriver == NULL )
  {
      printf( "\nERROR: %s driver not available.\n", pszDriverName );
      exit( 1 );
  }

  const size_t m_bands = raster.size();
  const size_t m_labels = labelpixels.size();

  GDALDataset *liDS;
  liDS = liDriver->Create( OutFilename, 0, 0, 0, GDT_Unknown, NULL );

  if( liDS == NULL )
  {
      printf( "\nERROR: Creation of output file failed.\n" );
      exit( 1 );
  }

  // dataset
  GDALDataset* piDataset;
  piDataset = (GDALDataset*) GDALOpen(InFilenames[0].c_str(), GA_ReadOnly);

  // spatialref
  OGRSpatialReference oSRS;
  oSRS.SetProjCS( piDataset->GetProjectionRef() );

  OGRLayer *liLayer;
  liLayer = liDS->CreateLayer( "segments", &oSRS, wkbPolygon, NULL );
  if( liLayer == NULL )
  {
      printf( "\nERROR: Layer creation failed.\n" );
      exit( 1 );
  }
  // spatial transform
  double adfGeoTransform[6];
  double oX = 0.0f; double oY = 0.0f;
  double mX = 1.0f; double mY = -1.0f;
  if( piDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) {
      oX = adfGeoTransform[0]; oY = adfGeoTransform[3];
      mX = adfGeoTransform[1]; mY = adfGeoTransform[5];
  }
  GDALClose( (GDALDatasetH) piDataset );

  OGRFieldDefn *clsIdField = new OGRFieldDefn( "CLASS", OFTInteger );
  liLayer->CreateField( clsIdField );

  OGRFieldDefn *pixArField = new OGRFieldDefn( "AREA", OFTInteger );
  liLayer->CreateField( pixArField );

  for ( size_t b = 0; b < m_bands; b++ )
  {
     stringstream value; value << b+1;
     std::string FieldName = value.str() + "_AVERAGE";
     OGRFieldDefn *lavrgField = new OGRFieldDefn( FieldName.c_str(), OFTReal );
     liLayer->CreateField( lavrgField );
  }

  for ( size_t b = 0; b < m_bands; b++ )
  {
     stringstream value; value << b+1;
     std::string FieldName = value.str() + "_STDDEV";
     OGRFieldDefn *lavrgField = new OGRFieldDefn( FieldName.c_str(), OFTReal );
     liLayer->CreateField( lavrgField );
  }

  int multiring = 0;
  printf ("Write File: %s (polygon)\n", OutFilename);
  for (size_t k = 0; k < m_labels; k++)
  {

      if (multiring == 1) {
        k = k - 1;
        multiring = 0;
      }

      if (linelists[k].size() == 0)
        continue;
      // insert field data
      OGRFeature *liFeature;
      liFeature = OGRFeature::CreateFeature( liLayer->GetLayerDefn() );
      liFeature->SetField( "CLASS", (int) k );
      liFeature->SetField( "AREA", (int) labelpixels.at(k) );
      for ( size_t b = 0; b < m_bands; b++ )
      {
        stringstream value; value << b+1;
        std::string FieldName = value.str() + "_AVERAGE";
        liFeature->SetField( FieldName.c_str(), (double) avgCH[b].at(k) );
      }
      for ( size_t b = 0; b < m_bands; b++ )
      {
        stringstream value; value << b+1;
        std::string FieldName = value.str() + "_STDDEV";
        liFeature->SetField( FieldName.c_str(), stdCH[b].at(k) );
      }

      // initiate polygon start
      OGRLinearRing linestring;
      linestring.setCoordinateDimension(2);
      linestring.addPoint( oX + (double) linelists[k][0].sX * mX, oY + mY * (double) linelists[k][0].sY );
      linestring.addPoint( oX + (double) linelists[k][0].eX * mX, oY + mY * (double) linelists[k][0].eY );
      linelists[k].erase( linelists[k].begin() );

      // construct polygon from lines
      while ( linelists[k].size() > 0 )
      {
        if (multiring == 1) break;

        vector<LINE>::iterator it = linelists[k].begin();
        for (; it != linelists[k].end(); ++it)
        {
          double ltX = linestring.getX(linestring.getNumPoints()-1);
          double ltY = linestring.getY(linestring.getNumPoints()-1);
          double csX = oX + (double) it->sX * mX;
          double csY = oY + mY * (double) it->sY;
          double ceX = oX + (double) it->eX * mX;
          double ceY = oY + mY * (double) it->eY;

          if ( ( csX == ltX  ) && ( csY == ltY ) ) {
              linestring.addPoint(ceX, ceY);
              linelists[k].erase(it);
              break;
          }
          if ( ( ceX == ltX  ) && ( ceY == ltY ) ) {
              linestring.addPoint(csX, csY);
              linelists[k].erase(it);
              break;
          }
          if (it == linelists[k].end()-1) {
              multiring = 1;
              break;
          }
        }
      }

      OGRPolygon polygon;
      linestring.closeRings();

      // simplify poligons
      // remove colinear vertices
      OGRLinearRing linesimple;
      float pointPrevX = 0, pointPrevY = 0;
      for (int i = 0; i < linestring.getNumPoints(); i++)
      {
        OGRPoint point;
        linestring.getPoint(i, &point);

        // start
        if ( i == 0)
        {
          linesimple.addPoint( &point );
          pointPrevX = point.getX();
          pointPrevY = point.getY();
          continue;
        }
        // end vertex
        if ( i == linestring.getNumPoints() - 1 )
        {
          linesimple.addPoint( &point );
          continue;
        }

        OGRPoint pointNext;
        linestring.getPoint(i+1, &pointNext);
        //     | x1 y1 1 |
        // det | x2 y2 1 | = 0 => p1,p2,p3 are colinear
        //     | x3 y3 1 |
        // x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2) == 0
        // only if not colinear with previous and next
        if ( pointPrevX*(point.getY()-pointNext.getY()) +
             point.getX()*(pointNext.getY()-pointPrevY) +
             pointNext.getX()*(pointPrevY-point.getY()) != 0 )
        {
          linesimple.addPoint( &point );
          pointPrevX = point.getX();
          pointPrevY = point.getY();
        }
      }

      // as polygon geometry
      polygon.addRing( &linesimple );
      liFeature->SetGeometry( &polygon );

      if( liLayer->CreateFeature( liFeature ) != OGRERR_NONE )
      {
         printf( "\nERROR: Failed to create feature in shapefile.\n" );
         exit( 1 );
      }
      OGRFeature::DestroyFeature( liFeature );
      GDALTermProgress( (float)(k+1) / (float)(m_labels), NULL, NULL );
  }
  GDALTermProgress( 1.0f, NULL, NULL );

  GDALClose( liDS );

}