/*! \file io.cpp With a little bit of a elaboration, should you feel it necessary. */ int printRasterInfo(const char* pszFilename) { /** An enum type. * The documentation block cannot be put after the enum! */ GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDataset == NULL ) { std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl; return -1; } else { std::cout << "Dataset: " << pszFilename << std::endl; double adfGeoTransform[6]; std::cout << " Driver: " << poDataset->GetDriver()->GetDescription() << "/" << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; std::cout << " Size: " << poDataset->GetRasterXSize() << "x" << poDataset->GetRasterYSize() << "x" << poDataset->GetRasterCount() << std::endl; if( poDataset->GetProjectionRef() != NULL ) std::cout << " Projection: " << poDataset->GetProjectionRef() << std::endl; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { std::cout << " Origin: (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; std::cout << " Pixel Size: (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << std::endl; } } return 0; }
Raster* import_raster(string raster_filename, int band_number) { GDALAllRegister(); GDALDataset* poDataset = (GDALDataset *) GDALOpen( raster_filename.c_str(), GA_ReadOnly ); if( poDataset == NULL ) { cerr << "Error: Could not open raster data file" << endl; exit(1); } fprintf(stderr, "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); fprintf(stderr, "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) cerr << "Projection is `" << poDataset->GetProjectionRef() << "'" << endl;; GDALRasterBand* poBand = poDataset->GetRasterBand( band_number ); int nBlockXSize, nBlockYSize; poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); fprintf(stderr, "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); Raster* raster = extract_raster_attributes( poDataset ); raster->band = poBand; return raster; }
int main() { GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( "GE01.tif", GA_ReadOnly ); printf("Working! \n"); if( poDataset != NULL ){ //Get Dataset Information double adfGeoTransform[6]; printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) printf( "Projection is `%s'\n", poDataset->GetProjectionRef() ); if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ){ printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } //Fetch Raster Band GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; poBand = poDataset->GetRasterBand( 1 ); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews.\n", poBand->GetOverviewCount() ); if( poBand->GetColorTable() != NULL ) printf( "Band has a color table with %d entries.\n", poBand->GetColorTable()->GetColorEntryCount() ); //Close Dataset GDALClose(poDataset); //Exit return 0; } }
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; }
SEXP RGDAL_GetDatasetDriver(SEXP sDataset) { GDALDataset *pDataset = getGDALDatasetPtr(sDataset); GDALDriver *pDriver = pDataset->GetDriver(); SEXP sxpDriver = R_MakeExternalPtr((void *) pDriver, mkChar("GDAL Dataset"), R_NilValue); return(sxpDriver); }
SEXP RGDAL_GetDatasetDriver(SEXP sDataset) { GDALDataset *pDataset = getGDALDatasetPtr(sDataset); installErrorHandler(); GDALDriver *pDriver = pDataset->GetDriver(); uninstallErrorHandlerAndTriggerError(); SEXP sxpDriver = R_MakeExternalPtr((void *) pDriver, mkChar("GDAL Dataset"), R_NilValue); return(sxpDriver); }
SEXP RGDAL_DeleteHandle(SEXP sxpHandle) { GDALDataset *pDataset = (GDALDataset *) R_ExternalPtrAddr(sxpHandle); if (pDataset == NULL) return(R_NilValue); GDALDriver *pDriver = pDataset->GetDriver(); const char *filename = pDataset->GetDescription(); deleteFile(pDriver, filename); RGDAL_CloseHandle(sxpHandle); return(R_NilValue); }
int BIGGIFDataset::CloseDependentDatasets() { int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets(); if( poWorkDS != NULL ) { bHasDroppedRef = TRUE; CPLString osTempFilename = poWorkDS->GetDescription(); GDALDriver* poDrv = poWorkDS->GetDriver(); GDALClose( (GDALDatasetH) poWorkDS ); poWorkDS = NULL; if( poDrv != NULL ) poDrv->Delete( osTempFilename ); poWorkDS = NULL; } return bHasDroppedRef; }
SEXP RGDAL_DeleteHandle(SEXP sxpHandle) { GDALDataset *pDataset = (GDALDataset *) R_ExternalPtrAddr(sxpHandle); if (pDataset == NULL) return(R_NilValue); installErrorHandler(); GDALDriver *pDriver = pDataset->GetDriver(); // 131202 ASAN fix const char *desc = GDALGetDriverShortName( pDriver ); //Rprintf("Driver short name %s\n", desc); GDALDriver *pDriver1 = (GDALDriver *) GDALGetDriverByName(desc); char *filename = strdup(pDataset->GetDescription()); //Rprintf("file: %s\n", filename); // 131105 Even Roualt idea GDALClose((GDALDatasetH) pDataset); //Rprintf("after GDALClose\n"); GDALDeleteDataset((GDALDriverH) pDriver1, filename); //Rprintf("after GDALDeleteDataset\n"); free(filename); /* #ifndef OSGEO4W deleteFile(pDriver, filename); #endif */ R_ClearExternalPtr(sxpHandle); // RGDAL_CloseHandle(sxpHandle); uninstallErrorHandlerAndTriggerError(); return(R_NilValue); }
void CCreateMapFineTune::slotSave() { IMap& map = CMapDB::self().getMap(); GDALDataset * srcds = map.getDataset(); if(srcds == 0) { return; } double adfGeoTransform[6]; double u1, v1, u2, v2; map.dimensions(u1, v1, u2, v2); map.convertRad2M(u1, v1); map.convertRad2M(u2, v2); srcds->GetGeoTransform( adfGeoTransform ); adfGeoTransform[0] = u1; adfGeoTransform[3] = v1; progressBar->show(); GDALDriver * driver = srcds->GetDriver(); char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "TILED", "YES" ); papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "DEFLATE" ); GDALDataset * dstds = driver->CreateCopy(labelOutfile->text().toLocal8Bit(), srcds, false, papszOptions, ProgressFunc, this); if(dstds) { dstds->SetGeoTransform( adfGeoTransform ); GDALClose(dstds); } CSLDestroy( papszOptions ); progressBar->hide(); }
std::tuple<boost::shared_ptr<Map_Matrix<DataFormat> >, std::string, GeoTransform> read_in_map(fs::path file_path, GDALDataType data_type, const bool doCategorise) throw(std::runtime_error) { std::string projection; GeoTransform transformation; GDALDriver driver; //Check that the file name is valid if (!(fs::is_regular_file(file_path))) { throw std::runtime_error("Input file is not a regular file"); } // Get GDAL to open the file - code is based on the tutorial at http://www.gdal.org/gdal_tutorial.html GDALDataset *poDataset; GDALAllRegister(); //This registers all availble raster file formats for use with this utility. How neat is that. We can input any GDAL supported rater file format. //Open the Raster by calling GDALOpen. http://www.gdal.org/gdal_8h.html#a6836f0f810396c5e45622c8ef94624d4 //char pszfilename[] = file_path.c_str(); //Set this to the file name, as GDALOpen requires the standard C char pointer as function parameter. poDataset = (GDALDataset *) GDALOpen (file_path.string().c_str(), GA_ReadOnly); if (poDataset == NULL) { throw std::runtime_error("Unable to open file"); } // Print some general information about the raster double adfGeoTransform[6]; //An array of doubles that will be used to save information about the raster - where the origin is, what the raster pizel size is. printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) { printf( "Projection is `%s'\n", poDataset->GetProjectionRef() ); projection = poDataset->GetProjectionRef(); } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); transformation.x_origin = adfGeoTransform[0]; transformation.pixel_width = adfGeoTransform[1]; transformation.x_line_space = adfGeoTransform[2]; transformation.y_origin = adfGeoTransform[3]; transformation.pixel_height = adfGeoTransform[4]; transformation.y_line_space = adfGeoTransform[5]; } /// Some raster file formats allow many layers of data (called a 'band', with each having the same pixel size and origin location and spatial extent). We will get the data for the first layer into a Boost Array. //Get the data from the first band, // TODO implement method with input to specify what band. GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; poBand = poDataset->GetRasterBand( 1 ); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews.\n", poBand->GetOverviewCount() ); if( poBand->GetColorTable() != NULL ) printf( "Band has a color table with %d entries.\n", poBand->GetColorTable()->GetColorEntryCount() ); DataFormat * pafScanline; int nXSize = poBand->GetXSize(); int nYSize = poBand->GetYSize(); boost::shared_ptr<Map_Matrix<DataFormat> > in_map(new Map_Matrix<DataFormat>(nYSize, nXSize)); //get a c array of this size and read into this. //pafScanline = new DataFormat[nXSize]; //for (int i = 0; i < nYSize; i++) //rows //{ // poBand->RasterIO(GF_Read, 0, i, nXSize, 1, // pafScanline, nXSize, 1, data_type, // 0, 0); // for (int j = 0; j < nXSize; j++) //cols // { // in_map->Get(i, j) = pafScanline[j]; // } //} //get a c array of this size and read into this. pafScanline = new DataFormat[nXSize * nYSize]; //pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize); poBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, pafScanline, nXSize, nYSize, data_type, 0, 0 ); //Copy into Map_Matrix. int pafIterator = 0; // Note: Map Matrixes indexes are in opposite order to C arrays. e.g. map matrix is indexed by (row, Col) which is (y, x) and c matrices are done by (x, y) which is (Col, Row) //for (int i = 0; i < nXSize; i++) //{ // for(int j = 0; j < nYSize; j++) // { // in_map->Get(j, i) = pafScanline[pafIterator]; // pafIterator++; // } //} for (int i = 0; i < nYSize; i++) //rows { for (int j = 0; j < nXSize; j++) //cols { in_map->Get(i, j) = pafScanline[pafIterator]; pafIterator++; } } //free the c array storage delete pafScanline; int pbsuccess; // can be used with get no data value in_map->SetNoDataValue(poBand->GetNoDataValue(&pbsuccess)); //This creates a list (map?) listing all the unique values contained in the raster. if (doCategorise) in_map->updateCategories(); //Close GDAL, freeing the memory GDAL is using GDALClose( (GDALDatasetH)poDataset); return (std::make_tuple(in_map, projection, transformation)); }
void readFrames( int argc, char* argv[] ) { pfs::DOMIO pfsio; bool verbose = false; // Parse command line parameters static struct option cmdLineOptions[] = { { "help", no_argument, NULL, 'h' }, { "verbose", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char optstring[] = "hv"; pfs::FrameFileIterator it( argc, argv, "rb", NULL, NULL, optstring, cmdLineOptions ); int optionIndex = 0; while( 1 ) { int c = getopt_long (argc, argv, optstring, cmdLineOptions, &optionIndex); if( c == -1 ) break; switch( c ) { case 'h': printHelp(); throw QuietException(); case 'v': verbose = true; break; case '?': throw QuietException(); case ':': throw QuietException(); } } GDALAllRegister(); GDALDataset *poDataset; GDALRasterBand *poBand; double adfGeoTransform[6]; size_t nBlockXSize, nBlockYSize, nBands; int bGotMin, bGotMax; double adfMinMax[2]; float *pafScanline; while( true ) { pfs::FrameFile ff = it.getNextFrameFile(); if( ff.fh == NULL ) break; // No more frames it.closeFrameFile( ff ); VERBOSE_STR << "reading file '" << ff.fileName << "'" << std::endl; if( !( poDataset = (GDALDataset *) GDALOpen( ff.fileName, GA_ReadOnly ) ) ) { std::cerr << "input does not seem to be in a format supported by GDAL" << std::endl; throw QuietException(); } VERBOSE_STR << "GDAL driver: " << poDataset->GetDriver()->GetDescription() << " / " << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; nBlockXSize = poDataset->GetRasterXSize(); nBlockYSize = poDataset->GetRasterYSize(); nBands = poDataset->GetRasterCount(); VERBOSE_STR << "Data size " << nBlockXSize << "x" << nBlockYSize << "x" << nBands << std::endl; if( poDataset->GetProjectionRef() ) { VERBOSE_STR << "Projection " << poDataset->GetProjectionRef() << std::endl; } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { VERBOSE_STR << "Origin = (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; VERBOSE_STR << "Pixel Size = (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << ")" << std::endl; } if( nBlockXSize==0 || nBlockYSize==0 || ( SIZE_MAX / nBlockYSize < nBlockXSize ) || ( SIZE_MAX / (nBlockXSize * nBlockYSize ) < 4 ) ) { std::cerr << "input data has invalid size" << std::endl; throw QuietException(); } if( !(pafScanline = (float *) CPLMalloc( sizeof(float) * nBlockXSize ) ) ) { std::cerr << "not enough memory" << std::endl; throw QuietException(); } pfs::Frame *frame = pfsio.createFrame( nBlockXSize, nBlockYSize ); pfs::Channel *C[nBands]; char channel_name[32]; frame->getTags()->setString( "X-GDAL_DRIVER_SHORTNAME", poDataset->GetDriver()->GetDescription() ); frame->getTags()->setString( "X-GDAL_DRIVER_LONGNAME", poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); frame->getTags()->setString( "X-PROJECTION", poDataset->GetProjectionRef() ); if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { frame->getTags()->setString( "X-ORIGIN_X", stringify(adfGeoTransform[0]).c_str() ); frame->getTags()->setString( "X-ORIGIN_Y", stringify(adfGeoTransform[3]).c_str() ); frame->getTags()->setString( "X-PIXEL_WIDTH", stringify(adfGeoTransform[1]).c_str() ); frame->getTags()->setString( "X-PIXEL_HEIGHT", stringify(adfGeoTransform[5]).c_str() ); } for ( size_t band = 1; band <= nBands; band++) { size_t nBandXSize, nBandYSize; VERBOSE_STR << "Band " << band << ": " << std::endl; snprintf( channel_name, 32, "X-GDAL%zu", band ); C[band - 1] = frame->createChannel( channel_name ); poBand = poDataset->GetRasterBand( band ); nBandXSize = poBand->GetXSize(); nBandYSize = poBand->GetYSize(); VERBOSE_STR << " " << nBandXSize << "x" << nBandYSize << std::endl; if( nBandXSize != (int)nBlockXSize || nBandYSize != (int)nBlockYSize ) { std::cerr << "data in band " << band << " has different size" << std::endl; throw QuietException(); } VERBOSE_STR << " Type " << GDALGetDataTypeName( poBand->GetRasterDataType() ) << ", " << "Color Interpretation " << GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) << std::endl; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) { GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); } VERBOSE_STR << " Min " << adfMinMax[0] << ", Max " << adfMinMax[1] << std::endl; C[band - 1]->getTags()->setString( "X-TYPE", GDALGetDataTypeName( poBand->GetRasterDataType() ) ); C[band - 1]->getTags()->setString( "X-COLOR_INTERPRETATION", GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) ); C[band - 1]->getTags()->setString( "X-MIN", stringify(adfMinMax[0]).c_str() ); C[band - 1]->getTags()->setString( "X-MAX", stringify(adfMinMax[1]).c_str() ); for( size_t y = 0; y < nBlockYSize; y++ ) { if( poBand->RasterIO( GF_Read, 0, y, nBlockXSize, 1, pafScanline, nBlockXSize, 1, GDT_Float32, 0, 0) != CE_None ) { std::cerr << "input error" << std::endl; throw QuietException(); } memcpy( C[band - 1]->getRawData() + y * nBlockXSize, pafScanline, nBlockXSize * sizeof(float) ); } } CPLFree( pafScanline ); GDALClose( poDataset ); const char *fileNameTag = strcmp( "-", ff.fileName )==0 ? "stdin" : ff.fileName; frame->getTags()->setString( "FILE_NAME", fileNameTag ); pfsio.writeFrame( frame, stdout ); pfsio.freeFrame( frame ); } }
CC_FILE_ERROR RasterGridFilter::loadFile(QString filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/) { GDALAllRegister(); ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount()); GDALDataset* poDataset = static_cast<GDALDataset*>(GDALOpen( qPrintable(filename), GA_ReadOnly )); if( poDataset != NULL ) { ccLog::Print(QString("Raster file: '%1'").arg(filename)); ccLog::Print( "Driver: %s/%s", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); int rasterCount = poDataset->GetRasterCount(); int rasterX = poDataset->GetRasterXSize(); int rasterY = poDataset->GetRasterYSize(); ccLog::Print( "Size is %dx%dx%d", rasterX, rasterY, rasterCount ); ccPointCloud* pc = new ccPointCloud(); if (!pc->reserve(static_cast<unsigned>(rasterX * rasterY))) { delete pc; return CC_FERR_NOT_ENOUGH_MEMORY; } if( poDataset->GetProjectionRef() != NULL ) ccLog::Print( "Projection is `%s'", poDataset->GetProjectionRef() ); double adfGeoTransform[6] = { 0, //top left x 1, //w-e pixel resolution (can be negative) 0, //0 0, //top left y 0, //0 1 //n-s pixel resolution (can be negative) }; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { ccLog::Print( "Origin = (%.6f,%.6f)", adfGeoTransform[0], adfGeoTransform[3] ); ccLog::Print( "Pixel Size = (%.6f,%.6f)", adfGeoTransform[1], adfGeoTransform[5] ); } if (adfGeoTransform[1] == 0 || adfGeoTransform[5] == 0) { ccLog::Warning("Invalid pixel size! Forcing it to (1,1)"); adfGeoTransform[1] = adfGeoTransform[5] = 1; } CCVector3d origin( adfGeoTransform[0], adfGeoTransform[3], 0.0 ); CCVector3d Pshift(0,0,0); //check for 'big' coordinates { bool shiftAlreadyEnabled = (coordinatesShiftEnabled && *coordinatesShiftEnabled && coordinatesShift); if (shiftAlreadyEnabled) Pshift = *coordinatesShift; bool applyAll = false; if ( sizeof(PointCoordinateType) < 8 && ccCoordinatesShiftManager::Handle(origin,0,alwaysDisplayLoadDialog,shiftAlreadyEnabled,Pshift,0,&applyAll)) { pc->setGlobalShift(Pshift); ccLog::Warning("[RasterFilter::loadFile] Raster has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z); //we save coordinates shift information if (applyAll && coordinatesShiftEnabled && coordinatesShift) { *coordinatesShiftEnabled = true; *coordinatesShift = Pshift; } } } //create blank raster 'grid' { double z = 0.0 /*+ Pshift.z*/; for (int j=0; j<rasterY; ++j) { double y = adfGeoTransform[3] + static_cast<double>(j) * adfGeoTransform[5] + Pshift.y; CCVector3 P( 0, static_cast<PointCoordinateType>(y), static_cast<PointCoordinateType>(z)); for (int i=0; i<rasterX; ++i) { double x = adfGeoTransform[0] + static_cast<double>(i) * adfGeoTransform[1] + Pshift.x; P.x = static_cast<PointCoordinateType>(x); pc->addPoint(P); } } QVariant xVar = QVariant::fromValue<int>(rasterX); QVariant yVar = QVariant::fromValue<int>(rasterY); pc->setMetaData("raster_width",xVar); pc->setMetaData("raster_height",yVar); } //fetch raster bands bool zRasterProcessed = false; unsigned zInvalid = 0; double zMinMax[2] = {0, 0}; for (int i=1; i<=rasterCount; ++i) { ccLog::Print( "Reading band #%i", i); GDALRasterBand* poBand = poDataset->GetRasterBand(i); GDALColorInterp colorInterp = poBand->GetColorInterpretation(); GDALDataType bandType = poBand->GetRasterDataType(); int nBlockXSize, nBlockYSize; poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); ccLog::Print( "Block=%dx%d Type=%s, ColorInterp=%s", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(colorInterp) ); //fetching raster scan-line int nXSize = poBand->GetXSize(); int nYSize = poBand->GetYSize(); assert(nXSize == rasterX); assert(nYSize == rasterY); int bGotMin, bGotMax; double adfMinMax[2] = {0, 0}; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if (!bGotMin || !bGotMax ) //DGM FIXME: if the file is corrupted (e.g. ASCII ArcGrid with missing rows) this method will enter in a infinite loop! GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); ccLog::Print( "Min=%.3fd, Max=%.3f", adfMinMax[0], adfMinMax[1] ); GDALColorTable* colTable = poBand->GetColorTable(); if( colTable != NULL ) printf( "Band has a color table with %d entries", colTable->GetColorEntryCount() ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews", poBand->GetOverviewCount() ); if (colorInterp == GCI_Undefined && !zRasterProcessed/*&& !colTable*/) //probably heights? { zRasterProcessed = true; zMinMax[0] = adfMinMax[0]; zMinMax[1] = adfMinMax[1]; double* scanline = (double*) CPLMalloc(sizeof(double)*nXSize); //double* scanline = new double[nXSize]; memset(scanline,0,sizeof(double)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/scanline, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { delete pc; CPLFree(scanline); GDALClose(poDataset); return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { double z = static_cast<double>(scanline[k]) + Pshift[2]; unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { if (z < zMinMax[0] || z > zMinMax[1]) { z = zMinMax[0] - 1.0; ++zInvalid; } const_cast<CCVector3*>(pc->getPoint(pointIndex))->z = static_cast<PointCoordinateType>(z); } } } //update bounding-box pc->invalidateBoundingBox(); if (scanline) CPLFree(scanline); scanline = 0; } else //colors { bool isRGB = false; bool isScalar = false; bool isPalette = false; switch(colorInterp) { case GCI_Undefined: isScalar = true; break; case GCI_PaletteIndex: isPalette = true; break; case GCI_RedBand: case GCI_GreenBand: case GCI_BlueBand: isRGB = true; break; case GCI_AlphaBand: if (adfMinMax[0] != adfMinMax[1]) isScalar = true; else ccLog::Warning(QString("Alpha band ignored as it has a unique value (%1)").arg(adfMinMax[0])); break; default: isScalar = true; break; } if (isRGB || isPalette) { //first check that a palette exists if the band is a palette index if (isPalette && !colTable) { ccLog::Warning(QString("Band is declared as a '%1' but no palette is associated!").arg(GDALGetColorInterpretationName(colorInterp))); isPalette = false; } else { //instantiate memory for RBG colors if necessary if (!pc->hasColors() && !pc->setRGBColor(MAX_COLOR_COMP,MAX_COLOR_COMP,MAX_COLOR_COMP)) { ccLog::Warning(QString("Failed to instantiate memory for storing color band '%1'!").arg(GDALGetColorInterpretationName(colorInterp))); } else { assert(bandType <= GDT_Int32); int* colIndexes = (int*) CPLMalloc(sizeof(int)*nXSize); //double* scanline = new double[nXSize]; memset(colIndexes,0,sizeof(int)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colIndexes, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Int32, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { CPLFree(colIndexes); delete pc; return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { colorType* C = const_cast<colorType*>(pc->getPointColor(pointIndex)); switch(colorInterp) { case GCI_PaletteIndex: assert(colTable); { GDALColorEntry col; colTable->GetColorEntryAsRGB(colIndexes[k],&col); C[0] = static_cast<colorType>(col.c1 & MAX_COLOR_COMP); C[1] = static_cast<colorType>(col.c2 & MAX_COLOR_COMP); C[2] = static_cast<colorType>(col.c3 & MAX_COLOR_COMP); } break; case GCI_RedBand: C[0] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; case GCI_GreenBand: C[1] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; case GCI_BlueBand: C[2] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; default: assert(false); break; } } } } if (colIndexes) CPLFree(colIndexes); colIndexes = 0; pc->showColors(true); } } } else if (isScalar) { ccScalarField* sf = new ccScalarField(GDALGetColorInterpretationName(colorInterp)); if (!sf->resize(pc->size(),true,NAN_VALUE)) { ccLog::Warning(QString("Failed to instantiate memory for storing '%1' as a scalar field!").arg(sf->getName())); sf->release(); sf = 0; } else { double* colValues = (double*) CPLMalloc(sizeof(double)*nXSize); //double* scanline = new double[nXSize]; memset(colValues,0,sizeof(double)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colValues, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { CPLFree(colValues); delete pc; return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { ScalarType s = static_cast<ScalarType>(colValues[k]); sf->setValue(pointIndex,s); } } } if (colValues) CPLFree(colValues); colValues = 0; sf->computeMinAndMax(); pc->addScalarField(sf); if (pc->getNumberOfScalarFields() == 1) pc->setCurrentDisplayedScalarField(0); pc->showSF(true); } } } } if (pc) { if (!zRasterProcessed) { ccLog::Warning("Raster has no height (Z) information: you can convert one of its scalar fields to Z with 'Edit > Scalar Fields > Set SF as coordinate(s)'"); } else if (zInvalid != 0 && zInvalid < pc->size()) { //shall we remove the points with invalid heights? if (QMessageBox::question(0,"Remove NaN points?","This raster has pixels with invalid heights. Shall we remove them?",QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { CCLib::ReferenceCloud validPoints(pc); unsigned count = pc->size(); bool error = true; if (validPoints.reserve(count-zInvalid)) { for (unsigned i=0; i<count; ++i) { if (pc->getPoint(i)->z >= zMinMax[0]) validPoints.addPointIndex(i); } if (validPoints.size() > 0) { validPoints.resize(validPoints.size()); ccPointCloud* newPC = pc->partialClone(&validPoints); if (newPC) { delete pc; pc = newPC; error = false; } } else { assert(false); } } if (error) { ccLog::Error("Not enough memory to remove the points with invalid heights!"); } } } container.addChild(pc); } GDALClose(poDataset); } else { return CC_FERR_UNKNOWN_FILE; } return CC_FERR_NO_ERROR; }
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; }
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); }
// 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 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); }
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 ogrDeleteLayer (SEXP ogrSource, SEXP Layer, SEXP ogrDriver) { OGRLayer *poLayer; #ifdef GDALV2 GDALDataset *poDS; GDALDriver *poDriver; #else OGRDataSource *poDS; OGRSFDriver *poDriver; #endif int iLayer = -1; int flag = 0; installErrorHandler(); #ifdef GDALV2 poDriver = GetGDALDriverManager()->GetDriverByName(CHAR(STRING_ELT(ogrDriver, 0))); #else poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName( CHAR(STRING_ELT(ogrDriver, 0)) ); #endif uninstallErrorHandlerAndTriggerError(); if (poDriver == NULL) { error("Driver not available"); } installErrorHandler(); #ifdef GDALV2 poDS=(GDALDataset*) GDALOpenEx(CHAR(STRING_ELT(ogrSource, 0)), GDAL_OF_VECTOR, NULL, NULL, NULL); if(poDS==NULL) { error("Cannot open data source"); } if (!EQUAL(CHAR(STRING_ELT(ogrDriver, 0)), poDS->GetDriver()->GetDescription())) { GDALClose( poDS ); poDS = NULL; } #else poDS = poDriver->Open(CHAR(STRING_ELT(ogrSource, 0)), TRUE); #endif uninstallErrorHandlerAndTriggerError(); if (poDS==NULL) error("Cannot open data source for update"); installErrorHandler(); for(iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++) { poLayer = poDS->GetLayer(iLayer); #ifdef GDALV2 if (poLayer != NULL && EQUAL(poLayer->GetName(), CHAR(STRING_ELT(Layer, 0)))) { flag = 1; break; } #else if (poLayer != NULL && EQUAL(poLayer->GetLayerDefn()->GetName(), CHAR(STRING_ELT(Layer, 0)))) { flag = 1; break; } #endif } uninstallErrorHandlerAndTriggerError(); installErrorHandler(); if (flag != 0) { int res = poDS->DeleteLayer(iLayer); if (res != OGRERR_NONE) { #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); error("ogrDeleteLayer: failed to delete layer"); } } else { warning("ogrDeleteLayer: no such layer"); } #ifdef GDALV2 GDALClose( poDS ); #else OGRDataSource::DestroyDataSource( poDS ); #endif uninstallErrorHandlerAndTriggerError(); return(R_NilValue); }