int main(int argc, char **argv) { // Get data from ogr OGRRegisterAll(); std::cout << "Opening: " << argv[1] << std::endl; OGRDataSource *shp = OGRSFDriverRegistrar::Open(argv[1], FALSE); IsValid(shp, "Error opening file."); std::cout << "Shape contains " << shp->GetLayerCount() << " layers." << std::endl; OGRLayer *layer = shp->GetLayerByName(argv[2]); IsValid(layer, "Couldn't grab layer"); OGRSpatialReference *srcSRS = NULL; srcSRS = layer->GetSpatialRef(); // Set up writing const char *kDriverName = "ESRI Shapefile"; OGRSFDriver *shpDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(kDriverName); IsValid(shpDriver, "Couldn't grab the shapefile driver."); IsValid(argv[3], "Please provide a output shp."); std::cout << "Writing to: " << argv[3] << std::endl; OGRDataSource *shpOut = shpDriver->CreateDataSource(argv[3], NULL); IsValid(shpOut, "Couldn't open output file"); OGRLayer *outLayer = shpOut->CreateLayer(layer->GetName(), srcSRS, wkbMultiLineString, NULL); IsValid(outLayer, "Couldn't create an output layer"); // copy over the fields from the source file OGRFeatureDefn *source = layer->GetLayerDefn(); for(int i=0; i < source->GetFieldCount(); i++){ OGRFieldDefn *field = source->GetFieldDefn(i); if(outLayer->CreateField(field) != OGRERR_NONE) { std::cout << "Couldn't make layer" << std::endl; exit(1); }; } // Loop through features and grab the hull and put it into CGAL then // skeletonize the points OGRFeature *feature; int count = 0; while((feature = layer->GetNextFeature()) != NULL) { OGRMultiPolygon *geometry = dynamic_cast<OGRMultiPolygon *>(OGRGeometryFactory::forceToMultiPolygon(feature->GetGeometryRef())); IsValid(geometry, "No geometry."); OGRFeature *outFeature = OGRFeature::CreateFeature(outLayer->GetLayerDefn()); IsValid(outFeature, "Couldn't make a feature."); for(int i=0; i < source->GetFieldCount(); i++){ OGRField *field = feature->GetRawFieldRef(i); outFeature->SetField(i, field); } OGRGeometry* line = NULL; for(int i=0; i < geometry->getNumGeometries(); i++){ OGRGeometry* segment = BuildMultiLine(geometry->getGeometryRef(i)); if(segment != NULL){ if(line == NULL) { line = new OGRLineString; } OGRGeometry* tmp = line->Union(segment); if(tmp != NULL){ delete line; line = tmp; } delete segment; } } outFeature->SetGeometry(line); if(outLayer->CreateFeature(outFeature) != OGRERR_NONE){ std::cout << "Couldn't create feature." << std::endl; exit(1); } // clean up OGRFeature::DestroyFeature(outFeature); std::cout << std::endl << ++count << std::endl; } // cleanup OGRDataSource::DestroyDataSource(shp); OGRDataSource::DestroyDataSource(shpOut); return 0; }
OGRMSSQLSpatialSelectLayer::OGRMSSQLSpatialSelectLayer( OGRMSSQLSpatialDataSource *poDSIn, CPLODBCStatement * poStmtIn ) { poDS = poDSIn; iNextShapeId = 0; nSRSId = -1; poFeatureDefn = NULL; poStmt = poStmtIn; pszBaseStatement = CPLStrdup( poStmtIn->GetCommand() ); /* identify the geometry column */ pszGeomColumn = NULL; for ( int iColumn = 0; iColumn < poStmt->GetColCount(); iColumn++ ) { if ( EQUAL(poStmt->GetColTypeName( iColumn ), "image") ) { SQLCHAR szTableName[256]; SQLSMALLINT nTableNameLength = 0; SQLColAttribute(poStmt->GetStatement(), (SQLSMALLINT)(iColumn + 1), SQL_DESC_TABLE_NAME, szTableName, sizeof(szTableName), &nTableNameLength, NULL); if (nTableNameLength > 0) { OGRLayer *poBaseLayer = poDS->GetLayerByName((const char*)szTableName); if (poBaseLayer != NULL && EQUAL(poBaseLayer->GetGeometryColumn(), poStmt->GetColName(iColumn))) { nGeomColumnType = MSSQLCOLTYPE_BINARY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); /* copy spatial reference */ if (!poSRS && poBaseLayer->GetSpatialRef()) poSRS = poBaseLayer->GetSpatialRef()->Clone(); break; } } } else if ( EQUAL(poStmt->GetColTypeName( iColumn ), "geometry") ) { nGeomColumnType = MSSQLCOLTYPE_GEOMETRY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); break; } else if ( EQUAL(poStmt->GetColTypeName( iColumn ), "geography") ) { nGeomColumnType = MSSQLCOLTYPE_GEOGRAPHY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); break; } } BuildFeatureDefn( "SELECT", poStmt ); if ( GetSpatialRef() && poFeatureDefn->GetGeomFieldCount() == 1) poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef( poSRS ); }
bool V2vProj::Compute(const data::VectorBarral * barrel) { OGRDataSource * poSourceDs = VectorOpen(barrel->GetSrcDataSource().c_str(), GA_ReadOnly); ON_SCOPE_EXIT([&]() {OGRDataSource::DestroyDataSource(poSourceDs); }); OGRDataSource * poOutputDs = VectorOpen(barrel->GetDstDataSource().c_str(), GA_Update); ON_SCOPE_EXIT([&]() {OGRDataSource::DestroyDataSource(poOutputDs); }); OGRLayer * poSrcLayer = poSourceDs->GetLayerByName( barrel->GetSrcLayer().c_str()); OGRLayer * poDstLayer = poOutputDs->GetLayerByName( barrel->GetDstLayer().c_str()); OGRSpatialReference * poSourceSRS = poSrcLayer->GetSpatialRef(); OGRCoordinateTransformation * poCT = poCT = OGRCreateCoordinateTransformation( poSourceSRS, m_ogrSr); OGRFeatureDefn * poDstFeatureDefn = poDstLayer->GetLayerDefn(); auto features = barrel->GetFeatures(); std::for_each(begin(features), end(features) , [&](int fid) { poSrcLayer->GetFeature(fid); OGRFeature * poDstFeature = OGRFeature::CreateFeature(poDstFeatureDefn); ON_SCOPE_EXIT([&]() {OGRFeature::DestroyFeature(poDstFeature); }); poDstFeature->SetFrom(poSrcLayer->GetFeature(fid)); OGRGeometry * poDstGeometry = poDstFeature->GetGeometryRef(); OGRGeometry * poReprojectedGeom = OGRGeometryFactory::transformWithOptions( poDstGeometry, poCT, NULL); poDstFeature->SetGeometryDirectly(poReprojectedGeom); poDstLayer->CreateFeature(poDstFeature); }); return true; }
OGRPGeoSelectLayer::OGRPGeoSelectLayer( OGRPGeoDataSource *poDSIn, CPLODBCStatement * poStmtIn ) { poDS = poDSIn; iNextShapeId = 0; nSRSId = -1; poFeatureDefn = NULL; poStmt = poStmtIn; pszBaseStatement = CPLStrdup( poStmtIn->GetCommand() ); /* Just to make test_ogrsf happy, but would/could need be extended to */ /* other cases */ if( EQUALN(pszBaseStatement, "SELECT * FROM ", strlen("SELECT * FROM ")) ) { OGRLayer* poBaseLayer = poDSIn->GetLayerByName(pszBaseStatement + strlen("SELECT * FROM ")); if( poBaseLayer != NULL ) { poSRS = poBaseLayer->GetSpatialRef(); if( poSRS != NULL ) poSRS->Reference(); } } BuildFeatureDefn( "SELECT", poStmt ); }
bool OGRPointToLatLon(double &x, double &y, OGRDataSourceH hDS, const char *datum) { char *pszPrj = NULL; OGRSpatialReference *poSrcSRS; OGRSpatialReference oSourceSRS, oTargetSRS; OGRCoordinateTransformation *poCT; if (hDS == NULL) { return false; } OGRLayer *poLayer; poLayer = (OGRLayer *)OGR_DS_GetLayer(hDS, 0); poLayer->ResetReading(); poSrcSRS = poLayer->GetSpatialRef(); if (poSrcSRS == NULL) { return false; } oTargetSRS.SetWellKnownGeogCS(datum); poCT = OGRCreateCoordinateTransformation(poSrcSRS, &oTargetSRS); if (poCT == NULL) { return false; } if (!poCT->Transform(1, &x, &y)) { OGRCoordinateTransformation::DestroyCT(poCT); return false; } OGRCoordinateTransformation::DestroyCT(poCT); return true; }
void readQuadIndex(int series, QString file, QString layerName, Projection *pj) { OGRDataSource *ds = OGRSFDriverRegistrar::Open(file.toLatin1().data(), false); if (!ds) { fprintf(stderr, "Could not open quad index '%s'.\n", file.toLatin1().data()); exit(-1); } OGRLayer *layer; layer = ds->GetLayerByName(layerName.toLatin1().data()); if (!layer) { fprintf(stderr, "Could not read layer '%s'.\n", layerName.toLatin1().data()); exit(-1); } OGRSpatialReference *srs = layer->GetSpatialRef(); if (!srs) { fprintf(stderr, "Missing spatial reference for layer '%s'.\n", layerName.toLatin1().data()); exit(-1); } char *proj = NULL; srs->exportToProj4(&proj); if (!proj) { fprintf(stderr, "Error computing PROJ4 spatial reference for layer '%s'.\n", layerName.toLatin1().data()); exit(-1); } Projection pjIndex(proj); CPLFree(proj); layer->ResetReading(); OGRFeatureDefn *def = layer->GetLayerDefn(); int idFieldNr = def->GetFieldIndex("ID"); int nameFieldNr = def->GetFieldIndex("NAME"); if (idFieldNr < 0 || nameFieldNr < 0) { fprintf(stderr, "Missing index layer fields.\n"); exit(-1); } OGRFeature *f; while ((f = layer->GetNextFeature()) != NULL) { QString id(f->GetFieldAsString(idFieldNr)); QString name(f->GetFieldAsString(nameFieldNr)); // printf("Quad id: %s; name: %s\n", id.toLatin1().data(), name.toLatin1().data()); OGRGeometry *g; g = f->GetGeometryRef(); if (g != NULL && wkbFlatten(g->getGeometryType()) == wkbPolygon) { OGRPolygon *p = (OGRPolygon *)g; OGRLinearRing *r = p->getExteriorRing(); if (!r) { fprintf(stderr, "Quad has no exterior polygon ring %s\n", id.toLatin1().data()); continue; } int size = r->getNumPoints(); QPolygonF boundary; for (int i = 0; i < size; i++) { OGRPoint p; r->getPoint(i, &p); boundary << QPointF(p.getX(), p.getY()); } QPolygonF projBoundary = pj->transformFrom(&pjIndex, boundary); quads[id] = Quad(series, id, name, projBoundary); } else { fprintf(stderr, "Missing or invalid geometry for quad %s\n", id.toLatin1().data()); } } OGRDataSource::DestroyDataSource(ds); }
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. */ /* -------------------------------------------------------------------- */ OGRDataSource *poDstDS; OGRLayer *poDstLayer = NULL; poDstDS = OGRSFDriverRegistrar::Open( pszOutputName, TRUE ); /* -------------------------------------------------------------------- */ /* If that failed, find the driver so we can create the tile index.*/ /* -------------------------------------------------------------------- */ if( poDstDS == NULL ) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); OGRSFDriver *poDriver = NULL; int iDriver; for( iDriver = 0; iDriver < poR->GetDriverCount() && poDriver == NULL; iDriver++ ) { if( EQUAL(poR->GetDriver(iDriver)->GetName(),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)->GetName() ); } exit( 1 ); } if( !poDriver->TestCapability( ODrCCreateDataSource ) ) { fprintf( stderr, "%s driver does not support data source creation.\n", pszFormat ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Now create it. */ /* -------------------------------------------------------------------- */ poDstDS = poDriver->CreateDataSource( pszOutputName, 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) { OGRDataSource* poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], FALSE ); 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; } } OGRDataSource::DestroyDataSource( 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 = 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) { OGRDataSource *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 = OGRSFDriverRegistrar::Open(filename, FALSE ); 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(); } OGRDataSource::DestroyDataSource( 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; OGRDataSource *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 = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], FALSE ); 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." ); OGRDataSource::DestroyDataSource( poDstDS ); exit( 1 ); } } /* -------------------------------------------------------------------- */ /* Cleanup this data source. */ /* -------------------------------------------------------------------- */ CPLFree(fileNameToWrite); OGRDataSource::DestroyDataSource( poDS ); } /* -------------------------------------------------------------------- */ /* Close tile index and clear buffers. */ /* -------------------------------------------------------------------- */ OGRDataSource::DestroyDataSource( 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); } return 0; }
void PCLoaderArcView::load(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, PCTypeMap&) { #ifdef HAVE_GDAL GeoConvHelper& geoConvHelper = GeoConvHelper::getProcessing(); // get defaults std::string prefix = oc.getString("prefix"); std::string type = oc.getString("type"); RGBColor color = RGBColor::parseColor(oc.getString("color")); int layer = oc.getInt("layer"); std::string idField = oc.getString("shapefile.id-column"); bool useRunningID = oc.getBool("shapefile.use-running-id"); // start parsing std::string shpName = file + ".shp"; OGRRegisterAll(); OGRDataSource* poDS = OGRSFDriverRegistrar::Open(shpName.c_str(), FALSE); if (poDS == NULL) { throw ProcessError("Could not open shape description '" + shpName + "'."); } // begin file parsing OGRLayer* poLayer = poDS->GetLayer(0); poLayer->ResetReading(); // build coordinate transformation OGRSpatialReference* origTransf = poLayer->GetSpatialRef(); OGRSpatialReference destTransf; // use wgs84 as destination destTransf.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf); if (poCT == NULL) { if (oc.isSet("shapefile.guess-projection")) { OGRSpatialReference origTransf2; origTransf2.SetWellKnownGeogCS("WGS84"); poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf); } if (poCT == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } } OGRFeature* poFeature; poLayer->ResetReading(); unsigned int runningID = 0; while ((poFeature = poLayer->GetNextFeature()) != NULL) { // read in edge attributes std::string id = useRunningID ? toString(runningID) : poFeature->GetFieldAsString(idField.c_str()); ++runningID; id = StringUtils::prune(id); if (id == "") { throw ProcessError("Missing id under '" + idField + "'"); } id = prefix + id; // read in the geometry OGRGeometry* poGeometry = poFeature->GetGeometryRef(); if (poGeometry == 0) { OGRFeature::DestroyFeature(poFeature); continue; } // try transform to wgs84 poGeometry->transform(poCT); OGRwkbGeometryType gtype = poGeometry->getGeometryType(); switch (gtype) { case wkbPoint: { OGRPoint* cgeom = (OGRPoint*) poGeometry; Position pos((SUMOReal) cgeom->getX(), (SUMOReal) cgeom->getY()); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for POI '" + id + "'."); } PointOfInterest* poi = new PointOfInterest(id, type, color, pos, (SUMOReal)layer); if (!toFill.insert(id, poi, layer)) { WRITE_ERROR("POI '" + id + "' could not be added."); delete poi; } } break; case wkbLineString: { OGRLineString* cgeom = (OGRLineString*) poGeometry; PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + id + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(id, type, color, shape, false, (SUMOReal)layer); if (!toFill.insert(id, poly, layer)) { WRITE_ERROR("Polygon '" + id + "' could not be added."); delete poly; } } break; case wkbPolygon: { OGRLinearRing* cgeom = ((OGRPolygon*) poGeometry)->getExteriorRing(); PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + id + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(id, type, color, shape, true, (SUMOReal)layer); if (!toFill.insert(id, poly, layer)) { WRITE_ERROR("Polygon '" + id + "' could not be added."); delete poly; } } break; case wkbMultiPoint: { OGRMultiPoint* cgeom = (OGRMultiPoint*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRPoint* cgeom2 = (OGRPoint*) cgeom->getGeometryRef(i); Position pos((SUMOReal) cgeom2->getX(), (SUMOReal) cgeom2->getY()); std::string tid = id + "#" + toString(i); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for POI '" + tid + "'."); } PointOfInterest* poi = new PointOfInterest(tid, type, color, pos, (SUMOReal)layer); if (!toFill.insert(tid, poi, layer)) { WRITE_ERROR("POI '" + tid + "' could not be added."); delete poi; } } } break; case wkbMultiLineString: { OGRMultiLineString* cgeom = (OGRMultiLineString*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRLineString* cgeom2 = (OGRLineString*) cgeom->getGeometryRef(i); PositionVector shape; std::string tid = id + "#" + toString(i); for (int j = 0; j < cgeom2->getNumPoints(); j++) { Position pos((SUMOReal) cgeom2->getX(j), (SUMOReal) cgeom2->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + tid + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(tid, type, color, shape, false, (SUMOReal)layer); if (!toFill.insert(tid, poly, layer)) { WRITE_ERROR("Polygon '" + tid + "' could not be added."); delete poly; } } } break; case wkbMultiPolygon: { OGRMultiPolygon* cgeom = (OGRMultiPolygon*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRLinearRing* cgeom2 = ((OGRPolygon*) cgeom->getGeometryRef(i))->getExteriorRing(); PositionVector shape; std::string tid = id + "#" + toString(i); for (int j = 0; j < cgeom2->getNumPoints(); j++) { Position pos((SUMOReal) cgeom2->getX(j), (SUMOReal) cgeom2->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + tid + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(tid, type, color, shape, true, (SUMOReal)layer); if (!toFill.insert(tid, poly, layer)) { WRITE_ERROR("Polygon '" + tid + "' could not be added."); delete poly; } } } break; default: WRITE_WARNING("Unsupported shape type occured (id='" + id + "')."); break; } OGRFeature::DestroyFeature(poFeature); } PROGRESS_DONE_MESSAGE(); #else WRITE_ERROR("SUMO was compiled without GDAL support."); #endif }
void NIImporter_ArcView::load() { #ifdef HAVE_GDAL PROGRESS_BEGIN_MESSAGE("Loading data from '" + mySHPName + "'"); #if GDAL_VERSION_MAJOR < 2 OGRRegisterAll(); OGRDataSource* poDS = OGRSFDriverRegistrar::Open(mySHPName.c_str(), FALSE); #else GDALAllRegister(); GDALDataset* poDS = (GDALDataset*)GDALOpenEx(mySHPName.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL); #endif if (poDS == NULL) { WRITE_ERROR("Could not open shape description '" + mySHPName + "'."); return; } // begin file parsing OGRLayer* poLayer = poDS->GetLayer(0); poLayer->ResetReading(); // build coordinate transformation OGRSpatialReference* origTransf = poLayer->GetSpatialRef(); OGRSpatialReference destTransf; // use wgs84 as destination destTransf.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf); if (poCT == NULL) { if (myOptions.isSet("shapefile.guess-projection")) { OGRSpatialReference origTransf2; origTransf2.SetWellKnownGeogCS("WGS84"); poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf); } if (poCT == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } } OGRFeature* poFeature; poLayer->ResetReading(); while ((poFeature = poLayer->GetNextFeature()) != NULL) { // read in edge attributes std::string id, name, from_node, to_node; if (!getStringEntry(poFeature, "shapefile.street-id", "LINK_ID", true, id)) { WRITE_ERROR("Needed field '" + id + "' (from node id) is missing."); } if (id == "") { WRITE_ERROR("Could not obtain edge id."); return; } getStringEntry(poFeature, "shapefile.street-id", "ST_NAME", true, name); name = StringUtils::replace(name, "&", "&"); if (!getStringEntry(poFeature, "shapefile.from-id", "REF_IN_ID", true, from_node)) { WRITE_ERROR("Needed field '" + from_node + "' (from node id) is missing."); } if (!getStringEntry(poFeature, "shapefile.to-id", "NREF_IN_ID", true, to_node)) { WRITE_ERROR("Needed field '" + to_node + "' (to node id) is missing."); } if (from_node == "" || to_node == "") { from_node = toString(myRunningNodeID++); to_node = toString(myRunningNodeID++); } std::string type; if (myOptions.isSet("shapefile.type-id") && poFeature->GetFieldIndex(myOptions.getString("shapefile.type-id").c_str()) >= 0) { type = poFeature->GetFieldAsString(myOptions.getString("shapefile.type-id").c_str()); } else if (poFeature->GetFieldIndex("ST_TYP_AFT") >= 0) { type = poFeature->GetFieldAsString("ST_TYP_AFT"); } SUMOReal width = myTypeCont.getWidth(type); SUMOReal speed = getSpeed(*poFeature, id); int nolanes = getLaneNo(*poFeature, id, speed); int priority = getPriority(*poFeature, id); if (nolanes == 0 || speed == 0) { if (myOptions.getBool("shapefile.use-defaults-on-failure")) { nolanes = myTypeCont.getNumLanes(""); speed = myTypeCont.getSpeed(""); } else { OGRFeature::DestroyFeature(poFeature); WRITE_ERROR("The description seems to be invalid. Please recheck usage of types."); return; } } if (mySpeedInKMH) { speed = speed / (SUMOReal) 3.6; } // read in the geometry OGRGeometry* poGeometry = poFeature->GetGeometryRef(); OGRwkbGeometryType gtype = poGeometry->getGeometryType(); assert(gtype == wkbLineString); UNUSED_PARAMETER(gtype); // ony used for assertion OGRLineString* cgeom = (OGRLineString*) poGeometry; if (poCT != 0) { // try transform to wgs84 cgeom->transform(poCT); } PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!NBNetBuilder::transformCoordinate(pos)) { WRITE_WARNING("Unable to project coordinates for edge '" + id + "'."); } shape.push_back_noDoublePos(pos); } // build from-node NBNode* from = myNodeCont.retrieve(from_node); if (from == 0) { Position from_pos = shape[0]; from = myNodeCont.retrieve(from_pos); if (from == 0) { from = new NBNode(from_node, from_pos); if (!myNodeCont.insert(from)) { WRITE_ERROR("Node '" + from_node + "' could not be added"); delete from; continue; } } } // build to-node NBNode* to = myNodeCont.retrieve(to_node); if (to == 0) { Position to_pos = shape[-1]; to = myNodeCont.retrieve(to_pos); if (to == 0) { to = new NBNode(to_node, to_pos); if (!myNodeCont.insert(to)) { WRITE_ERROR("Node '" + to_node + "' could not be added"); delete to; continue; } } } if (from == to) { WRITE_WARNING("Edge '" + id + "' connects identical nodes, skipping."); continue; } // retrieve the information whether the street is bi-directional std::string dir; int index = poFeature->GetDefnRef()->GetFieldIndex("DIR_TRAVEL"); if (index >= 0 && poFeature->IsFieldSet(index)) { dir = poFeature->GetFieldAsString(index); } // add positive direction if wanted if (dir == "B" || dir == "F" || dir == "" || myOptions.getBool("shapefile.all-bidirectional")) { if (myEdgeCont.retrieve(id) == 0) { LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LANESPREAD_RIGHT : LANESPREAD_CENTER; NBEdge* edge = new NBEdge(id, from, to, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape, name, id, spread); myEdgeCont.insert(edge); checkSpread(edge); } } // add negative direction if wanted if (dir == "B" || dir == "T" || myOptions.getBool("shapefile.all-bidirectional")) { if (myEdgeCont.retrieve("-" + id) == 0) { LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LANESPREAD_RIGHT : LANESPREAD_CENTER; NBEdge* edge = new NBEdge("-" + id, to, from, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape.reverse(), name, id, spread); myEdgeCont.insert(edge); checkSpread(edge); } } // OGRFeature::DestroyFeature(poFeature); } #if GDAL_VERSION_MAJOR < 2 OGRDataSource::DestroyDataSource(poDS); #else GDALClose(poDS); #endif PROGRESS_DONE_MESSAGE(); #else WRITE_ERROR("SUMO was compiled without GDAL support."); #endif }
int Raster::VectortoRaster(const char * sVectorSourcePath, const char * sRasterOutputPath, const char * psFieldName, RasterMeta * p_rastermeta ){ OGRRegisterAll(); OGRDataSource * pDSVectorInput; pDSVectorInput = OGRSFDriverRegistrar::Open( sVectorSourcePath, FALSE ); if (pDSVectorInput == NULL) return INPUT_FILE_ERROR; OGRLayer * poLayer = pDSVectorInput->GetLayer(0); // The type of the field. OGRFeature * feat1 = poLayer->GetFeature(0); int fieldindex = feat1->GetFieldIndex(psFieldName); OGRFieldType fieldType = feat1->GetFieldDefnRef(fieldindex)->GetType(); OGRFeature::DestroyFeature( feat1 ); // The data type we're going to use for the file GDALDataType OutputDataType = GDT_Byte; // Handle field types according to their type: switch (fieldType) { case OFTString: CSVWriteVectorValues(poLayer, psFieldName, sRasterOutputPath); break; case OFTInteger: break; case OFTReal: OutputDataType = GDT_Float64; default: throw RasterManagerException(VECTOR_FIELD_NOT_VALID, "Type of field not recognized."); break; } // Get our projection and set the rastermeta accordingly. // ------------------------------------------------------- char *pszWKT = NULL; OGRSpatialReference* poSRS = poLayer->GetSpatialRef(); poSRS->exportToWkt(&pszWKT); p_rastermeta->SetProjectionRef(pszWKT); CPLFree(pszWKT); OSRDestroySpatialReference(poSRS); // Create the output dataset for writing GDALDataset * pDSOutput = CreateOutputDS(sRasterOutputPath, p_rastermeta); // Create a list of burn-in values // ------------------------------------------------------- std::vector<OGRGeometryH> ogrBurnGeometries; std::vector<double> dBurnValues; poLayer->ResetReading(); OGRFeature * ogrFeat = poLayer->GetNextFeature(); // <------- DRMEM!!! UNADDRESSABLE ACCESS of freed memory while( ogrFeat != NULL ){ OGRGeometry * ogrGeom = ogrFeat->GetGeometryRef(); // No geometry found. Move along. if( ogrGeom == NULL ) { OGRFeature::DestroyFeature( ogrFeat ); continue; } OGRGeometry * geoClone = ogrGeom->clone(); // <------- DRMEM!!! UNADDRESSABLE ACCESS of freed memory AND LEAK 20 direct bytes // Push a clone of this geometry onto the list of shapes to burn ogrBurnGeometries.push_back( (OGRGeometryH) geoClone ); if (fieldType == OFTString){ // If it's a string type we burn the FID. The value is then placed in a CSV file dBurnValues.push_back( ogrFeat->GetFID() ); } else { // If it's a float type or a byte type we write it directly. dBurnValues.push_back( ogrFeat->GetFieldAsDouble(psFieldName) ); } // GetNextFeature() creates a clone so we must delete it. OGRFeature::DestroyFeature( ogrFeat ); // <------- DRMEM!!! UNADDRESSABLE ACCESS beyond heap bounds: ogrFeat = poLayer->GetNextFeature(); // <------- DRMEM!!! UNADDRESSABLE ACCESS of freed memory } // Do the Actual Burning of Geometries. // ------------------------------------------------------- int band = 1; char **papszRasterizeOptions = NULL; papszRasterizeOptions = CSLSetNameValue( papszRasterizeOptions, "ALL_TOUCHED", "TRUE" ); CPLErr err = GDALRasterizeGeometries( pDSOutput, 1, &band, ogrBurnGeometries.size(), &(ogrBurnGeometries[0]), NULL, NULL, &(dBurnValues[0]), NULL, NULL, NULL ); if (err) { } ogrBurnGeometries.clear(); dBurnValues.clear(); // Done. Calculate stats and close file CalculateStats(pDSOutput->GetRasterBand(1)); CSLDestroy(papszRasterizeOptions); GDALClose(pDSOutput); pDSVectorInput->Release(); // <------- DRMEM!!! UNADDRESSABLE ACCESS beyond heap bounds: //This is where the implementation actually goes return PROCESS_OK; }
FBErr FBProjectGdal::readFromDataset (QString datasetPath) { // Firstly try to open dataset and check its correctness. QByteArray ba; ba = datasetPath.toUtf8(); GDALDataset *dataset; dataset = (GDALDataset*) GDALOpenEx(ba.data(), GDAL_OF_VECTOR, NULL, NULL, NULL); if (dataset == NULL) { FBProject::CUR_ERR_INFO = QObject::tr("Unable to open dataset via GDAL"); return FBErrIncorrectGdalDataset; } // Check layer's count. int layerCount = dataset->GetLayerCount(); if (layerCount == 0 || layerCount > 1) { GDALClose(dataset); FBProject::CUR_ERR_INFO = QObject::tr("Selected GDAL dataset must contain 1" "layer, while it contains ") + QString::number(layerCount); return FBErrIncorrectGdalDataset; } OGRLayer *layer = dataset->GetLayer(0); if (layer == NULL) { GDALClose(dataset); FBProject::CUR_ERR_INFO = QObject::tr("Unable to read layer in selected GDAL" "dataset"); return FBErrIncorrectGdalDataset; } OGRFeatureDefn *layerDefn = layer->GetLayerDefn(); if (layerDefn->GetFieldCount() == 0) { GDALClose(dataset); FBProject::CUR_ERR_INFO = QObject::tr("Selected GDAL dataset's layer must" " contain at least one field, while it contains no fields"); return FBErrIncorrectGdalDataset_NotForNgw; } OGRSpatialReference *layerSpaRef = layer->GetSpatialRef(); if (layerSpaRef == NULL) { GDALClose(dataset); FBProject::CUR_ERR_INFO = QObject::tr("Selected GDAL dataset does not contain" " its spatial reference system description"); return FBErrIncorrectGdalDataset; } // All checks were made and we can fill the rest metadata of the project, which // can be read via GDAL. OGRwkbGeometryType geomType = layerDefn->GetGeomType(); FbGeomType *gt = FBProject::findGeomTypeByGdal(geomType); if (gt == NULL) { // No default value for geometry type. NextGIS Mobile will not be able // to read "undefined" geometry. So rise error here. // TODO: do not rise error for GDAL types which can be translated, such as // wkbPolygon25D to simple Polygon. GDALClose(dataset); FBProject::CUR_ERR_INFO = QObject::tr("Selected GDAL dataset has unsupported" " geometry type: ") + OGRGeometryTypeToName(geomType); return FBErrIncorrectGdalDataset_NotForNgw; } geometry_type = gt; for (int i=0; i<layerDefn->GetFieldCount(); i++) { FBField descr; OGRFieldDefn *fieldDefn = layerDefn->GetFieldDefn(i); OGRFieldType fieldType = fieldDefn->GetType(); FbDataType *dt = FBProject::findDataTypeByGdal(fieldType); if (dt == NULL) { // Default datatype. // Data will be converted to string during the writing into JSON file. descr.datataype = DATA_TYPES[FB_TYPEINDEX_DATA_STRING]; } else { descr.datataype = dt; } descr.display_name = QString::fromUtf8(fieldDefn->GetNameRef()); fields.insert(QString::fromUtf8(fieldDefn->GetNameRef()), descr); } GDALClose(dataset); return FBErrNone; }
int main( int argc, char ** argv ) { int i; int bGotSRS = FALSE; int bPretty = FALSE; int bOutputAll = FALSE; int bValidate = FALSE; const char *pszInput = NULL; const char *pszOutputType = "all"; char *pszOutput = NULL; OGRSpatialReference oSRS; VSILFILE *fp = NULL; GDALDataset *poGDALDS = NULL; OGRDataSource *poOGRDS = NULL; OGRLayer *poLayer = NULL; char *pszProjection = NULL; int bDebug = FALSE; CPLErrorHandler oErrorHandler = NULL; int bIsFile = FALSE; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); /* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */ /* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */ /* for the --format or --formats options */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i],"--config") && i + 2 < argc && EQUAL(argv[i + 1], "GDAL_SKIP") ) { CPLSetConfigOption( argv[i+1], argv[i+2] ); i += 2; } } argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Parse arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { CPLDebug( "gdalsrsinfo", "got arg #%d : [%s]", i, argv[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], "-h") ) Usage(); else if( EQUAL(argv[i], "-o") && i < argc - 1) pszOutputType = argv[++i]; else if( EQUAL(argv[i], "-p") ) bPretty = TRUE; else if( EQUAL(argv[i], "-V") ) bValidate = TRUE; else if( argv[i][0] == '-' ) { CSLDestroy( argv ); Usage(); } else pszInput = argv[i]; } if ( pszInput == NULL ) { CSLDestroy( argv ); Usage(); } /* Register drivers */ GDALAllRegister(); OGRRegisterAll(); /* Search for SRS */ /* temporarily supress error messages we may get from xOpen() */ bDebug = CSLTestBoolean(CPLGetConfigOption("CPL_DEBUG", "OFF")); if ( ! bDebug ) oErrorHandler = CPLSetErrorHandler ( CPLQuietErrorHandler ); /* If argument is a file, try to open it with GDALOpen() and get the projection */ fp = VSIFOpenL( pszInput, "r" ); if ( fp ) { bIsFile = TRUE; VSIFCloseL( fp ); /* try to open with GDAL */ CPLDebug( "gdalsrsinfo", "trying to open with GDAL" ); poGDALDS = (GDALDataset *) GDALOpen( pszInput, GA_ReadOnly ); if ( poGDALDS != NULL && poGDALDS->GetProjectionRef( ) != NULL ) { pszProjection = (char *) poGDALDS->GetProjectionRef( ); if( oSRS.importFromWkt( &pszProjection ) == CE_None ) { CPLDebug( "gdalsrsinfo", "got SRS from GDAL" ); bGotSRS = TRUE; } GDALClose( (GDALDatasetH) poGDALDS ); } if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with GDAL" ); /* if unsuccessful, try to open with OGR */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to open with OGR" ); poOGRDS = OGRSFDriverRegistrar::Open( pszInput, FALSE, NULL ); if( poOGRDS != NULL ) { poLayer = poOGRDS->GetLayer( 0 ); if ( poLayer != NULL ) { OGRSpatialReference *poSRS = poLayer->GetSpatialRef( ); if ( poSRS != NULL ) { CPLDebug( "gdalsrsinfo", "got SRS from OGR" ); bGotSRS = TRUE; OGRSpatialReference* poSRSClone = poSRS->Clone(); oSRS = *poSRSClone; OGRSpatialReference::DestroySpatialReference( poSRSClone ); } } OGRDataSource::DestroyDataSource( poOGRDS ); poOGRDS = NULL; } if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with OGR" ); /* OGR_DS_Destroy( hOGRDS ); */ } } /* If didn't get the projection from the file, try OSRSetFromUserInput() */ /* File might not be a dataset, but contain projection info (e.g. .prf files) */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from user input [%s]", pszInput ); if( oSRS.SetFromUserInput( pszInput ) != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from user input" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from user input" ); bGotSRS = TRUE; } } /* restore error messages */ if ( ! bDebug ) CPLSetErrorHandler ( oErrorHandler ); CPLDebug( "gdalsrsinfo", "bGotSRS: %d bValidate: %d pszOutputType: %s bPretty: %d", bGotSRS, bValidate, pszOutputType, bPretty ); /* Make sure we got a SRS */ if ( ! bGotSRS ) { CPLError( CE_Failure, CPLE_AppDefined, "ERROR - failed to load SRS definition from %s", pszInput ); } else { /* Validate - not well tested!*/ if ( bValidate ) { OGRErr eErr = oSRS.Validate( ); if ( eErr != OGRERR_NONE ) { printf( "\nValidate Fails" ); if ( eErr == OGRERR_CORRUPT_DATA ) printf( " - SRS is not well formed"); else if ( eErr == OGRERR_UNSUPPORTED_SRS ) printf(" - contains non-standard PROJECTION[] values"); printf("\n"); } else printf( "\nValidate Succeeds\n" ); } /* Output */ if ( EQUAL("all", pszOutputType ) ) { bOutputAll = TRUE; bPretty = TRUE; } printf("\n"); if ( bOutputAll || EQUAL("proj4", pszOutputType ) ) { if ( bOutputAll ) printf("PROJ.4 : "); oSRS.exportToProj4( &pszOutput ); printf("\'%s\'\n\n",pszOutput); CPLFree( pszOutput ); } if ( bOutputAll || EQUAL("wkt", pszOutputType ) ) { if ( bOutputAll ) printf("OGC WKT :\n"); if ( bPretty ) oSRS.exportToPrettyWkt( &pszOutput, FALSE ); else oSRS.exportToWkt( &pszOutput ); printf("%s\n\n",pszOutput); CPLFree( pszOutput ); } if ( bOutputAll || EQUAL("wkt_simple", pszOutputType ) ) { if ( bOutputAll ) printf("OGC WKT (simple) :\n"); oSRS.exportToPrettyWkt( &pszOutput, TRUE ); printf("%s\n\n",pszOutput); CPLFree( pszOutput ); } if ( EQUAL("wkt_old", pszOutputType ) ) { if ( bOutputAll ) printf("OGC WKT (old) :\n"); oSRS.StripCTParms( ); if ( bPretty ) oSRS.exportToPrettyWkt( &pszOutput, FALSE ); else oSRS.exportToWkt( &pszOutput ); printf("%s\n\n",pszOutput); CPLFree( pszOutput ); } if ( bOutputAll || EQUAL("wkt_esri", pszOutputType ) ) { if ( bOutputAll ) printf("ESRI WKT :\n"); OGRSpatialReference *poSRS = oSRS.Clone(); poSRS->morphToESRI( ); if ( bPretty ) poSRS->exportToPrettyWkt( &pszOutput, FALSE ); else poSRS->exportToWkt( &pszOutput ); printf("%s\n\n",pszOutput); CPLFree( pszOutput ); OGRSpatialReference::DestroySpatialReference( poSRS ); } /* mapinfo and xml are not output with "all" */ if ( EQUAL("mapinfo", pszOutputType ) ) { if ( bOutputAll ) printf("MAPINFO : "); oSRS.exportToMICoordSys( &pszOutput ); printf("\'%s\'\n\n",pszOutput); CPLFree( pszOutput ); } if ( EQUAL("xml", pszOutputType ) ) { if ( bOutputAll ) printf("XML :\n"); oSRS.exportToXML( &pszOutput, NULL ); printf("%s\n\n",pszOutput); CPLFree( pszOutput ); } } /* cleanup anything left */ GDALDestroyDriverManager(); OGRCleanupAll(); CSLDestroy( argv ); return 0; }
void LevelTerrainCallback::loaded(osgTerrain::TerrainTile *tile, const osgDB::ReaderWriter::Options *options) const { //Change TerrainTechnique tile->setTerrainTechnique(new DecoratedGeometryTechnique(voidBoundingAreaVector, treeStateSet.get(), buildingStateSet.get(), shapeFileVector)); std::stringstream nameStream; nameStream << "tile_L" << tile->getTileID().level << "_X" << tile->getTileID().x << "_Y" << tile->getTileID().y; tile->setName(nameStream.str()); /*tile->setName("TerrainTile"); osg::Vec3d model; tile->getLocator()->convertLocalToModel(osg::Vec3d(0.0,0.0,0.0), model); char name[1000]; sprintf(name,"X%f_Y%f_Z%f", model.x(), model.y(), model.z()); tile->setName(name);*/ //MTRand mt(10101); osgTerrain::HeightFieldLayer *hflayer = dynamic_cast<osgTerrain::HeightFieldLayer *>(tile->getElevationLayer()); osg::HeightField *field = NULL; if (hflayer) { field = hflayer->getHeightField(); } else { return; } double tileXInterval = field->getXInterval(); double tileYInterval = field->getYInterval(); double tileElementArea = tileXInterval * tileYInterval; double tileXMin = offset.x() + field->getOrigin().x(); double tileXMax = tileXMin + tileXInterval * (double)field->getNumColumns(); double tileYMin = offset.y() + field->getOrigin().y(); double tileYMax = tileYMin + tileYInterval * (double)field->getNumRows(); //osg::BoundingBox tileBB(tileXMin, tileYMin, -10.000, tileXMax, tileYMax, 10.000); if (tileXInterval > 10.0 && tileYInterval > 10.0) { return; } for (int i = 0; i < RoadSystem::Instance()->getNumRoads(); ++i) { Road *road = RoadSystem::Instance()->getRoad(i); double roadLength = road->getLength(); const osg::BoundingBox &roadBB = road->getRoadGeode()->getBoundingBox(); //if(roadBB.intersects(tileBB)) { if (((roadBB.xMax() >= tileXMin && roadBB.xMax() <= tileXMax) || (roadBB.xMin() >= tileXMin && roadBB.xMin() <= tileXMax) || (roadBB.xMin() <= tileXMin && roadBB.xMax() >= tileXMax)) && (roadBB.yMax() >= tileYMin && roadBB.yMin() <= tileYMax)) { //double h = sqrt(tileXInterval*tileXInterval + tileYInterval*tileYInterval); double h = 20.0; std::deque<RoadPoint> pointDeque(4); double widthRight, widthLeft; road->getRoadSideWidths(0.0, widthRight, widthLeft); pointDeque.pop_front(); pointDeque.pop_front(); pointDeque.push_back(road->getRoadPoint(0.0, widthLeft + 10.0)); pointDeque.push_back(road->getRoadPoint(0.0, widthRight - 10.0)); std::map<std::pair<int, int>, double> coordHeightMap; for (double s_ = h; s_ < roadLength + h; s_ = s_ + h) { double s = s_; if (s > roadLength) s = roadLength; road->getRoadSideWidths(s, widthRight, widthLeft); pointDeque.pop_front(); pointDeque.pop_front(); pointDeque.push_back(road->getRoadPoint(s, widthLeft + 10.0)); pointDeque.push_back(road->getRoadPoint(s, widthRight - 10.0)); //Bresenham // y x z std::map<int, std::map<int, double> > fillBorderMap; //iteration over four lines for (int i = 0; i < 4; ++i) { int j; switch (i) { case 0: j = 1; break; case 1: j = 3; break; case 2: j = 0; break; case 3: j = 2; break; } double fx0 = (pointDeque[i].x() - tileXMin) / tileXInterval; double fy0 = (pointDeque[i].y() - tileYMin) / tileYInterval; double fx1 = (pointDeque[j].x() - tileXMin) / tileXInterval; double fy1 = (pointDeque[j].y() - tileYMin) / tileYInterval; double dir_x = (fx0 - fx1) < 0.0 ? -1.0 : 1.0; double dir_y = (fy0 - fy1) < 0.0 ? -1.0 : 1.0; int x0 = (int)floor(fx0 + dir_x + 0.5); //if(x0<0) x0=0; else if(x0>=field->getNumColumns()) x0=field->getNumColumns()-1; int y0 = (int)floor(fy0 + dir_y + 0.5); //if(y0<0) y0=0; else if(y0>=field->getNumRows()) y0=field->getNumRows()-1; int x1 = (int)floor(fx1 - dir_x + 0.5); //if(x1<0) x1=0; else if(x1>=field->getNumColumns()) x1=field->getNumColumns()-1; int y1 = (int)floor(fy1 - dir_y + 0.5); //if(y1<0) y1=0; else if(y1>=field->getNumRows()) y1=field->getNumRows()-1; double z = 0.5 * (pointDeque[i].z() + pointDeque[j].z()); //wikipedia implementation int dx = abs(x1 - x0); int sx = x0 < x1 ? 1 : -1; int dy = -abs(y1 - y0); int sy = y0 < y1 ? 1 : -1; int err = dx + dy; int e2; /* error value e_xy */ do { /* loop */ //setPixel(x0,y0); fillBorderMap[y0][x0] = z; //fillBorderMap[y0][x0] = 0.5; //if (x0==x1 && y0==y1) break; e2 = 2 * err; if (e2 >= dy) { err += dy; x0 += sx; } /* e_xy+e_x > 0 */ if (e2 <= dx) { err += dx; y0 += sy; } /* e_xy+e_y < 0 */ } while (!(x0 == x1 && y0 == y1)); } for (std::map<int, std::map<int, double> >::iterator yScanlineIt = fillBorderMap.begin(); yScanlineIt != fillBorderMap.end(); ++yScanlineIt) { int x0 = (yScanlineIt->second.begin())->first; double z0 = (yScanlineIt->second.begin())->second; int x1 = (--(yScanlineIt->second.end()))->first; double z1 = (--(yScanlineIt->second.end()))->second; unsigned int y = yScanlineIt->first; //if(y==field->getNumRows()-1) continue; for (int x = x0; x <= x1; ++x) { if (x >= 0 && x < (int)field->getNumColumns() && y >= 0 && y < field->getNumRows()) { //field->setHeight(x,y,0.5*(z0+z1)-0.5); //double z = field->getHeight(x,y); double rl_x = 0.5 * (pointDeque[0].x() + pointDeque[1].x()); double rl_y = 0.5 * (pointDeque[0].y() + pointDeque[1].y()); double ru_x = 0.5 * (pointDeque[2].x() + pointDeque[3].x()); double ru_y = 0.5 * (pointDeque[2].y() + pointDeque[3].y()); double t_x = ru_x - rl_x; double t_y = ru_y - rl_y; double mag_t = sqrt(t_x * t_x + t_y * t_y); if (mag_t != mag_t) continue; t_x /= mag_t; t_y /= mag_t; double rp_x = tileXInterval * ((double)(x)) + tileXMin - rl_x; double rp_y = tileYInterval * ((double)(y)) + tileYMin - rl_y; double d_x = -t_y * t_x * rp_y + t_y * t_y * rp_x; double d_y = t_x * t_x * rp_y - t_x * t_y * rp_x; double d = sqrt(d_x * d_x + d_y * d_y); //double mag_d = sqrt(d_x*d_x + d_y*d_y); //double d = 0.0; //if(mag_d==mag_d) { // d = (d_x*d_x+d_y*d_y)/mag_d; //} double s_x = rp_x - d_x; double s_y = rp_y - d_y; double s = sqrt(s_x * s_x + s_y * s_y); double wl = sqrt(pow(pointDeque[0].x() - pointDeque[1].x(), 2) + pow(pointDeque[0].y() - pointDeque[1].y(), 2)); double wu = sqrt(pow(pointDeque[2].x() - pointDeque[3].x(), 2) + pow(pointDeque[2].y() - pointDeque[3].y(), 2)); double l = sqrt(pow(0.5 * (pointDeque[0].x() - pointDeque[2].x() + pointDeque[1].x() - pointDeque[3].x()), 2) + pow(0.5 * (pointDeque[0].y() - pointDeque[2].y() + pointDeque[1].y() - pointDeque[3].y()), 2)); double zt; std::map<std::pair<int, int>, double>::iterator coordHeightMapIt = coordHeightMap.find(std::make_pair(x, y)); if (coordHeightMapIt == coordHeightMap.end()) { zt = (double)field->getHeight(x, y); coordHeightMap[std::make_pair(x, y)] = zt; } else { zt = coordHeightMapIt->second; } double zf0 = 7.0; double zf = 0.5 * (z0 + z1) - zf0; double kt0 = 50.0; double kt = (d / (0.5 * (wl + (wu - wl) * s / l))) * kt0; double kf0 = 10.0; double kf = (1.0 - d / (0.5 * (wl + (wu - wl) * s / l))) * kf0; double zl = (zt * kt + zf * kf) / (kt + kf); double z_field = field->getHeight(x, y); if (z_field > zl) { field->setHeight(x, y, zl); } //std::cout << "(x,y): (" << x << "," << y << "), zt: " << zt << ", zf: " << zf << ", kt: " << kt << ", kf: " << kf << std::endl; //field->setHeight(x,y, std::min(zf, 0.5*(z0+z1) - 1.0*(1.0- d/(wl+(wu-wl)*s/l)) ) ); //std::cout << "(x,y): (" << x << "," << y << "), z0: " << z0 << ", z1: " << z1 << ", d: " << d << ", wl: " << wl << ", wu: " << wu << ", s: " << s << ", l: " << l << std::endl; } } } /*Vector3D roadCenterPoint = road->getCenterLinePoint(s); int x = floor((roadCenterPoint.x() - tileXMin)/tileXInterval + 0.5); int y = floor((roadCenterPoint.y() - tileYMin)/tileYInterval + 0.5); if(x>=0 && x<field->getNumColumns() && y>=0 && y<field->getNumRows()) { field->setHeight(x,y,0.0); }*/ } } } #if 0 //osg::Group* treeGroup = new osg::Group(); //tile->addChild(treeGroup); //treeGroup->setName("TreeGroup"); osg::PositionAttitudeTransform* treeGeodeTransform = new osg::PositionAttitudeTransform; tile->addChild(treeGeodeTransform); treeGeodeTransform->setName("TreeGeodeTransform"); osg::Vec3 tileMin(tileXMin, tileYMin, 0.0); treeGeodeTransform->setPosition(-offset + tileMin); osg::Geode* treeGeode = new osg::Geode(); //tile->addChild(treeGeode); treeGeodeTransform->addChild(treeGeode); treeGeode->setName("TreeGeode"); treeGeode->setStateSet(treeStateSet); #endif #if 0 for(int layerIt = 0; layerIt < layers.size(); ++layerIt) { OGRLayer* layer = layers[layerIt]; layer->ResetReading(); OGRFeature* poFeature = NULL; while((poFeature = layer->GetNextFeature()) != NULL) { OGRGeometry *poGeometry = poFeature->GetGeometryRef(); if(poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon) { OGRPolygon *poPolygon = dynamic_cast<OGRPolygon*>(poGeometry); //std::cout << "Geometry name: " << poPolygon->getGeometryName() << std::endl; //std::cout << "Polgon area: " << poPolygon->get_Area() << std::endl; OGRSpatialReference *poSource = layer->GetSpatialRef(); OGRSpatialReference *poTarget = new OGRSpatialReference(); poTarget->importFromProj4("+proj=utm +zone=32"); OGRCoordinateTransformation* poCoordTrans = OGRCreateCoordinateTransformation(poSource, poTarget); poPolygon->transform(poCoordTrans); OGRLinearRing* poRing = poPolygon->getExteriorRing(); /*for(int pointIt = 0; pointIt<poRing->getNumPoints(); ++pointIt) { std::cout << "Point " << pointIt << ": (" << poRing->getX(pointIt) + offset.x() << ", " << poRing->getY(pointIt) + offset.y() << ", " << poRing->getZ(pointIt) << ")" << std::endl; }*/ /*double interval = 10.0*sqrt(tileXInterval*tileXInterval + tileYInterval*tileYInterval); OGRPoint point; poRing->Value(0, &point); OGRPoint point_next; for(double s = 0; s<poRing->get_Length(); s += interval*mt()) { double s_next = s+interval; if(s_next>poRing->get_Length()) s_next = poRing->get_Length(); poRing->Value(s_next, &point_next); double ccw = poRing->isClockwise() ? -1.0 : 1.0; double t_x = point_next.getX() - point.getX(); double t_y = point_next.getY() - point.getY(); double n_x = -t_y*ccw; double n_y = t_x*ccw; double mag_n = sqrt(n_x*n_x+n_y*n_y); if(mag_n>1e-3) { n_x /= mag_n; n_y /= mag_n; } double n_mt = mt(); double x = point.getX()+offset.x() + 0.5*t_x + 10.0*n_mt*n_x; double y = point.getY()+offset.y() + 0.5*t_y + 10.0*n_mt*n_y; //std::cout << "t_x: " << t_x << ", t_y: " << t_y << ", n_x: " << 10.0*n_mt*n_x << ", n_y: " << 10.0*n_mt*n_y << std::endl; std::cout << "x: " << x << ", y: " << y << std::endl; point = point_next; //std::cout << "Boundary trace: s: " << s << ", x: " << x << ", y:" << y << ", tile min: (" << tileXMin << ", " << tileYMin << "), max: (" << tileXMax << ", " << tileYMax << ")" << std::endl; osg::BoundingBox tileBB(tileXMin, tileYMin, -1.0, tileXMax, tileYMax, 1.0); if(tileBB.contains(osg::Vec3(x,y,0.0))) { osg::PositionAttitudeTransform* treeTrans = new osg::PositionAttitudeTransform(); treeGroup->addChild(treeTrans); //hflayer->getInterpolatedValue(x,y,z); int x_int = floor((x-tileXMin)/tileXInterval+0.5); if(x_int<0) x_int=0; else if(x_int>=field->getNumColumns()) x_int=field->getNumColumns()-1; int y_int = floor((y-tileYMin)/tileYInterval+0.5); if(y_int<0) y_int=0; else if(y_int>=field->getNumRows()) y_int=field->getNumRows()-1; double z = field->getHeight(x_int,y_int); //osg::Vec3 treePos(x,y,z); osg::Vec3 treePos(point.getX(),point.getY(),z); treeTrans->setPosition(treePos); int treeIt = (int)floor(mt()*(double)treeNodeVector.size()); treeTrans->addChild(treeNodeVector[treeIt].get()); treeTrans->setName("TreeTransform"); } }*/ OGREnvelope psEnvelope; poPolygon->getEnvelope(&psEnvelope); int nTrees = (int)((psEnvelope.MaxX-psEnvelope.MinX)*(psEnvelope.MaxY-psEnvelope.MinY)*1e-5/tileElementArea); for(int i = 0; i<nTrees; ++i) { OGRPoint point; //point.setX(mt()*(psEnvelope.MaxX-psEnvelope.MinX) + psEnvelope.MinX); //point.setY(mt()*(psEnvelope.MaxY-psEnvelope.MinY) + psEnvelope.MinY); point.setX(mt()*(tileXMax-tileXMin) + tileXMin); point.setY(mt()*(tileYMax-tileYMin) + tileYMin); //if(poPolygon->Contains(&point)) { osg::PositionAttitudeTransform* treeTrans = new osg::PositionAttitudeTransform(); treeGroup->addChild(treeTrans); //hflayer->getInterpolatedValue(x,y,z); double x = point.getX() + offset.x(); double y = point.getY() + offset.y(); int x_int = floor((x-tileXMin)/tileXInterval+0.5); if(x_int<0) x_int=0; else if(x_int>=field->getNumColumns()) x_int=field->getNumColumns()-1; int y_int = floor((y-tileYMin)/tileYInterval+0.5); if(y_int<0) y_int=0; else if(y_int>=field->getNumRows()) y_int=field->getNumRows()-1; double z = field->getHeight(x_int,y_int); std::cout << "int x: " << x_int << ", x: " << x-tileXMin << ", y: " << y_int << ", y: " << y-tileYMin << std::endl; //osg::Vec3 treePos(x,y,z); osg::Vec3 treePos(x,y,z); treeTrans->setPosition(treePos); int treeIt = (int)floor(mt()*(double)treeNodeVector.size()); treeTrans->addChild(treeNodeVector[treeIt].get()); treeTrans->setName("TreeTransform"); //} } } } } #endif #if 0 typedef gaalet::algebra< gaalet::signature<3,0> > em; typedef em::mv<1, 2, 4>::type Vector; typedef em::mv<3, 5, 6>::type Bivector; typedef em::mv<0, 3, 5, 6>::type Rotor; static const em::mv<0>::type one(1.0); static const em::mv<1>::type e1(1.0); static const em::mv<2>::type e2(1.0); static const em::mv<4>::type e3(1.0); static const em::mv<7>::type e123(1.0); osgTerrain::Layer* colorLayer = tile->getColorLayer(0); if(colorLayer) { osg::Image* inputImage = colorLayer->getImage(); /*static int tileLoadCounter = 0; osg::Image* outputImage = NULL; if(tileLoadCounter==0) { outputImage = new osg::Image(); outputImage->allocateImage(inputImage->s(), inputImage->t(), 1, 0x1907, 0x1401); } tileLoadCounter += 1;*/ em::mv<0,6>::type *fftwImag1 = (em::mv<0,6>::type*) fftw_malloc(sizeof(em::mv<0,6>::type)*inputImage->s()*inputImage->t()); em::mv<0,3>::type *fftwImag2 = (em::mv<0,3>::type*) fftw_malloc(sizeof(em::mv<0,3>::type)*inputImage->s()*inputImage->t()); em::mv<0,6>::type *fftwFreq1 = (em::mv<0,6>::type*) fftw_malloc(sizeof(em::mv<0,6>::type)*inputImage->s()*inputImage->t()); em::mv<0,3>::type *fftwFreq2 = (em::mv<0,3>::type*) fftw_malloc(sizeof(em::mv<0,3>::type)*inputImage->s()*inputImage->t()); fftw_plan fftwForward1 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwImag1), reinterpret_cast<fftw_complex*>(fftwFreq1), FFTW_FORWARD, FFTW_ESTIMATE); fftw_plan fftwForward2 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwImag2), reinterpret_cast<fftw_complex*>(fftwFreq2), FFTW_FORWARD, FFTW_ESTIMATE); fftw_plan fftwBackward1 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwFreq1), reinterpret_cast<fftw_complex*>(fftwImag1), FFTW_BACKWARD, FFTW_ESTIMATE); fftw_plan fftwBackward2 = fftw_plan_dft_2d(inputImage->s(), inputImage->t(), reinterpret_cast<fftw_complex*>(fftwFreq2), reinterpret_cast<fftw_complex*>(fftwImag2), FFTW_BACKWARD, FFTW_ESTIMATE); for(int x=0; x<inputImage->s(); ++x) { for(int y=0; y<inputImage->t(); ++y) { if(inputImage->getPixelFormat()==0x83f0) { //COMPRESSED_RGB_S3TC_DXT1_EXT decompression unsigned int blocksize = 8; unsigned char* data = inputImage->data(); unsigned char* block = data + (blocksize*(unsigned int)(ceil(double(inputImage->s()/4.0)*floor(y/4.0) + floor(x/4.0)))); int rel_x = x % 4; int rel_y = y % 4; unsigned char& c0_lo = *(block+0); unsigned char& c0_hi = *(block+1); unsigned char& c1_lo = *(block+2); unsigned char& c1_hi = *(block+3); unsigned char& bits_0 = *(block+4); unsigned char& bits_1 = *(block+5); unsigned char& bits_2 = *(block+6); unsigned char& bits_3 = *(block+7); unsigned short color0 = c0_lo + c0_hi * 256; unsigned short color1 = c1_lo + c1_hi * 256; unsigned int bits = bits_0 + 256 * (bits_1 + 256 * (bits_2 + 256 * bits_3)); unsigned int code_bits_pos = 2*(4*rel_y+rel_x); unsigned int code = (bits>>code_bits_pos) & 0x03; unsigned char r0 = ((color0>>11) & 0x1f); unsigned char g0 = ((color0>>5) & 0x3f); unsigned char b0 = ((color0>>0) & 0x1f); unsigned char r1 = ((color1>>11) & 0x1f); unsigned char g1 = ((color1>>5) & 0x3f); unsigned char b1 = ((color1>>0) & 0x1f); unsigned char r = 0; unsigned char g = 0; unsigned char b = 0; if(color0>color1) { switch(code) { case 0: r = r0; g = g0; b = b0; break; case 1: r = r1; g = g1; b = b1; break; case 2: r = (2*r0+r1)/3; g = (2*g0+g1)/3; b = (2*b0+b1)/3; break; case 3: r = (r0+2*r1)/3; g = (g0+2*g1)/3; b = (b0+2*b1)/3; break; }; } else { switch(code) { case 0: r = r0; g = g0; b = b0; break; case 1: r = r1; g = g1; b = b1; break; case 2: r = (r0+r1)/2; g = (g0+g1)/2; b = (b0+b1)/2; break; case 3: r = 0; g = 0; b = 0; break; }; } (*(fftwImag1+inputImage->t()*x+y)) = (0.0*one)+((double)r*(double)0xff/(double)0x1f*e2*e3); (*(fftwImag2+inputImage->t()*x+y)) = ((double)g*(double)0xff/(double)0x3f*e3*e1)*e3*e1 + ((double)b*(double)0xff/(double)0x1f*e1*e2); /*if(outputImage) { *(outputImage->data(x,y)+0) = (unsigned int)((double)r*(double)0xff/(double)0x1f); *(outputImage->data(x,y)+1) = (unsigned int)((double)g*(double)0xff/(double)0x3f); *(outputImage->data(x,y)+2) = (unsigned int)((double)b*(double)0xff/(double)0x1f); }*/ } else { unsigned char& r = *(inputImage->data(x,y)+0); unsigned char& g = *(inputImage->data(x,y)+1); unsigned char& b = *(inputImage->data(x,y)+2); (*(fftwImag1+inputImage->t()*x+y)) = (0.0*one)+((double)r*e2*e3); (*(fftwImag2+inputImage->t()*x+y)) = ((double)g*e3*e1)*e3*e1 + ((double)b*e1*e2); //if(x==0 && y==0) std::cout << "(0,0): r: " << (int)r << ", g: " << (int)g << ", b: " << (int)b << std::endl; } } }
OGRSQLiteSelectLayer::OGRSQLiteSelectLayer( OGRSQLiteDataSource *poDSIn, CPLString osSQLIn, sqlite3_stmt *hStmtIn, int bUseStatementForGetNextFeature, int bEmptyLayer ) { poDS = poDSIn; iNextShapeId = 0; poFeatureDefn = NULL; bAllowResetReadingEvenIfIndexAtZero = FALSE; std::set<CPLString> aosEmpty; BuildFeatureDefn( "SELECT", hStmtIn, aosEmpty ); if( bUseStatementForGetNextFeature ) { hStmt = hStmtIn; bDoStep = FALSE; // Try to extract SRS from first geometry if( !bEmptyLayer && osGeomColumn.size() != 0 ) { int nRawColumns = sqlite3_column_count( hStmt ); for( int iCol = 0; iCol < nRawColumns; iCol++ ) { int nBytes; if( sqlite3_column_type( hStmt, iCol ) == SQLITE_BLOB && strcmp(OGRSQLiteParamsUnquote(sqlite3_column_name( hStmt, iCol )).c_str(), osGeomColumn.c_str()) == 0 && (nBytes = sqlite3_column_bytes( hStmt, iCol )) > 39 ) { const GByte* pabyBlob = (const GByte*)sqlite3_column_blob( hStmt, iCol ); int eByteOrder = pabyBlob[1]; if( pabyBlob[0] == 0x00 && (eByteOrder == wkbNDR || eByteOrder == wkbXDR) && pabyBlob[38] == 0x7C ) { memcpy(&nSRSId, pabyBlob + 2, 4); #ifdef CPL_LSB if( eByteOrder != wkbNDR) CPL_SWAP32PTR(&nSRSId); #else if( eByteOrder == wkbNDR) CPL_SWAP32PTR(&nSRSId); #endif CPLPushErrorHandler(CPLQuietErrorHandler); poSRS = poDS->FetchSRS( nSRSId ); CPLPopErrorHandler(); if( poSRS != NULL ) poSRS->Reference(); else CPLErrorReset(); } #ifdef SQLITE_HAS_COLUMN_METADATA else { const char* pszTableName = sqlite3_column_table_name( hStmt, iCol ); if( pszTableName != NULL ) { OGRLayer* poLayer = poDS->GetLayerByName(pszTableName); if( poLayer != NULL ) { poSRS = poLayer->GetSpatialRef(); if( poSRS != NULL ) poSRS->Reference(); } } } #endif break; } } } } else sqlite3_finalize( hStmtIn ); osSQLBase = osSQLIn; osSQLCurrent = osSQLIn; this->bEmptyLayer = bEmptyLayer; bSpatialFilterInSQL = TRUE; }
SEXP ogrP4S(SEXP ogrsourcename, SEXP Layer) { #ifdef GDALV2 // GDALDriver *poDriver; GDALDataset *poDS; #else OGRSFDriver *poDriver; OGRDataSource *poDS; #endif OGRLayer *poLayer; OGRSpatialReference *hSRS = NULL; char *pszProj4 = NULL; SEXP ans; installErrorHandler(); #ifdef GDALV2 poDS=(GDALDataset*) GDALOpenEx(CHAR(STRING_ELT(ogrsourcename, 0)), GDAL_OF_VECTOR, NULL, NULL, NULL); #else poDS=OGRSFDriverRegistrar::Open(CHAR(STRING_ELT(ogrsourcename, 0)), FALSE, &poDriver); #endif uninstallErrorHandlerAndTriggerError(); if(poDS==NULL){ error("Cannot open file"); } installErrorHandler(); poLayer = poDS->GetLayerByName(CHAR(STRING_ELT(Layer, 0))); uninstallErrorHandlerAndTriggerError(); if(poLayer == NULL){ error("Cannot open layer"); } PROTECT(ans=NEW_CHARACTER(1)); installErrorHandler(); hSRS = poLayer->GetSpatialRef(); uninstallErrorHandlerAndTriggerError(); if (hSRS != NULL) { installErrorHandler(); hSRS->morphFromESRI(); if (hSRS->exportToProj4(&pszProj4) != OGRERR_NONE) { // SET_VECTOR_ELT(ans, 0, NA_STRING); SET_STRING_ELT(ans, 0, NA_STRING); } else { // SET_VECTOR_ELT(ans, 0, COPY_TO_USER_STRING(pszProj4)); SET_STRING_ELT(ans, 0, COPY_TO_USER_STRING(pszProj4)); } uninstallErrorHandlerAndTriggerError(); // } else SET_VECTOR_ELT(ans, 0, NA_STRING); } else SET_STRING_ELT(ans, 0, NA_STRING); installErrorHandler(); delete poDS; uninstallErrorHandlerAndTriggerError(); UNPROTECT(1); return(ans); }
void ogr_datasource::init(mapnik::parameters const& params) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "ogr_datasource::init"); #endif boost::optional<std::string> file = params.get<std::string>("file"); boost::optional<std::string> string = params.get<std::string>("string"); if (!string) string = params.get<std::string>("inline"); if (! file && ! string) { throw datasource_exception("missing <file> or <string> parameter"); } if (string) { dataset_name_ = *string; } else { boost::optional<std::string> base = params.get<std::string>("base"); if (base) { dataset_name_ = *base + "/" + *file; } else { dataset_name_ = *file; } } std::string driver = *params.get<std::string>("driver",""); if (! driver.empty()) { #if GDAL_VERSION_MAJOR >= 2 unsigned int nOpenFlags = GDAL_OF_READONLY | GDAL_OF_VECTOR; const char* papszAllowedDrivers[] = { driver.c_str(), nullptr }; dataset_ = reinterpret_cast<gdal_dataset_type>(GDALOpenEx(dataset_name_.c_str(),nOpenFlags,papszAllowedDrivers, nullptr, nullptr)); #else OGRSFDriver * ogr_driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver.c_str()); if (ogr_driver && ogr_driver != nullptr) { dataset_ = ogr_driver->Open((dataset_name_).c_str(), false); } #endif } else { // open ogr driver #if GDAL_VERSION_MAJOR >= 2 dataset_ = reinterpret_cast<gdal_dataset_type>(OGROpen(dataset_name_.c_str(), false, nullptr)); #else dataset_ = OGRSFDriverRegistrar::Open(dataset_name_.c_str(), false); #endif } if (! dataset_) { const std::string err = CPLGetLastErrorMsg(); if (err.size() == 0) { throw datasource_exception("OGR Plugin: connection failed: " + dataset_name_ + " was not found or is not a supported format"); } else { throw datasource_exception("OGR Plugin: " + err); } } // initialize layer boost::optional<std::string> layer_by_name = params.get<std::string>("layer"); boost::optional<mapnik::value_integer> layer_by_index = params.get<mapnik::value_integer>("layer_by_index"); boost::optional<std::string> layer_by_sql = params.get<std::string>("layer_by_sql"); int passed_parameters = 0; passed_parameters += layer_by_name ? 1 : 0; passed_parameters += layer_by_index ? 1 : 0; passed_parameters += layer_by_sql ? 1 : 0; if (passed_parameters > 1) { throw datasource_exception("OGR Plugin: you can only select an ogr layer by name " "('layer' parameter), by number ('layer_by_index' parameter), " "or by sql ('layer_by_sql' parameter), " "do not supply 2 or more of them at the same time" ); } if (layer_by_name) { layer_name_ = *layer_by_name; layer_.layer_by_name(dataset_, layer_name_); } else if (layer_by_index) { int num_layers = dataset_->GetLayerCount(); if (*layer_by_index >= num_layers) { std::ostringstream s; s << "OGR Plugin: only " << num_layers << " layer(s) exist, cannot find layer by index '" << *layer_by_index << "'"; throw datasource_exception(s.str()); } layer_.layer_by_index(dataset_, *layer_by_index); layer_name_ = layer_.layer_name(); } else if (layer_by_sql) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats_sql__(std::clog, "ogr_datasource::init(layer_by_sql)"); #endif layer_.layer_by_sql(dataset_, *layer_by_sql); layer_name_ = layer_.layer_name(); } else { std::string s("OGR Plugin: missing <layer> or <layer_by_index> or <layer_by_sql> parameter, available layers are: "); unsigned num_layers = dataset_->GetLayerCount(); bool layer_found = false; std::vector<std::string> layer_names; for (unsigned i = 0; i < num_layers; ++i ) { OGRLayer* ogr_layer = dataset_->GetLayer(i); OGRFeatureDefn* ogr_layer_def = ogr_layer->GetLayerDefn(); if (ogr_layer_def != 0) { layer_found = true; layer_names.push_back(std::string("'") + ogr_layer_def->GetName() + std::string("'")); } } if (! layer_found) { s += "None (no layers were found in dataset)"; } else { s += boost::algorithm::join(layer_names,", "); } throw datasource_exception(s); } if (! layer_.is_valid()) { std::ostringstream s; s << "OGR Plugin: "; if (layer_by_name) { s << "cannot find layer by name '" << *layer_by_name; } else if (layer_by_index) { s << "cannot find layer by index number '" << *layer_by_index; } else if (layer_by_sql) { s << "cannot find layer by sql query '" << *layer_by_sql; } s << "' in dataset '" << dataset_name_ << "'"; throw datasource_exception(s.str()); } // work with real OGR layer OGRLayer* layer = layer_.layer(); // initialize envelope boost::optional<std::string> ext = params.get<std::string>("extent"); if (ext && !ext->empty()) { extent_.from_string(*ext); } else { OGREnvelope envelope; OGRErr e = layer->GetExtent(&envelope); if (e == OGRERR_FAILURE) { if (layer->GetFeatureCount() == 0) { MAPNIK_LOG_ERROR(ogr) << "could not determine extent, layer '" << layer->GetLayerDefn()->GetName() << "' appears to have no features"; } else { std::ostringstream s; s << "OGR Plugin: Cannot determine extent for layer '" << layer->GetLayerDefn()->GetName() << "'. Please provide a manual extent string (minx,miny,maxx,maxy)."; throw datasource_exception(s.str()); } } extent_.init(envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY); } // scan for index file // TODO - layer names don't match dataset name, so this will break for // any layer types of ogr than shapefiles, etc // fix here and in ogrindex size_t breakpoint = dataset_name_.find_last_of("."); if (breakpoint == std::string::npos) { breakpoint = dataset_name_.length(); } index_name_ = dataset_name_.substr(0, breakpoint) + ".ogrindex"; #if defined (_WINDOWS) std::ifstream index_file(mapnik::utf8_to_utf16(index_name_), std::ios::in | std::ios::binary); #else std::ifstream index_file(index_name_.c_str(), std::ios::in | std::ios::binary); #endif if (index_file) { indexed_ = true; index_file.close(); } #if 0 // TODO - enable this warning once the ogrindex tool is a bit more stable/mature else { MAPNIK_LOG_DEBUG(ogr) << "ogr_datasource: no ogrindex file found for " << dataset_name_ << ", use the 'ogrindex' program to build an index for faster rendering"; } #endif #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "ogr_datasource::init(get_column_description)"); #endif // deal with attributes descriptions OGRFeatureDefn* def = layer->GetLayerDefn(); if (def != 0) { const int fld_count = def->GetFieldCount(); for (int i = 0; i < fld_count; i++) { OGRFieldDefn* fld = def->GetFieldDefn(i); const std::string fld_name = fld->GetNameRef(); const OGRFieldType type_oid = fld->GetType(); switch (type_oid) { case OFTInteger: #if GDAL_VERSION_MAJOR >= 2 case OFTInteger64: #endif desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Integer)); break; case OFTReal: desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Double)); break; case OFTString: case OFTWideString: // deprecated desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::String)); break; case OFTBinary: desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Object)); break; case OFTIntegerList: #if GDAL_VERSION_MAJOR >= 2 case OFTInteger64List: #endif case OFTRealList: case OFTStringList: case OFTWideStringList: // deprecated ! MAPNIK_LOG_WARN(ogr) << "ogr_datasource: Unhandled type_oid=" << type_oid; break; case OFTDate: case OFTTime: case OFTDateTime: // unhandled ! desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Object)); MAPNIK_LOG_WARN(ogr) << "ogr_datasource: Unhandled type_oid=" << type_oid; break; } } } mapnik::parameters & extra_params = desc_.get_extra_parameters(); OGRSpatialReference * srs_ref = layer->GetSpatialRef(); char * srs_output = nullptr; if (srs_ref && srs_ref->exportToProj4( &srs_output ) == OGRERR_NONE ) { extra_params["proj4"] = mapnik::util::trim_copy(srs_output); } CPLFree(srs_output); }
int FindSRS( const char *pszInput, OGRSpatialReference &oSRS ) { int bGotSRS = FALSE; VSILFILE *fp = NULL; GDALDataset *poGDALDS = NULL; OGRLayer *poLayer = NULL; const char *pszProjection = NULL; CPLErrorHandler oErrorHandler = NULL; int bIsFile = FALSE; OGRErr eErr = OGRERR_NONE; int bDebug = FALSE; /* temporarily suppress error messages we may get from xOpen() */ bDebug = CSLTestBoolean(CPLGetConfigOption("CPL_DEBUG", "OFF")); if ( ! bDebug ) oErrorHandler = CPLSetErrorHandler ( CPLQuietErrorHandler ); /* Test if argument is a file */ fp = VSIFOpenL( pszInput, "r" ); if ( fp ) { bIsFile = TRUE; VSIFCloseL( fp ); CPLDebug( "gdalsrsinfo", "argument is a file" ); } /* try to open with GDAL */ if( strncmp(pszInput, "http://spatialreference.org/", strlen("http://spatialreference.org/")) != 0 ) { CPLDebug( "gdalsrsinfo", "trying to open with GDAL" ); poGDALDS = (GDALDataset *) GDALOpenEx( pszInput, 0, NULL, NULL, NULL ); } if ( poGDALDS != NULL ) { pszProjection = poGDALDS->GetProjectionRef( ); if( pszProjection != NULL && pszProjection[0] != '\0' ) { char* pszProjectionTmp = (char*) pszProjection; if( oSRS.importFromWkt( &pszProjectionTmp ) == OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "got SRS from GDAL" ); bGotSRS = TRUE; } } else if( poGDALDS->GetLayerCount() > 0 ) { poLayer = poGDALDS->GetLayer( 0 ); if ( poLayer != NULL ) { OGRSpatialReference *poSRS = poLayer->GetSpatialRef( ); if ( poSRS != NULL ) { CPLDebug( "gdalsrsinfo", "got SRS from OGR" ); bGotSRS = TRUE; OGRSpatialReference* poSRSClone = poSRS->Clone(); oSRS = *poSRSClone; OGRSpatialReference::DestroySpatialReference( poSRSClone ); } } } GDALClose( (GDALDatasetH) poGDALDS ); if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with GDAL" ); } /* Try ESRI file */ if ( ! bGotSRS && bIsFile && (strstr(pszInput,".prj") != NULL) ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from ESRI .prj file [%s]", pszInput ); char **pszTemp; if ( strstr(pszInput,"ESRI::") != NULL ) pszTemp = CSLLoad( pszInput+6 ); else pszTemp = CSLLoad( pszInput ); if( pszTemp ) { eErr = oSRS.importFromESRI( pszTemp ); CSLDestroy( pszTemp ); } else eErr = OGRERR_UNSUPPORTED_SRS; if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from ESRI .prj file" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from ESRI .prj file" ); bGotSRS = TRUE; } } /* Last resort, try OSRSetFromUserInput() */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from user input [%s]", pszInput ); eErr = oSRS.SetFromUserInput( pszInput ); if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from user input" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from user input" ); bGotSRS = TRUE; } } /* restore error messages */ if ( ! bDebug ) CPLSetErrorHandler ( oErrorHandler ); return bGotSRS; }
void ShapefileWriter::writeLines(shared_ptr<const OsmMap> map, const QString& path) { OGRRegisterAll(); _removeShapefile(path); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if( poDriver == NULL ) { throw HootException(QString("%1 driver not available.").arg(pszDriverName)); } OGRDataSource* poDS = poDriver->CreateDataSource(path.toAscii(), NULL ); if( poDS == NULL ) { throw HootException(QString("Data source creation failed. %1").arg(path)); } OGRLayer *poLayer; OgrOptions options; options["ENCODING"] = "UTF-8"; QString layerName; layerName = QFileInfo(path).baseName(); poLayer = poDS->CreateLayer(layerName.toAscii(), map->getProjection().get(), wkbLineString, options.getCrypticOptions()); if( poLayer == NULL ) { throw HootException(QString("Layer creation failed. %1").arg(path)); } QStringList shpColumns; QStringList columns = getColumns(map, ElementType::Way); for (int i = 0; i < columns.size(); i++) { OGRFieldDefn oField(columns[i].toAscii(), OFTString); oField.SetWidth(64); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (%1).").arg(columns[i])); } shpColumns.append(poLayer->GetLayerDefn()->GetFieldDefn(i)->GetNameRef()); } if (_includeInfo) { OGRFieldDefn oField("error_circ", OFTReal); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (error:circular).")); } _circularErrorIndex = poLayer->GetLayerDefn()->GetFieldCount() - 1; } const WayMap& ways = map->getWays(); for (WayMap::const_iterator it = ways.begin(); it != ways.end(); it++) { shared_ptr<Way> way = it->second; if (OsmSchema::getInstance().isArea(way) == false) { OGRFeature* poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); // set all the column values. for (int i = 0; i < columns.size(); i++) { if (way->getTags().contains(columns[i])) { QByteArray c = shpColumns[i].toAscii(); QByteArray v = way->getTags()[columns[i]].toUtf8(); poFeature->SetField(c.constData(), v.constData()); } } if (_includeInfo) { poFeature->SetField(_circularErrorIndex, way->getCircularError()); } // convert the geometry. std::string wkt = ElementConverter(map).convertToLineString(way)->toString(); char* t = (char*)wkt.data(); OGRGeometry* geom; if (OGRGeometryFactory::createFromWkt(&t, poLayer->GetSpatialRef(), &geom) != OGRERR_NONE) { throw HootException(QString("Error parsing WKT (%1)").arg(QString::fromStdString(wkt))); } if (poFeature->SetGeometryDirectly(geom) != OGRERR_NONE) { throw HootException(QString("Error setting geometry")); } if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) { throw HootException(QString("Error creating feature")); } OGRFeature::DestroyFeature(poFeature); } } OGRDataSource::DestroyDataSource(poDS); }
int NBHeightMapper::loadShapeFile(const std::string& file) { #ifdef HAVE_GDAL #if GDAL_VERSION_MAJOR < 2 OGRRegisterAll(); OGRDataSource* ds = OGRSFDriverRegistrar::Open(file.c_str(), FALSE); #else GDALAllRegister(); GDALDataset* ds = (GDALDataset*)GDALOpenEx(file.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL); #endif if (ds == NULL) { throw ProcessError("Could not open shape file '" + file + "'."); } // begin file parsing OGRLayer* layer = ds->GetLayer(0); layer->ResetReading(); // triangle coordinates are stored in WGS84 and later matched with network coordinates in WGS84 // build coordinate transformation OGRSpatialReference* sr_src = layer->GetSpatialRef(); OGRSpatialReference sr_dest; sr_dest.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* toWGS84 = OGRCreateCoordinateTransformation(sr_src, &sr_dest); if (toWGS84 == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } int numFeatures = 0; OGRFeature* feature; layer->ResetReading(); while ((feature = layer->GetNextFeature()) != NULL) { OGRGeometry* geom = feature->GetGeometryRef(); assert(geom != 0); // @todo gracefull handling of shapefiles with unexpected contents or any error handling for that matter assert(std::string(geom->getGeometryName()) == std::string("POLYGON")); // try transform to wgs84 geom->transform(toWGS84); OGRLinearRing* cgeom = ((OGRPolygon*) geom)->getExteriorRing(); // assume TIN with with 4 points and point0 == point3 assert(cgeom->getNumPoints() == 4); PositionVector corners; for (int j = 0; j < 3; j++) { Position pos((double) cgeom->getX(j), (double) cgeom->getY(j), (double) cgeom->getZ(j)); corners.push_back(pos); myBoundary.add(pos); } addTriangle(corners); numFeatures++; /* OGRwkbGeometryType gtype = geom->getGeometryType(); switch (gtype) { case wkbPolygon: { break; } case wkbPoint: { WRITE_WARNING("got wkbPoint"); break; } case wkbLineString: { WRITE_WARNING("got wkbLineString"); break; } case wkbMultiPoint: { WRITE_WARNING("got wkbMultiPoint"); break; } case wkbMultiLineString: { WRITE_WARNING("got wkbMultiLineString"); break; } case wkbMultiPolygon: { WRITE_WARNING("got wkbMultiPolygon"); break; } default: WRITE_WARNING("Unsupported shape type occurred"); break; } */ OGRFeature::DestroyFeature(feature); } #if GDAL_VERSION_MAJOR < 2 OGRDataSource::DestroyDataSource(ds); #else GDALClose(ds); #endif OCTDestroyCoordinateTransformation(toWGS84); OGRCleanupAll(); return numFeatures; #else UNUSED_PARAMETER(file); WRITE_ERROR("Cannot load shape file since SUMO was compiled without GDAL support."); return 0; #endif }
void Dust::MakeGrid(WindNinjaInputs &input, AsciiGrid<double> &grid) { /*------------------------------------------*/ /* Open grid as a GDAL dataset */ /*------------------------------------------*/ int nXSize = grid.get_nCols(); int nYSize = grid.get_nRows(); GDALDriverH hDriver = GDALGetDriverByName( "MEM" ); GDALDatasetH hMemDS = GDALCreate(hDriver, "", nXSize, nYSize, 1, GDT_Float64, NULL); double *padfScanline; padfScanline = new double[nXSize]; double adfGeoTransform[6]; adfGeoTransform[0] = grid.get_xllCorner(); adfGeoTransform[1] = grid.get_cellSize(); adfGeoTransform[2] = 0; adfGeoTransform[3] = grid.get_yllCorner()+(grid.get_nRows()*grid.get_cellSize()); adfGeoTransform[4] = 0; adfGeoTransform[5] = -grid.get_cellSize(); char* pszDstWKT = (char*)grid.prjString.c_str(); GDALSetProjection(hMemDS, pszDstWKT); GDALSetGeoTransform(hMemDS, adfGeoTransform); GDALRasterBandH hBand = GDALGetRasterBand( hMemDS, 1 ); GDALSetRasterNoDataValue(hBand, -9999.0); for(int i=nYSize-1; i>=0; i--) { for(int j=0; j<nXSize; j++) { padfScanline[j] = grid.get_cellValue(nYSize-1-i, j); } GDALRasterIO(hBand, GF_Write, 0, i, nXSize, 1, padfScanline, nXSize, 1, GDT_Float64, 0, 0); } /*------------------------------------------*/ /* Get the geometry info */ /*------------------------------------------*/ OGRDataSourceH hOGRDS = 0; hOGRDS = OGROpen(input.dustFilename.c_str(), FALSE, 0); if(hOGRDS == NULL) { throw std::runtime_error("Could not open the fire perimeter file '" + input.dustFilename + "' for reading."); } OGRLayer *poLayer; OGRFeature *poFeature; OGRGeometry *poGeo; poLayer = (OGRLayer*)OGR_DS_GetLayer(hOGRDS, 0); poLayer->ResetReading(); poFeature = poLayer->GetNextFeature(); poGeo = poFeature->GetGeometryRef(); OGRGeometryH hPolygon = (OGRGeometryH) poGeo; /* -------------------------------------------------------------------- */ /* Check for same CRS in fire perimeter and DEM files */ /* -------------------------------------------------------------------- */ char *pszSrcWKT; OGRSpatialReference *poSrcSRS, oDstSRS; poSrcSRS = poLayer->GetSpatialRef(); //shapefile CRS poSrcSRS->exportToWkt( &pszSrcWKT ); //printf("CRS of DEM is:\n %s\n", pszDstWKT); //printf("WKT CRS of .shp is:\n %s\n", pszSrcWKT); oDstSRS.importFromWkt( &pszDstWKT ); char *pszDstProj4, *pszSrcProj4; oDstSRS.exportToProj4( &pszDstProj4 ); poSrcSRS->exportToProj4( &pszSrcProj4 ); //printf("proj4 of .shp is:\n %s\n", pszSrcProj4); //printf("proj4 of dem is:\n %s\n", pszDstProj4); /* -------------------------------------------------------------------- */ /* If the CRSs are not equal, convert shapefile CRS to DEM CRS */ /* -------------------------------------------------------------------- */ GDALTransformerFunc pfnTransformer = NULL; if( !EQUAL( pszSrcProj4, pszDstProj4 ) ){ //tranform shp CRS to DEM CRS poGeo->transformTo(&oDstSRS); } /* -------------------------------------------------------------------- */ /* Rasterize the shapefile */ /* -------------------------------------------------------------------- */ int nTargetBand = 1; double BurnValue = 1.0; CPLErr eErr; eErr = GDALRasterizeGeometries(hMemDS, 1, &nTargetBand, 1, &hPolygon, pfnTransformer, NULL, &BurnValue, NULL, NULL, NULL); if(eErr != CE_None) { throw std::runtime_error("Error in GDALRasterizeGeometies in Dust:MakeGrid()."); } GDAL2AsciiGrid((GDALDataset*)hMemDS, 1, grid); /* -------------------------------------------------------------------- */ /* clean up */ /* -------------------------------------------------------------------- */ if( hMemDS != NULL ){ GDALClose( hMemDS ); hMemDS = NULL; } OGR_DS_Destroy(hOGRDS); }
OGRDataSource *AoIIntersection::intersectAoIWithLayers ( OGRDataSource *ogrSourceData, OGRPolygon *aoiPoly, IntersectionSummary *summary, const char *outFmt ) { OGRDataSource *ogrIntersection = NULL; // Spatial reference setup // make a spatial reference for the area of interest polygon OGRSpatialReference aoiRef; aoiRef.SetWellKnownGeogCS( "WGS84" ); // make a spatial reference for the coord sys we will use to calculate area in acres - Albers USA equal area conic bool acreageCalcAvailable = true; char *aecWkt = "PROJCS[\"USA_Contiguous_Lambert_Conformal_Conic\",GEOGCS[\"GCS_North_American_1983\",DATUM[\"North_American_Datum_1983\",SPHEROID[\"GRS_1980\",6378137,298.257222101]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Lambert_Conformal_Conic_2SP\"],PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",-96],PARAMETER[\"Standard_Parallel_1\",33],PARAMETER[\"Standard_Parallel_2\",45],PARAMETER[\"Latitude_Of_Origin\",39],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"102004\"]]"; OGRSpatialReference aecRef; OGRErr ogrErr = aecRef.importFromWkt( &aecWkt ); if ( ogrErr != OGRERR_NONE ) { setError ( NO_SPATIAL_REFERENCE ); acreageCalcAvailable = false; } // begin creating the output data structure // OGRDataSource is the root ogrIntersection = buildIntersectionDataSource( outFmt ); if (! ogrIntersection ) { setError( NO_OUTPUT_DATASOURCE ); return 0; } int acreIndex = 0, areaIndex = 0; OGRFieldDefn *acreFldDefn = NULL, *areaPctFldDefn = NULL; OGRFeatureDefn *featureDefn = buildFeatureDefinition( acreIndex, areaIndex, acreFldDefn, areaPctFldDefn ); // walk the layers in the input data // OGRLayer *inputLayer; summary->numLayers = ogrSourceData->GetLayerCount(); for (int layerCt = 0; layerCt < summary->numLayers; ++layerCt) { inputLayer = ogrSourceData->GetLayer( layerCt ); if ( inputLayer == NULL ) { setError( NO_INPUT_LAYER ); // clean up delete ogrIntersection; return 0; } // make a clone of aoi polygon to be manipulated OGRPolygon *aoiClone = (OGRPolygon *)aoiPoly->clone(); if ( ! aoiClone ) { setError( NO_AOI_CLONE ); // clean up delete ogrIntersection; return 0; } // ensure that the area of interest polygon is in the same spatial reference as the data layer // find the spatial reference for the layer OGRSpatialReference *dataRef = inputLayer->GetSpatialRef(); if ( dataRef ) { OGRCoordinateTransformation *aoiTransform = OGRCreateCoordinateTransformation( &aoiRef, dataRef ); if( aoiTransform == NULL ) { setError( NO_AOI_TRANSFORM ); // clean up delete ogrIntersection; delete aoiClone; return 0; } aoiClone->transform( aoiTransform ); delete aoiTransform; } // find the transform from data layer's CS to Albers USA // for acreage calculation OGRCoordinateTransformation *aecTransform = NULL; acreageCalcAvailable = false; if ( dataRef ) { aecTransform = OGRCreateCoordinateTransformation( dataRef, &aecRef ); if( aecTransform == NULL ) { setError( NO_ACRE_TRANSFORM ); } else acreageCalcAvailable = true; } // the area enclosed by the AoI // used for computing the percentage of the AoI intersected by polygons summary->aoiArea = aoiClone->getExteriorRing()->get_Area(); // create a layer for outputting the intersecting polygons OGRLayer *intersectionLayer = ogrIntersection->CreateLayer( inputLayer->GetLayerDefn()->GetName(), dataRef, wkbPolygon, 0 ); if ( ! intersectionLayer ) { setError( NO_OUTPUT_LAYER ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; return 0; } // add fields to layer ogrErr = intersectionLayer->CreateField( acreFldDefn ); if ( ogrErr != OGRERR_NONE ) { setError( NO_ACRE_FIELD ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; return 0; } ogrErr = intersectionLayer->CreateField( areaPctFldDefn ); if ( ogrErr != OGRERR_NONE ) { setError( NO_AREA_FIELD ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; return 0; } // march through the geometry in the layer seeking overlap with area of interest // inputLayer->ResetReading(); OGRFeature *inputFeature; while( (inputFeature = inputLayer->GetNextFeature()) != NULL ) { // get the geometry part of the feature OGRGeometry *inputGeometry = inputFeature->GetGeometryRef(); // test for polygon type - the only type we read if( inputGeometry != NULL && wkbFlatten(inputGeometry->getGeometryType()) == wkbPolygon ) { OGRPolygon *inputPolygon = (OGRPolygon *) inputGeometry; ++summary->totalInputPolyCt; double inputPolyArea = inputPolygon->get_Area(); summary->totalInputPolyArea += inputPolyArea; // here's the important test - does this polygon intersect our area of interest? if (aoiClone->Intersects( inputGeometry )) { // generate a polygon that represents the intersection of the polygon with the AoI OGRGeometry *intersectionGeometry = aoiClone->Intersection( inputGeometry ); if ( intersectionGeometry && wkbFlatten(intersectionGeometry->getGeometryType()) == wkbPolygon ) { double intersectionArea = ((OGRPolygon *)intersectionGeometry)->get_Area(); summary->totalIntersectionArea += intersectionArea; ++summary->intersectionCt; if (intersectionArea < inputPolyArea) ++summary->partEnclosedCt; // create a feature with feature definition, add geometry to it and add it to our layer OGRFeature *intersectionFeature = new OGRFeature( featureDefn ); if (! intersectionFeature ) { setError( NO_OUTPUT_FEATURE ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; return 0; } intersectionFeature->SetGeometry( intersectionGeometry ); double percentOfAoI = intersectionArea / summary->aoiArea; intersectionFeature->SetField( areaIndex, percentOfAoI); summary->totalPercentOfAoI += percentOfAoI; if ( acreageCalcAvailable ) { OGRGeometry *intersectionCopy = intersectionGeometry->clone(); if ( intersectionCopy ) { ogrErr = intersectionCopy->transform( aecTransform ); if ( ogrErr != OGRERR_NONE ) { setError( NO_ACRE_TRANSFORMATION ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; delete intersectionCopy; return 0; } // get area in known metric CS double intersectionAcreage = ((OGRPolygon *)intersectionCopy)->get_Area(); // convert sq m to acres double MetersToFt = 3.28084; double SqFtPerAcre = 43560.0; intersectionAcreage *= ((MetersToFt * MetersToFt) / SqFtPerAcre); intersectionFeature->SetField( acreIndex, intersectionAcreage ); summary->totalIntersectionAcres += intersectionAcreage; delete intersectionCopy; } else { setError( NO_ACRE_OBJECT ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; return 0; } } intersectionLayer->CreateFeature( intersectionFeature ); if ( ogrErr != OGRERR_NONE ) { setError( NO_FEATURE_ADDED ); // clean up delete ogrIntersection; delete aoiClone; delete aecTransform; return 0; } } else { } } } else { printf( "no polygon geometry\n" ); } OGRFeature::DestroyFeature( inputFeature ); } delete aoiClone; delete aecTransform; } return ogrIntersection; }
bool shape::load(string filename) { OGRRegisterAll(); // First open the shape file ds = OGRSFDriverRegistrar::Open( filename.c_str(), FALSE ); // Now to load in the points ..... points = vector<vector<glm::vec2>>(); // Grab the first layer OGRLayer* layer = ds->GetLayer(0); // Grab the spatial reference and create a coordinate transform function sr = layer->GetSpatialRef(); // Taking from http://www.compsci.wm.edu/SciClone/documentation/software/geo/gdal-1.9.0/html/ogr/ogr_apitut.html OGRFeature *poFeature; layer->ResetReading(); while( (poFeature = layer->GetNextFeature()) != NULL ) { OGRFeatureDefn *poFDefn = layer->GetLayerDefn(); int iField; OGRGeometry *poGeometry; poGeometry = poFeature->GetGeometryRef(); if( poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPoint ) { OGRPoint *poPoint = (OGRPoint *) poGeometry; //printf( "%.3f,%3.f\n", poPoint->getX(), poPoint->getY() ); } else if (poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbLineString) { //cout << "LINES!!!!" << endl; OGRLineString* ls= (OGRLineString*)poGeometry; points.push_back(vector<glm::vec2>()); for(int i = 0; i < ls->getNumPoints(); i++ ) { OGRPoint p; ls->getPoint(i,&p); // This function can transform a larget set of points..... double x = p.getX(); double y = p.getY(); points[points.size()-1].push_back(glm::vec2(x,y)); //poTransform->Transform (1, &x, &y); //cout << p.getX() << " " << p.getY() << "Transformed!: " << x << " " << y << endl; } } else if (poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon) { OGRLineString* ls= (OGRLineString*)poGeometry->getBoundary(); points.push_back(vector<glm::vec2>()); cout << "POLYGON" << ls->getNumPoints() << endl; //exit(0); for(int i = 0; i < ls->getNumPoints(); i++ ) { OGRPoint p; ls->getPoint(i,&p); // This function can transform a larget set of points..... double x = p.getX(); double y = p.getY(); points[points.size()-1].push_back(glm::vec2(x,y)); //poTransform->Transform (1, &x, &y); //cout << p.getX() << " " << p.getY() << "Transformed!: " << x << " " << y << endl; } } OGRFeature::DestroyFeature( poFeature ); } return true; }
CPLErr GDALRasterizeLayersBuf( void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, int nLineSpace, int nLayerCount, OGRLayerH *pahLayers, const char *pszDstProjection, double *padfDstGeoTransform, GDALTransformerFunc pfnTransformer, void *pTransformArg, double dfBurnValue, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressArg ) { /* -------------------------------------------------------------------- */ /* If pixel and line spaceing are defaulted assign reasonable */ /* value assuming a packed buffer. */ /* -------------------------------------------------------------------- */ if( nPixelSpace == 0 ) nPixelSpace = GDALGetDataTypeSize( eBufType ) / 8; if( nLineSpace == 0 ) nLineSpace = nPixelSpace * nBufXSize; if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; /* -------------------------------------------------------------------- */ /* Do some rudimentary arg checking. */ /* -------------------------------------------------------------------- */ if( nLayerCount == 0 ) return CE_None; int bAllTouched = CSLFetchBoolean( papszOptions, "ALL_TOUCHED", FALSE ); const char *pszOpt = CSLFetchNameValue( papszOptions, "BURN_VALUE_FROM" ); GDALBurnValueSrc eBurnValueSource = GBV_UserBurnValue; if( pszOpt ) { if( EQUAL(pszOpt,"Z")) eBurnValueSource = GBV_Z; /*else if( EQUAL(pszOpt,"M")) eBurnValueSource = GBV_M;*/ } /* ==================================================================== */ /* Read thes pecified layers transfoming and rasterizing */ /* geometries. */ /* ==================================================================== */ CPLErr eErr = CE_None; int iLayer; const char *pszBurnAttribute = CSLFetchNameValue( papszOptions, "ATTRIBUTE" ); pfnProgress( 0.0, NULL, pProgressArg ); for( iLayer = 0; iLayer < nLayerCount; iLayer++ ) { int iBurnField = -1; OGRLayer *poLayer = (OGRLayer *) pahLayers[iLayer]; if ( !poLayer ) { CPLError( CE_Warning, CPLE_AppDefined, "Layer element number %d is NULL, skipping.\n", iLayer ); continue; } /* -------------------------------------------------------------------- */ /* If the layer does not contain any features just skip it. */ /* Do not force the feature count, so if driver doesn't know */ /* exact number of features, go down the normal way. */ /* -------------------------------------------------------------------- */ if ( poLayer->GetFeatureCount(FALSE) == 0 ) continue; if ( pszBurnAttribute ) { iBurnField = poLayer->GetLayerDefn()->GetFieldIndex( pszBurnAttribute ); if ( iBurnField == -1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.\n", pszBurnAttribute, poLayer->GetLayerDefn()->GetName() ); continue; } } /* -------------------------------------------------------------------- */ /* If we have no transformer, create the one from input file */ /* projection. Note that each layer can be georefernced */ /* separately. */ /* -------------------------------------------------------------------- */ int bNeedToFreeTransformer = FALSE; if( pfnTransformer == NULL ) { char *pszProjection = NULL; bNeedToFreeTransformer = TRUE; OGRSpatialReference *poSRS = poLayer->GetSpatialRef(); if ( !poSRS ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to fetch spatial reference on layer %s " "to build transformer, assuming matching coordinate systems.\n", poLayer->GetLayerDefn()->GetName() ); } else poSRS->exportToWkt( &pszProjection ); pTransformArg = GDALCreateGenImgProjTransformer3( pszProjection, NULL, pszDstProjection, padfDstGeoTransform ); pfnTransformer = GDALGenImgProjTransform; CPLFree( pszProjection ); } OGRFeature *poFeat; poLayer->ResetReading(); while( (poFeat = poLayer->GetNextFeature()) != NULL ) { OGRGeometry *poGeom = poFeat->GetGeometryRef(); if ( pszBurnAttribute ) dfBurnValue = poFeat->GetFieldAsDouble( iBurnField ); gv_rasterize_one_shape( (unsigned char *) pData, 0, nBufXSize, nBufYSize, 1, eBufType, bAllTouched, poGeom, &dfBurnValue, eBurnValueSource, pfnTransformer, pTransformArg ); delete poFeat; } poLayer->ResetReading(); if( !pfnProgress(1, "", pProgressArg) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } if ( bNeedToFreeTransformer ) { GDALDestroyTransformer( pTransformArg ); pTransformArg = NULL; pfnTransformer = NULL; } } return eErr; }
OGRMSSQLSpatialSelectLayer::OGRMSSQLSpatialSelectLayer( OGRMSSQLSpatialDataSource *poDSIn, CPLODBCStatement * poStmtIn ) { poDS = poDSIn; iNextShapeId = 0; nSRSId = 0; poFeatureDefn = nullptr; poStmt = poStmtIn; pszBaseStatement = CPLStrdup( poStmtIn->GetCommand() ); /* identify the geometry column */ pszGeomColumn = nullptr; int iImageCol = -1; for ( int iColumn = 0; iColumn < poStmt->GetColCount(); iColumn++ ) { if ( EQUAL(poStmt->GetColTypeName( iColumn ), "image") ) { SQLCHAR szTableName[256]; SQLSMALLINT nTableNameLength = 0; SQLColAttribute(poStmt->GetStatement(), (SQLSMALLINT)(iColumn + 1), SQL_DESC_TABLE_NAME, szTableName, sizeof(szTableName), &nTableNameLength, nullptr); if (nTableNameLength > 0) { OGRLayer *poBaseLayer = poDS->GetLayerByName((const char*)szTableName); if (poBaseLayer != nullptr && EQUAL(poBaseLayer->GetGeometryColumn(), poStmt->GetColName(iColumn))) { nGeomColumnType = MSSQLCOLTYPE_BINARY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); /* copy spatial reference */ if (!poSRS && poBaseLayer->GetSpatialRef()) poSRS = poBaseLayer->GetSpatialRef()->Clone(); break; } } else if (iImageCol == -1) iImageCol = iColumn; } else if ( EQUAL(poStmt->GetColTypeName( iColumn ), "geometry") ) { nGeomColumnType = MSSQLCOLTYPE_GEOMETRY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); break; } else if ( EQUAL(poStmt->GetColTypeName( iColumn ), "geography") ) { nGeomColumnType = MSSQLCOLTYPE_GEOGRAPHY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); break; } else if ( EQUAL(poStmt->GetColTypeName( iColumn ), "udt") ) { SQLCHAR szUDTTypeName[256]; SQLSMALLINT nUDTTypeNameLength = 0; SQLColAttribute(poStmt->GetStatement(), (SQLSMALLINT)(iColumn + 1), SQL_CA_SS_UDT_TYPE_NAME, szUDTTypeName, sizeof(szUDTTypeName), &nUDTTypeNameLength, nullptr); // For some reason on unixODBC, a UCS2 string is returned if ( EQUAL((char*)szUDTTypeName, "geometry") || (nUDTTypeNameLength == 16 && memcmp(szUDTTypeName, "g\0e\0o\0m\0e\0t\0r\0y", 16) == 0) ) { nGeomColumnType = MSSQLCOLTYPE_GEOMETRY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); } else if ( EQUAL((char*)szUDTTypeName, "geography") || (nUDTTypeNameLength == 18 && memcmp(szUDTTypeName, "g\0e\0o\0g\0r\0a\0p\0h\0y", 18) == 0) ) { nGeomColumnType = MSSQLCOLTYPE_GEOGRAPHY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iColumn)); } break; } } if (pszGeomColumn == nullptr && iImageCol >= 0) { /* set the image col as geometry column as the last resort */ nGeomColumnType = MSSQLCOLTYPE_BINARY; pszGeomColumn = CPLStrdup(poStmt->GetColName(iImageCol)); } BuildFeatureDefn( "SELECT", poStmt ); if ( GetSpatialRef() && poFeatureDefn->GetGeomFieldCount() == 1) poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef( poSRS ); }
CPLErr GDALRasterizeLayers( GDALDatasetH hDS, int nBandCount, int *panBandList, int nLayerCount, OGRLayerH *pahLayers, GDALTransformerFunc pfnTransformer, void *pTransformArg, double *padfLayerBurnValues, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressArg ) { GDALDataType eType; unsigned char *pabyChunkBuf; GDALDataset *poDS = (GDALDataset *) hDS; if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; /* -------------------------------------------------------------------- */ /* Do some rudimentary arg checking. */ /* -------------------------------------------------------------------- */ if( nBandCount == 0 || nLayerCount == 0 ) return CE_None; // prototype band. GDALRasterBand *poBand = poDS->GetRasterBand( panBandList[0] ); if (poBand == NULL) return CE_Failure; int bAllTouched = CSLFetchBoolean( papszOptions, "ALL_TOUCHED", FALSE ); const char *pszOpt = CSLFetchNameValue( papszOptions, "BURN_VALUE_FROM" ); GDALBurnValueSrc eBurnValueSource = GBV_UserBurnValue; if( pszOpt ) { if( EQUAL(pszOpt,"Z")) eBurnValueSource = GBV_Z; /*else if( EQUAL(pszOpt,"M")) eBurnValueSource = GBV_M;*/ } /* -------------------------------------------------------------------- */ /* Establish a chunksize to operate on. The larger the chunk */ /* size the less times we need to make a pass through all the */ /* shapes. */ /* -------------------------------------------------------------------- */ int nYChunkSize, nScanlineBytes; const char *pszYChunkSize = CSLFetchNameValue( papszOptions, "CHUNKYSIZE" ); if( poBand->GetRasterDataType() == GDT_Byte ) eType = GDT_Byte; else eType = GDT_Float32; nScanlineBytes = nBandCount * poDS->GetRasterXSize() * (GDALGetDataTypeSize(eType)/8); if ( pszYChunkSize && (nYChunkSize = atoi(pszYChunkSize)) ) ; else nYChunkSize = GDALGetCacheMax() / nScanlineBytes; if( nYChunkSize < 1 ) nYChunkSize = 1; if( nYChunkSize > poDS->GetRasterYSize() ) nYChunkSize = poDS->GetRasterYSize(); pabyChunkBuf = (unsigned char *) VSIMalloc(nYChunkSize * nScanlineBytes); if( pabyChunkBuf == NULL ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to allocate rasterization buffer." ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Read the image once for all layers if user requested to render */ /* the whole raster in single chunk. */ /* -------------------------------------------------------------------- */ if ( nYChunkSize == poDS->GetRasterYSize() ) { if ( poDS->RasterIO( GF_Read, 0, 0, poDS->GetRasterXSize(), nYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ) != CE_None ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to read buffer." ); CPLFree( pabyChunkBuf ); return CE_Failure; } } /* ==================================================================== */ /* Read the specified layers transfoming and rasterizing */ /* geometries. */ /* ==================================================================== */ CPLErr eErr = CE_None; int iLayer; const char *pszBurnAttribute = CSLFetchNameValue( papszOptions, "ATTRIBUTE" ); pfnProgress( 0.0, NULL, pProgressArg ); for( iLayer = 0; iLayer < nLayerCount; iLayer++ ) { int iBurnField = -1; double *padfBurnValues = NULL; OGRLayer *poLayer = (OGRLayer *) pahLayers[iLayer]; if ( !poLayer ) { CPLError( CE_Warning, CPLE_AppDefined, "Layer element number %d is NULL, skipping.\n", iLayer ); continue; } /* -------------------------------------------------------------------- */ /* If the layer does not contain any features just skip it. */ /* Do not force the feature count, so if driver doesn't know */ /* exact number of features, go down the normal way. */ /* -------------------------------------------------------------------- */ if ( poLayer->GetFeatureCount(FALSE) == 0 ) continue; if ( pszBurnAttribute ) { iBurnField = poLayer->GetLayerDefn()->GetFieldIndex( pszBurnAttribute ); if ( iBurnField == -1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.\n", pszBurnAttribute, poLayer->GetLayerDefn()->GetName() ); continue; } } else padfBurnValues = padfLayerBurnValues + iLayer * nBandCount; /* -------------------------------------------------------------------- */ /* If we have no transformer, create the one from input file */ /* projection. Note that each layer can be georefernced */ /* separately. */ /* -------------------------------------------------------------------- */ int bNeedToFreeTransformer = FALSE; if( pfnTransformer == NULL ) { char *pszProjection = NULL; bNeedToFreeTransformer = TRUE; OGRSpatialReference *poSRS = poLayer->GetSpatialRef(); if ( !poSRS ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to fetch spatial reference on layer %s " "to build transformer, assuming matching coordinate systems.\n", poLayer->GetLayerDefn()->GetName() ); } else poSRS->exportToWkt( &pszProjection ); pTransformArg = GDALCreateGenImgProjTransformer( NULL, pszProjection, hDS, NULL, FALSE, 0.0, 0 ); pfnTransformer = GDALGenImgProjTransform; CPLFree( pszProjection ); } OGRFeature *poFeat; poLayer->ResetReading(); /* -------------------------------------------------------------------- */ /* Loop over image in designated chunks. */ /* -------------------------------------------------------------------- */ int iY; for( iY = 0; iY < poDS->GetRasterYSize() && eErr == CE_None; iY += nYChunkSize ) { int nThisYChunkSize; nThisYChunkSize = nYChunkSize; if( nThisYChunkSize + iY > poDS->GetRasterYSize() ) nThisYChunkSize = poDS->GetRasterYSize() - iY; // Only re-read image if not a single chunk is being rendered if ( nYChunkSize < poDS->GetRasterYSize() ) { eErr = poDS->RasterIO( GF_Read, 0, iY, poDS->GetRasterXSize(), nThisYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nThisYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ); if( eErr != CE_None ) break; } double *padfAttrValues = (double *) VSIMalloc(sizeof(double) * nBandCount); while( (poFeat = poLayer->GetNextFeature()) != NULL ) { OGRGeometry *poGeom = poFeat->GetGeometryRef(); if ( pszBurnAttribute ) { int iBand; double dfAttrValue; dfAttrValue = poFeat->GetFieldAsDouble( iBurnField ); for (iBand = 0 ; iBand < nBandCount ; iBand++) padfAttrValues[iBand] = dfAttrValue; padfBurnValues = padfAttrValues; } gv_rasterize_one_shape( pabyChunkBuf, iY, poDS->GetRasterXSize(), nThisYChunkSize, nBandCount, eType, bAllTouched, poGeom, padfBurnValues, eBurnValueSource, pfnTransformer, pTransformArg ); delete poFeat; } VSIFree( padfAttrValues ); // Only write image if not a single chunk is being rendered if ( nYChunkSize < poDS->GetRasterYSize() ) { eErr = poDS->RasterIO( GF_Write, 0, iY, poDS->GetRasterXSize(), nThisYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nThisYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ); } poLayer->ResetReading(); if( !pfnProgress((iY+nThisYChunkSize)/((double)poDS->GetRasterYSize()), "", pProgressArg) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } } if ( bNeedToFreeTransformer ) { GDALDestroyTransformer( pTransformArg ); pTransformArg = NULL; pfnTransformer = NULL; } } /* -------------------------------------------------------------------- */ /* Write out the image once for all layers if user requested */ /* to render the whole raster in single chunk. */ /* -------------------------------------------------------------------- */ if ( nYChunkSize == poDS->GetRasterYSize() ) { poDS->RasterIO( GF_Write, 0, 0, poDS->GetRasterXSize(), nYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ); } /* -------------------------------------------------------------------- */ /* cleanup */ /* -------------------------------------------------------------------- */ VSIFree( pabyChunkBuf ); return eErr; }
void ShpReader::VectorMetaDataInfo(OGRDataSource* OGRDataset, StudyControllerPtr studyController, VectorMapControllerPtr vectorMapController) { vFileMetaData* vHeader = vectorMapController->GetVectorMapModel()->GetVectorMetaData(); OGRLayer *poLayer = OGRDataset->GetLayer( 0 ); char *originalWkt = NULL; char *destinationWkt = NULL; OGREnvelope psEnvelope; poLayer->GetExtent( &psEnvelope ); vHeader->originalExtents.x = psEnvelope.MinX; vHeader->originalExtents.dx = psEnvelope.MaxX; vHeader->originalExtents.y = psEnvelope.MinY; vHeader->originalExtents.dy = psEnvelope.MaxY; Log::Inst().Write("Original Extents: "); Log::Inst().Write(_T("Lower, Left (x,y): ") +wxString(StringTools::ToStringW(vHeader->originalExtents.x, 2).c_str()) + _T(", ") + wxString(StringTools::ToStringW(vHeader->originalExtents.y, 2).c_str())); Log::Inst().Write(_T("Upper, Right (x,y): ") +wxString(StringTools::ToStringW(vHeader->originalExtents.dx, 2).c_str()) + _T(", ") + wxString(StringTools::ToStringW(vHeader->originalExtents.dy, 2).c_str())); vHeader->numFeatures= poLayer->GetFeatureCount(); Log::Inst().Write("Number of Features: " + StringTools::ToString(vHeader->numFeatures)); std::string type; OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn(); if ( wkbFlatten( poFDefn->GetGeomType() ) == wkbPoint || wkbFlatten( poFDefn->GetGeomType() ) == wkbMultiPoint ) type="Point"; else if ( wkbFlatten(poFDefn->GetGeomType() ) == wkbLineString || wkbFlatten(poFDefn->GetGeomType() ) == wkbMultiLineString ) type="Polyline"; else if ( wkbFlatten( poFDefn->GetGeomType() ) == wkbPolygon || wkbFlatten( poFDefn->GetGeomType() ) == wkbMultiPolygon ) type="Polygon"; else type="Unknown"; vHeader->geometryType=type; Log::Inst().Write("Geometry Type: "+ type); OGRSpatialReference* originalShpSR = poLayer->GetSpatialRef(); if (originalShpSR != NULL) { originalShpSR->exportToWkt(&originalWkt); vHeader->originalProjection = std::string(originalWkt); } Log::Inst().Write("Original Projection: " + vHeader->originalProjection); Log::Inst().Write(""); ProjectionToolPtr projTool = studyController->GetProjectionTool(); if (projTool != NULL) { OGRSpatialReference *destinationCS= projTool->GetTargetCS (); destinationCS->exportToWkt(&destinationWkt); vHeader->destinationProjection = std::string(destinationWkt); } vHeader->currentExtents.x = vectorMapController->GetVectorMapModel()->GetVectorBoundary_MinX(); vHeader->currentExtents.y = vectorMapController->GetVectorMapModel()->GetVectorBoundary_MinY(); vHeader->currentExtents.dx = vectorMapController->GetVectorMapModel()->GetVectorBoundary_MaxX(); vHeader->currentExtents.dy = vectorMapController->GetVectorMapModel()->GetVectorBoundary_MaxY(); //Log::Inst().Write("Upper, Right (x,y): " + // StringTools::ToString(vHeader->currentExtents.dx) + ", " + //StringTools::ToString(vHeader->currentExtents.dy)); }
int FindSRS( const char *pszInput, OGRSpatialReference &oSRS, int bDebug ) { int bGotSRS = FALSE; VSILFILE *fp = NULL; GDALDataset *poGDALDS = NULL; OGRDataSource *poOGRDS = NULL; OGRLayer *poLayer = NULL; char *pszProjection = NULL; CPLErrorHandler oErrorHandler = NULL; int bIsFile = FALSE; OGRErr eErr = CE_None; /* temporarily supress error messages we may get from xOpen() */ if ( ! bDebug ) oErrorHandler = CPLSetErrorHandler ( CPLQuietErrorHandler ); /* Test if argument is a file */ fp = VSIFOpenL( pszInput, "r" ); if ( fp ) { bIsFile = TRUE; VSIFCloseL( fp ); CPLDebug( "gdalsrsinfo", "argument is a file" ); } /* try to open with GDAL */ CPLDebug( "gdalsrsinfo", "trying to open with GDAL" ); poGDALDS = (GDALDataset *) GDALOpen( pszInput, GA_ReadOnly ); if ( poGDALDS != NULL && poGDALDS->GetProjectionRef( ) != NULL ) { pszProjection = (char *) poGDALDS->GetProjectionRef( ); if( oSRS.importFromWkt( &pszProjection ) == CE_None ) { CPLDebug( "gdalsrsinfo", "got SRS from GDAL" ); bGotSRS = TRUE; } GDALClose( (GDALDatasetH) poGDALDS ); if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with GDAL" ); } #ifdef OGR_ENABLED /* if unsuccessful, try to open with OGR */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to open with OGR" ); poOGRDS = OGRSFDriverRegistrar::Open( pszInput, FALSE, NULL ); if( poOGRDS != NULL ) { poLayer = poOGRDS->GetLayer( 0 ); if ( poLayer != NULL ) { OGRSpatialReference *poSRS = poLayer->GetSpatialRef( ); if ( poSRS != NULL ) { CPLDebug( "gdalsrsinfo", "got SRS from OGR" ); bGotSRS = TRUE; OGRSpatialReference* poSRSClone = poSRS->Clone(); oSRS = *poSRSClone; OGRSpatialReference::DestroySpatialReference( poSRSClone ); } } OGRDataSource::DestroyDataSource( poOGRDS ); poOGRDS = NULL; } if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with OGR" ); } #endif // OGR_ENABLED /* Try ESRI file */ if ( ! bGotSRS && bIsFile && (strstr(pszInput,".prj") != NULL) ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from ESRI .prj file [%s]", pszInput ); char **pszTemp; if ( strstr(pszInput,"ESRI::") != NULL ) pszTemp = CSLLoad( pszInput+6 ); else pszTemp = CSLLoad( pszInput ); if( pszTemp ) { eErr = oSRS.importFromESRI( pszTemp ); CSLDestroy( pszTemp ); } else eErr = OGRERR_UNSUPPORTED_SRS; if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from ESRI .prj file" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from ESRI .prj file" ); bGotSRS = TRUE; } } /* Last resort, try OSRSetFromUserInput() */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from user input [%s]", pszInput ); eErr = oSRS.SetFromUserInput( pszInput ); if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from user input" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from user input" ); bGotSRS = TRUE; } } /* restore error messages */ if ( ! bDebug ) CPLSetErrorHandler ( oErrorHandler ); return bGotSRS; }
bool rspfOgrVectorTileSource::open() { const char* MODULE = "rspfOgrVectorTileSource::open"; if (isOgrVectorDataSource() == false) { close(); return false; } if(isOpen()) { close(); } theDataSource = OGRSFDriverRegistrar::Open(theImageFile, false); if (theDataSource) { int layerCount = theDataSource->GetLayerCount(); theLayerVector.resize(layerCount); if(layerCount) { for(int i = 0; i < layerCount; ++i) { OGRLayer* layer = theDataSource->GetLayer(i); if(layer) { OGRSpatialReference* spatialReference = layer->GetSpatialRef(); if(!spatialReference) { if(traceDebug()) { rspfNotify(rspfNotifyLevel_NOTICE) << MODULE << " No spatial reference given, assuming geographic" << endl; } } } else { if(traceDebug()) { rspfNotify(rspfNotifyLevel_NOTICE) << MODULE << " layer " << i << " is null." << endl; } } if (layer) { layer->GetExtent(&theBoundingExtent, true); rspfRefPtr<rspfProjection> proj = createProjFromReference(layer->GetSpatialRef()); rspfRefPtr<rspfImageGeometry> imageGeometry = 0; bool isDefaultProjection = false; if(proj.valid()) { imageGeometry = new rspfImageGeometry(0, proj.get()); } rspfMapProjection* mapProj = 0; if(imageGeometry.valid()) { mapProj = PTR_CAST(rspfMapProjection, imageGeometry->getProjection()); } else { mapProj = createDefaultProj(); imageGeometry = new rspfImageGeometry(0, mapProj); isDefaultProjection = true; } if(mapProj) { rspfDrect rect(theBoundingExtent.MinX, theBoundingExtent.MaxY, theBoundingExtent.MaxX, theBoundingExtent.MinY, RSPF_RIGHT_HANDED); std::vector<rspfGpt> points; if (isDefaultProjection || mapProj->isGeographic()) { rspfGpt g1(rect.ul().y, rect.ul().x); rspfGpt g2(rect.ur().y, rect.ur().x); rspfGpt g3(rect.lr().y, rect.lr().x); rspfGpt g4(rect.ll().y, rect.ll().x); points.push_back(g1); points.push_back(g2); points.push_back(g3); points.push_back(g4); } else { rspfGpt g1 = mapProj->inverse(rect.ul()); rspfGpt g2 = mapProj->inverse(rect.ur()); rspfGpt g3 = mapProj->inverse(rect.lr()); rspfGpt g4 = mapProj->inverse(rect.ll()); points.push_back(g1); points.push_back(g2); points.push_back(g3); points.push_back(g4); } std::vector<rspfDpt> rectTmp; rectTmp.resize(4); for(std::vector<rspfGpt>::size_type index=0; index < 4; ++index) { imageGeometry->worldToLocal(points[(int)index], rectTmp[(int)index]); } rspfDrect rect2 = rspfDrect(rectTmp[0], rectTmp[1], rectTmp[2], rectTmp[3]); theLayerVector[i] = new rspfOgrVectorLayerNode(rect2); theLayerVector[i]->setGeoImage(imageGeometry); if (i == 0) theImageGeometry = imageGeometry; } } } } } else { delete theDataSource; theDataSource = 0; return false; } return (theDataSource!=0); }
OGRLayer * OGRSQLiteExecuteSQL( OGRDataSource* poDS, const char *pszStatement, OGRGeometry *poSpatialFilter, const char *pszDialect ) { char* pszTmpDBName = (char*) CPLMalloc(256); sprintf(pszTmpDBName, "/vsimem/ogr2sqlite/temp_%p.db", pszTmpDBName); OGRSQLiteDataSource* poSQLiteDS = NULL; int nRet; int bSpatialiteDB = FALSE; CPLString osOldVal; const char* pszOldVal = CPLGetConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", NULL); if( pszOldVal != NULL ) { osOldVal = pszOldVal; pszOldVal = osOldVal.c_str(); } /* -------------------------------------------------------------------- */ /* Create in-memory sqlite/spatialite DB */ /* -------------------------------------------------------------------- */ #ifdef HAVE_SPATIALITE /* -------------------------------------------------------------------- */ /* Creating an empty spatialite DB (with spatial_ref_sys populated */ /* has a non-neglectable cost. So at the first attempt, let's make */ /* one and cache it for later use. */ /* -------------------------------------------------------------------- */ #if 1 static vsi_l_offset nEmptyDBSize = 0; static GByte* pabyEmptyDB = NULL; { static void* hMutex = NULL; CPLMutexHolder oMutexHolder(&hMutex); static int bTried = FALSE; if( !bTried && CSLTestBoolean(CPLGetConfigOption("OGR_SQLITE_DIALECT_USE_SPATIALITE", "YES")) ) { bTried = TRUE; char* pszCachedFilename = (char*) CPLMalloc(256); sprintf(pszCachedFilename, "/vsimem/ogr2sqlite/reference_%p.db",pszCachedFilename); char** papszOptions = CSLAddString(NULL, "SPATIALITE=YES"); OGRSQLiteDataSource* poCachedDS = new OGRSQLiteDataSource(); nRet = poCachedDS->Create( pszCachedFilename, papszOptions ); CSLDestroy(papszOptions); papszOptions = NULL; delete poCachedDS; if( nRet ) /* Note: the reference file keeps the ownership of the data, so that */ /* it gets released with VSICleanupFileManager() */ pabyEmptyDB = VSIGetMemFileBuffer( pszCachedFilename, &nEmptyDBSize, FALSE ); CPLFree( pszCachedFilename ); } } /* The following configuration option is usefull mostly for debugging/testing */ if( pabyEmptyDB != NULL && CSLTestBoolean(CPLGetConfigOption("OGR_SQLITE_DIALECT_USE_SPATIALITE", "YES")) ) { GByte* pabyEmptyDBClone = (GByte*)VSIMalloc(nEmptyDBSize); if( pabyEmptyDBClone == NULL ) { CPLFree(pszTmpDBName); return NULL; } memcpy(pabyEmptyDBClone, pabyEmptyDB, nEmptyDBSize); VSIFCloseL(VSIFileFromMemBuffer( pszTmpDBName, pabyEmptyDBClone, nEmptyDBSize, TRUE )); poSQLiteDS = new OGRSQLiteDataSource(); CPLSetThreadLocalConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", "NO"); nRet = poSQLiteDS->Open( pszTmpDBName, TRUE ); CPLSetThreadLocalConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", pszOldVal); if( !nRet ) { /* should not happen really ! */ delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } bSpatialiteDB = TRUE; } #else /* No caching version */ poSQLiteDS = new OGRSQLiteDataSource(); char** papszOptions = CSLAddString(NULL, "SPATIALITE=YES"); CPLSetThreadLocalConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", "NO"); nRet = poSQLiteDS->Create( pszTmpDBName, papszOptions ); CPLSetThreadLocalConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", pszOldVal); CSLDestroy(papszOptions); papszOptions = NULL; if( nRet ) { bSpatialiteDB = TRUE; } #endif else { delete poSQLiteDS; poSQLiteDS = NULL; #else // HAVE_SPATIALITE if( TRUE ) { #endif // HAVE_SPATIALITE poSQLiteDS = new OGRSQLiteDataSource(); CPLSetThreadLocalConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", "NO"); nRet = poSQLiteDS->Create( pszTmpDBName, NULL ); CPLSetThreadLocalConfigOption("OGR_SQLITE_STATIC_VIRTUAL_OGR", pszOldVal); if( !nRet ) { delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } } /* -------------------------------------------------------------------- */ /* Attach the Virtual Table OGR2SQLITE module to it. */ /* -------------------------------------------------------------------- */ OGR2SQLITEModule* poModule = OGR2SQLITE_Setup(poDS, poSQLiteDS); sqlite3* hDB = poSQLiteDS->GetDB(); /* -------------------------------------------------------------------- */ /* Analysze the statement to determine which tables will be used. */ /* -------------------------------------------------------------------- */ std::set<LayerDesc> oSetLayers; std::set<CPLString> oSetSpatialIndex; CPLString osModifiedSQL; OGR2SQLITEGetPotentialLayerNames(pszStatement, oSetLayers, oSetSpatialIndex, osModifiedSQL); std::set<LayerDesc>::iterator oIter = oSetLayers.begin(); if( strcmp(pszStatement, osModifiedSQL.c_str()) != 0 ) CPLDebug("OGR", "Modified SQL: %s", osModifiedSQL.c_str()); pszStatement = osModifiedSQL.c_str(); /* do not use it anymore */ int bFoundOGRStyle = ( osModifiedSQL.ifind("OGR_STYLE") != std::string::npos ); /* -------------------------------------------------------------------- */ /* For each of those tables, create a Virtual Table. */ /* -------------------------------------------------------------------- */ for(; oIter != oSetLayers.end(); ++oIter) { const LayerDesc& oLayerDesc = *oIter; /*CPLDebug("OGR", "Layer desc : %s, %s, %s, %s", oLayerDesc.osOriginalStr.c_str(), oLayerDesc.osSubstitutedName.c_str(), oLayerDesc.osDSName.c_str(), oLayerDesc.osLayerName.c_str());*/ CPLString osSQL; OGRLayer* poLayer = NULL; CPLString osTableName; int nExtraDS; if( oLayerDesc.osDSName.size() == 0 ) { poLayer = poDS->GetLayerByName(oLayerDesc.osLayerName); /* Might be a false positive (unlikely) */ if( poLayer == NULL ) continue; osTableName = oLayerDesc.osLayerName; nExtraDS = -1; osSQL.Printf("CREATE VIRTUAL TABLE \"%s\" USING VirtualOGR(%d,'%s',%d)", OGRSQLiteEscapeName(osTableName).c_str(), nExtraDS, OGRSQLiteEscape(osTableName).c_str(), bFoundOGRStyle); } else { OGRDataSource* poOtherDS = (OGRDataSource* ) OGROpen(oLayerDesc.osDSName, FALSE, NULL); if( poOtherDS == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot open datasource '%s'", oLayerDesc.osDSName.c_str() ); delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } poLayer = poOtherDS->GetLayerByName(oLayerDesc.osLayerName); if( poLayer == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find layer '%s' in '%s'", oLayerDesc.osLayerName.c_str(), oLayerDesc.osDSName.c_str() ); delete poOtherDS; delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } osTableName = oLayerDesc.osSubstitutedName; nExtraDS = OGR2SQLITE_AddExtraDS(poModule, poOtherDS); osSQL.Printf("CREATE VIRTUAL TABLE \"%s\" USING VirtualOGR(%d,'%s',%d)", OGRSQLiteEscapeName(osTableName).c_str(), nExtraDS, OGRSQLiteEscape(oLayerDesc.osLayerName).c_str(), bFoundOGRStyle); } char* pszErrMsg = NULL; int rc = sqlite3_exec( hDB, osSQL.c_str(), NULL, NULL, &pszErrMsg ); if( rc != SQLITE_OK ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot create virtual table for layer '%s' : %s", osTableName.c_str(), pszErrMsg); sqlite3_free(pszErrMsg); continue; } if( poLayer->GetGeomType() == wkbNone ) continue; CPLString osGeomColRaw(OGR2SQLITE_GetNameForGeometryColumn(poLayer)); const char* pszGeomColRaw = osGeomColRaw.c_str(); CPLString osGeomColEscaped(OGRSQLiteEscape(pszGeomColRaw)); const char* pszGeomColEscaped = osGeomColEscaped.c_str(); CPLString osLayerNameEscaped(OGRSQLiteEscape(osTableName)); const char* pszLayerNameEscaped = osLayerNameEscaped.c_str(); CPLString osIdxNameRaw(CPLSPrintf("idx_%s_%s", oLayerDesc.osLayerName.c_str(), pszGeomColRaw)); CPLString osIdxNameEscaped(OGRSQLiteEscapeName(osIdxNameRaw)); /* Make sure that the SRS is injected in spatial_ref_sys */ OGRSpatialReference* poSRS = poLayer->GetSpatialRef(); int nSRSId = poSQLiteDS->GetUndefinedSRID(); if( poSRS != NULL ) nSRSId = poSQLiteDS->FetchSRSId(poSRS); int bCreateSpatialIndex = FALSE; if( !bSpatialiteDB ) { osSQL.Printf("INSERT INTO geometry_columns (f_table_name, " "f_geometry_column, geometry_format, geometry_type, " "coord_dimension, srid) " "VALUES ('%s','%s','SpatiaLite',%d,%d,%d)", pszLayerNameEscaped, pszGeomColEscaped, (int) wkbFlatten(poLayer->GetGeomType()), ( poLayer->GetGeomType() & wkb25DBit ) ? 3 : 2, nSRSId); } #ifdef HAVE_SPATIALITE else { /* We detect the need for creating a spatial index by 2 means : */ /* 1) if there's an explicit reference to a 'idx_layername_geometrycolumn' */ /* table in the SQL --> old/traditionnal way of requesting spatial indices */ /* with spatialite. */ std::set<LayerDesc>::iterator oIter2 = oSetLayers.begin(); for(; oIter2 != oSetLayers.end(); ++oIter2) { const LayerDesc& oLayerDescIter = *oIter2; if( EQUAL(oLayerDescIter.osLayerName, osIdxNameRaw) ) { bCreateSpatialIndex = TRUE; break; } } /* 2) or if there's a SELECT FROM SpatialIndex WHERE f_table_name = 'layername' */ if( !bCreateSpatialIndex ) { std::set<CPLString>::iterator oIter3 = oSetSpatialIndex.begin(); for(; oIter3 != oSetSpatialIndex.end(); ++oIter3) { const CPLString& osNameIter = *oIter3; if( EQUAL(osNameIter, oLayerDesc.osLayerName) ) { bCreateSpatialIndex = TRUE; break; } } } if( poSQLiteDS->HasSpatialite4Layout() ) { int nGeomType = poLayer->GetGeomType(); int nCoordDimension = 2; if( nGeomType & wkb25DBit ) { nGeomType += 1000; nCoordDimension = 3; } osSQL.Printf("INSERT INTO geometry_columns (f_table_name, " "f_geometry_column, geometry_type, coord_dimension, " "srid, spatial_index_enabled) " "VALUES ('%s',Lower('%s'),%d ,%d ,%d, %d)", pszLayerNameEscaped, pszGeomColEscaped, nGeomType, nCoordDimension, nSRSId, bCreateSpatialIndex ); } else { const char *pszGeometryType = OGRToOGCGeomType(poLayer->GetGeomType()); if (pszGeometryType[0] == '\0') pszGeometryType = "GEOMETRY"; osSQL.Printf("INSERT INTO geometry_columns (f_table_name, " "f_geometry_column, type, coord_dimension, " "srid, spatial_index_enabled) " "VALUES ('%s','%s','%s','%s',%d, %d)", pszLayerNameEscaped, pszGeomColEscaped, pszGeometryType, ( poLayer->GetGeomType() & wkb25DBit ) ? "XYZ" : "XY", nSRSId, bCreateSpatialIndex ); } } #endif // HAVE_SPATIALITE sqlite3_exec( hDB, osSQL.c_str(), NULL, NULL, NULL ); #ifdef HAVE_SPATIALITE /* -------------------------------------------------------------------- */ /* Should we create a spatial index ?. */ /* -------------------------------------------------------------------- */ if( !bSpatialiteDB || !bCreateSpatialIndex ) continue; CPLDebug("SQLITE", "Create spatial index %s", osIdxNameRaw.c_str()); /* ENABLE_VIRTUAL_OGR_SPATIAL_INDEX is not defined */ #ifdef ENABLE_VIRTUAL_OGR_SPATIAL_INDEX osSQL.Printf("CREATE VIRTUAL TABLE \"%s\" USING " "VirtualOGRSpatialIndex(%d, '%s', pkid, xmin, xmax, ymin, ymax)", osIdxNameEscaped.c_str(), nExtraDS, OGRSQLiteEscape(oLayerDesc.osLayerName).c_str()); rc = sqlite3_exec( hDB, osSQL.c_str(), NULL, NULL, NULL ); if( rc != SQLITE_OK ) { CPLDebug("SQLITE", "Error occured during spatial index creation : %s", sqlite3_errmsg(hDB)); } #else // ENABLE_VIRTUAL_OGR_SPATIAL_INDEX rc = sqlite3_exec( hDB, "BEGIN", NULL, NULL, NULL ); osSQL.Printf("CREATE VIRTUAL TABLE \"%s\" " "USING rtree(pkid, xmin, xmax, ymin, ymax)", osIdxNameEscaped.c_str()); if( rc == SQLITE_OK ) rc = sqlite3_exec( hDB, osSQL.c_str(), NULL, NULL, NULL ); sqlite3_stmt *hStmt = NULL; if( rc == SQLITE_OK ) { const char* pszInsertInto = CPLSPrintf( "INSERT INTO \"%s\" (pkid, xmin, xmax, ymin, ymax) " "VALUES (?,?,?,?,?)", osIdxNameEscaped.c_str()); rc = sqlite3_prepare(hDB, pszInsertInto, -1, &hStmt, NULL); } OGRFeature* poFeature; OGREnvelope sEnvelope; OGR2SQLITE_IgnoreAllFieldsExceptGeometry(poLayer); poLayer->ResetReading(); while( rc == SQLITE_OK && (poFeature = poLayer->GetNextFeature()) != NULL ) { OGRGeometry* poGeom = poFeature->GetGeometryRef(); if( poGeom != NULL && !poGeom->IsEmpty() ) { poGeom->getEnvelope(&sEnvelope); sqlite3_bind_int64(hStmt, 1, (sqlite3_int64) poFeature->GetFID() ); sqlite3_bind_double(hStmt, 2, sEnvelope.MinX); sqlite3_bind_double(hStmt, 3, sEnvelope.MaxX); sqlite3_bind_double(hStmt, 4, sEnvelope.MinY); sqlite3_bind_double(hStmt, 5, sEnvelope.MaxY); rc = sqlite3_step(hStmt); if( rc == SQLITE_OK || rc == SQLITE_DONE ) rc = sqlite3_reset(hStmt); } delete poFeature; } poLayer->SetIgnoredFields(NULL); sqlite3_finalize(hStmt); if( rc == SQLITE_OK ) rc = sqlite3_exec( hDB, "COMMIT", NULL, NULL, NULL ); else { CPLDebug("SQLITE", "Error occured during spatial index creation : %s", sqlite3_errmsg(hDB)); rc = sqlite3_exec( hDB, "ROLLBACK", NULL, NULL, NULL ); } #endif // ENABLE_VIRTUAL_OGR_SPATIAL_INDEX #endif // HAVE_SPATIALITE } /* -------------------------------------------------------------------- */ /* Reload, so that virtual tables are recognized */ /* -------------------------------------------------------------------- */ poSQLiteDS->ReloadLayers(); /* -------------------------------------------------------------------- */ /* Prepare the statement. */ /* -------------------------------------------------------------------- */ /* This will speed-up layer creation */ /* ORDER BY are costly to evaluate and are not necessary to establish */ /* the layer definition. */ int bUseStatementForGetNextFeature = TRUE; int bEmptyLayer = FALSE; sqlite3_stmt *hSQLStmt = NULL; int rc = sqlite3_prepare( hDB, pszStatement, strlen(pszStatement), &hSQLStmt, NULL ); if( rc != SQLITE_OK ) { CPLError( CE_Failure, CPLE_AppDefined, "In ExecuteSQL(): sqlite3_prepare(%s):\n %s", pszStatement, sqlite3_errmsg(hDB) ); if( hSQLStmt != NULL ) { sqlite3_finalize( hSQLStmt ); } delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } /* -------------------------------------------------------------------- */ /* Do we get a resultset? */ /* -------------------------------------------------------------------- */ rc = sqlite3_step( hSQLStmt ); if( rc != SQLITE_ROW ) { if ( rc != SQLITE_DONE ) { CPLError( CE_Failure, CPLE_AppDefined, "In ExecuteSQL(): sqlite3_step(%s):\n %s", pszStatement, sqlite3_errmsg(hDB) ); sqlite3_finalize( hSQLStmt ); delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } if( !EQUALN(pszStatement, "SELECT ", 7) ) { sqlite3_finalize( hSQLStmt ); delete poSQLiteDS; VSIUnlink(pszTmpDBName); CPLFree(pszTmpDBName); return NULL; } bUseStatementForGetNextFeature = FALSE; bEmptyLayer = TRUE; } /* -------------------------------------------------------------------- */ /* Create layer. */ /* -------------------------------------------------------------------- */ OGRSQLiteSelectLayer *poLayer = NULL; poLayer = new OGRSQLiteExecuteSQLLayer( pszTmpDBName, poSQLiteDS, pszStatement, hSQLStmt, bUseStatementForGetNextFeature, bEmptyLayer ); if( poSpatialFilter != NULL ) poLayer->SetSpatialFilter( poSpatialFilter ); return poLayer; } /************************************************************************/ /* OGRSQLiteGetReferencedLayers() */ /************************************************************************/ std::set<LayerDesc> OGRSQLiteGetReferencedLayers(const char* pszStatement) { /* -------------------------------------------------------------------- */ /* Analysze the statement to determine which tables will be used. */ /* -------------------------------------------------------------------- */ std::set<LayerDesc> oSetLayers; std::set<CPLString> oSetSpatialIndex; CPLString osModifiedSQL; OGR2SQLITEGetPotentialLayerNames(pszStatement, oSetLayers, oSetSpatialIndex, osModifiedSQL); return oSetLayers; }