OGRSpatialReference* OGRGeomediaDataSource::GetGeomediaSRS(const char* pszGCoordSystemTable, const char* pszGCoordSystemGUID) { if (pszGCoordSystemTable == NULL || pszGCoordSystemGUID == NULL) return NULL; OGRLayer* poGCoordSystemTable = GetLayerByName(pszGCoordSystemTable); if (poGCoordSystemTable == NULL) return NULL; poGCoordSystemTable->ResetReading(); OGRFeature* poFeature; while((poFeature = poGCoordSystemTable->GetNextFeature()) != NULL) { const char* pszCSGUID = poFeature->GetFieldAsString("CSGUID"); if (pszCSGUID && strcmp(pszCSGUID, pszGCoordSystemGUID) == 0) { OGRSpatialReference* poSRS = OGRGetGeomediaSRS(poFeature); delete poFeature; return poSRS; } delete poFeature; } return NULL; }
GNMGFID GNMGenericNetwork::FindNearestPoint(const OGRPoint* poPoint, const std::vector<OGRLayer*>& paPointLayers, double dfTolerance) { VALIDATE_POINTER1(poPoint, "GNMGenericNetwork::FindNearestPoint", -1); double dfMinX = poPoint->getX() - dfTolerance; double dfMinY = poPoint->getY() - dfTolerance; double dfMaxX = poPoint->getX() + dfTolerance; double dfMaxY = poPoint->getY() + dfTolerance; OGRFeature *poFeature; for(size_t i = 0; i < paPointLayers.size(); ++i) { OGRLayer *poLayer = paPointLayers[i]; poLayer->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX, dfMaxY); poLayer->ResetReading(); while((poFeature = poLayer->GetNextFeature()) != NULL) { GNMGFID nRetFID = poFeature->GetFieldAsGNMGFID(GNM_SYSFIELD_GFID); OGRFeature::DestroyFeature(poFeature); return nRetFID; } } return -1; }
//#include "s57.h" int main(int argc, char **argv) { OGRRegisterAll(); OGRDataSource *poDS; printf("Opening %s\n",argv[1]); poDS = OGRSFDriverRegistrar::Open( argv[1], FALSE ); if( poDS == NULL ) { printf( "Open failed.\n" ); exit( 1 ); } OGRLayer *poLayer; int layers = poDS->GetLayerCount(); for (int layer =0 ; layer< layers; layer++) { poLayer = poDS->GetLayer(layer); if (poLayer == NULL) continue; printf("%d, %s, %s",layer, poLayer->GetName(), OGRGeometryTypeToName(poLayer->GetGeomType())); poLayer->ResetReading(); OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn(); int iField; for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ ) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField ); printf(", %s",poFieldDefn->GetNameRef()); } printf("\n"); } }
//本函数返回矢量点的数目 int CGouTIN::read_samplenum(const char* pDataSource,const char* pLayerName,char** pSpatialRefWkt) { //将类CIDW做参数 OGRRegisterAll(); OGRDataSource *poDS=OGRSFDriverRegistrar::Open(pDataSource,FALSE); //OGRDataSource *poDS=OGRSFDriverRegistrar::Open("point.shp",FALSE); if( poDS == NULL ) { printf( "[ERROR] zmw Open failed.\n" ); exit( 1 ); } OGRLayer *poLayer = poDS->GetLayerByName(pLayerName); //cout<<f3.c_str()<<endl; //cout<<"here2"<<endl; //OGRSpatialReference * sref= poLayer->GetSpatialRef(); //sref->exportToWkt(pSpatialRefWkt); //cout<<"here3"<<endl; OGRFeature *poFeature; poLayer->ResetReading(); //cout<<"here4"<<endl; int count = 0;//统计散点数 while((poFeature=poLayer->GetNextFeature())!=NULL) { count++; } OGRDataSource::DestroyDataSource( poDS ); return count; }
int FGdbDataSource::FixIndexes() { int bRet = TRUE; if( m_pConnection && m_pConnection->IsFIDHackInProgress() ) { m_pConnection->CloseGeodatabase(); char* apszDrivers[2]; apszDrivers[0] = (char*) "OpenFileGDB"; apszDrivers[1] = NULL; const char* pszSystemCatalog = CPLFormFilename(m_osFSName, "a00000001.gdbtable", NULL); GDALDataset* poOpenFileGDBDS = (GDALDataset*) GDALOpenEx(pszSystemCatalog, GDAL_OF_VECTOR, apszDrivers, NULL, NULL); if( poOpenFileGDBDS == NULL || poOpenFileGDBDS->GetLayer(0) == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s with OpenFileGDB driver. " "Should not happen. Some layers will be corrupted", pszSystemCatalog); bRet = FALSE; } else { OGRLayer* poLayer = poOpenFileGDBDS->GetLayer(0); size_t count = m_layers.size(); for(size_t i = 0; i < count; ++i ) { if( m_layers[i]->m_oMapOGRFIDToFGDBFID.size() == 0) continue; CPLString osFilter = "name = '"; osFilter += m_layers[i]->GetName(); osFilter += "'"; poLayer->SetAttributeFilter(osFilter); poLayer->ResetReading(); OGRFeature* poF = poLayer->GetNextFeature(); if( poF == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find filename for layer %s", m_layers[i]->GetName()); bRet = FALSE; } else { if( !m_layers[i]->EditIndexesForFIDHack(CPLFormFilename(m_osFSName, CPLSPrintf("a%08x", (int)poF->GetFID()), NULL)) ) { bRet = FALSE; } } delete poF; } } GDALClose(poOpenFileGDBDS); m_pConnection->SetFIDHackInProgress(FALSE); } return bRet; }
//--------------------------------------------------------- CSG_Shapes * COGR_DataSource::Read_Shapes(int iLayer) { OGRLayer *pLayer = Get_Layer(iLayer); //----------------------------------------------------- if( pLayer && Get_Type(iLayer) != SHAPE_TYPE_Undefined ) { int iField; OGRFeature *pFeature; OGRFeatureDefn *pDef = pLayer->GetLayerDefn(); CSG_Shapes *pShapes = SG_Create_Shapes(Get_Type(iLayer), CSG_String(pDef->GetName())); for(iField=0; iField<pDef->GetFieldCount(); iField++) { OGRFieldDefn *pDefField = pDef->GetFieldDefn(iField); pShapes->Add_Field(pDefField->GetNameRef(), COGR_Driver::Get_Type(pDefField->GetType())); } pLayer->ResetReading(); //------------------------------------------------- while( (pFeature = pLayer->GetNextFeature()) != NULL && SG_UI_Process_Get_Okay(false) ) { OGRGeometry *pGeometry = pFeature->GetGeometryRef(); if( pGeometry != NULL ) { CSG_Shape *pShape = pShapes->Add_Shape(); for(iField=0; iField<pDef->GetFieldCount(); iField++) { OGRFieldDefn *pDefField = pDef->GetFieldDefn(iField); switch( pDefField->GetType() ) { default: pShape->Set_Value(iField, SG_STR_MBTOSG(pFeature->GetFieldAsString (iField))); break; case OFTString: pShape->Set_Value(iField, SG_STR_MBTOSG(pFeature->GetFieldAsString (iField))); break; case OFTInteger: pShape->Set_Value(iField, pFeature->GetFieldAsInteger(iField)); break; case OFTReal: pShape->Set_Value(iField, pFeature->GetFieldAsDouble (iField)); break; } } //----------------------------------------- if( _Read_Geometry(pShape, pGeometry) == false ) { pShapes->Del_Shape(pShape); } } OGRFeature::DestroyFeature(pFeature); } return( pShapes ); } //----------------------------------------------------- return( NULL ); }
bool AoIIntersection::compareIntersectionResults( OGRDataSource *resultData, IntersectionSummary *origSummary ) { bool success = true; IntersectionSummary resultSummary; OGRLayer *resultLayer; resultSummary.numLayers = resultData->GetLayerCount(); if ( resultSummary.numLayers != origSummary->numLayers ) { printf( "Test results: Layer count mismatch.\n" ); success = false; } for (int layerCt = 0; layerCt < resultSummary.numLayers; ++layerCt) { resultLayer = resultData->GetLayer( layerCt ); if ( resultLayer == NULL ) { printf( "Test results: Layer count mismatch.\n" ); success = false; } // get field indices for the fields we wrote int acreIndex = resultLayer->GetLayerDefn()->GetFieldIndex( "Acres in AoI" ); int areaIndex = resultLayer->GetLayerDefn()->GetFieldIndex( "Percent of AOI" ); resultLayer->ResetReading(); OGRFeature *resultFeature; while( (resultFeature = resultLayer->GetNextFeature()) != NULL ) { double acres = resultFeature->GetFieldAsDouble( acreIndex ); double area = resultFeature->GetFieldAsDouble( areaIndex ); resultSummary.totalPercentOfAoI += area; resultSummary.totalIntersectionAcres += acres; } } if ( resultSummary.totalPercentOfAoI != origSummary->totalPercentOfAoI ) { printf( "Test results: Percent of AoI mismatch.\n" ); success = false; } if ( resultSummary.totalIntersectionAcres != origSummary->totalIntersectionAcres ) { printf( "Test results: Acreage mismatch.\n" ); success = false; } return success; }
OGRLayer* OGRGeoJSONDataSource::GetLayer( int nLayer ) { if( 0 <= nLayer || nLayer < nLayers_ ) { CPLAssert( NULL != papoLayers_[nLayer] ); OGRLayer* poLayer = papoLayers_[nLayer]; /* Return layer in readable state. */ poLayer->ResetReading(); return poLayer; } return NULL; }
bool LoadShapes(GDALDataset* dataset, QueryIntermediateData& qid) { OGRLayer* waterLayer = dataset->GetLayerByName("water"); if (!waterLayer) return true; // requested layer may not be present in requested dataset waterLayer->ResetReading(); OGRFeature* feature; while ((feature = waterLayer->GetNextFeature()) != NULL) { auto geo = feature->GetGeometryRef(); auto featureId = feature->GetFID(); if (qid.transform) { if (geo->transform(qid.transform) != OGRERR_NONE) { continue; } } if (geo->getGeometryType() == wkbMultiPolygon) { auto mp = (OGRMultiPolygon*)geo; const int numPolys = mp->getNumGeometries(); for (int p = 0; p < numPolys; p++) { auto poly = new Polygon((OGRPolygon*)mp->getGeometryRef(p), featureId); qid.waterPolyQuadtree.Insert(poly); qid.waterPolygons.push_back(poly); } } else if (geo->getGeometryType() == wkbPolygon) { auto poly = new Polygon((OGRPolygon*)geo, featureId); qid.waterPolyQuadtree.Insert(poly); qid.waterPolygons.push_back(poly); } OGRFeature::DestroyFeature(feature); } return true; }
/** @brief Get list of shapes from file, optional search by name * * read in shape file, extract shapes return as list * optional string argument returns only matching shapes (by string.find) * (!case sensitive!) */ void getAvailShapes(vector<OGRFeature*>* availShapes_p, const string selected = "") { OGRRegisterAll(); OGRDataSource * poDS; string path = "../admin_level_6/shape_al6/admin_level_6.shp"; if (exists(path)) { poDS = OGRSFDriverRegistrar::Open(path.c_str()); if (poDS == NULL) { cout << "Data read error" << endl; exit (1); } } else { cout << "File not found" << endl; exit(1); } // cout << "Found " << poDS->GetLayerCount() << "Layers in File" << endl; OGRLayer *poLayer; OGRFeature *poFeature; poLayer = poDS->GetLayer(0); poLayer->ResetReading(); while ( (poFeature = poLayer->GetNextFeature()) != NULL) { if (selected.empty()) { availShapes_p->push_back(poFeature); } else { if (string(poFeature->GetFieldAsString(1)).find(selected) != string::npos) availShapes_p->push_back(poFeature); else OGRFeature::DestroyFeature(poFeature); } } OGRDataSource::DestroyDataSource(poDS); }
int wxStation::GetFirstStationLine(const char *xFilename) { OGRDataSourceH hDS; OGRLayer *poLayer; OGRFeature *poFeature; OGRLayerH hLayer; GIntBig iBig = 1; hDS = OGROpen( xFilename, FALSE, NULL ); if(hDS == NULL) { return -1; //very bad! } poLayer = (OGRLayer*)OGR_DS_GetLayer( hDS, 0 ); hLayer=OGR_DS_GetLayer(hDS,0); OGR_L_ResetReading(hLayer); poLayer->ResetReading(); poFeature = poLayer->GetFeature(iBig); if (poFeature==NULL) { return -1; //If there are no stations in the csv! } std::string start_datetime(poFeature->GetFieldAsString(15)); if(start_datetime.empty()==true) { return 1; } if(start_datetime.empty()==false) { return 2; } }
MapExtruder::MapExtruder(const char* map2dFile,double height) { _map2dFile = map2dFile; _height = height; OGRRegisterAll(); OGRDataSource *poDS = OGRSFDriverRegistrar::Open(_map2dFile,FALSE); if( poDS == NULL) { printf("Open failed.\n"); exit(1); } _map2d = new OGRMultiPolygon(); OGRLayer *poLayer; poLayer = poDS->GetLayer(0); OGRFeature *poFeature; poLayer->ResetReading(); while((poFeature = poLayer->GetNextFeature())!=NULL) { OGRGeometry *poGeometry; poGeometry = poFeature ->GetGeometryRef(); if(poGeometry!=NULL) { if(poGeometry ->getGeometryType()==wkbPolygon) _map2d->addGeometry((OGRPolygon*) poGeometry); if(poGeometry ->getGeometryType()==wkbMultiPolygon) { int nPolygons = ((OGRMultiPolygon*)poGeometry)->getNumGeometries(); for(int i=0;i<nPolygons;i++) _map2d->addGeometry((OGRPolygon*)(((OGRMultiPolygon*)poGeometry)->getGeometryRef(i))); } } } extrusion(); }
bool OGRPointToLatLon(double &x, double &y, OGRDataSourceH hDS, const char *datum) { char *pszPrj = NULL; OGRSpatialReference *poSrcSRS; OGRSpatialReference oSourceSRS, oTargetSRS; OGRCoordinateTransformation *poCT; if (hDS == NULL) { return false; } OGRLayer *poLayer; poLayer = (OGRLayer *)OGR_DS_GetLayer(hDS, 0); poLayer->ResetReading(); poSrcSRS = poLayer->GetSpatialRef(); if (poSrcSRS == NULL) { return false; } oTargetSRS.SetWellKnownGeogCS(datum); poCT = OGRCreateCoordinateTransformation(poSrcSRS, &oTargetSRS); if (poCT == NULL) { return false; } if (!poCT->Transform(1, &x, &y)) { OGRCoordinateTransformation::DestroyCT(poCT); return false; } OGRCoordinateTransformation::DestroyCT(poCT); return true; }
bool MapWidget::loadCountyShapes() { OGRRegisterAll(); std::string filename = g_dataDirectory + "/counties/tl_2009_48_county00.shp"; OGRDataSource * dataSource = OGRSFDriverRegistrar::Open(filename.c_str(), false); if(dataSource == NULL) { put_flog(LOG_ERROR, "could not open %s", filename.c_str()); return false; } OGRLayer * layer = dataSource->GetLayerByName("tl_2009_48_county00"); layer->ResetReading(); OGRFeature * feature; while((feature = layer->GetNextFeature()) != NULL) { // get county FIPS code int nodeId = feature->GetFieldAsInteger("COUNTYFP00"); if(nodeId == 0) { put_flog(LOG_WARN, "invalid county"); } // add a new county to the counties map corresponding to this nodeId boost::shared_ptr<MapShape> county(new MapShape()); counties_[nodeId] = county; OGRGeometry * geometry = feature->GetGeometryRef(); if(geometry != NULL && geometry->getGeometryType() == wkbPolygon) { OGRPolygon * polygon = (OGRPolygon *)geometry; OGRLinearRing * ring = polygon->getExteriorRing(); for(int i=0; i<ring->getNumPoints(); i++) { // x is longitude, y latitude county->addVertex(ring->getY(i), ring->getX(i)); } // set the centroid OGRPoint centroidPoint; if(polygon->Centroid(¢roidPoint) == OGRERR_NONE) { county->setCentroid(centroidPoint.getY(), centroidPoint.getX()); } else { put_flog(LOG_WARN, "no polygon centroid"); } } else { put_flog(LOG_WARN, "no polygon geometry"); } OGRFeature::DestroyFeature(feature); } OGRDataSource::DestroyDataSource(dataSource); return true; }
bool ShortNavigation::createObstaclesTables() { // OGRLayer* layer; status = true; if ( !status==false ) { qDebug()<<"bool ShortNavigation::createObstaclesTables()"; /// POINT_OFFSET is the area around the obstacle, /// so is it's value is 5, it will draw 10 m^2 //float POINT_OFFSET = settingsManager->getPOffset(); float POINT_OFFSET = 5; //test values, above comment from old code //float NOT_ALLOWED_DEPTH = settingsManager->getMinDepth(); float NOT_ALLOWED_DEPTH = 2; //test values, above comment from old code /// signsound with depth from 0 to this value are /// taken in consideration for the obstacles layer //float SIGNSOUND_THRESHOLD = settingsManager->getSignsound(); float SIGNSOUND_THRESHOLD = 1; //test values, above comment from old code // ################################################## // list of polygon layers considered obstacles QList<QString> polygon_layers; polygon_layers.append("generarea_r"); // list of point layers to be considered as obstacles QList<QString> point_layers; point_layers.append("rock_p"); point_layers.append("wreck_p"); point_layers.append("navaid_p"); point_layers.append("signsound_p"); // line layers to be considered as obstacles QList<QString> line_layers; line_layers.append("depthcont_l"); //#################################################### for (int i = 0 ; i < this->chartObjects.size(); i++) { // qDebug() << "chartObjects size" << chartObjects.size(); if(this->chartObjects.at(i)->getTableName() == "generarea_r") { for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { this->polyObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j)); } } if(this->chartObjects.at(i)->getTableName() == "depthcont_l") { for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { //TODO: parse line from polygon //this->lineObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j)); //Not used in Shortnavigation -> can be removed! } } if(this->chartObjects.at(i)->getTableName() == "rock_p") { for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { //need to check how vectors are written from DB. is getfeaturecount = polygonvector.size ? for(int k = 0; k < this->chartObjects.at(i)->getCoordinateGeometry().at(j).size();k++) { this->pointObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j).at(k)); } } } if(this->chartObjects.at(i)->getTableName() == "wreck_p") { for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { for(int k = 0; k < this->chartObjects.at(i)->getCoordinateGeometry().at(j).size();k++) { this->pointObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j).at(k)); } } } if(this->chartObjects.at(i)->getTableName() == "navaid_p") { for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { for(int k = 0; k < this->chartObjects.at(i)->getCoordinateGeometry().at(j).size();k++) { this->pointObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j).at(k)); } } } if(this->chartObjects.at(i)->getTableName() == "signsound_p") { QVector<QPolygonF> qpoint; QList<QPointF> listqpoint; OGRLayer* layer; OGRFeatureDefn *poFDefn; OGRFeature *poFeature; qpoint = this->chartObjects.at(i)->getCoordinateGeometry(); for(int n = 0; n < qpoint.size(); n++){ listqpoint = qpoint.value(n).toList(); } layer = this->chartObjects.at(i)->getFeatureData(); layer->ResetReading(); QString /*sql("SELECT * FROM *"); //FIX THIS! //*/ sql("SELECT * FROM ( SELECT DISTINCT Intersects( wkb_geometry, "); for(int m= 0; m < layer->GetFeatureCount();m++ ) { poFDefn = layer->GetLayerDefn(); poFeature = layer->GetNextFeature(); for(int j = 0; j < poFDefn->GetFieldCount(); j++ ){ OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( j ); QString str = poFieldDefn->GetNameRef(); if(str.contains("depth") == true) { if (poFeature->GetFieldAsDouble(j) < SIGNSOUND_THRESHOLD) { //parse out depths above signsound threshold since they are not obstacles pointObstacles.append(listqpoint.at(m)); } } } } // // CREATE NEW TABLES sql = "CREATE TABLE obstacles_r (ogc_fid serial);"; sql.append( "CREATE TABLE obstacles_l (ogc_fid serial);" ); sql.append( "SELECT AddGeometryColumn ('obstacles_r','wkb_geometry',-1,'POLYGON',2);" ); sql.append( "SELECT AddGeometryColumn ('obstacles_l','wkb_geometry',-1,'LINESTRING',2);" ); sql.append( "ALTER TABLE obstacles_r ADD COLUMN source_table char(11);" ); sql.append( "ALTER TABLE obstacles_l ADD COLUMN source_table char(11);" ); res = PQexec(conn, sql.toAscii() ); PQclear(res); // INSERT POLYGON LAYERS sql.clear(); // DIRECT VERSION, WITHOUT ADDING THE OFFSET for ( int i = 0; i < polygon_layers.size(); i++ ) { sql.append( "INSERT INTO obstacles_r( wkb_geometry, source_table) SELECT wkb_geometry, '"); sql.append( polygon_layers[i] ); sql.append( "' AS source_table FROM " ); sql.append( polygon_layers[i] ); sql.append( ";" ); if (debug) qDebug() << QString("UwShort: Adding obstacles of %1").arg( polygon_layers[i]); } // WARNING: very long string: res = PQexec(conn, sql.toAscii() ); PQclear(res); qDebug() << "for in 1"; // INSERT POINT LAYERS WITH OFFSET for ( int i = 0; i < point_layers.size(); i++ ) { bool signsound = ( point_layers[i] == "signsound_p" ); sql = "SELECT X(wkb_geometry),Y(wkb_geometry)"; if ( signsound) sql.append( ",depth"); sql.append( " FROM "); sql.append( point_layers[i] ); if ( signsound) sql.append( QString(" WHERE depth < %1 ").arg( QString::number( SIGNSOUND_THRESHOLD))); sql.append( ";"); res = PQexec(conn, sql.toAscii() ); if (debug) qDebug() << QString("UwShort: Adding obstacles of %1 (%2/%3): %4 obstacles").arg( point_layers[i], QString::number(i+1), QString::number(point_layers.size()), QString::number(PQntuples(res))); sql.clear(); for ( int j = 0; j < PQntuples(res); j++ ) { QPointF point( QString( PQgetvalue( res, j, 0)).toDouble(), QString( PQgetvalue( res, j, 1)).toDouble()); //forms a qpoint double precision sql.append( "INSERT INTO obstacles_r ( wkb_geometry, source_table) VALUES ( "); if ( point_layers[i] == "rock_p") sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET * POINT_OFFSET_FACTOR_ROCK )); else if ( point_layers[i] == "wreck_p" ) sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET * POINT_OFFSET_FACTOR_ROCK )); else if ( signsound) // for signsound POINT_OFFSET = POINT_OFFSET / ( depth of signsound / factor ) // the bigger the signsound is, the bigger the point offset gets sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET / ( QString( PQgetvalue( res, j, 2)).toDouble() / POINT_OFFSET_FACTOR_SIGNSOUND ) )); else sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET)); sql.append( ", '"); sql.append( point_layers[i]); sql.append( "'); "); } PQclear(res); res = PQexec( conn, sql.toAscii()); PQclear(res); //INSERT LINE LAYERS sql.clear(); for ( int i = 0; i < line_layers.size(); i++ ) { sql.append( "INSERT INTO obstacles_l( wkb_geometry, source_table) SELECT wkb_geometry, '"); sql.append( line_layers[i]); sql.append( "' AS source_table FROM " ); sql.append( line_layers[i] ); if ( line_layers[i] == "depthcont_l" ) { sql.append( " WHERE valdco<=" ); sql.append( QString::number( NOT_ALLOWED_DEPTH)); } sql.append( ";"); if (debug) { // WARNING: very long string: qDebug() << QString("UwShort: Adding obstacles of ").append( line_layers[i]); } res = PQexec(conn, sql.toAscii() ); PQclear(res); } // for loop for testing // for (int s=0; s<pointObstacles.size();s++){ // qDebug() << " index: " << s << "point x" << pointObstacles.at(s).x() << "y" << pointObstacles.at(s).y(); // } // tables are done this->obstaclesTablesCreated = true; qDebug("createObstaclesTables() returns = true"); return true; } } } }else { // tables are not done this->obstaclesTablesCreated = false; return false; } }
int main() { GDALAllRegister(); //register all the format drivers cout << "GDAL All Registed!" << endl; GDALDataset *poDS; //Data source poDS = (GDALDataset*) GDALOpenEx("./beijing/road/Nbeijing_point.shp", GDAL_OF_VECTOR, NULL, NULL, NULL); if(poDS == NULL) { cout << "Open shp file failed!" << endl; exit(1); } cout << "Data source open success!" << endl; int layerNum = poDS->GetLayerCount(); //a dataset may have many layers cout << "Layer number:" << layerNum << endl; OGRLayer *poLayer; poLayer = poDS->GetLayerByName("Nbeijing_point"); //feature is a geometry and a set of attributes OGRFeature *poFeature; poLayer->ResetReading(); //Start at the beginning of the layer cout << "Feature number:" << poLayer->GetFeatureCount() << endl; stringstream ss; map<string, pair<double, double> > mip; map<string, pair<double, double> >::iterator imip; ofstream ofile("beijingNode"); string id; int crossFlag; string stmp, stmp2; vector<string> vs; vector<string>::iterator ivs; while((poFeature = poLayer->GetNextFeature()) != NULL) { //Defn contains the definition of all the fields OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn(); // for(iField = 0; iField < poFDefn->GetFieldCount(); iField++) // { // OGRFieldDefn * poFieldDefn = poFDefn->GetFieldDefn(iField); id = poFeature->GetFieldAsString(1); ofile << id; crossFlag = poFeature->GetFieldAsInteger(4); if(crossFlag == 0) { ofile << "\t" << crossFlag << "\t" << 0 << "\t" << 0 << "\t" << 0; } else if(crossFlag == 1) { ofile << "\t" << crossFlag << "\t" << 0 << "\t" << poFeature->GetFieldAsInteger(7) << "\t" << 0; } else if(crossFlag == 2) { stmp = poFeature->GetFieldAsString(6); vs = split(stmp, "|"); ofile << "\t" << crossFlag << "\t" << vs.size(); for(ivs = vs.begin(); ivs != vs.end(); ivs++) ofile << "\t" << *ivs; vs.clear(); ofile << "\t" << poFeature->GetFieldAsInteger(7) << "\t" << 0; } else if(crossFlag == 3) { stmp = poFeature->GetFieldAsString(6); vs = split(stmp, "|"); ofile << "\t" << crossFlag << "\t" << vs.size(); for(ivs = vs.begin(); ivs != vs.end(); ivs++) ofile << "\t" << *ivs; vs.clear(); ofile << "\t" << poFeature->GetFieldAsInteger(7); stmp = poFeature->GetFieldAsString(8); stmp2 = poFeature->GetFieldAsString(9); if(stmp2 != "") stmp += "|" + stmp2; vs = split(stmp, "|"); ofile << "\t" << vs.size(); for(ivs = vs.begin(); ivs != vs.end(); ivs++) ofile << "\t" << *ivs; vs.clear(); } ofile << "\t" << poFeature->GetFieldAsString(11); stmp = poFeature->GetFieldAsString(12); vs = split(stmp, "|"); ofile << "\t" << vs.size(); for(ivs = vs.begin(); ivs != vs.end(); ivs++) ofile << "\t" << *ivs; vs.clear(); /* if(poFieldDefn->GetType() == OFTInteger) cout << poFeature->GetFieldAsInteger(iField) << ", "; else if(poFieldDefn->GetType() == OFTInteger64) cout << poFeature->GetFieldAsInteger64(iField) << ", "; else if(poFieldDefn->GetType() == OFTReal) cout << setprecision(15) << poFeature->GetFieldAsDouble(iField) << ", "; else if(poFieldDefn->GetType() == OFTString) cout << poFeature->GetFieldAsString(iField) << ", "; else cout << poFeature->GetFieldAsString(iField) << ", ";*/ // } OGRGeometry *poGeometry; poGeometry = poFeature->GetGeometryRef(); // cout << "Geometry Type:" << poGeometry->getGeometryType() << endl; if(poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPoint) { OGRMultiPoint *poMultiPoint = (OGRMultiPoint*)poGeometry; // cout << "Number in the MultiPoint:" << poMultiPoint->getNumGeometries() << endl; OGRGeometry *pG; pG = poMultiPoint->getGeometryRef(0); OGRPoint *pP = (OGRPoint*)pG; ofile << "\t" << pP->getY() << "\t" << pP->getX(); // pP->flattenTo2D(); // cout << setprecision(15) << pP->getY() << ", " << pP->getX() << endl; // mip[id] = make_pair(pP->getY(), pP->getX()); } else cout << "No Point Geometry" << endl; ofile << endl; OGRFeature::DestroyFeature(poFeature); } /* cout << "Writing nodes" << endl; for(imip = mip.begin(); imip != mip.end(); imip++) ofile << setprecision(15) << (*imip).first << "\t" << (*imip).second.first << "\t" << (*imip).second.second << endl;*/ GDALClose(poFeature); ofile.close(); return 0; }
int main (int argc, const char * argv[]) { time_t startTime = time(NULL); if (argc < 2 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { usage(); return(0); } OGRGeometry *geometry; for (int argNum = 1; argNum < argc; ++argNum) { //-- whether to compute the robustness or not if (strcmp(argv[argNum], "--robustness") == 0) { computeRobustness = true; } //-- whether to use the point set topology paradigm or not //-- if not, odd-even paradigm is used by default else if (strcmp(argv[argNum], "--setdiff") == 0) { pointSet = true; } //-- mininum area to keep in output else if (strcmp(argv[argNum], "--minarea") == 0) { minArea = atof(argv[argNum+1]); ++argNum; } //-- ISR snapping tolerance else if (strcmp(argv[argNum], "--isr") == 0) { isrTolerance = atof(argv[argNum+1]); ++argNum; // TODO : scale dataset if tolerance < 1.0 because of CGAL bug } //-- output a shapefile (out.shp) instead of a WKT else if (strcmp(argv[argNum], "--shpOut") == 0) { shpOut = true; } //-- time the results else if (strcmp(argv[argNum], "--time") == 0) { timeResults = true; } //-- reading from WKT passed directly else if (strcmp(argv[argNum], "--wkt") == 0) { unsigned int bufferSize = 100000000; char *inputWKT = (char *)malloc(bufferSize*sizeof(char)); strcpy(inputWKT, argv[argNum+1]); ++argNum; OGRErr err = OGRGeometryFactory::createFromWkt(&inputWKT, NULL, &geometry); if (err != OGRERR_NONE) { switch (err) { case OGRERR_UNSUPPORTED_GEOMETRY_TYPE: std::cerr << "Error: geometry must be Polygon or MultiPolygon" << std::endl; break; case OGRERR_NOT_ENOUGH_DATA: case OGRERR_CORRUPT_DATA: std::cerr << "Error: corrupted input" << std::endl; break; default: std::cerr << "Error: corrupted input" << std::endl; break; } return 1; } if (geometry->IsEmpty() == 1) { std::cerr << "Error: empty geometry" << std::endl; return 1; } if ( (geometry->getGeometryType() != wkbPolygon) && (geometry->getGeometryType() != wkbMultiPolygon) ) { std::cerr << "Error: geometry must be Polygon or MultiPolygon" << std::endl; return 1; } } //-- reading from WKT stored in first line of a text file else if (strcmp(argv[argNum], "-f") == 0) { unsigned int bufferSize = 100000000; char *inputWKT = (char *)malloc(bufferSize*sizeof(char)); if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') { std::ifstream infile(argv[argNum+1], std::ifstream::in); infile.getline(inputWKT, bufferSize); ++argNum; } else { std::cerr << "Error: Missing input file name." << std::endl; return 1; } OGRGeometryFactory::createFromWkt(&inputWKT, NULL, &geometry); if (geometry == NULL) { std::cout << "Error: WKT is not valid" << std::endl; return 1; } } //-- reading from a ogr dataset (most supported: shp, geojson, gml, etc) else if (strcmp(argv[argNum], "--ogr") == 0) { OGRRegisterAll(); OGRDataSource *dataSource = OGRSFDriverRegistrar::Open(argv[argNum+1], false); ++argNum; if (dataSource == NULL) { std::cerr << "Error: Could not open file." << std::endl; return false; } OGRLayer *dataLayer = dataSource->GetLayer(0); //-- get first layer dataLayer->ResetReading(); //-- Reads all features in this layer OGRFeature *feature; //-- get first feature if (dataLayer->GetFeatureCount(true) > 1) std::cout << "Reading only the first feature in the shapefile." << std::endl; feature = dataLayer->GetNextFeature(); if (feature->GetGeometryRef()->getGeometryType() == wkbPolygon) { geometry = static_cast<OGRPolygon *>(feature->GetGeometryRef());feature->GetGeometryRef(); } else { std::cout << "First feature ain't a POLYGON." << std::endl; return(0); } } else { usage(); return(0); } } if (!timeResults) startTime = 0; PolygonRepair prepair; //-- compute robustness if (computeRobustness == true) std::cout << "Robustness of input polygon: " << sqrt(prepair.computeRobustness(geometry)) <<std::endl; OGRMultiPolygon *outPolygons; if (pointSet) { outPolygons = prepair.repairPointSet(geometry, startTime); } else { outPolygons = prepair.repairOddEven(geometry, startTime); } if (minArea > 0) { prepair.removeSmallPolygons(outPolygons, minArea); } //-- output well known text if (shpOut) { prepair.saveToShp(outPolygons, "out.shp"); } else { char *outputWKT; outPolygons->exportToWkt(&outputWKT); std::cout << outputWKT << std::endl; } //-- compute robustness if (computeRobustness == true) std::cout << "Robustness of output polygon: " << sqrt(prepair.computeRobustness()) <<std::endl; //-- time results if (timeResults) { time_t totalTime = time(NULL)-startTime; std::cout << "Done! Process finished in " << totalTime/60 << " minutes " << totalTime%60 << " seconds." << std::endl; } return 0; }
void Dust::MakeGrid(WindNinjaInputs &input, AsciiGrid<double> &grid) { /*------------------------------------------*/ /* Open grid as a GDAL dataset */ /*------------------------------------------*/ int nXSize = grid.get_nCols(); int nYSize = grid.get_nRows(); GDALDriverH hDriver = GDALGetDriverByName( "MEM" ); GDALDatasetH hMemDS = GDALCreate(hDriver, "", nXSize, nYSize, 1, GDT_Float64, NULL); double *padfScanline; padfScanline = new double[nXSize]; double adfGeoTransform[6]; adfGeoTransform[0] = grid.get_xllCorner(); adfGeoTransform[1] = grid.get_cellSize(); adfGeoTransform[2] = 0; adfGeoTransform[3] = grid.get_yllCorner()+(grid.get_nRows()*grid.get_cellSize()); adfGeoTransform[4] = 0; adfGeoTransform[5] = -grid.get_cellSize(); char* pszDstWKT = (char*)grid.prjString.c_str(); GDALSetProjection(hMemDS, pszDstWKT); GDALSetGeoTransform(hMemDS, adfGeoTransform); GDALRasterBandH hBand = GDALGetRasterBand( hMemDS, 1 ); GDALSetRasterNoDataValue(hBand, -9999.0); for(int i=nYSize-1; i>=0; i--) { for(int j=0; j<nXSize; j++) { padfScanline[j] = grid.get_cellValue(nYSize-1-i, j); } GDALRasterIO(hBand, GF_Write, 0, i, nXSize, 1, padfScanline, nXSize, 1, GDT_Float64, 0, 0); } /*------------------------------------------*/ /* Get the geometry info */ /*------------------------------------------*/ OGRDataSourceH hOGRDS = 0; hOGRDS = OGROpen(input.dustFilename.c_str(), FALSE, 0); if(hOGRDS == NULL) { throw std::runtime_error("Could not open the fire perimeter file '" + input.dustFilename + "' for reading."); } OGRLayer *poLayer; OGRFeature *poFeature; OGRGeometry *poGeo; poLayer = (OGRLayer*)OGR_DS_GetLayer(hOGRDS, 0); poLayer->ResetReading(); poFeature = poLayer->GetNextFeature(); poGeo = poFeature->GetGeometryRef(); OGRGeometryH hPolygon = (OGRGeometryH) poGeo; /* -------------------------------------------------------------------- */ /* Check for same CRS in fire perimeter and DEM files */ /* -------------------------------------------------------------------- */ char *pszSrcWKT; OGRSpatialReference *poSrcSRS, oDstSRS; poSrcSRS = poLayer->GetSpatialRef(); //shapefile CRS poSrcSRS->exportToWkt( &pszSrcWKT ); //printf("CRS of DEM is:\n %s\n", pszDstWKT); //printf("WKT CRS of .shp is:\n %s\n", pszSrcWKT); oDstSRS.importFromWkt( &pszDstWKT ); char *pszDstProj4, *pszSrcProj4; oDstSRS.exportToProj4( &pszDstProj4 ); poSrcSRS->exportToProj4( &pszSrcProj4 ); //printf("proj4 of .shp is:\n %s\n", pszSrcProj4); //printf("proj4 of dem is:\n %s\n", pszDstProj4); /* -------------------------------------------------------------------- */ /* If the CRSs are not equal, convert shapefile CRS to DEM CRS */ /* -------------------------------------------------------------------- */ GDALTransformerFunc pfnTransformer = NULL; if( !EQUAL( pszSrcProj4, pszDstProj4 ) ){ //tranform shp CRS to DEM CRS poGeo->transformTo(&oDstSRS); } /* -------------------------------------------------------------------- */ /* Rasterize the shapefile */ /* -------------------------------------------------------------------- */ int nTargetBand = 1; double BurnValue = 1.0; CPLErr eErr; eErr = GDALRasterizeGeometries(hMemDS, 1, &nTargetBand, 1, &hPolygon, pfnTransformer, NULL, &BurnValue, NULL, NULL, NULL); if(eErr != CE_None) { throw std::runtime_error("Error in GDALRasterizeGeometies in Dust:MakeGrid()."); } GDAL2AsciiGrid((GDALDataset*)hMemDS, 1, grid); /* -------------------------------------------------------------------- */ /* clean up */ /* -------------------------------------------------------------------- */ if( hMemDS != NULL ){ GDALClose( hMemDS ); hMemDS = NULL; } OGR_DS_Destroy(hOGRDS); }
CPLErr GDALRasterizeLayersBuf( void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, int nLineSpace, int nLayerCount, OGRLayerH *pahLayers, const char *pszDstProjection, double *padfDstGeoTransform, GDALTransformerFunc pfnTransformer, void *pTransformArg, double dfBurnValue, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressArg ) { /* -------------------------------------------------------------------- */ /* If pixel and line spaceing are defaulted assign reasonable */ /* value assuming a packed buffer. */ /* -------------------------------------------------------------------- */ if( nPixelSpace == 0 ) nPixelSpace = GDALGetDataTypeSize( eBufType ) / 8; if( nLineSpace == 0 ) nLineSpace = nPixelSpace * nBufXSize; if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; /* -------------------------------------------------------------------- */ /* Do some rudimentary arg checking. */ /* -------------------------------------------------------------------- */ if( nLayerCount == 0 ) return CE_None; int bAllTouched = CSLFetchBoolean( papszOptions, "ALL_TOUCHED", FALSE ); const char *pszOpt = CSLFetchNameValue( papszOptions, "BURN_VALUE_FROM" ); GDALBurnValueSrc eBurnValueSource = GBV_UserBurnValue; if( pszOpt ) { if( EQUAL(pszOpt,"Z")) eBurnValueSource = GBV_Z; /*else if( EQUAL(pszOpt,"M")) eBurnValueSource = GBV_M;*/ } /* ==================================================================== */ /* Read thes pecified layers transfoming and rasterizing */ /* geometries. */ /* ==================================================================== */ CPLErr eErr = CE_None; int iLayer; const char *pszBurnAttribute = CSLFetchNameValue( papszOptions, "ATTRIBUTE" ); pfnProgress( 0.0, NULL, pProgressArg ); for( iLayer = 0; iLayer < nLayerCount; iLayer++ ) { int iBurnField = -1; OGRLayer *poLayer = (OGRLayer *) pahLayers[iLayer]; if ( !poLayer ) { CPLError( CE_Warning, CPLE_AppDefined, "Layer element number %d is NULL, skipping.\n", iLayer ); continue; } /* -------------------------------------------------------------------- */ /* If the layer does not contain any features just skip it. */ /* Do not force the feature count, so if driver doesn't know */ /* exact number of features, go down the normal way. */ /* -------------------------------------------------------------------- */ if ( poLayer->GetFeatureCount(FALSE) == 0 ) continue; if ( pszBurnAttribute ) { iBurnField = poLayer->GetLayerDefn()->GetFieldIndex( pszBurnAttribute ); if ( iBurnField == -1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.\n", pszBurnAttribute, poLayer->GetLayerDefn()->GetName() ); continue; } } /* -------------------------------------------------------------------- */ /* If we have no transformer, create the one from input file */ /* projection. Note that each layer can be georefernced */ /* separately. */ /* -------------------------------------------------------------------- */ int bNeedToFreeTransformer = FALSE; if( pfnTransformer == NULL ) { char *pszProjection = NULL; bNeedToFreeTransformer = TRUE; OGRSpatialReference *poSRS = poLayer->GetSpatialRef(); if ( !poSRS ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to fetch spatial reference on layer %s " "to build transformer, assuming matching coordinate systems.\n", poLayer->GetLayerDefn()->GetName() ); } else poSRS->exportToWkt( &pszProjection ); pTransformArg = GDALCreateGenImgProjTransformer3( pszProjection, NULL, pszDstProjection, padfDstGeoTransform ); pfnTransformer = GDALGenImgProjTransform; CPLFree( pszProjection ); } OGRFeature *poFeat; poLayer->ResetReading(); while( (poFeat = poLayer->GetNextFeature()) != NULL ) { OGRGeometry *poGeom = poFeat->GetGeometryRef(); if ( pszBurnAttribute ) dfBurnValue = poFeat->GetFieldAsDouble( iBurnField ); gv_rasterize_one_shape( (unsigned char *) pData, 0, nBufXSize, nBufYSize, 1, eBufType, bAllTouched, poGeom, &dfBurnValue, eBurnValueSource, pfnTransformer, pTransformArg ); delete poFeat; } poLayer->ResetReading(); if( !pfnProgress(1, "", pProgressArg) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } if ( bNeedToFreeTransformer ) { GDALDestroyTransformer( pTransformArg ); pTransformArg = NULL; pfnTransformer = NULL; } } return eErr; }
//coordinate;//(double x, double y); //contains the baseline/collection of baselines for the shoreline void ShoreLine::getShapePoints(string filename){ RegisterOGRShape(); // OGR Drivers for reading shapefiles only OGRDataSource *poDS; cout<<"Reading in file shapefile"<<filename<<endl; poDS = OGRSFDriverRegistrar::Open( filename.c_str(), FALSE ); if ( poDS == NULL ){ printf("Open fail"); exit(1); } OGRLayer *poLayer; poLayer = poDS->GetLayer(0); OGRGeometry *poGeometry; //poGeometry = poLayer-> OGRFeature *poFeature; poFeature= poLayer->GetNextFeature(); poLayer->ResetReading(); if (poGeometry==NULL){ return; } switch(wkbFlatten(poGeometry->getGeometryType())) { case wkbPoint: { ((OGRPoint*)poGeometry);///////////////////////// break; } case wkbLineString: case wkbLinearRing: { OGRLineString* poLS = (OGRLineString*) poGeometry; for(int i=0;i<poLS->getNumPoints();i++) shoreLinePoints.push_back(coordinate(poLS->getX(i),poLS->getY(i))); break; } case wkbPolygon: { int i; OGRPolygon* poPoly = (OGRPolygon*) poGeometry; //SetZ(poPoly->getExteriorRing(), dfZ); for(i=0;i<poPoly->getNumInteriorRings();i++) // SetZ(poPoly->getInteriorRing(i), dfZ); break; } case wkbMultiPoint: case wkbMultiLineString: case wkbMultiPolygon: case wkbGeometryCollection: { int i; OGRGeometryCollection* poGeometryColl = (OGRGeometryCollection*) poGeometry; for(i=0;i<poGeometryColl->getNumGeometries();i++) // SetZ(poGeometryColl->getGeometryRef(i), dfZ); break; } default: printf( "no readable geometry\n" ); break; } OGRFeature::DestroyFeature( poFeature ); OGRDataSource::DestroyDataSource( poDS ); return; }
int Raster::VectortoRaster(const char * sVectorSourcePath, const char * sRasterOutputPath, const char * psFieldName, RasterMeta * p_rastermeta ){ OGRRegisterAll(); OGRDataSource * pDSVectorInput; pDSVectorInput = OGRSFDriverRegistrar::Open( sVectorSourcePath, FALSE ); if (pDSVectorInput == NULL) return INPUT_FILE_ERROR; OGRLayer * poLayer = pDSVectorInput->GetLayer(0); // The type of the field. OGRFeature * feat1 = poLayer->GetFeature(0); int fieldindex = feat1->GetFieldIndex(psFieldName); OGRFieldType fieldType = feat1->GetFieldDefnRef(fieldindex)->GetType(); OGRFeature::DestroyFeature( feat1 ); // The data type we're going to use for the file GDALDataType OutputDataType = GDT_Byte; // Handle field types according to their type: switch (fieldType) { case OFTString: CSVWriteVectorValues(poLayer, psFieldName, sRasterOutputPath); break; case OFTInteger: break; case OFTReal: OutputDataType = GDT_Float64; default: throw RasterManagerException(VECTOR_FIELD_NOT_VALID, "Type of field not recognized."); break; } // Get our projection and set the rastermeta accordingly. // ------------------------------------------------------- char *pszWKT = NULL; OGRSpatialReference* poSRS = poLayer->GetSpatialRef(); poSRS->exportToWkt(&pszWKT); p_rastermeta->SetProjectionRef(pszWKT); CPLFree(pszWKT); OSRDestroySpatialReference(poSRS); // Create the output dataset for writing GDALDataset * pDSOutput = CreateOutputDS(sRasterOutputPath, p_rastermeta); // Create a list of burn-in values // ------------------------------------------------------- std::vector<OGRGeometryH> ogrBurnGeometries; std::vector<double> dBurnValues; poLayer->ResetReading(); OGRFeature * ogrFeat = poLayer->GetNextFeature(); // <------- DRMEM!!! UNADDRESSABLE ACCESS of freed memory while( ogrFeat != NULL ){ OGRGeometry * ogrGeom = ogrFeat->GetGeometryRef(); // No geometry found. Move along. if( ogrGeom == NULL ) { OGRFeature::DestroyFeature( ogrFeat ); continue; } OGRGeometry * geoClone = ogrGeom->clone(); // <------- DRMEM!!! UNADDRESSABLE ACCESS of freed memory AND LEAK 20 direct bytes // Push a clone of this geometry onto the list of shapes to burn ogrBurnGeometries.push_back( (OGRGeometryH) geoClone ); if (fieldType == OFTString){ // If it's a string type we burn the FID. The value is then placed in a CSV file dBurnValues.push_back( ogrFeat->GetFID() ); } else { // If it's a float type or a byte type we write it directly. dBurnValues.push_back( ogrFeat->GetFieldAsDouble(psFieldName) ); } // GetNextFeature() creates a clone so we must delete it. OGRFeature::DestroyFeature( ogrFeat ); // <------- DRMEM!!! UNADDRESSABLE ACCESS beyond heap bounds: ogrFeat = poLayer->GetNextFeature(); // <------- DRMEM!!! UNADDRESSABLE ACCESS of freed memory } // Do the Actual Burning of Geometries. // ------------------------------------------------------- int band = 1; char **papszRasterizeOptions = NULL; papszRasterizeOptions = CSLSetNameValue( papszRasterizeOptions, "ALL_TOUCHED", "TRUE" ); CPLErr err = GDALRasterizeGeometries( pDSOutput, 1, &band, ogrBurnGeometries.size(), &(ogrBurnGeometries[0]), NULL, NULL, &(dBurnValues[0]), NULL, NULL, NULL ); if (err) { } ogrBurnGeometries.clear(); dBurnValues.clear(); // Done. Calculate stats and close file CalculateStats(pDSOutput->GetRasterBand(1)); CSLDestroy(papszRasterizeOptions); GDALClose(pDSOutput); pDSVectorInput->Release(); // <------- DRMEM!!! UNADDRESSABLE ACCESS beyond heap bounds: //This is where the implementation actually goes return PROCESS_OK; }
void CDlg_GIS_Setting_Config::OnBnClickedButtonLoadZoneFile() { #ifndef _WIN64 static char BASED_CODE szFilter[] = "GIS Shape File (*.shp)|*.shp||"; CFileDialog dlg(TRUE, 0, 0, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter); if(dlg.DoModal() == IDOK) { m_ZoneShapeFileString = dlg.GetPathName(); UpdateData(false); } if(m_ZoneShapeFileString.GetLength () == 0 ) { return; } CEdit* pEdit1 = (CEdit*)GetDlgItem(IDC_STATIC_Z1); CEdit* pEdit2 = (CEdit*)GetDlgItem(IDC_STATIC_Z2); pEdit1->ShowWindow (1); pEdit2->ShowWindow (1); m_ZoneTAZ.ShowWindow (1); m_ZoneNodeID.ShowWindow (1); CWaitCursor wait; OGRRegisterAll(); OGRDataSource *poDS; bool bFindOverlappingNode = false; poDS = OGRSFDriverRegistrar::Open(m_ZoneShapeFileString, FALSE ); if( poDS == NULL ) { AfxMessageBox("Open file failed." ); return; } int point_index = 0; int poLayers = ((OGRDataSource*)poDS)->GetLayerCount() ; for (int i=0; i < poLayers; i++) { OGRLayer *poLayer; poLayer = ((OGRDataSource*)poDS)->GetLayer(i); if(poLayer == NULL) { message_str.Format("Open layer %d failed", i+1); AfxMessageBox(message_str); return; } OGRFeature *poFeature; int feature_count = 0; poLayer->ResetReading(); while( (poFeature = poLayer->GetNextFeature()) != NULL ) { OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn(); int iField; CString str = " "; m_ZoneTAZ.ResetContent (); m_ZoneNodeID.ResetContent (); m_ZoneTAZ.AddString (str); m_ZoneNodeID.AddString (str); for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ ) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField ); str = poFieldDefn->GetNameRef(); if(str.GetLength ()!=0) { m_ZoneTAZ.AddString (str); m_ZoneNodeID.AddString (str); } } break; } } #endif }
void CDlg_GIS_Setting_Config::OnBnClickedButtonLoadLinkFile() { #ifndef _WIN64 CString str; static char BASED_CODE szFilter[] = "GIS Shape File (*.shp)|*.shp||"; CFileDialog dlg(TRUE, 0, 0, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter); if(dlg.DoModal() == IDOK) { m_LinkShapeFileString = dlg.GetPathName(); UpdateData(false); } if(m_LinkShapeFileString.GetLength () == 0 ) { return; } m_pDoc->m_ProjectFile = m_LinkShapeFileString; CString directory = m_LinkShapeFileString.Left(m_pDoc->m_ProjectFile.ReverseFind('\\') + 1); m_pDoc->m_ProjectDirectory = directory; m_pDoc->m_ProjectTitle = m_pDoc->GetWorkspaceTitleName(m_LinkShapeFileString); m_pDoc->SetTitle(m_pDoc->m_ProjectTitle); m_pDoc->CopyDefaultFiles(); m_pDoc->ReadLinkTypeCSVFile(directory+"input_link_type.csv"); CWaitCursor wait; OGRRegisterAll(); OGRDataSource *poDS; bool bFindOverlappingNode = false; poDS = OGRSFDriverRegistrar::Open(m_LinkShapeFileString, FALSE ); if( poDS == NULL ) { AfxMessageBox("Open file failed." ); return; } int point_index = 0; int poLayers = ((OGRDataSource*)poDS)->GetLayerCount() ; for (int i=0; i < poLayers; i++) { OGRLayer *poLayer; poLayer = ((OGRDataSource*)poDS)->GetLayer(i); if(poLayer == NULL) { message_str.Format("Open layer %d failed", i+1); AfxMessageBox(message_str); return; } OGRFeature *poFeature; int feature_count = 0; // 0.03 miles // 0.02: shape length / miles double threashold = 0.02*0.001; poLayer->ResetReading(); while( (poFeature = poLayer->GetNextFeature()) != NULL ) { OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn(); int iField; CString str = " "; m_LinkFieldStringVector.push_back (str); m_LinkIDList.ResetContent (); m_LinkNameList.ResetContent (); m_TMCList.ResetContent (); m_SensorIDList.ResetContent (); m_LinkDirection.ResetContent (); m_LengthList.ResetContent (); m_FromNodeList.ResetContent (); m_ToNodeList.ResetContent (); m_LinkType.ResetContent (); m_ModeType.ResetContent (); m_NumberOfLanes.ResetContent (); m_SpeedLimit.ResetContent (); m_Capacity.ResetContent (); m_RNumberOfLanes.ResetContent (); m_RSpeedLimit.ResetContent (); m_RCapacity.ResetContent (); m_RTMC.ResetContent (); m_RSensorID.ResetContent (); m_LinkIDList.AddString(str); m_LinkNameList.AddString(str); m_TMCList.AddString(str); m_SensorIDList.AddString(str); m_LinkDirection.AddString(str); m_LengthList.AddString(str); m_FromNodeList.AddString(str); m_ToNodeList.AddString(str); m_LinkType.AddString(str); m_ModeType.AddString(str); m_NumberOfLanes.AddString(str); m_SpeedLimit.AddString(str); m_Capacity.AddString(str); m_RNumberOfLanes.AddString(str); m_RSpeedLimit.AddString(str); m_RCapacity.AddString(str); m_RTMC.AddString(str); m_RSensorID.AddString(str); for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ ) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField ); str = poFieldDefn->GetNameRef(); if(str.GetLength ()!=0) { m_LinkFieldStringVector.push_back(str); m_LinkIDList.AddString(str); m_LinkNameList.AddString(str); m_TMCList.AddString(str); m_SensorIDList.AddString(str); m_LinkDirection.AddString(str); m_LengthList.AddString(str); m_FromNodeList.AddString(str); m_ToNodeList.AddString(str); m_LinkType.AddString(str); m_ModeType.AddString(str); m_RNumberOfLanes.AddString(str); m_RSpeedLimit.AddString(str); m_RCapacity.AddString(str); m_RTMC.AddString(str); m_RSensorID.AddString(str); m_NumberOfLanes.AddString(str); m_SpeedLimit.AddString(str); m_Capacity.AddString(str); m_RNumberOfLanes.AddString(str); m_RSpeedLimit.AddString(str); m_RCapacity.AddString(str); m_RTMC.AddString(str); m_RSensorID.AddString(str); } } break; } CEdit* pEdit1 = (CEdit*)GetDlgItem(IDC_STATIC1); CEdit* pEdit2 = (CEdit*)GetDlgItem(IDC_STATIC2); CEdit* pEdit5 = (CEdit*)GetDlgItem(IDC_STATIC5); CEdit* pEdit7 = (CEdit*)GetDlgItem(IDC_STATIC7); CEdit* pEdit8 = (CEdit*)GetDlgItem(IDC_STATIC8); CEdit* pEdit9 = (CEdit*)GetDlgItem(IDC_STATIC9); CEdit* pEdit10 = (CEdit*)GetDlgItem(IDC_STATIC10); CEdit* pEdit12 = (CEdit*)GetDlgItem(IDC_STATIC12); CEdit* pEdit13 = (CEdit*)GetDlgItem(IDC_STATIC13); pEdit1->ShowWindow (1); pEdit2->ShowWindow (1); pEdit5->ShowWindow (1); pEdit7->ShowWindow (1); pEdit8->ShowWindow (1); pEdit12->ShowWindow (1); pEdit13->ShowWindow (1); m_LinkIDList.ShowWindow (1); m_LinkNameList.ShowWindow (1); m_LengthList.ShowWindow (1); m_LinkType.ShowWindow(1); m_ModeType.ShowWindow(1); m_LinkDirectionOption.ShowWindow(1); m_UnitLengthOption.ShowWindow(1); m_LinkIDList.SetCurSel(0); m_LinkNameList.SetCurSel(0); m_TMCList.SetCurSel(0); m_SensorIDList.SetCurSel(0); m_LinkDirection.SetCurSel(0); m_LengthList.SetCurSel(0); m_FromNodeList.SetCurSel(0); m_ToNodeList.SetCurSel(0); m_LinkType.SetCurSel(0); m_ModeType.SetCurSel(0); CEdit* pEdit100 = (CEdit*)GetDlgItem(IDC_CHECK_AUTO_GENERATE_FROM_TO_NODES); CEdit* pEdit101 = (CEdit*)GetDlgItem(IDC_CHECK_AUTO_GENERATE_FROM_TO_NODES3); CEdit* pEdit103 = (CEdit*)GetDlgItem(IDC_CHECK_Centroid_Connector); CEdit* pEdit104 = (CEdit*)GetDlgItem(IDC_CHECK_WITH_SENSOR_DATA); CEdit* pEdit105 = (CEdit*)GetDlgItem(IDC_ReservedFields); pEdit100->ShowWindow (1); pEdit101->ShowWindow (1); pEdit103->ShowWindow (1); pEdit104->ShowWindow (1); pEdit105->ShowWindow (1); } std::map<int, DTALinkType>:: const_iterator itr; #endif }
int main( int nArgc, char ** papszArgv ) { const char *pszWHERE = NULL; const char *pszDataSource = NULL; char **papszLayers = NULL; OGRGeometry *poSpatialFilter = NULL; int nRepeatCount = 1, bAllLayers = FALSE; const char *pszSQLStatement = NULL; const char *pszDialect = NULL; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(papszArgv[0])) exit(1); /* -------------------------------------------------------------------- */ /* Register format(s). */ /* -------------------------------------------------------------------- */ OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ nArgc = OGRGeneralCmdLineProcessor( nArgc, &papszArgv, 0 ); if( nArgc < 1 ) exit( -nArgc ); 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")); return 0; } else if( EQUAL(papszArgv[iArg],"-ro") ) bReadOnly = TRUE; else if( EQUAL(papszArgv[iArg],"-q") || EQUAL(papszArgv[iArg],"-quiet")) bVerbose = FALSE; else if( EQUAL(papszArgv[iArg],"-fid") && iArg < nArgc-1 ) nFetchFID = atoi(papszArgv[++iArg]); else if( EQUAL(papszArgv[iArg],"-spat") && papszArgv[iArg+1] != NULL && papszArgv[iArg+2] != NULL && papszArgv[iArg+3] != NULL && papszArgv[iArg+4] != NULL ) { OGRLinearRing oRing; oRing.addPoint( atof(papszArgv[iArg+1]), atof(papszArgv[iArg+2]) ); oRing.addPoint( atof(papszArgv[iArg+1]), atof(papszArgv[iArg+4]) ); oRing.addPoint( atof(papszArgv[iArg+3]), atof(papszArgv[iArg+4]) ); oRing.addPoint( atof(papszArgv[iArg+3]), atof(papszArgv[iArg+2]) ); oRing.addPoint( atof(papszArgv[iArg+1]), atof(papszArgv[iArg+2]) ); poSpatialFilter = new OGRPolygon(); ((OGRPolygon *) poSpatialFilter)->addRing( &oRing ); iArg += 4; } else if( EQUAL(papszArgv[iArg],"-where") && papszArgv[iArg+1] != NULL ) { pszWHERE = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-sql") && papszArgv[iArg+1] != NULL ) { pszSQLStatement = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-dialect") && papszArgv[iArg+1] != NULL ) { pszDialect = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-rc") && papszArgv[iArg+1] != NULL ) { 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( EQUALN(papszArgv[iArg],"-fields=", strlen("-fields=")) ) { char* pszTemp = (char*)CPLMalloc(32 + strlen(papszArgv[iArg])); sprintf(pszTemp, "DISPLAY_FIELDS=%s", papszArgv[iArg] + strlen("-fields=")); papszOptions = CSLAddString(papszOptions, pszTemp); CPLFree(pszTemp); } else if( EQUALN(papszArgv[iArg],"-geom=", strlen("-geom=")) ) { char* pszTemp = (char*)CPLMalloc(32 + strlen(papszArgv[iArg])); sprintf(pszTemp, "DISPLAY_GEOMETRY=%s", papszArgv[iArg] + strlen("-geom=")); papszOptions = CSLAddString(papszOptions, pszTemp); CPLFree(pszTemp); } else if( papszArgv[iArg][0] == '-' ) { Usage(); } else if( pszDataSource == NULL ) pszDataSource = papszArgv[iArg]; else { papszLayers = CSLAddString( papszLayers, papszArgv[iArg] ); bAllLayers = FALSE; } } if( pszDataSource == NULL ) Usage(); /* -------------------------------------------------------------------- */ /* Open data source. */ /* -------------------------------------------------------------------- */ OGRDataSource *poDS = NULL; OGRSFDriver *poDriver = NULL; poDS = OGRSFDriverRegistrar::Open( pszDataSource, !bReadOnly, &poDriver ); if( poDS == NULL && !bReadOnly ) { poDS = OGRSFDriverRegistrar::Open( pszDataSource, FALSE, &poDriver ); if( poDS != NULL && bVerbose ) { printf( "Had to open data source read-only.\n" ); bReadOnly = TRUE; } } /* -------------------------------------------------------------------- */ /* Report failure */ /* -------------------------------------------------------------------- */ if( poDS == NULL ) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); printf( "FAILURE:\n" "Unable to open datasource `%s' with the following drivers.\n", pszDataSource ); for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { printf( " -> %s\n", poR->GetDriver(iDriver)->GetName() ); } exit( 1 ); } CPLAssert( poDriver != NULL); /* -------------------------------------------------------------------- */ /* Some information messages. */ /* -------------------------------------------------------------------- */ if( bVerbose ) printf( "INFO: Open of `%s'\n" " using driver `%s' successful.\n", pszDataSource, poDriver->GetName() ); if( bVerbose && !EQUAL(pszDataSource,poDS->GetName()) ) { printf( "INFO: Internal data source name `%s'\n" " different from user name `%s'.\n", poDS->GetName(), pszDataSource ); } /* -------------------------------------------------------------------- */ /* Special case for -sql clause. No source layers required. */ /* -------------------------------------------------------------------- */ if( pszSQLStatement != NULL ) { OGRLayer *poResultSet = NULL; nRepeatCount = 0; // skip layer reporting. if( CSLCount(papszLayers) > 0 ) printf( "layer names ignored in combination with -sql.\n" ); poResultSet = poDS->ExecuteSQL( pszSQLStatement, poSpatialFilter, pszDialect ); if( poResultSet != NULL ) { if( pszWHERE != NULL ) poResultSet->SetAttributeFilter( pszWHERE ); ReportOnLayer( poResultSet, NULL, NULL ); poDS->ReleaseResultSet( poResultSet ); } } CPLDebug( "OGR", "GetLayerCount() = %d\n", poDS->GetLayerCount() ); for( int iRepeat = 0; iRepeat < nRepeatCount; iRepeat++ ) { if ( CSLCount(papszLayers) == 0 ) { /* -------------------------------------------------------------------- */ /* Process each data source layer. */ /* -------------------------------------------------------------------- */ for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if( poLayer == NULL ) { printf( "FAILURE: Couldn't fetch advertised layer %d!\n", iLayer ); exit( 1 ); } if (!bAllLayers) { printf( "%d: %s", iLayer+1, poLayer->GetLayerDefn()->GetName() ); if( poLayer->GetLayerDefn()->GetGeomType() != wkbUnknown ) printf( " (%s)", OGRGeometryTypeToName( poLayer->GetLayerDefn()->GetGeomType() ) ); printf( "\n" ); } else { if( iRepeat != 0 ) poLayer->ResetReading(); ReportOnLayer( poLayer, pszWHERE, poSpatialFilter ); } } } else { /* -------------------------------------------------------------------- */ /* Process specified data source layers. */ /* -------------------------------------------------------------------- */ char** papszIter = papszLayers; for( ; *papszIter != NULL; papszIter++ ) { OGRLayer *poLayer = poDS->GetLayerByName(*papszIter); if( poLayer == NULL ) { printf( "FAILURE: Couldn't fetch requested layer %s!\n", *papszIter ); exit( 1 ); } if( iRepeat != 0 ) poLayer->ResetReading(); ReportOnLayer( poLayer, pszWHERE, poSpatialFilter ); } } } /* -------------------------------------------------------------------- */ /* Close down. */ /* -------------------------------------------------------------------- */ CSLDestroy( papszArgv ); CSLDestroy( papszLayers ); CSLDestroy( papszOptions ); OGRDataSource::DestroyDataSource( poDS ); if (poSpatialFilter) OGRGeometryFactory::destroyGeometry( poSpatialFilter ); OGRCleanupAll(); return 0; }
CPLErr GNMGenericNetwork::ConnectPointsByLines(char **papszLayerList, double dfTolerance, double dfCost, double dfInvCost, GNMDirection eDir) { if( CSLCount(papszLayerList) < 2 ) { CPLError( CE_Failure, CPLE_IllegalArg, "Minimum 2 layers needed to connect" ); return CE_Failure; } std::vector<OGRLayer*> paLineLayers; std::vector<OGRLayer*> paPointLayers; int eType; int iLayer; OGRLayer* poLayer; for(iLayer = 0; papszLayerList[iLayer] != NULL; ++iLayer) { poLayer = GetLayerByName(papszLayerList[iLayer]); if(NULL == poLayer) continue; eType = wkbFlatten(poLayer->GetGeomType()); if(eType == wkbLineString || eType == wkbMultiLineString) { paLineLayers.push_back(poLayer); } else if(eType == wkbPoint) { paPointLayers.push_back(poLayer); } } if (paLineLayers.empty() || paPointLayers.empty() ) { CPLError( CE_Failure, CPLE_IllegalArg, "Need at least one line (or " "multiline) layer and one point layer to connect" ); return CE_Failure; } // now walk through all lines and find nearest points for line start and end OGRFeature* poFeature; for(size_t i = 0; i < paLineLayers.size(); ++i) { poLayer = paLineLayers[i]; eType = wkbFlatten(poLayer->GetGeomType()); poLayer->ResetReading(); while((poFeature = poLayer->GetNextFeature()) != NULL) { const OGRGeometry* poGeom = poFeature->GetGeometryRef(); if(NULL != poGeom) { if(eType == wkbLineString) { const OGRLineString* poLineString = (const OGRLineString*) poGeom; ConnectPointsByLine(poFeature->GetFID(), poLineString, paPointLayers, dfTolerance, dfCost, dfInvCost, eDir); } else if( eType == wkbMultiLineString) { const OGRMultiLineString* poMultiLineString = (const OGRMultiLineString*) poGeom; ConnectPointsByMultiline(poFeature->GetFID(), poMultiLineString, paPointLayers, dfTolerance, dfCost, dfInvCost, eDir); } } OGRFeature::DestroyFeature(poFeature); } } return CE_None; }
void NIImporter_ArcView::load() { #ifdef HAVE_GDAL PROGRESS_BEGIN_MESSAGE("Loading data from '" + mySHPName + "'"); #if GDAL_VERSION_MAJOR < 2 OGRRegisterAll(); OGRDataSource* poDS = OGRSFDriverRegistrar::Open(mySHPName.c_str(), FALSE); #else GDALAllRegister(); GDALDataset* poDS = (GDALDataset*)GDALOpenEx(mySHPName.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL); #endif if (poDS == NULL) { WRITE_ERROR("Could not open shape description '" + mySHPName + "'."); return; } // begin file parsing OGRLayer* poLayer = poDS->GetLayer(0); poLayer->ResetReading(); // build coordinate transformation OGRSpatialReference* origTransf = poLayer->GetSpatialRef(); OGRSpatialReference destTransf; // use wgs84 as destination destTransf.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf); if (poCT == NULL) { if (myOptions.isSet("shapefile.guess-projection")) { OGRSpatialReference origTransf2; origTransf2.SetWellKnownGeogCS("WGS84"); poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf); } if (poCT == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } } OGRFeature* poFeature; poLayer->ResetReading(); while ((poFeature = poLayer->GetNextFeature()) != NULL) { // read in edge attributes std::string id, name, from_node, to_node; if (!getStringEntry(poFeature, "shapefile.street-id", "LINK_ID", true, id)) { WRITE_ERROR("Needed field '" + id + "' (from node id) is missing."); } if (id == "") { WRITE_ERROR("Could not obtain edge id."); return; } getStringEntry(poFeature, "shapefile.street-id", "ST_NAME", true, name); name = StringUtils::replace(name, "&", "&"); if (!getStringEntry(poFeature, "shapefile.from-id", "REF_IN_ID", true, from_node)) { WRITE_ERROR("Needed field '" + from_node + "' (from node id) is missing."); } if (!getStringEntry(poFeature, "shapefile.to-id", "NREF_IN_ID", true, to_node)) { WRITE_ERROR("Needed field '" + to_node + "' (to node id) is missing."); } if (from_node == "" || to_node == "") { from_node = toString(myRunningNodeID++); to_node = toString(myRunningNodeID++); } std::string type; if (myOptions.isSet("shapefile.type-id") && poFeature->GetFieldIndex(myOptions.getString("shapefile.type-id").c_str()) >= 0) { type = poFeature->GetFieldAsString(myOptions.getString("shapefile.type-id").c_str()); } else if (poFeature->GetFieldIndex("ST_TYP_AFT") >= 0) { type = poFeature->GetFieldAsString("ST_TYP_AFT"); } SUMOReal width = myTypeCont.getWidth(type); SUMOReal speed = getSpeed(*poFeature, id); int nolanes = getLaneNo(*poFeature, id, speed); int priority = getPriority(*poFeature, id); if (nolanes == 0 || speed == 0) { if (myOptions.getBool("shapefile.use-defaults-on-failure")) { nolanes = myTypeCont.getNumLanes(""); speed = myTypeCont.getSpeed(""); } else { OGRFeature::DestroyFeature(poFeature); WRITE_ERROR("The description seems to be invalid. Please recheck usage of types."); return; } } if (mySpeedInKMH) { speed = speed / (SUMOReal) 3.6; } // read in the geometry OGRGeometry* poGeometry = poFeature->GetGeometryRef(); OGRwkbGeometryType gtype = poGeometry->getGeometryType(); assert(gtype == wkbLineString); UNUSED_PARAMETER(gtype); // ony used for assertion OGRLineString* cgeom = (OGRLineString*) poGeometry; if (poCT != 0) { // try transform to wgs84 cgeom->transform(poCT); } PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!NBNetBuilder::transformCoordinate(pos)) { WRITE_WARNING("Unable to project coordinates for edge '" + id + "'."); } shape.push_back_noDoublePos(pos); } // build from-node NBNode* from = myNodeCont.retrieve(from_node); if (from == 0) { Position from_pos = shape[0]; from = myNodeCont.retrieve(from_pos); if (from == 0) { from = new NBNode(from_node, from_pos); if (!myNodeCont.insert(from)) { WRITE_ERROR("Node '" + from_node + "' could not be added"); delete from; continue; } } } // build to-node NBNode* to = myNodeCont.retrieve(to_node); if (to == 0) { Position to_pos = shape[-1]; to = myNodeCont.retrieve(to_pos); if (to == 0) { to = new NBNode(to_node, to_pos); if (!myNodeCont.insert(to)) { WRITE_ERROR("Node '" + to_node + "' could not be added"); delete to; continue; } } } if (from == to) { WRITE_WARNING("Edge '" + id + "' connects identical nodes, skipping."); continue; } // retrieve the information whether the street is bi-directional std::string dir; int index = poFeature->GetDefnRef()->GetFieldIndex("DIR_TRAVEL"); if (index >= 0 && poFeature->IsFieldSet(index)) { dir = poFeature->GetFieldAsString(index); } // add positive direction if wanted if (dir == "B" || dir == "F" || dir == "" || myOptions.getBool("shapefile.all-bidirectional")) { if (myEdgeCont.retrieve(id) == 0) { LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LANESPREAD_RIGHT : LANESPREAD_CENTER; NBEdge* edge = new NBEdge(id, from, to, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape, name, id, spread); myEdgeCont.insert(edge); checkSpread(edge); } } // add negative direction if wanted if (dir == "B" || dir == "T" || myOptions.getBool("shapefile.all-bidirectional")) { if (myEdgeCont.retrieve("-" + id) == 0) { LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LANESPREAD_RIGHT : LANESPREAD_CENTER; NBEdge* edge = new NBEdge("-" + id, to, from, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape.reverse(), name, id, spread); myEdgeCont.insert(edge); checkSpread(edge); } } // OGRFeature::DestroyFeature(poFeature); } #if GDAL_VERSION_MAJOR < 2 OGRDataSource::DestroyDataSource(poDS); #else GDALClose(poDS); #endif PROGRESS_DONE_MESSAGE(); #else WRITE_ERROR("SUMO was compiled without GDAL support."); #endif }
bool shape::load(string filename) { OGRRegisterAll(); // First open the shape file ds = OGRSFDriverRegistrar::Open( filename.c_str(), FALSE ); // Now to load in the points ..... points = vector<vector<glm::vec2>>(); // Grab the first layer OGRLayer* layer = ds->GetLayer(0); // Grab the spatial reference and create a coordinate transform function sr = layer->GetSpatialRef(); // Taking from http://www.compsci.wm.edu/SciClone/documentation/software/geo/gdal-1.9.0/html/ogr/ogr_apitut.html OGRFeature *poFeature; layer->ResetReading(); while( (poFeature = layer->GetNextFeature()) != NULL ) { OGRFeatureDefn *poFDefn = layer->GetLayerDefn(); int iField; OGRGeometry *poGeometry; poGeometry = poFeature->GetGeometryRef(); if( poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPoint ) { OGRPoint *poPoint = (OGRPoint *) poGeometry; //printf( "%.3f,%3.f\n", poPoint->getX(), poPoint->getY() ); } else if (poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbLineString) { //cout << "LINES!!!!" << endl; OGRLineString* ls= (OGRLineString*)poGeometry; points.push_back(vector<glm::vec2>()); for(int i = 0; i < ls->getNumPoints(); i++ ) { OGRPoint p; ls->getPoint(i,&p); // This function can transform a larget set of points..... double x = p.getX(); double y = p.getY(); points[points.size()-1].push_back(glm::vec2(x,y)); //poTransform->Transform (1, &x, &y); //cout << p.getX() << " " << p.getY() << "Transformed!: " << x << " " << y << endl; } } else if (poGeometry != NULL && wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon) { OGRLineString* ls= (OGRLineString*)poGeometry->getBoundary(); points.push_back(vector<glm::vec2>()); cout << "POLYGON" << ls->getNumPoints() << endl; //exit(0); for(int i = 0; i < ls->getNumPoints(); i++ ) { OGRPoint p; ls->getPoint(i,&p); // This function can transform a larget set of points..... double x = p.getX(); double y = p.getY(); points[points.size()-1].push_back(glm::vec2(x,y)); //poTransform->Transform (1, &x, &y); //cout << p.getX() << " " << p.getY() << "Transformed!: " << x << " " << y << endl; } } OGRFeature::DestroyFeature( poFeature ); } return true; }
void PCLoaderArcView::load(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, PCTypeMap&) { #ifdef HAVE_GDAL GeoConvHelper& geoConvHelper = GeoConvHelper::getProcessing(); // get defaults std::string prefix = oc.getString("prefix"); std::string type = oc.getString("type"); RGBColor color = RGBColor::parseColor(oc.getString("color")); int layer = oc.getInt("layer"); std::string idField = oc.getString("shapefile.id-column"); bool useRunningID = oc.getBool("shapefile.use-running-id"); // start parsing std::string shpName = file + ".shp"; OGRRegisterAll(); OGRDataSource* poDS = OGRSFDriverRegistrar::Open(shpName.c_str(), FALSE); if (poDS == NULL) { throw ProcessError("Could not open shape description '" + shpName + "'."); } // begin file parsing OGRLayer* poLayer = poDS->GetLayer(0); poLayer->ResetReading(); // build coordinate transformation OGRSpatialReference* origTransf = poLayer->GetSpatialRef(); OGRSpatialReference destTransf; // use wgs84 as destination destTransf.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf); if (poCT == NULL) { if (oc.isSet("shapefile.guess-projection")) { OGRSpatialReference origTransf2; origTransf2.SetWellKnownGeogCS("WGS84"); poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf); } if (poCT == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } } OGRFeature* poFeature; poLayer->ResetReading(); unsigned int runningID = 0; while ((poFeature = poLayer->GetNextFeature()) != NULL) { // read in edge attributes std::string id = useRunningID ? toString(runningID) : poFeature->GetFieldAsString(idField.c_str()); ++runningID; id = StringUtils::prune(id); if (id == "") { throw ProcessError("Missing id under '" + idField + "'"); } id = prefix + id; // read in the geometry OGRGeometry* poGeometry = poFeature->GetGeometryRef(); if (poGeometry == 0) { OGRFeature::DestroyFeature(poFeature); continue; } // try transform to wgs84 poGeometry->transform(poCT); OGRwkbGeometryType gtype = poGeometry->getGeometryType(); switch (gtype) { case wkbPoint: { OGRPoint* cgeom = (OGRPoint*) poGeometry; Position pos((SUMOReal) cgeom->getX(), (SUMOReal) cgeom->getY()); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for POI '" + id + "'."); } PointOfInterest* poi = new PointOfInterest(id, type, color, pos, (SUMOReal)layer); if (!toFill.insert(id, poi, layer)) { WRITE_ERROR("POI '" + id + "' could not be added."); delete poi; } } break; case wkbLineString: { OGRLineString* cgeom = (OGRLineString*) poGeometry; PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + id + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(id, type, color, shape, false, (SUMOReal)layer); if (!toFill.insert(id, poly, layer)) { WRITE_ERROR("Polygon '" + id + "' could not be added."); delete poly; } } break; case wkbPolygon: { OGRLinearRing* cgeom = ((OGRPolygon*) poGeometry)->getExteriorRing(); PositionVector shape; for (int j = 0; j < cgeom->getNumPoints(); j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + id + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(id, type, color, shape, true, (SUMOReal)layer); if (!toFill.insert(id, poly, layer)) { WRITE_ERROR("Polygon '" + id + "' could not be added."); delete poly; } } break; case wkbMultiPoint: { OGRMultiPoint* cgeom = (OGRMultiPoint*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRPoint* cgeom2 = (OGRPoint*) cgeom->getGeometryRef(i); Position pos((SUMOReal) cgeom2->getX(), (SUMOReal) cgeom2->getY()); std::string tid = id + "#" + toString(i); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for POI '" + tid + "'."); } PointOfInterest* poi = new PointOfInterest(tid, type, color, pos, (SUMOReal)layer); if (!toFill.insert(tid, poi, layer)) { WRITE_ERROR("POI '" + tid + "' could not be added."); delete poi; } } } break; case wkbMultiLineString: { OGRMultiLineString* cgeom = (OGRMultiLineString*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRLineString* cgeom2 = (OGRLineString*) cgeom->getGeometryRef(i); PositionVector shape; std::string tid = id + "#" + toString(i); for (int j = 0; j < cgeom2->getNumPoints(); j++) { Position pos((SUMOReal) cgeom2->getX(j), (SUMOReal) cgeom2->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + tid + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(tid, type, color, shape, false, (SUMOReal)layer); if (!toFill.insert(tid, poly, layer)) { WRITE_ERROR("Polygon '" + tid + "' could not be added."); delete poly; } } } break; case wkbMultiPolygon: { OGRMultiPolygon* cgeom = (OGRMultiPolygon*) poGeometry; for (int i = 0; i < cgeom->getNumGeometries(); ++i) { OGRLinearRing* cgeom2 = ((OGRPolygon*) cgeom->getGeometryRef(i))->getExteriorRing(); PositionVector shape; std::string tid = id + "#" + toString(i); for (int j = 0; j < cgeom2->getNumPoints(); j++) { Position pos((SUMOReal) cgeom2->getX(j), (SUMOReal) cgeom2->getY(j)); if (!geoConvHelper.x2cartesian(pos)) { WRITE_ERROR("Unable to project coordinates for polygon '" + tid + "'."); } shape.push_back_noDoublePos(pos); } Polygon* poly = new Polygon(tid, type, color, shape, true, (SUMOReal)layer); if (!toFill.insert(tid, poly, layer)) { WRITE_ERROR("Polygon '" + tid + "' could not be added."); delete poly; } } } break; default: WRITE_WARNING("Unsupported shape type occured (id='" + id + "')."); break; } OGRFeature::DestroyFeature(poFeature); } PROGRESS_DONE_MESSAGE(); #else WRITE_ERROR("SUMO was compiled without GDAL support."); #endif }
bool ShpReader::Open(std::wstring fullPath, StudyControllerPtr studyController, VectorMapControllerPtr vectorMapController, ProgressDlgPtr progressDlg) { // Registers all format drivers built into GDAL/OGR. OGRRegisterAll(); OGRDataSource *OGRDataset; // Open vector file path std::string tempStr( fullPath.begin(), fullPath.end() ); OGRDataset = OGRSFDriverRegistrar::Open( tempStr.c_str(), FALSE ); // Return if no vector files are found if( OGRDataset == NULL ) { Log::Inst().Warning("(Warning) Failed to open file at " + tempStr + "."); return false; } if ( App::Inst().GetLayerTreeController()->GetNumMapLayers() >0 ) MapControllerPtr mapController= App::Inst().GetLayerTreeController()->GetLayerTreeModel()->GetStudy(0)->GetMapLayer(0)->GetMapController(); // It appears that shapefiles (*.SHP) only support up to one layer per file // This will need to be further investigated for other vector filetypes (e.g., KML) // For now just grab layer at position 0 OGRLayer *poLayer = OGRDataset->GetLayer( 0 ); // Determine the XY boundaries for the entire vector dataset OGREnvelope psEnvelope; VectorMapModelPtr vectorMapModel = vectorMapController->GetVectorMapModel(); poLayer->GetExtent( &psEnvelope ); vectorMapModel->SetVectorBoundary(psEnvelope); if(!SetupVectorProjection(OGRDataset,studyController,poLayer,vectorMapController )) { OGRDataset->DestroyDataSource(OGRDataset); return false; } if(progressDlg) { if(!progressDlg->Update(0, _T("Reading Vector Map Information..."))) { OGRDataset->DestroyDataSource(OGRDataset); return false; } } GLdouble minX, minY, maxX, maxY; minX = minY = std::numeric_limits<float>::max(); maxX = maxY = -std::numeric_limits<float>::max(); // Retrieve features from the dataset OGRFeature *poFeature; poLayer->ResetReading(); int numFeatures = poLayer->GetFeatureCount(); int count=0; //Log::Inst().Write("Loading shapefile with the following meta data:"); while ( ( poFeature = poLayer->GetNextFeature() ) != NULL ) { ///////////////////////////////////////////////// // PHASE 1: Retrieve METADATA from the dataset // ///////////////////////////////////////////////// OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn(); int iField; for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ ) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField ); //if( poFieldDefn->GetType() == OFTInteger ) // printf( "%d,", poFeature->GetFieldAsInteger( iField ) ); //else if( poFieldDefn->GetType() == OFTReal ) // printf( "%.3f,", poFeature->GetFieldAsDouble(iField) ); //else if( poFieldDefn->GetType() == OFTString ) // printf( "%s,", poFeature->GetFieldAsString(iField) ); //else // printf( "%s,", poFeature->GetFieldAsString(iField) ); //ofs << poFeature->GetFieldAsString(iField) << ","; std::string metaData = poFeature->GetFieldAsString(iField); // do something with the meta data... //Log::Inst().Write(metaData); } count++; if(progressDlg) { if(!progressDlg->Update(int(50 + (float(count)/numFeatures)*50))) return false; } /////////////////////////////////////////////////// // PHASE 2: Retrieve GEOMETRIES from the dataset // /////////////////////////////////////////////////// OGRGeometry *poGeometry; poGeometry = poFeature->GetGeometryRef(); // Move to the next feature in the set if no geometry present if( poGeometry == NULL ) { OGRFeature::DestroyFeature( poFeature ); continue; } OGRwkbGeometryType whatisit = poGeometry->getGeometryType(); // Handle POINTS if ( wkbFlatten( poGeometry->getGeometryType() ) == wkbPoint ) { GeoVector* geoVector = new GeoVector(); OGRPoint *poPoint = (OGRPoint *) poGeometry; geoVector->SetGeometryType( wkbPoint ); geoVector->SetNumberOfPoints( 1 ); if(needProjection) { double x,y; x= poPoint->getX(); y= poPoint->getY(); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector->pointX[0] = x; geoVector->pointY[0] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector->pointX[0] = poPoint->getX(); geoVector->pointY[0] = poPoint->getY(); } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector ); } //Handle MultiPoint else if ( wkbFlatten( poGeometry->getGeometryType() ) == wkbMultiPoint ) { OGRMultiPoint *poMultiPoint = (OGRMultiPoint *) poGeometry; for ( int currGeometry = 0; currGeometry < poMultiPoint->getNumGeometries(); currGeometry++ ) { GeoVector* geoVector = new GeoVector(); OGRPoint *poPoint = ( OGRPoint* )poMultiPoint->getGeometryRef( currGeometry ); geoVector->SetGeometryType( wkbPoint ); geoVector->SetNumberOfPoints( 1 ); if(needProjection) { double x,y; x= poPoint->getX(); y= poPoint->getY(); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector->pointX[0] = x; geoVector->pointY[0] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector->pointX[0] = poPoint->getX(); geoVector->pointY[0] = poPoint->getY(); } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector ); } } //Handle Polylines else if ( wkbFlatten( poGeometry->getGeometryType() ) == wkbLineString ) { GeoVector* geoVector = new GeoVector(); OGRLineString *poLine = (OGRLineString *) poGeometry; geoVector->SetGeometryType( wkbLineString ); geoVector->SetNumberOfPoints( poLine->getNumPoints() ); // Convert and store the points for ( int currentPoint = 0; currentPoint < poLine->getNumPoints(); currentPoint++ ) { // Convert and store the points if(needProjection) { double x,y; x= poLine->getX( currentPoint ); y= poLine->getY( currentPoint ); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector->pointX[currentPoint] = x; geoVector->pointY[currentPoint] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector->pointX[currentPoint] = poLine->getX( currentPoint ); geoVector->pointY[currentPoint] = poLine->getY( currentPoint ); } } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector ); } // Handle MultiPolyLine else if ( wkbFlatten( poGeometry->getGeometryType() ) == wkbMultiLineString ) { OGRMultiLineString *poMultiLine = (OGRMultiLineString *) poGeometry; for ( int currGeometry = 0; currGeometry < poMultiLine->getNumGeometries(); currGeometry++ ) { GeoVector* geoVector = new GeoVector(); OGRLineString *poLine = ( OGRLineString* )poMultiLine->getGeometryRef( currGeometry ); geoVector->SetGeometryType( wkbLineString ); geoVector->SetNumberOfPoints( poLine->getNumPoints() ); for ( int currentPoint = 0; currentPoint < poLine ->getNumPoints(); currentPoint++ ) { if(needProjection) { double x,y; x= poLine->getX( currentPoint ); y= poLine->getY( currentPoint ); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector->pointX[currentPoint] = x; geoVector->pointY[currentPoint] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector->pointX[currentPoint] = poLine->getX( currentPoint ); geoVector->pointY[currentPoint] = poLine->getY( currentPoint ); } } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector ); } } // Handle POLYGONS else if ( wkbFlatten( poGeometry->getGeometryType() ) == wkbPolygon ) { GeoVector* geoVector = new GeoVector(); OGRPolygon *poPolygon = ( OGRPolygon* )poGeometry; OGRLinearRing *poLinearRing = poPolygon->getExteriorRing(); geoVector->SetGeometryType( wkbLinearRing ); geoVector->SetNumberOfPoints( poLinearRing->getNumPoints() ); for ( int currentPoint = 0; currentPoint < poLinearRing->getNumPoints(); currentPoint++ ) { if(needProjection) { double x,y; x= poLinearRing->getX( currentPoint ); y= poLinearRing->getY( currentPoint ); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector->pointX[currentPoint] = x; geoVector->pointY[currentPoint] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector->pointX[currentPoint] = poLinearRing->getX( currentPoint ); geoVector->pointY[currentPoint] = poLinearRing->getY( currentPoint ); } } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector ); } // Handle MULTIPOLYGONS else if ( wkbFlatten( poGeometry->getGeometryType() ) == wkbMultiPolygon ) { OGRMultiPolygon *poMultiPolygon = (OGRMultiPolygon *) poGeometry; for ( int currGeometry = 0; currGeometry < poMultiPolygon->getNumGeometries(); currGeometry++ ) { GeoVector* geoVector = new GeoVector(); // OGRPolygon http://www.gdal.org/ogr/classOGRPolygon.html OGRPolygon *poPolygon = ( OGRPolygon* )poMultiPolygon->getGeometryRef( currGeometry ); // Retrieve the EXTERNAL ring of the multipolygon OGRLinearRing *poLinearRing = poPolygon->getExteriorRing(); geoVector->SetGeometryType( wkbLinearRing ); geoVector->SetNumberOfPoints( poLinearRing->getNumPoints() ); for ( int currentPoint = 0; currentPoint < poLinearRing->getNumPoints(); currentPoint++ ) { if(needProjection) { double x,y; x= poLinearRing->getX( currentPoint ); y= poLinearRing->getY( currentPoint ); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector->pointX[currentPoint] = x; geoVector->pointY[currentPoint] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector->pointX[currentPoint] = poLinearRing->getX( currentPoint ); geoVector->pointY[currentPoint] = poLinearRing->getY( currentPoint ); } } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector ); // Retrieve all the INTERNAL rings of the multipolygon for ( int currentRing = 0; currentRing < poPolygon->getNumInteriorRings(); currentRing++ ) { GeoVector* geoVector2 = new GeoVector(); poLinearRing = poPolygon->getInteriorRing( currentRing ); geoVector2->SetGeometryType( wkbLinearRing ); geoVector2->SetNumberOfPoints( poLinearRing->getNumPoints() ); for ( int currentPoint = 0; currentPoint < poLinearRing->getNumPoints(); currentPoint++ ) { if(needProjection) { double x,y; x= poLinearRing->getX( currentPoint ); y= poLinearRing->getY( currentPoint ); if(!poTransform->Transform(1, &x, &y)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } // project and store the points geoVector2->pointX[currentPoint] = x; geoVector2->pointY[currentPoint] = y; if(x < minX) minX=x; if(y < minY) minY=y; if(x > maxX) maxX=x; if(y > maxY) maxY=y; } else { geoVector2->pointX[currentPoint] = poLinearRing->getX( currentPoint ); geoVector2->pointY[currentPoint] = poLinearRing->getY( currentPoint ); } } vectorMapController->GetVectorMapModel()->AddGeoVector( geoVector2 ); } } } // Report a warning message for unhandled geometries else { Log::Inst().Warning("(Warning) Could not load vector data: unsupported geometry."); } OGRFeature::DestroyFeature( poFeature ); } if (float(minX) == float(maxX) && float(minY) == float(maxY)) { Log::Inst().Warning("(Warning) Failed to project vector map."); OGRDataset->DestroyDataSource(OGRDataset); return false; } if(needProjection) { vectorMapModel->SetVectorBoundary_MinX(minX); vectorMapModel->SetVectorBoundary_MaxX(maxX); vectorMapModel->SetVectorBoundary_MinY(minY); vectorMapModel->SetVectorBoundary_MaxY(maxY); } if(!SetupVectorScaling(vectorMapModel,progressDlg)) { OGRDataset->DestroyDataSource(OGRDataset); return false; } VectorMetaDataInfo(OGRDataset, studyController, vectorMapController); OGRDataSource::DestroyDataSource( OGRDataset ); return true; }
CPLErr GDALRasterizeLayers( GDALDatasetH hDS, int nBandCount, int *panBandList, int nLayerCount, OGRLayerH *pahLayers, GDALTransformerFunc pfnTransformer, void *pTransformArg, double *padfLayerBurnValues, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressArg ) { GDALDataType eType; unsigned char *pabyChunkBuf; GDALDataset *poDS = (GDALDataset *) hDS; if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; /* -------------------------------------------------------------------- */ /* Do some rudimentary arg checking. */ /* -------------------------------------------------------------------- */ if( nBandCount == 0 || nLayerCount == 0 ) return CE_None; // prototype band. GDALRasterBand *poBand = poDS->GetRasterBand( panBandList[0] ); if (poBand == NULL) return CE_Failure; int bAllTouched = CSLFetchBoolean( papszOptions, "ALL_TOUCHED", FALSE ); const char *pszOpt = CSLFetchNameValue( papszOptions, "BURN_VALUE_FROM" ); GDALBurnValueSrc eBurnValueSource = GBV_UserBurnValue; if( pszOpt ) { if( EQUAL(pszOpt,"Z")) eBurnValueSource = GBV_Z; /*else if( EQUAL(pszOpt,"M")) eBurnValueSource = GBV_M;*/ } /* -------------------------------------------------------------------- */ /* Establish a chunksize to operate on. The larger the chunk */ /* size the less times we need to make a pass through all the */ /* shapes. */ /* -------------------------------------------------------------------- */ int nYChunkSize, nScanlineBytes; const char *pszYChunkSize = CSLFetchNameValue( papszOptions, "CHUNKYSIZE" ); if( poBand->GetRasterDataType() == GDT_Byte ) eType = GDT_Byte; else eType = GDT_Float32; nScanlineBytes = nBandCount * poDS->GetRasterXSize() * (GDALGetDataTypeSize(eType)/8); if ( pszYChunkSize && (nYChunkSize = atoi(pszYChunkSize)) ) ; else nYChunkSize = GDALGetCacheMax() / nScanlineBytes; if( nYChunkSize < 1 ) nYChunkSize = 1; if( nYChunkSize > poDS->GetRasterYSize() ) nYChunkSize = poDS->GetRasterYSize(); pabyChunkBuf = (unsigned char *) VSIMalloc(nYChunkSize * nScanlineBytes); if( pabyChunkBuf == NULL ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to allocate rasterization buffer." ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Read the image once for all layers if user requested to render */ /* the whole raster in single chunk. */ /* -------------------------------------------------------------------- */ if ( nYChunkSize == poDS->GetRasterYSize() ) { if ( poDS->RasterIO( GF_Read, 0, 0, poDS->GetRasterXSize(), nYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ) != CE_None ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to read buffer." ); CPLFree( pabyChunkBuf ); return CE_Failure; } } /* ==================================================================== */ /* Read the specified layers transfoming and rasterizing */ /* geometries. */ /* ==================================================================== */ CPLErr eErr = CE_None; int iLayer; const char *pszBurnAttribute = CSLFetchNameValue( papszOptions, "ATTRIBUTE" ); pfnProgress( 0.0, NULL, pProgressArg ); for( iLayer = 0; iLayer < nLayerCount; iLayer++ ) { int iBurnField = -1; double *padfBurnValues = NULL; OGRLayer *poLayer = (OGRLayer *) pahLayers[iLayer]; if ( !poLayer ) { CPLError( CE_Warning, CPLE_AppDefined, "Layer element number %d is NULL, skipping.\n", iLayer ); continue; } /* -------------------------------------------------------------------- */ /* If the layer does not contain any features just skip it. */ /* Do not force the feature count, so if driver doesn't know */ /* exact number of features, go down the normal way. */ /* -------------------------------------------------------------------- */ if ( poLayer->GetFeatureCount(FALSE) == 0 ) continue; if ( pszBurnAttribute ) { iBurnField = poLayer->GetLayerDefn()->GetFieldIndex( pszBurnAttribute ); if ( iBurnField == -1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.\n", pszBurnAttribute, poLayer->GetLayerDefn()->GetName() ); continue; } } else padfBurnValues = padfLayerBurnValues + iLayer * nBandCount; /* -------------------------------------------------------------------- */ /* If we have no transformer, create the one from input file */ /* projection. Note that each layer can be georefernced */ /* separately. */ /* -------------------------------------------------------------------- */ int bNeedToFreeTransformer = FALSE; if( pfnTransformer == NULL ) { char *pszProjection = NULL; bNeedToFreeTransformer = TRUE; OGRSpatialReference *poSRS = poLayer->GetSpatialRef(); if ( !poSRS ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to fetch spatial reference on layer %s " "to build transformer, assuming matching coordinate systems.\n", poLayer->GetLayerDefn()->GetName() ); } else poSRS->exportToWkt( &pszProjection ); pTransformArg = GDALCreateGenImgProjTransformer( NULL, pszProjection, hDS, NULL, FALSE, 0.0, 0 ); pfnTransformer = GDALGenImgProjTransform; CPLFree( pszProjection ); } OGRFeature *poFeat; poLayer->ResetReading(); /* -------------------------------------------------------------------- */ /* Loop over image in designated chunks. */ /* -------------------------------------------------------------------- */ int iY; for( iY = 0; iY < poDS->GetRasterYSize() && eErr == CE_None; iY += nYChunkSize ) { int nThisYChunkSize; nThisYChunkSize = nYChunkSize; if( nThisYChunkSize + iY > poDS->GetRasterYSize() ) nThisYChunkSize = poDS->GetRasterYSize() - iY; // Only re-read image if not a single chunk is being rendered if ( nYChunkSize < poDS->GetRasterYSize() ) { eErr = poDS->RasterIO( GF_Read, 0, iY, poDS->GetRasterXSize(), nThisYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nThisYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ); if( eErr != CE_None ) break; } double *padfAttrValues = (double *) VSIMalloc(sizeof(double) * nBandCount); while( (poFeat = poLayer->GetNextFeature()) != NULL ) { OGRGeometry *poGeom = poFeat->GetGeometryRef(); if ( pszBurnAttribute ) { int iBand; double dfAttrValue; dfAttrValue = poFeat->GetFieldAsDouble( iBurnField ); for (iBand = 0 ; iBand < nBandCount ; iBand++) padfAttrValues[iBand] = dfAttrValue; padfBurnValues = padfAttrValues; } gv_rasterize_one_shape( pabyChunkBuf, iY, poDS->GetRasterXSize(), nThisYChunkSize, nBandCount, eType, bAllTouched, poGeom, padfBurnValues, eBurnValueSource, pfnTransformer, pTransformArg ); delete poFeat; } VSIFree( padfAttrValues ); // Only write image if not a single chunk is being rendered if ( nYChunkSize < poDS->GetRasterYSize() ) { eErr = poDS->RasterIO( GF_Write, 0, iY, poDS->GetRasterXSize(), nThisYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nThisYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ); } poLayer->ResetReading(); if( !pfnProgress((iY+nThisYChunkSize)/((double)poDS->GetRasterYSize()), "", pProgressArg) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } } if ( bNeedToFreeTransformer ) { GDALDestroyTransformer( pTransformArg ); pTransformArg = NULL; pfnTransformer = NULL; } } /* -------------------------------------------------------------------- */ /* Write out the image once for all layers if user requested */ /* to render the whole raster in single chunk. */ /* -------------------------------------------------------------------- */ if ( nYChunkSize == poDS->GetRasterYSize() ) { poDS->RasterIO( GF_Write, 0, 0, poDS->GetRasterXSize(), nYChunkSize, pabyChunkBuf, poDS->GetRasterXSize(), nYChunkSize, eType, nBandCount, panBandList, 0, 0, 0 ); } /* -------------------------------------------------------------------- */ /* cleanup */ /* -------------------------------------------------------------------- */ VSIFree( pabyChunkBuf ); return eErr; }