Handle<Value> GDALDrivers::getNames(const Arguments& args) { HandleScope scope; int gdal_count = GetGDALDriverManager()->GetDriverCount(); int i, ogr_count = 0; std::string name; #if GDAL_VERSION_MAJOR < 2 ogr_count = OGRSFDriverRegistrar::GetRegistrar()->GetDriverCount(); #endif int n = gdal_count + ogr_count; Local<Array> driver_names = Array::New(n); for (i = 0; i < gdal_count; ++i) { GDALDriver *driver = GetGDALDriverManager()->GetDriver(i); name = driver->GetDescription(); #if GDAL_VERSION_MAJOR < 2 if(name == "VRT") name = "VRT:raster"; #endif driver_names->Set(i, SafeString::New(name.c_str())); } for (; i < n; ++i) { OGRSFDriver *driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriver(i - gdal_count); name = driver->GetName(); #if GDAL_VERSION_MAJOR < 2 if(name == "VRT") name = "VRT:vector"; #endif driver_names->Set(i, SafeString::New(name.c_str())); } return scope.Close(driver_names); }
GDALDataset* openGDALDataSet() { cout << "Opening " << inDataFile->c_str() << "...\n"; GDALDataset* ds = (GDALDataset *)GDALOpen(inDataFile->c_str(), GA_ReadOnly); if (ds != NULL) { GDALDriver* drv = ds->GetDriver(); if (drv == NULL) { cout << " -- Unable to find GDAL driver for " << (char *)inDataFile->c_str() << " -- "; ds = NULL; } else { cout << "GDAL FILE TYPE: " << drv->GetDescription() << "\n"; cout << "CONTAINS " << ds->GetRasterCount() << " dataset(s); size " << ds->GetRasterXSize() << "x" << ds->GetRasterYSize() << "\n"; if (ds->GetRasterCount() == 0) { ds = NULL; cout << " -- FILE " << (char *)inDataFile->c_str() << " contains zero raster bands -- "; } } } else cout << " -- Unable to open " << (char *)inDataFile->c_str() << " -- "; cout << "...Done.\n"; return ds; }
OGRDataSourceH OGR_Dr_CopyDataSource( OGRSFDriverH hDriver, OGRDataSourceH hSrcDS, const char *pszNewName, char **papszOptions ) { VALIDATE_POINTER1( hDriver, "OGR_Dr_CopyDataSource", NULL ); VALIDATE_POINTER1( hSrcDS, "OGR_Dr_CopyDataSource", NULL ); VALIDATE_POINTER1( pszNewName, "OGR_Dr_CopyDataSource", NULL ); GDALDriver* poDriver = (GDALDriver*)hDriver; if( !poDriver->GetMetadataItem( GDAL_DCAP_CREATE ) ) { CPLError( CE_Failure, CPLE_NotSupported, "%s driver does not support data source creation.", poDriver->GetDescription() ); return NULL; } GDALDataset *poSrcDS = (GDALDataset*) hSrcDS; GDALDataset *poODS; poODS = poDriver->Create( pszNewName, 0, 0, 0, GDT_Unknown, papszOptions ); if( poODS == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Process each data source layer. */ /* -------------------------------------------------------------------- */ for( int iLayer = 0; iLayer < poSrcDS->GetLayerCount(); iLayer++ ) { OGRLayer *poLayer = poSrcDS->GetLayer(iLayer); if( poLayer == NULL ) continue; poODS->CopyLayer( poLayer, poLayer->GetLayerDefn()->GetName(), papszOptions ); } return (OGRDataSourceH)poODS; }
MAIN_START(nArgc, papszArgv) { // Check strict compilation and runtime library version as we use C++ API. if( !GDAL_CHECK_VERSION(papszArgv[0]) ) exit(1); EarlySetConfigOptions(nArgc, papszArgv); OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ nArgc = OGRGeneralCmdLineProcessor(nArgc, &papszArgv, 0); if( nArgc < 1 ) exit(-nArgc); char *pszWHERE = nullptr; const char *pszDataSource = nullptr; char **papszLayers = nullptr; OGRGeometry *poSpatialFilter = nullptr; int nRepeatCount = 1; bool bAllLayers = false; char *pszSQLStatement = nullptr; const char *pszDialect = nullptr; int nRet = 0; const char* pszGeomField = nullptr; char **papszOpenOptions = nullptr; char **papszExtraMDDomains = nullptr; bool bListMDD = false; bool bShowMetadata = true; bool bFeatureCount = true; bool bExtent = true; bool bDatasetGetNextFeature = false; bool bReadOnly = false; bool bUpdate = false; const char* pszWKTFormat = "WKT2"; for( int 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")); CSLDestroy(papszArgv); return 0; } else if( EQUAL(papszArgv[iArg], "--help") ) { Usage(); } else if( EQUAL(papszArgv[iArg], "-ro") ) { bReadOnly = true; } else if( EQUAL(papszArgv[iArg], "-update") ) { bUpdate = true; } else if( EQUAL(papszArgv[iArg], "-q") || EQUAL(papszArgv[iArg], "-quiet")) { bVerbose = false; } else if( EQUAL(papszArgv[iArg], "-qq") ) { /* Undocumented: mainly only useful for AFL testing */ bVerbose = false; bSuperQuiet = true; } else if( EQUAL(papszArgv[iArg], "-fid") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); nFetchFID = CPLAtoGIntBig(papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-spat") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(4); OGRLinearRing oRing; oRing.addPoint(CPLAtof(papszArgv[iArg+1]), CPLAtof(papszArgv[iArg+2])); oRing.addPoint(CPLAtof(papszArgv[iArg+1]), CPLAtof(papszArgv[iArg+4])); oRing.addPoint(CPLAtof(papszArgv[iArg+3]), CPLAtof(papszArgv[iArg+4])); oRing.addPoint(CPLAtof(papszArgv[iArg+3]), CPLAtof(papszArgv[iArg+2])); oRing.addPoint(CPLAtof(papszArgv[iArg+1]), CPLAtof(papszArgv[iArg+2])); poSpatialFilter = new OGRPolygon(); static_cast<OGRPolygon *>(poSpatialFilter)->addRing(&oRing); iArg += 4; } else if( EQUAL(papszArgv[iArg], "-geomfield") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszGeomField = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg], "-where") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); iArg++; CPLFree(pszWHERE); GByte* pabyRet = nullptr; if( papszArgv[iArg][0] == '@' && VSIIngestFile(nullptr, papszArgv[iArg] + 1, &pabyRet, nullptr, 1024*1024) ) { RemoveBOM(pabyRet); pszWHERE = reinterpret_cast<char *>(pabyRet); } else { pszWHERE = CPLStrdup(papszArgv[iArg]); } } else if( EQUAL(papszArgv[iArg], "-sql") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); iArg++; CPLFree(pszSQLStatement); GByte* pabyRet = nullptr; if( papszArgv[iArg][0] == '@' && VSIIngestFile(nullptr, papszArgv[iArg] + 1, &pabyRet, nullptr, 1024*1024) ) { RemoveBOM(pabyRet); pszSQLStatement = reinterpret_cast<char *>(pabyRet); RemoveSQLComments(pszSQLStatement); } else { pszSQLStatement = CPLStrdup(papszArgv[iArg]); } } else if( EQUAL(papszArgv[iArg], "-dialect") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszDialect = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg], "-rc") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); nRepeatCount = atoi(papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-al") ) { bAllLayers = true; } else if( EQUAL(papszArgv[iArg], "-so") || EQUAL(papszArgv[iArg], "-summary") ) { bSummaryOnly = true; } else if( STARTS_WITH_CI(papszArgv[iArg], "-fields=") ) { char* pszTemp = static_cast<char *>(CPLMalloc(32 + strlen(papszArgv[iArg]))); snprintf(pszTemp, 32 + strlen(papszArgv[iArg]), "DISPLAY_FIELDS=%s", papszArgv[iArg] + strlen("-fields=")); papszOptions = CSLAddString(papszOptions, pszTemp); CPLFree(pszTemp); } else if( STARTS_WITH_CI(papszArgv[iArg], "-geom=") ) { char* pszTemp = static_cast<char *>(CPLMalloc(32 + strlen(papszArgv[iArg]))); snprintf(pszTemp, 32 + strlen(papszArgv[iArg]), "DISPLAY_GEOMETRY=%s", papszArgv[iArg] + strlen("-geom=")); papszOptions = CSLAddString(papszOptions, pszTemp); CPLFree(pszTemp); } else if( EQUAL(papszArgv[iArg], "-oo") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszOpenOptions = CSLAddString(papszOpenOptions, papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-nomd") ) { bShowMetadata = false; } else if( EQUAL(papszArgv[iArg], "-listmdd") ) { bListMDD = true; } else if( EQUAL(papszArgv[iArg], "-mdd") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszExtraMDDomains = CSLAddString(papszExtraMDDomains, papszArgv[++iArg]); } else if( EQUAL(papszArgv[iArg], "-nocount") ) { bFeatureCount = false; } else if( EQUAL(papszArgv[iArg], "-noextent") ) { bExtent = false; } else if( EQUAL(papszArgv[iArg], "-rl")) { bDatasetGetNextFeature = true; } else if( EQUAL(papszArgv[iArg], "-wkt_format") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszWKTFormat = papszArgv[++iArg]; } else if( papszArgv[iArg][0] == '-' ) { Usage(CPLSPrintf("Unknown option name '%s'", papszArgv[iArg])); } else if( pszDataSource == nullptr ) { pszDataSource = papszArgv[iArg]; } else { papszLayers = CSLAddString(papszLayers, papszArgv[iArg]); bAllLayers = false; } } if( pszDataSource == nullptr ) Usage("No datasource specified."); if( pszDialect != nullptr && pszWHERE != nullptr && pszSQLStatement == nullptr ) printf("Warning: -dialect is ignored with -where. Use -sql instead"); if( bDatasetGetNextFeature && pszSQLStatement ) { Usage("-rl is incompatible with -sql"); } #ifdef __AFL_HAVE_MANUAL_CONTROL while (__AFL_LOOP(1000)) { #endif /* -------------------------------------------------------------------- */ /* Open data source. */ /* -------------------------------------------------------------------- */ GDALDataset *poDS = static_cast<GDALDataset *>(GDALOpenEx( pszDataSource, ((bReadOnly || pszSQLStatement == nullptr) && !bUpdate ? GDAL_OF_READONLY : GDAL_OF_UPDATE) | GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr)); if( poDS == nullptr && !bReadOnly && !bUpdate && pszSQLStatement == nullptr ) { // In some cases (empty geopackage for example), opening in read-only // mode fails, so retry in update mode if( GDALIdentifyDriverEx(pszDataSource, GDAL_OF_VECTOR, nullptr, nullptr) ) { poDS = static_cast<GDALDataset *>(GDALOpenEx( pszDataSource, GDAL_OF_UPDATE | GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr)); } } if( poDS == nullptr && !bReadOnly && !bUpdate && pszSQLStatement != nullptr ) { poDS = static_cast<GDALDataset *>(GDALOpenEx( pszDataSource, GDAL_OF_READONLY | GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr)); if( poDS != nullptr && bVerbose ) { printf("Had to open data source read-only.\n"); #ifdef __AFL_HAVE_MANUAL_CONTROL bReadOnly = true; #endif } } GDALDriver *poDriver = nullptr; if( poDS != nullptr ) poDriver = poDS->GetDriver(); /* -------------------------------------------------------------------- */ /* Report failure */ /* -------------------------------------------------------------------- */ if( poDS == nullptr ) { printf("FAILURE:\n" "Unable to open datasource `%s' with the following drivers.\n", pszDataSource); #ifdef __AFL_HAVE_MANUAL_CONTROL continue; #else OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { printf(" -> %s\n", poR->GetDriver(iDriver)->GetDescription()); } nRet = 1; goto end; #endif } CPLAssert(poDriver != nullptr); /* -------------------------------------------------------------------- */ /* Some information messages. */ /* -------------------------------------------------------------------- */ if( bVerbose ) printf("INFO: Open of `%s'\n" " using driver `%s' successful.\n", pszDataSource, poDriver->GetDescription()); if( bVerbose && !EQUAL(pszDataSource,poDS->GetDescription()) ) { printf("INFO: Internal data source name `%s'\n" " different from user name `%s'.\n", poDS->GetDescription(), pszDataSource); } GDALInfoReportMetadata(static_cast<GDALMajorObjectH>(poDS), bListMDD, bShowMetadata, papszExtraMDDomains); if( bDatasetGetNextFeature ) { nRepeatCount = 0; // skip layer reporting. /* -------------------------------------------------------------------- */ /* Set filters if provided. */ /* -------------------------------------------------------------------- */ if( pszWHERE != nullptr || poSpatialFilter != nullptr ) { for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if( poLayer == nullptr ) { printf("FAILURE: Couldn't fetch advertised layer %d!\n", iLayer); exit(1); } if( pszWHERE != nullptr ) { if( poLayer->SetAttributeFilter(pszWHERE) != OGRERR_NONE ) { printf("WARNING: SetAttributeFilter(%s) " "failed on layer %s.\n", pszWHERE, poLayer->GetName()); } } if( poSpatialFilter != nullptr ) { if( pszGeomField != nullptr ) { OGRFeatureDefn *poDefn = poLayer->GetLayerDefn(); const int iGeomField = poDefn->GetGeomFieldIndex(pszGeomField); if( iGeomField >= 0 ) poLayer->SetSpatialFilter(iGeomField, poSpatialFilter); else printf("WARNING: Cannot find geometry field %s.\n", pszGeomField); } else { poLayer->SetSpatialFilter(poSpatialFilter); } } } } std::set<OGRLayer*> oSetLayers; while( true ) { OGRLayer* poLayer = nullptr; OGRFeature* poFeature = poDS->GetNextFeature(&poLayer, nullptr, nullptr, nullptr); if( poFeature == nullptr ) break; if( papszLayers == nullptr || poLayer == nullptr || CSLFindString(papszLayers, poLayer->GetName()) >= 0 ) { if( bVerbose && poLayer != nullptr && oSetLayers.find(poLayer) == oSetLayers.end() ) { oSetLayers.insert(poLayer); const bool bSummaryOnlyBackup = bSummaryOnly; bSummaryOnly = true; ReportOnLayer(poLayer, nullptr, nullptr, nullptr, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); bSummaryOnly = bSummaryOnlyBackup; } if( !bSuperQuiet && !bSummaryOnly ) poFeature->DumpReadable(nullptr, papszOptions); } OGRFeature::DestroyFeature(poFeature); } } /* -------------------------------------------------------------------- */ /* Special case for -sql clause. No source layers required. */ /* -------------------------------------------------------------------- */ else if( pszSQLStatement != nullptr ) { nRepeatCount = 0; // skip layer reporting. if( CSLCount(papszLayers) > 0 ) printf("layer names ignored in combination with -sql.\n"); OGRLayer *poResultSet = poDS->ExecuteSQL( pszSQLStatement, pszGeomField == nullptr ? poSpatialFilter : nullptr, pszDialect); if( poResultSet != nullptr ) { if( pszWHERE != nullptr ) { if( poResultSet->SetAttributeFilter(pszWHERE) != OGRERR_NONE ) { printf("FAILURE: SetAttributeFilter(%s) failed.\n", pszWHERE); exit(1); } } if( pszGeomField != nullptr ) ReportOnLayer(poResultSet, nullptr, pszGeomField, poSpatialFilter, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); else ReportOnLayer(poResultSet, nullptr, nullptr, nullptr, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); poDS->ReleaseResultSet(poResultSet); } } // coverity[tainted_data] for( int iRepeat = 0; iRepeat < nRepeatCount; iRepeat++ ) { if( papszLayers == nullptr || *papszLayers == nullptr ) { if( iRepeat == 0 ) CPLDebug("OGR", "GetLayerCount() = %d\n", poDS->GetLayerCount()); /* -------------------------------------------------------------------- */ /* Process each data source layer. */ /* -------------------------------------------------------------------- */ for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if( poLayer == nullptr ) { printf("FAILURE: Couldn't fetch advertised layer %d!\n", iLayer); exit(1); } if( !bAllLayers ) { printf("%d: %s", iLayer + 1, poLayer->GetName()); const int nGeomFieldCount = poLayer->GetLayerDefn()->GetGeomFieldCount(); if( nGeomFieldCount > 1 ) { printf(" ("); for( int iGeom = 0; iGeom < nGeomFieldCount; iGeom++ ) { if( iGeom > 0 ) printf(", "); OGRGeomFieldDefn* poGFldDefn = poLayer->GetLayerDefn()-> GetGeomFieldDefn(iGeom); printf( "%s", OGRGeometryTypeToName( poGFldDefn->GetType())); } printf(")"); } else if( poLayer->GetGeomType() != wkbUnknown ) printf(" (%s)", OGRGeometryTypeToName( poLayer->GetGeomType())); printf("\n"); } else { if( iRepeat != 0 ) poLayer->ResetReading(); ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); } } } else { /* -------------------------------------------------------------------- */ /* Process specified data source layers. */ /* -------------------------------------------------------------------- */ for( char** papszIter = papszLayers; *papszIter != nullptr; ++papszIter ) { OGRLayer *poLayer = poDS->GetLayerByName(*papszIter); if( poLayer == nullptr ) { printf("FAILURE: Couldn't fetch requested layer %s!\n", *papszIter); exit(1); } if( iRepeat != 0 ) poLayer->ResetReading(); ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, bListMDD, bShowMetadata, papszExtraMDDomains, bFeatureCount, bExtent, pszWKTFormat); } } } /* -------------------------------------------------------------------- */ /* Close down. */ /* -------------------------------------------------------------------- */ GDALClose(poDS); #ifdef __AFL_HAVE_MANUAL_CONTROL } #else end: #endif CSLDestroy(papszArgv); CSLDestroy(papszLayers); CSLDestroy(papszOptions); CSLDestroy(papszOpenOptions); CSLDestroy(papszExtraMDDomains); if( poSpatialFilter ) OGRGeometryFactory::destroyGeometry(poSpatialFilter); CPLFree(pszSQLStatement); CPLFree(pszWHERE); OGRCleanupAll(); return nRet; }
SEXP ogrCheckExists (SEXP ogrSource, SEXP Layer) { OGRLayer *poLayer; #ifdef GDALV2 GDALDataset *poDS; GDALDriver *poDriver; #else OGRDataSource *poDS; OGRSFDriver *poDriver; #endif SEXP ans, drv; int pc=0; PROTECT(ans=NEW_LOGICAL(1)); pc++; installErrorHandler(); #ifdef GDALV2 poDS=(GDALDataset*) GDALOpenEx(CHAR(STRING_ELT(ogrSource, 0)), GDAL_OF_VECTOR, NULL, NULL, NULL); if (poDS != NULL) poDriver = poDS->GetDriver(); #else poDS=OGRSFDriverRegistrar::Open(CHAR(STRING_ELT(ogrSource, 0)), FALSE, &poDriver); #endif uninstallErrorHandlerAndTriggerError(); if (poDS==NULL) { // installErrorHandler(); // OGRDataSource::DestroyDataSource( poDS ); // uninstallErrorHandlerAndTriggerError(); // delete poDS; LOGICAL_POINTER(ans)[0] = FALSE; UNPROTECT(pc); return(ans); } installErrorHandler(); poLayer = poDS->GetLayerByName(CHAR(STRING_ELT(Layer, 0))); uninstallErrorHandlerAndTriggerError(); if (poLayer == NULL) { installErrorHandler(); #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); // delete poDS; LOGICAL_POINTER(ans)[0] = FALSE; UNPROTECT(pc); return(ans); } LOGICAL_POINTER(ans)[0] = TRUE; PROTECT(drv=allocVector(STRSXP,1)); pc++; installErrorHandler(); #ifdef GDALV2 SET_STRING_ELT(drv, 0, mkChar(poDriver->GetDescription())); #else SET_STRING_ELT(drv, 0, mkChar(poDriver->GetName())); #endif uninstallErrorHandlerAndTriggerError(); setAttrib(ans, install("driver"), drv); installErrorHandler(); #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); // delete poDS; UNPROTECT(pc); return(ans); }
// extern "C" { SEXP ogrInfo(SEXP ogrsourcename, SEXP Layer) { // return FIDs, nFields, fieldInfo SEXP ans, vec1, vec2, vec3,/*mat,*/drv, dvec; SEXP itemlist, itemnames, itemwidth, itemtype, itemTypeNames; SEXP itemlistmaxcount; #ifdef GDALV2 SEXP dFIDs; #endif /*SEXP geotype;*/ int nFIDs, nFields, iField, *nCount, pc=0; #ifdef GDALV2 GDALDriver *poDriver; GDALDataset *poDS; #else OGRDataSource *poDS; OGRSFDriver *poDriver; #endif OGRLayer *poLayer; OGRFeature *poFeature; OGRFeatureDefn *poDefn; /* OGRGeometry *poGeom;*/ installErrorHandler(); #ifdef GDALV2 poDS=(GDALDataset*) GDALOpenEx(CHAR(STRING_ELT(ogrsourcename, 0)), GDAL_OF_VECTOR, NULL, NULL, NULL); if(poDS==NULL) { uninstallErrorHandlerAndTriggerError(); error("Cannot open data source"); } poDriver = poDS->GetDriver(); #else poDS=OGRSFDriverRegistrar::Open(CHAR(STRING_ELT(ogrsourcename, 0)), FALSE, &poDriver); #endif uninstallErrorHandlerAndTriggerError(); if(poDS==NULL) { installErrorHandler(); #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); // delete poDS; error("Cannot open file"); } installErrorHandler(); poLayer = poDS->GetLayerByName(CHAR(STRING_ELT(Layer, 0))); uninstallErrorHandlerAndTriggerError(); if(poLayer == NULL) { installErrorHandler(); #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); // delete poDS; error("Cannot open layer"); } // allocate a list for return values PROTECT(ans=allocVector(VECSXP,6)); pc++; PROTECT(drv=allocVector(STRSXP,1)); pc++; installErrorHandler(); #ifdef GDALV2 SET_STRING_ELT(drv, 0, mkChar(poDriver->GetDescription())); #else SET_STRING_ELT(drv, 0, mkChar(poDriver->GetName())); #endif uninstallErrorHandlerAndTriggerError(); SET_VECTOR_ELT(ans,3,drv); PROTECT(vec1=allocVector(INTSXP,1)); pc++; installErrorHandler(); #ifdef GDALV2 GIntBig nFIDs64 = poLayer->GetFeatureCount(); nFIDs = (nFIDs64 > INT_MAX) ? INT_MAX : (nFIDs64 < INT_MIN) ? INT_MIN : (int) nFIDs64; if ((GIntBig) nFIDs != nFIDs64) { warning("ogrInfo: feature count overflow"); INTEGER(vec1)[0]=NA_INTEGER; PROTECT(dFIDs=NEW_NUMERIC(1)); pc++; NUMERIC_POINTER(dFIDs)[0] = (double) nFIDs64; setAttrib(vec1, install("dFIDs"), dFIDs); } else { // store number of FIDs INTEGER(vec1)[0]=nFIDs; } #else nFIDs = poLayer->GetFeatureCount(); // store number of FIDs INTEGER(vec1)[0]=nFIDs; #endif uninstallErrorHandlerAndTriggerError(); if (nFIDs == -1) { int i=0; installErrorHandler(); while( ((poFeature = poLayer->GetNextFeature()) != NULL) && i <= INT_MAX) { i++; OGRFeature::DestroyFeature( poFeature ); // delete poFeature; } uninstallErrorHandlerAndTriggerError(); if (i == INT_MAX) { error("ogrInfo: undeclared feature count overflow"); } else { nFIDs = i; warning("ogrInfo: feature count not given; %d counted", nFIDs); } installErrorHandler(); poLayer->ResetReading(); uninstallErrorHandlerAndTriggerError(); INTEGER(vec1)[0]=nFIDs; } SET_VECTOR_ELT(ans,0,vec1); // store other stuff.... installErrorHandler(); poDefn = poLayer->GetLayerDefn(); nFields = poDefn->GetFieldCount(); uninstallErrorHandlerAndTriggerError(); // store number of fields PROTECT(vec2=allocVector(INTSXP,1)); pc++; INTEGER(vec2)[0]=nFields; SET_VECTOR_ELT(ans,1,vec2); installErrorHandler(); OGREnvelope oExt; if (poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE) { PROTECT(dvec=allocVector(REALSXP,4)); pc++; REAL(dvec)[0] = oExt.MinX; REAL(dvec)[1] = oExt.MinY; REAL(dvec)[2] = oExt.MaxX; REAL(dvec)[3] = oExt.MaxY; SET_VECTOR_ELT(ans,4,dvec); } uninstallErrorHandlerAndTriggerError(); PROTECT(itemnames=allocVector(STRSXP,nFields)); pc++; PROTECT(itemtype=allocVector(INTSXP,nFields)); pc++; PROTECT(itemwidth=allocVector(INTSXP,nFields)); pc++; // try List types PROTECT(itemlistmaxcount=allocVector(INTSXP,nFields)); pc++; PROTECT(itemTypeNames=allocVector(STRSXP,nFields)); pc++; int listFieldCount=0; installErrorHandler(); for(iField=0; iField<nFields; iField++) { OGRFieldDefn *poField = poDefn->GetFieldDefn(iField); SET_STRING_ELT(itemnames,iField,mkChar(poField->GetNameRef())); INTEGER(itemtype)[iField]=poField->GetType(); if (INTEGER(itemtype)[iField] == OFTIntegerList || INTEGER(itemtype)[iField] == OFTRealList || INTEGER(itemtype)[iField] == OFTStringList) listFieldCount++; INTEGER(itemwidth)[iField]=poField->GetWidth(); SET_STRING_ELT(itemTypeNames,iField,mkChar(poField->GetFieldTypeName( poField->GetType()))); INTEGER(itemlistmaxcount)[iField] = 0; } uninstallErrorHandlerAndTriggerError(); PROTECT(vec3=allocVector(INTSXP,1)); pc++; INTEGER(vec3)[0]=listFieldCount; SET_VECTOR_ELT(ans,5,vec3); PROTECT(itemlist=allocVector(VECSXP,5)); pc++; SET_VECTOR_ELT(itemlist,0,itemnames); SET_VECTOR_ELT(itemlist,1,itemtype); SET_VECTOR_ELT(itemlist,2,itemwidth); SET_VECTOR_ELT(itemlist,3,itemTypeNames); // try List types if (listFieldCount > 0) { poLayer->ResetReading(); OGRFeature* poFeature; nCount = (int *) R_alloc((size_t) nFields, sizeof(int)); for (iField=0; iField<nFields; iField++) nCount[iField] = 0; installErrorHandler(); OGRField* psField; while( (poFeature = poLayer->GetNextFeature()) != NULL ) { for(iField=0; iField<nFields; iField++) { psField = poFeature->GetRawFieldRef(iField); if (INTEGER(itemtype)[iField] == OFTIntegerList) { nCount[iField] = psField->IntegerList.nCount; if (nCount[iField] > INTEGER(itemlistmaxcount)[iField]) INTEGER(itemlistmaxcount)[iField] = nCount[iField]; } else if (INTEGER(itemtype)[iField] == OFTRealList) { nCount[iField] = psField->RealList.nCount; if (nCount[iField] > INTEGER(itemlistmaxcount)[iField]) INTEGER(itemlistmaxcount)[iField] = nCount[iField]; } else if (INTEGER(itemtype)[iField] == OFTStringList) { nCount[iField] = psField->StringList.nCount; if (nCount[iField] > INTEGER(itemlistmaxcount)[iField]) INTEGER(itemlistmaxcount)[iField] = nCount[iField]; } } OGRFeature::DestroyFeature( poFeature ); // delete poFeature; } uninstallErrorHandlerAndTriggerError(); } SET_VECTOR_ELT(itemlist,4,itemlistmaxcount); SET_VECTOR_ELT(ans,2,itemlist); UNPROTECT(pc); installErrorHandler(); #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); // delete poDS; return(ans); }
SEXP ogrListLayers (SEXP ogrSource) { #ifdef GDALV2 GDALDataset *poDS; GDALDriver *poDriver; #else OGRDataSource *poDS; OGRSFDriver *poDriver; #endif OGRLayer *poLayer; int i, nlayers; SEXP ans, debug; int pc=0; installErrorHandler(); #ifdef GDALV2 poDS=(GDALDataset*) GDALOpenEx(CHAR(STRING_ELT(ogrSource, 0)), GDAL_OF_VECTOR, NULL, NULL, NULL); if(poDS==NULL) { uninstallErrorHandlerAndTriggerError(); error("Cannot open data source"); } poDriver = poDS->GetDriver(); #else poDS=OGRSFDriverRegistrar::Open(CHAR(STRING_ELT(ogrSource, 0)), FALSE, &poDriver); #endif uninstallErrorHandlerAndTriggerError(); if(poDS==NULL) { error("Cannot open data source"); } debug = getAttrib(ogrSource, mkString("debug")); installErrorHandler(); nlayers = poDS->GetLayerCount(); uninstallErrorHandlerAndTriggerError(); if (LOGICAL_POINTER(debug)[0] == TRUE) Rprintf("ogrListLayers: nlayers %d\n", nlayers); PROTECT(ans=NEW_CHARACTER(nlayers+1)); pc++; for (i=0; i<nlayers; i++) { installErrorHandler(); poLayer = poDS->GetLayer(i); if(poLayer == NULL) { if (LOGICAL_POINTER(debug)[0] == TRUE) { SET_STRING_ELT(ans, i, mkChar("")); Rprintf("ogrListLayers: NULL layer %d\n", i); } else { uninstallErrorHandlerAndTriggerError(); error("Cannot open layer"); } } else { SET_STRING_ELT(ans, i, mkChar(poLayer->GetLayerDefn()->GetName())); } uninstallErrorHandlerAndTriggerError(); } installErrorHandler(); #ifdef GDALV2 SET_STRING_ELT(ans, nlayers, mkChar(poDriver->GetDescription())); #else SET_STRING_ELT(ans, nlayers, mkChar(poDriver->GetName())); #endif uninstallErrorHandlerAndTriggerError(); installErrorHandler(); #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); UNPROTECT(pc); return(ans); }
int main(int argc, const char * argv[]) { boost::filesystem::path p = boost::filesystem::current_path(); fprintf(stdout,"cwp := %s\n",p.c_str()); GDALAllRegister(); // for (int i = 0; i < GDALGetDriverCount(); i++) { // GDALDriver * d = (GDALDriver *)GDALGetDriver(i); // const char * desc = d->GetDescription(); // fprintf(stdout, "GDAL: %s\n",desc); // } GDALDataset *poDataset = (GDALDataset *) GDALOpen(DataPath.c_str(), GA_ReadOnly ); std::string SupportedDriver = {"GTiff"}; if (poDataset != NULL) { GDALDriver * drv = poDataset->GetDriver(); assert(0 == SupportedDriver.compare(drv->GetDescription())); assert (1 == poDataset->GetRasterCount()); fprintf(stdout,"RasterXSize := %d\n",poDataset->GetRasterXSize()); fprintf(stdout,"RasterYSize := %d\n",poDataset->GetRasterYSize()); fprintf(stdout,"ProjectionRef := %s\n",poDataset->GetProjectionRef()); double adfGeoTransform[6]; if ( poDataset->GetGeoTransform(adfGeoTransform) == CE_None ) { fprintf(stdout, "Origin = (%.6f, %.6f)\n", adfGeoTransform[0],adfGeoTransform[3]); // upper left courner fprintf(stdout, "Pixel Size = (%.6f, %.6f)\n", adfGeoTransform[1],adfGeoTransform[5]); // pixel width/height } GDALRasterBand *poBand = poDataset->GetRasterBand(1); int nBlockXSize, nBlockYSize; poBand->GetBlockSize(&nBlockXSize, &nBlockYSize); std::string SupportedDataType = {"Int16"}; assert (GDT_Int16 == poBand->GetRasterDataType()); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); FILE * patch = fopen("patch.txt","w"); for (int i = 0; i < poBand->GetYSize(); i++) { int nXSize = poBand->GetXSize(); float *pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize); poBand->RasterIO( GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0); for (int j = 0; j < nXSize; j++) { fprintf(patch, "%f ", pafScanline[j]); } fprintf(patch, "\n"); CPLFree(pafScanline); } fclose(patch); GDALClose(poDataset); } DelaunayTriangulation dt; //std::srand(static_cast<unsigned int>(std::time(0))); // use current time as seed for random generator /* std::srand(static_cast<unsigned int>(3652123216145)); for (int i = 0; i < 10 ; i++) { double x = 180.0 * static_cast <float> (rand()) / static_cast <float> (RAND_MAX);; double y = 180.0 * static_cast <float> (rand()) / static_cast <float> (RAND_MAX);; dt.addPt(x, y, 0.0); } */ /* dt.addPt(-0.02222276248244826, -0.4979727817680433, 0.0); dt.addPt(-0.4285431913366012, 0.4745826469497594, 0.0); dt.addPt( 0.3105396575392593, 0.2400179190933871, 0.0); dt.addPt(-0.01883958887200765, 0.3630260628303755, 0.0); dt.addPt( 0.3790312361708201, 0.3779794437605696, 0.0); dt.addPt(-0.2994955874043476, 0.3776609263174803, 0.0); dt.addPt( 0.3471817493878135, 0.08365533089605659, 0.0); dt.addPt(-0.00485819764887746, 0.3482682405489201, 0.0); dt.addPt( 0.3443122672329771, -0.1437312230875075, 0.0); dt.addPt( 0.309330780347186, -0.07758103877080702, 0.0); dt.compute(); */ return 0; }
MAIN_START(argc, argv) { /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); EarlySetConfigOptions(argc, argv); /* -------------------------------------------------------------------- */ /* Generic arg processing. */ /* -------------------------------------------------------------------- */ GDALAllRegister(); argc = GDALGeneralCmdLineProcessor(argc, &argv, 0); if( argc < 1 ) exit( -argc ); for( int i = 0; i < argc; i++ ) { if( EQUAL(argv[i], "--utility_version") ) { printf("%s was compiled against GDAL %s and " "is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); CSLDestroy(argv); return 0; } else if( EQUAL(argv[i], "--help") ) { Usage(); } } GDALRasterizeOptionsForBinary* psOptionsForBinary = GDALRasterizeOptionsForBinaryNew(); // coverity[tainted_data] GDALRasterizeOptions *psOptions = GDALRasterizeOptionsNew(argv + 1, psOptionsForBinary); CSLDestroy(argv); if( psOptions == nullptr ) { Usage(); } if( !(psOptionsForBinary->bQuiet) ) { GDALRasterizeOptionsSetProgress(psOptions, GDALTermProgress, nullptr); } if( psOptionsForBinary->pszSource == nullptr ) Usage("No input file specified."); if( psOptionsForBinary->pszDest == nullptr ) Usage("No output file specified."); /* -------------------------------------------------------------------- */ /* Open input file. */ /* -------------------------------------------------------------------- */ GDALDatasetH hInDS = GDALOpenEx( psOptionsForBinary->pszSource, GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR, nullptr, nullptr, nullptr); if( hInDS == nullptr ) exit(1); /* -------------------------------------------------------------------- */ /* Open output file if it exists. */ /* -------------------------------------------------------------------- */ GDALDatasetH hDstDS = nullptr; if( !(psOptionsForBinary->bCreateOutput) ) { CPLPushErrorHandler(CPLQuietErrorHandler); hDstDS = GDALOpenEx( psOptionsForBinary->pszDest, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr ); CPLPopErrorHandler(); } if( psOptionsForBinary->pszFormat != nullptr && (psOptionsForBinary->bCreateOutput || hDstDS == nullptr) ) { GDALDriverManager *poDM = GetGDALDriverManager(); GDALDriver *poDriver = poDM->GetDriverByName(psOptionsForBinary->pszFormat); char** papszDriverMD = (poDriver) ? poDriver->GetMetadata(): nullptr; if( poDriver == nullptr || !CPLTestBool(CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE")) || !CPLTestBool(CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE")) ) { fprintf(stderr, "Output driver `%s' not recognised or does not support " "direct output file creation.\n", psOptionsForBinary->pszFormat); fprintf(stderr, "The following format drivers are configured and " "support direct output:\n" ); for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ ) { GDALDriver* poIter = poDM->GetDriver(iDriver); papszDriverMD = poIter->GetMetadata(); if( CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE")) && CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE")) ) { fprintf(stderr, " -> `%s'\n", poIter->GetDescription()); } } exit(1); } } int bUsageError = FALSE; GDALDatasetH hRetDS = GDALRasterize(psOptionsForBinary->pszDest, hDstDS, hInDS, psOptions, &bUsageError); if(bUsageError == TRUE) Usage(); const int nRetCode = hRetDS ? 0 : 1; GDALClose(hInDS); GDALClose(hRetDS); GDALRasterizeOptionsFree(psOptions); GDALRasterizeOptionsForBinaryFree(psOptionsForBinary); GDALDestroyDriverManager(); return nRetCode; }
static void Usage(const char* pszAdditionalMsg, int bShort) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); printf( "Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update]\n" " [-select field_list] [-where restricted_where|@filename]\n" " [-progress] [-sql <sql statement>|@filename] [-dialect dialect]\n" " [-preserve_fid] [-fid FID]\n" " [-spat xmin ymin xmax ymax] [-spat_srs srs_def] [-geomfield field]\n" " [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]\n" " [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]\n" " dst_datasource_name src_datasource_name\n" " [-lco NAME=VALUE] [-nln name] \n" " [-nlt type|PROMOTE_TO_MULTI|CONVERT_TO_LINEAR|CONVERT_TO_CURVE]\n" " [-dim 2|3|layer_dim] [layer [layer ...]]\n" "\n" "Advanced options :\n" " [-gt n] [-ds_transaction]\n" " [[-oo NAME=VALUE] ...] [[-doo NAME=VALUE] ...]\n" " [-clipsrc [xmin ymin xmax ymax]|WKT|datasource|spat_extent]\n" " [-clipsrcsql sql_statement] [-clipsrclayer layer]\n" " [-clipsrcwhere expression]\n" " [-clipdst [xmin ymin xmax ymax]|WKT|datasource]\n" " [-clipdstsql sql_statement] [-clipdstlayer layer]\n" " [-clipdstwhere expression]\n" " [-wrapdateline][-datelineoffset val]\n" " [[-simplify tolerance] | [-segmentize max_dist]]\n" " [-addfields] [-unsetFid]\n" " [-relaxedFieldNameMatch] [-forceNullable] [-unsetDefault]\n" " [-fieldTypeToString All|(type1[,type2]*)] [-unsetFieldWidth]\n" " [-mapFieldType srctype|All=dsttype[,srctype2=dsttype2]*]\n" " [-fieldmap identity | index1[,index2]*]\n" " [-splitlistfields] [-maxsubfields val]\n" " [-explodecollections] [-zfield field_name]\n" " [-gcp pixel line easting northing [elevation]]* [-order n | -tps]\n" " [-nomd] [-mo \"META-TAG=VALUE\"]* [-noNativeData]\n"); if (bShort) { printf( "\nNote: ogr2ogr --long-usage for full help.\n"); if( pszAdditionalMsg ) fprintf(stderr, "\nFAILURE: %s\n", pszAdditionalMsg); exit( 1 ); } printf("\n -f format_name: output file format name, possible values are:\n"); std::vector<CPLString> aoSetDrivers; for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { GDALDriver *poDriver = poR->GetDriver(iDriver); if( CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) aoSetDrivers.push_back( poDriver->GetDescription() ); } std::sort (aoSetDrivers.begin(), aoSetDrivers.end(), StringCISortFunction); for( size_t i = 0; i < aoSetDrivers.size(); i++ ) { printf( " -f \"%s\"\n", aoSetDrivers[i].c_str() ); } printf( " -append: Append to existing layer instead of creating new if it exists\n" " -overwrite: delete the output layer and recreate it empty\n" " -update: Open existing output datasource in update mode\n" " -progress: Display progress on terminal. Only works if input layers have the \n" " \"fast feature count\" capability\n" " -select field_list: Comma-delimited list of fields from input layer to\n" " copy to the new layer (defaults to all)\n" " -where restricted_where: Attribute query (like SQL WHERE)\n" " -wrapdateline: split geometries crossing the dateline meridian\n" " (long. = +/- 180deg)\n" " -datelineoffset: offset from dateline in degrees\n" " (default long. = +/- 10deg,\n" " geometries within 170deg to -170deg will be split)\n" " -sql statement: Execute given SQL statement and save result.\n" " -dialect value: select a dialect, usually OGRSQL to avoid native sql.\n" " -skipfailures: skip features or layers that fail to convert\n" " -gt n: group n features per transaction (default 20000). n can be set to unlimited\n" " -spat xmin ymin xmax ymax: spatial query extents\n" " -simplify tolerance: distance tolerance for simplification.\n" " -segmentize max_dist: maximum distance between 2 nodes.\n" " Used to create intermediate points\n" " -dsco NAME=VALUE: Dataset creation option (format specific)\n" " -lco NAME=VALUE: Layer creation option (format specific)\n" " -oo NAME=VALUE: Input dataset open option (format specific)\n" " -doo NAME=VALUE: Destination dataset open option (format specific)\n" " -nln name: Assign an alternate name to the new layer\n" " -nlt type: Force a geometry type for new layer. One of NONE, GEOMETRY,\n" " POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT,\n" " MULTIPOLYGON, or MULTILINESTRING, or PROMOTE_TO_MULTI or CONVERT_TO_LINEAR. Add \"25D\" for 3D layers.\n" " Default is type of source layer.\n" " -dim dimension: Force the coordinate dimension to the specified value.\n" " -fieldTypeToString type1,...: Converts fields of specified types to\n" " fields of type string in the new layer. Valid types are : Integer,\n" " Integer64, Real, String, Date, Time, DateTime, Binary, IntegerList, Integer64List, RealList,\n" " StringList. Special value All will convert all fields to strings.\n" " -fieldmap index1,index2,...: Specifies the list of field indexes to be\n" " copied from the source to the destination. The (n)th value specified\n" " in the list is the index of the field in the target layer definition\n" " in which the n(th) field of the source layer must be copied. Index count\n" " starts at zero. There must be exactly as many values in the list as\n" " the count of the fields in the source layer. We can use the 'identity'\n" " setting to specify that the fields should be transferred by using the\n" " same order. This setting should be used along with the append setting."); printf(" -a_srs srs_def: Assign an output SRS\n" " -t_srs srs_def: Reproject/transform to this SRS on output\n" " -s_srs srs_def: Override source SRS\n" "\n" " Srs_def can be a full WKT definition (hard to escape properly),\n" " or a well known definition (i.e. EPSG:4326) or a file with a WKT\n" " definition.\n" ); if( pszAdditionalMsg ) fprintf(stderr, "\nFAILURE: %s\n", pszAdditionalMsg); }