extern int Dbf_GetFieldIndexFromObj (Tcl_Interp * interp, DBFHandle dbfHandle, Tcl_Obj * objPtr, int *indexPtr) { if (objPtr->typePtr == &dbfFieldType && GetDBFHandle (objPtr) == dbfHandle) { *indexPtr = GetFieldIndex (objPtr); return TCL_OK; } else { if ((*indexPtr = DBFGetFieldIndex (dbfHandle, Tcl_GetString (objPtr))) == -1) { Tcl_SetResult (interp, "missing value to go with key", TCL_STATIC); Tcl_SetErrorCode (interp, "DBF", "VALUE", "DICTIONARY", NULL); return TCL_ERROR; } FreeInternalRep (objPtr); objPtr->typePtr = &dbfFieldType; SetFieldIndex (objPtr, *indexPtr); SetDBFHandle (objPtr, dbfHandle); return TCL_OK; } }
// extract info from dbf void shapes_load_dbf(const char* filename, const char* column){ DBFHandle hDBF; hDBF = DBFOpen( filename, "rb" ); if( hDBF == NULL ) { fprintf(stderr, "DBFOpen(%s,\"r\") failed.\n", filename ); return; } // INFO ABOUT DBF // int *panWidth; // int nWidth, nDecimals; // fprintf (stderr, "Info for %s\n", filename); // i = DBFGetFieldCount(hDBF); // fprintf (stderr, "%d Columns, %d Records in file\n",i,DBFGetRecordCount(hDBF)); // panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) ); // for( int i = 0; i < DBFGetFieldCount(hDBF); i++ ) { // DBFFieldType eType; // char szTitle[256]; // eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals ); // fprintf(stderr, "%4d: %10s %c", i, szTitle, i%4 ? '|':'\n'); // } // fprintf(stderr, "\n"); // print names uint32_t fid = DBFGetFieldIndex(hDBF, column); for(uint32_t i = 0; i < DBFGetRecordCount(hDBF); i++ ) { char* name_long = (char *) DBFReadStringAttribute(hDBF, i, fid); fprintf(stderr, "%d: %s\n", i, name_long); } DBFClose( hDBF ); }
int dbf_get_field_index(DBFHandle handle, int row, const char *field_name) { assert(handle); assert(field_name); assert(row < DBFGetRecordCount(handle)); // if (row >= DBFGetRecordCount(handle)) throw(std::runtime_error("row=" + std::to_string(row) + " is out of bounds.")); int index = DBFGetFieldIndex(handle, field_name); if (index == -1) throw(std::runtime_error("DBFfile doesnt contain " + std::string(field_name))); return index; }
// Function to read outlets from a shapefile - overloaded to return an array of integer ID's int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y, int*& id) { SHPHandle shp = SHPOpen(outletsfile, "rb"); char dbffile[MAXLN]; nameadd(dbffile, outletsfile, ".dbf"); DBFHandle dbf = DBFOpen(dbffile, "rb"); if ((shp != NULL) && (dbf != NULL)) { int nEntities = 0; int nShapeType = 0; SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL ); if (nShapeType != SHPT_POINT) { fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile); fflush(stderr); return 1; } long p_size; long countPts = 0; int nfld = DBFGetFieldCount(dbf); //int idfld = DBFGetFieldIndex(dbf, "id"); int idfld = DBFGetFieldIndex(dbf, "OBJECTID"); // ZhuLJ, 2015/6/16 for( int i=0; i<nEntities; i++) { SHPObject * shape = SHPReadObject(shp, i); countPts += shape->nVertices; SHPDestroyObject(shape); } x = new double[countPts]; y = new double[countPts]; if (idfld >= 0) id = new int[countPts]; int nxy=0; for( int i=0; i<nEntities; i++) { SHPObject * shape = SHPReadObject(shp, i); p_size = shape->nVertices; for( int j=0; j<p_size; j++) { x[nxy] = shape->padfX[j]; y[nxy] = shape->padfY[j]; if (idfld >= 0) { id[nxy] = DBFReadIntegerAttribute(dbf, i, idfld); } nxy++; } SHPDestroyObject(shape); } *noutlets=nxy; SHPClose(shp); return 0; } else { fprintf(stderr, "Error opening outlets shapefile: %s\n", outletsfile); fflush(stderr); return 1; } }
strings_v shape_load_names(const char* filename, const char* colname) { DBFHandle hDBF; strings_v col; kv_init(col); hDBF = DBFOpen( filename, "rb" ); if( hDBF == NULL ) { fprintf(stderr, "DBFOpen(%s,\"r\") failed.\n", filename ); return col; } uint32_t fid = DBFGetFieldIndex(hDBF, colname); for(uint32_t i = 0; i < DBFGetRecordCount(hDBF); i++ ) { char* str = (char *) DBFReadStringAttribute(hDBF, i, fid); if(str != NULL) kv_push(char*, col, strdup(str)); else kv_push(char*, col, NULL); } DBFClose( hDBF ); return col; }
GeoDataDocument *ShpRunner::parseFile(const QString &fileName, DocumentRole role, QString &error) { QFileInfo fileinfo( fileName ); if (fileinfo.suffix().compare(QLatin1String("shp"), Qt::CaseInsensitive) != 0) { error = QStringLiteral("File %1 does not have a shp suffix").arg(fileName); mDebug() << error; return nullptr; } SHPHandle handle = SHPOpen( fileName.toStdString().c_str(), "rb" ); if ( !handle ) { error = QStringLiteral("Failed to read %1").arg(fileName); mDebug() << error; return nullptr; } int entities; int shapeType; SHPGetInfo( handle, &entities, &shapeType, NULL, NULL ); mDebug() << " SHP info " << entities << " Entities " << shapeType << " Shape Type "; DBFHandle dbfhandle; dbfhandle = DBFOpen( fileName.toStdString().c_str(), "rb"); int nameField = DBFGetFieldIndex( dbfhandle, "Name" ); int noteField = DBFGetFieldIndex( dbfhandle, "Note" ); int mapColorField = DBFGetFieldIndex( dbfhandle, "mapcolor13" ); GeoDataDocument *document = new GeoDataDocument; document->setDocumentRole( role ); if ( mapColorField != -1 ) { GeoDataSchema schema; schema.setId(QStringLiteral("default")); GeoDataSimpleField simpleField; simpleField.setName(QStringLiteral("mapcolor13")); simpleField.setType( GeoDataSimpleField::Double ); schema.addSimpleField( simpleField ); document->addSchema( schema ); } for ( int i=0; i< entities; ++i ) { GeoDataPlacemark *placemark = 0; placemark = new GeoDataPlacemark; document->append( placemark ); SHPObject *shape = SHPReadObject( handle, i ); if (nameField != -1) { const char* info = DBFReadStringAttribute( dbfhandle, i, nameField ); // TODO: defaults to utf-8 encoding, but could be also something else, optionally noted in a .cpg file placemark->setName( info ); mDebug() << "name " << placemark->name(); } if (noteField != -1) { const char* note = DBFReadStringAttribute( dbfhandle, i, noteField ); // TODO: defaults to utf-8 encoding, see comment for name placemark->setDescription( note ); mDebug() << "desc " << placemark->description(); } double mapColor = DBFReadDoubleAttribute( dbfhandle, i, mapColorField ); if ( mapColor ) { GeoDataStyle::Ptr style(new GeoDataStyle); if ( mapColor >= 0 && mapColor <=255 ) { quint8 colorIndex = quint8( mapColor ); style->polyStyle().setColorIndex( colorIndex ); } else { quint8 colorIndex = 0; // mapColor is undefined in this case style->polyStyle().setColorIndex( colorIndex ); } placemark->setStyle( style ); } switch ( shapeType ) { case SHPT_POINT: { GeoDataPoint *point = new GeoDataPoint( *shape->padfX, *shape->padfY, 0, GeoDataCoordinates::Degree ); placemark->setGeometry( point ); mDebug() << "point " << placemark->name(); break; } case SHPT_MULTIPOINT: { GeoDataMultiGeometry *geom = new GeoDataMultiGeometry; for( int j=0; j<shape->nVertices; ++j ) { geom->append( new GeoDataPoint( GeoDataCoordinates( shape->padfX[j], shape->padfY[j], 0, GeoDataCoordinates::Degree ) ) ); } placemark->setGeometry( geom ); mDebug() << "multipoint " << placemark->name(); break; } case SHPT_ARC: { if ( shape->nParts != 1 ) { GeoDataMultiGeometry *geom = new GeoDataMultiGeometry; for( int j=0; j<shape->nParts; ++j ) { GeoDataLineString *line = new GeoDataLineString; int itEnd = (j + 1 < shape->nParts) ? shape->panPartStart[j+1] : shape->nVertices; for( int k=shape->panPartStart[j]; k<itEnd; ++k ) { line->append( GeoDataCoordinates( shape->padfX[k], shape->padfY[k], 0, GeoDataCoordinates::Degree ) ); } geom->append( line ); } placemark->setGeometry( geom ); mDebug() << "arc " << placemark->name() << " " << shape->nParts; } else { GeoDataLineString *line = new GeoDataLineString; for( int j=0; j<shape->nVertices; ++j ) { line->append( GeoDataCoordinates( shape->padfX[j], shape->padfY[j], 0, GeoDataCoordinates::Degree ) ); } placemark->setGeometry( line ); mDebug() << "arc " << placemark->name() << " " << shape->nParts; } break; } case SHPT_POLYGON: { if ( shape->nParts != 1 ) { bool isRingClockwise = false; GeoDataMultiGeometry *multigeom = new GeoDataMultiGeometry; GeoDataPolygon *poly = 0; int polygonCount = 0; for( int j=0; j<shape->nParts; ++j ) { GeoDataLinearRing ring; int itStart = shape->panPartStart[j]; int itEnd = (j + 1 < shape->nParts) ? shape->panPartStart[j+1] : shape->nVertices; for( int k = itStart; k<itEnd; ++k ) { ring.append( GeoDataCoordinates( shape->padfX[k], shape->padfY[k], 0, GeoDataCoordinates::Degree ) ); } isRingClockwise = ring.isClockwise(); if ( j == 0 || isRingClockwise ) { poly = new GeoDataPolygon; ++polygonCount; poly->setOuterBoundary( ring ); if ( polygonCount > 1 ) { multigeom->append( poly ); } } else { poly->appendInnerBoundary( ring ); } } if ( polygonCount > 1 ) { placemark->setGeometry( multigeom ); } else { placemark->setGeometry( poly ); delete multigeom; multigeom = 0; } mDebug() << "donut " << placemark->name() << " " << shape->nParts; } else { GeoDataPolygon *poly = new GeoDataPolygon; GeoDataLinearRing ring; for( int j=0; j<shape->nVertices; ++j ) { ring.append( GeoDataCoordinates( shape->padfX[j], shape->padfY[j], 0, GeoDataCoordinates::Degree ) ); } poly->setOuterBoundary( ring ); placemark->setGeometry( poly ); mDebug() << "poly " << placemark->name() << " " << shape->nParts; } break; } } } SHPClose( handle ); DBFClose( dbfhandle ); if ( document->size() ) { document->setFileName( fileName ); return document; } else { delete document; return nullptr; } }
int main (int argc, char *argv[]) { SHPHandle inSHP, outSHP; DBFHandle inDBF, outDBF; int len; int i; char **fieldNames; char **strOrder = 0; struct DataStruct *index; int width; int decimals; SHPObject *feat; void *tuple; if (argc < 4) { printf("USAGE: shpsort <infile> <outfile> <field[;...]> [<(ASCENDING|DESCENDING)[;...]>]\n"); exit(EXIT_FAILURE); } inSHP = SHPOpen (argv[1], "rb"); if (!inSHP) { fputs("Couldn't open shapefile for reading!\n", stderr); exit(EXIT_FAILURE); } SHPGetInfo(inSHP, &nShapes, &shpType, NULL, NULL); /* If we can open the inSHP, open its DBF */ inDBF = DBFOpen (argv[1], "rb"); if (!inDBF) { fputs("Couldn't open dbf file for reading!\n", stderr); exit(EXIT_FAILURE); } /* Parse fields and validate existence */ fieldNames = split(argv[3], ";"); if (!fieldNames) { fputs("ERROR: parsing field names!\n", stderr); exit(EXIT_FAILURE); } for (nFields = 0; fieldNames[nFields] ; nFields++) { continue; } fldIdx = malloc(sizeof *fldIdx * nFields); if (!fldIdx) { fputs("malloc failed!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields; i++) { len = (int)strlen(fieldNames[i]); while(len > 0) { --len; fieldNames[i][len] = (char)toupper((unsigned char)fieldNames[i][len]); } fldIdx[i] = DBFGetFieldIndex(inDBF, fieldNames[i]); if (fldIdx[i] < 0) { /* try "SHAPE" */ if (strcmp(fieldNames[i], "SHAPE") == 0) { fldIdx[i] = -1; } else if (strcmp(fieldNames[i], "FID") == 0) { fldIdx[i] = -2; } else { fprintf(stderr, "ERROR: field '%s' not found!\n", fieldNames[i]); exit(EXIT_FAILURE); } } } /* set up field type array */ fldType = malloc(sizeof *fldType * nFields); if (!fldType) { fputs("malloc failed!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields; i++) { if (fldIdx[i] < 0) { fldType[i] = fldIdx[i]; } else { fldType[i] = DBFGetFieldInfo(inDBF, fldIdx[i], NULL, &width, &decimals); if (fldType[i] == FTInvalid) { fputs("Unrecognized field type in dBASE file!\n", stderr); exit(EXIT_FAILURE); } } } /* set up field order array */ fldOrder = malloc(sizeof *fldOrder * nFields); if (!fldOrder) { fputs("malloc failed!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields; i++) { /* default to ascending order */ fldOrder[i] = ASCENDING; } if (argc > 4) { strOrder = split(argv[4], ";"); if (!strOrder) { fputs("ERROR: parsing fields ordering!\n", stderr); exit(EXIT_FAILURE); } for (i = 0; i < nFields && strOrder[i]; i++) { if (strcmp(strOrder[i], "DESCENDING") == 0) { fldOrder[i] = DESCENDING; } } } /* build the index */ index = build_index (inSHP, inDBF); /* Create output shapefile */ outSHP = SHPCreate(argv[2], shpType); if (!outSHP) { fprintf(stderr, "%s:%d: couldn't create output shapefile!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } /* Create output dbf */ outDBF = DBFCloneEmpty(inDBF, argv[2]); if (!outDBF) { fprintf(stderr, "%s:%d: couldn't create output dBASE file!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } /* Copy projection file, if any */ copy_related(argv[1], argv[2], ".shp", ".prj"); /* Copy metadata file, if any */ copy_related(argv[1], argv[2], ".shp", ".shp.xml"); /* Write out sorted results */ for (i = 0; i < nShapes; i++) { feat = SHPReadObject(inSHP, index[i].record); if (SHPWriteObject(outSHP, -1, feat) < 0) { fprintf(stderr, "%s:%d: error writing shapefile!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } tuple = (void *) DBFReadTuple(inDBF, index[i].record); if (DBFWriteTuple(outDBF, i, tuple) < 0) { fprintf(stderr, "%s:%d: error writing dBASE file!\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } } SHPClose(inSHP); SHPClose(outSHP); DBFClose(inDBF); DBFClose(outDBF); return EXIT_SUCCESS; }
/** * Create Voronoi shape files using Triangle. * @param argc is the number of arguments provided from the command line * (including the command name). * @param argv is an array of strings that contains the argc arguments. * @return An error code if something goes wrong or 0 if there was no error * during the conversion process. * \todo Allow generation of empty report file. */ int main( int argc, char **argv ) { int error; char line[MAXLINE]; char wline[MAXLINE]; char *textpointer = NULL, *prev_textpointer = NULL; int nPolygons; int nShapeType, nEntities, nVertices, nParts, *panParts, i, j, iPart; int nNodes, nNodeRef; SHPObject *psCShape; int byRing = 1; int nPolygonPoints; char boolWriteShape; int nShapes = 0; double padfMinBound[4]; double padfMaxBound[4]; int nDcidIndex = -1; char *pDCID; strcpy(vertex_line_name, ""); num_vertices = 0; /* parameter check */ if(((argc != 3)|| ((!str_is_shp(argv[1])||(!str_is_shp(argv[2])))))) { printf("shpvoronoi 0.1.0 (c) 2005 Steffen Macke\n"); printf("usage: shpvoronoi input_shapefile voronoi_shapefile\n"); exit(1); } remove_shp(argv[2]); hPointSHP = SHPOpen(argv[1], "rb" ); hPointDBF = DBFOpen(argv[1], "rb"); if(hPointSHP == NULL || hPointDBF == NULL ) { printf("FATAL ERROR: Unable to open input file:%s\n", argv[1] ); exit(1); } nDcidIndex = DBFGetFieldIndex(hPointDBF, "dc_id"); if(nDcidIndex == -1) { printf("FATAL ERROR: Shapefile:%s is lacking the 'dc_id field.'\n", argv[1]); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } SHPGetInfo(hPointSHP, &nEntities, &nShapeType, padfMinBound, padfMaxBound); if(nShapeType != SHPT_POINT) { printf("FATAL ERROR: Input is not a point shapefile:%s\n", argv[1]); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } if(nEntities > MAXNUMNODES) { printf("FATAL ERROR: Too many nodes. Please recompile.\n"); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } /** * \todo Dynamic filename */ hTextFile = fopen("shptriangle.node", "wt"); if(hTextFile == NULL) { printf("FATAL ERROR: Cannot open output file:%s\n", "shptriangle.node"); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } fprintf(hTextFile, "2\n%d\n", nEntities+4); for(i=0; i<nEntities;i++) { psCShape = SHPReadObject(hPointSHP, i); fprintf(hTextFile, "%f %f\n", psCShape->dfXMin, psCShape->dfYMin); } fprintf(hTextFile, "%f %f\n", padfMinBound[0]-dBuffer, padfMinBound[1]-dBuffer); fprintf(hTextFile, "%f %f\n", padfMinBound[0]-dBuffer, padfMaxBound[1]+dBuffer); fprintf(hTextFile, "%f %f\n", padfMaxBound[0]+dBuffer, padfMaxBound[1]+dBuffer); fprintf(hTextFile, "%f %f\n", padfMaxBound[0]+dBuffer, padfMinBound[1]-dBuffer); fclose(hTextFile); SHPClose(hPointSHP); DBFClose(hPointDBF); system("qvoronoi.exe o < shptriangle.node > shptriangle.off"); hTextFile = fopen("shptriangle.off", "rt"); if(hTextFile == NULL) { printf("FATAL ERROR: Cannot open input file:%s\n", "shptriangle.off"); exit(1); } if(fgets(line, MAXLINE, hTextFile) == NULL) { printf("FATAL ERROR reading first line of shptriangle.off\n"); fclose(hTextFile); exit(1); } i = atoi(line); if(i != 2) { printf("FATAL ERROR: Wrong dimension in first line of shptriangle.off\n"); fclose(hTextFile); exit(1); } if(fgets(line, MAXLINE, hTextFile) == NULL) { printf("FATAL ERROR reading second line of shptriangle.off\n"); fclose(hTextFile); exit(1); } //printf("%s\n", line); num_vertices = atoi(line); if(num_vertices > MAXNUMNODES) { printf("FATAL ERROR: Too many nodes, please recompile: %d\n", num_vertices); fclose(hTextFile); exit(1); } //printf("%d nodes\n", num_vertices); textpointer = strchr(line, ' '); nPolygons = atoi(textpointer); //printf("%d polygons\n", nPolygons); /** * Build node list */ for(i=0; i < num_vertices; i++) { if(fgets(line, MAXLINE, hTextFile) == NULL) { printf("FATAL ERROR: shptriangle.off does not contain enough nodes.\n"); fclose(hTextFile); exit(1); } node_x[i] = atof(line); textpointer = strchr(line, ' '); node_y[i] = atof(textpointer); //printf("Vertex %d %f %f\n", i, node_x[i], node_y[i]); } hVoronoiSHP = SHPCreate(argv[2], SHPT_POLYGON); hVoronoiDBF = DBFCreate(argv[2]); hPointDBF = DBFOpen(argv[1], "rb"); if(hVoronoiSHP == NULL || hVoronoiDBF == NULL || hPointDBF == NULL) { fprintf(stderr, "FATAL ERROR: Unable to create file '%s'.\n", argv[2]); fclose(hTextFile); exit(1); } DBFAddField(hVoronoiDBF, "dc_id", FTString, 16, 0); for(i=0; i < nPolygons; i++) { //printf("Polygon %d\n", i); if(fgets(line, MAXLINE, hTextFile) == NULL) { printf("FATAL ERROR: shptriangle.off does not contain enough polygons.\n"); SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); exit(1); } nNodes = 0; nPolygonPoints = atoi(line); //printf("Polygon Point Count: %d\n", nPolygonPoints); if((nPolygonPoints < 0)||(nPolygonPoints > num_vertices)) { printf("FATAL ERROR: shptriangle.off contains illegal point count.\n"); SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); exit(1); } textpointer = line; boolWriteShape = 1; for(j=0; j < nPolygonPoints; j++) { textpointer = strchr(textpointer+1, ' '); nNodes++; nNodeRef = atoi(textpointer); if((nNodeRef < 0)||(nNodeRef > num_vertices)) { printf("FATAL ERROR: shptriangle.off contains illegal node reference.\n"); SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); exit(1); } /** * Don't write boundary shapes */ if(nNodeRef == 0) { boolWriteShape = 0; break; } //printf("Node reference %d\n", nNodeRef); polygon_x[nNodes-1] = node_x[nNodeRef]; polygon_y[nNodes-1] = node_y[nNodeRef]; } if(boolWriteShape == 1) { nNodes++; polygon_x[nNodes-1] = polygon_x[0]; polygon_y[nNodes-1] = polygon_y[0]; //printf("Polygon %d with %d nodes\n", i, nNodes); psCShape = SHPCreateSimpleObject( SHPT_POLYGON, nNodes, polygon_x, polygon_y, NULL ); SHPWriteObject(hVoronoiSHP, -1, psCShape); SHPDestroyObject(psCShape); /** * Take over DC_ID field. */ if(nShapes < nEntities) { pDCID = DBFReadStringAttribute(hPointDBF, nShapes, nDcidIndex); DBFWriteStringAttribute(hVoronoiDBF, nShapes, 0, pDCID); } else { DBFWriteStringAttribute(hVoronoiDBF, nShapes, 0, ""); } nShapes++; } } SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); }
bool writeAdminRegionsToDatabase(QString const &a0_dbf, QString const &a1_dbf, Kompex::SQLiteStatement * pStmt) { // because shapefiles are evil QTextCodec * codec = QTextCodec::codecForName("windows-1252"); // populate the admin0 temp table { DBFHandle a0_hDBF = DBFOpen(a0_dbf.toLocal8Bit().data(),"rb"); if(a0_hDBF == NULL) { qDebug() << "ERROR: Could not open admin0 dbf file"; return -1; } size_t a0_numRecords = DBFGetRecordCount(a0_hDBF); if(a0_numRecords == 0) { qDebug() << "ERROR: admin0 dbf file has no records!"; return -1; } size_t a0_idx_adm_name = DBFGetFieldIndex(a0_hDBF,"name"); size_t a0_idx_adm_a3 = DBFGetFieldIndex(a0_hDBF,"adm0_a3"); size_t a0_idx_sov_name = DBFGetFieldIndex(a0_hDBF,"sovereignt"); size_t a0_idx_sov_a3 = DBFGetFieldIndex(a0_hDBF,"sov_a3"); size_t a0_idx_type = DBFGetFieldIndex(a0_hDBF,"type"); size_t a0_idx_note = DBFGetFieldIndex(a0_hDBF,"note_adm0"); // create a temporary table we can use to lookup // the admin0 data we want for each admin1 entry pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS temp(" "id INTEGER PRIMARY KEY NOT NULL UNIQUE," "adm_a3 TEXT NOT NULL UNIQUE," "sov_a3 TEXT NOT NULL," "adm_name TEXT," "sov_name TEXT," "type TEXT," "note TEXT);"); pStmt->BeginTransaction(); for(size_t i=0; i < a0_numRecords; i++) { QString s0 = QString::number(i,10); QString s1(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_adm_a3))); QString s2(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_sov_a3))); QString s3(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_adm_name))); QString s4(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_sov_name))); QString s5(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_type))); QString s6(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_note))); QString stmt("INSERT INTO temp(" "id," "adm_a3," "sov_a3," "adm_name," "sov_name," "type," "note) VALUES(" + s0 + "," + "\"" + s1 + "\"," "\"" + s2 + "\"," "\"" + s3 + "\"," "\"" + s4 + "\"," "\"" + s5 + "\"," "\"" + s6 + "\");"); pStmt->SqlStatement(stmt.toStdString()); } pStmt->CommitTransaction(); DBFClose(a0_hDBF); } // populate the admin1 table { DBFHandle a1_hDBF = DBFOpen(a1_dbf.toLocal8Bit().data(),"rb"); if(a1_hDBF == NULL) { qDebug() << "ERROR: Could not open admin1 dbf file"; return false; } size_t a1_numRecords = DBFGetRecordCount(a1_hDBF); if(a1_numRecords == 0) { qDebug() << "ERROR: admin1 dbf file has no records!"; return false; } // open admin1 translation csv if it exists QStringList listAdmin1Subs; QString pathSubs = a1_dbf; pathSubs.chop(4); pathSubs.append("_translations.dat"); bool admin1_csv_sub = getAdmin1TranslationSubs(pathSubs,listAdmin1Subs); if(admin1_csv_sub) { if(listAdmin1Subs.size() == a1_numRecords) { qDebug() << "INFO: Using translation substitute file: "<< pathSubs; } else { qDebug() << "WARN: Translation file has wrong number " "of entries: " << listAdmin1Subs.size(); admin1_csv_sub = false; } } size_t a1_idx_adm_name = DBFGetFieldIndex(a1_hDBF,"name"); size_t a1_idx_adm_a3 = DBFGetFieldIndex(a1_hDBF,"sr_adm0_a3"); size_t a1_idx_sov_a3 = DBFGetFieldIndex(a1_hDBF,"sr_sov_a3"); size_t a1_idx_fclass = DBFGetFieldIndex(a1_hDBF,"featurecla"); size_t a1_idx_adminname = DBFGetFieldIndex(a1_hDBF,"admin"); QStringList listSqlSaveSov; QStringList listSqlSaveAdmin0; QStringList listSqlSaveAdmin1; for(size_t i=0; i < a1_numRecords; i++) { // get the name of this admin1 entry QString admin1_idx = QString::number(i,10); QString admin1_name(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_adm_name))); // if the adm1 fclass is an aggregation, minor island or // remainder, we grab the name from another field which // doesn't contain a bunch of additional metadata QString fclass(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_fclass))); if(fclass.contains("aggregation") || fclass.contains("minor island") || fclass.contains("remainder")) { admin1_name = QString(codec->toUnicode(DBFReadStringAttribute( a1_hDBF, i, a1_idx_adminname))); } else { // if there's no special feature class than we check // to see if there's a translation substitute available if(admin1_csv_sub && (listAdmin1Subs[i].size() > 0)) { admin1_name = listAdmin1Subs[i]; } } // get the adm_a3,sov_a3 code for this admin1 entry QString adm_a3(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_adm_a3))); QString sov_a3(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_sov_a3))); // check if the adm_a3 code exists in the temp database QString stmt("SELECT * FROM temp WHERE adm_a3=\""+ adm_a3 + "\";"); pStmt->Sql(stmt.toStdString()); if(pStmt->FetchRow()) { // save admin0 info QString admin0_idx = QString::number(pStmt->GetColumnInt("id"),10); QString admin0_type = QString::fromStdString(pStmt->GetColumnString("type")); QString admin0_note = QString::fromStdString(pStmt->GetColumnString("note")); pStmt->FreeQuery(); // save admin1 info; we currently derive the // disputed field from admin0 type and note fields QString admin1_disputed = "0"; if(admin0_type.contains("Disputed") || admin0_note.contains("Disputed")) { admin1_disputed = "1"; } stmt = QString("INSERT INTO admin1(id,name,disputed,admin0,sov) VALUES(" + admin1_idx + ",\"" + admin1_name + "\"," + admin1_disputed + "," + admin0_idx + "," + admin0_idx + ");"); listSqlSaveAdmin1.push_back(stmt); } else { pStmt->FreeQuery(); // if there isn't a matching adm_a3 code in the temp // database try to get the sovereign state instead stmt = QString("SELECT * FROM temp WHERE sov_a3=\""+ sov_a3 + "\";"); pStmt->Sql(stmt.toStdString()); if(pStmt->FetchRow()) { QString sov_idx = QString::number(pStmt->GetColumnInt("id")); pStmt->FreeQuery(); // since there's no true corresponding entry for // the admin1 region through the adm_a3 code, we // can't test for disputed regions QString admin1_disputed = "0"; // to indicate that no admin0 region data exists // for this entry, we use an index of value -1 QString admin0_idx = "-1"; stmt = QString("INSERT INTO admin1(id,name,disputed,admin0,sov) VALUES(" + admin1_idx + ",\"" + admin1_name + "\"," + admin1_disputed + "," + admin0_idx + "," + sov_idx + ");"); listSqlSaveAdmin1.push_back(stmt); } else { // fail without a matching adm_a3 or sov_a3 pStmt->FreeQuery(); return false; } } } // populate the admin0 and sov tables { QString stmt("SELECT * FROM temp;"); pStmt->Sql(stmt.toStdString()); while(pStmt->FetchRow()) { QString idx = QString::number(pStmt->GetColumnInt("id"),10); QString admin0_name = QString::fromStdString(pStmt->GetColumnString("adm_name")); QString sov_name = QString::fromStdString(pStmt->GetColumnString("sov_name")); stmt = QString("INSERT INTO sov(id,name) VALUES("+ idx + ",\"" + sov_name + "\");"); listSqlSaveSov.push_back(stmt); stmt = QString("INSERT INTO admin0(id,name) VALUES("+ idx + ",\"" + admin0_name + "\");"); listSqlSaveAdmin0.push_back(stmt); } pStmt->FreeQuery(); } // write prepared statements pStmt->BeginTransaction(); for(int i=0; i < listSqlSaveSov.size(); i++) { pStmt->SqlStatement(listSqlSaveSov[i].toUtf8().data()); } pStmt->CommitTransaction(); pStmt->BeginTransaction(); for(int i=0; i < listSqlSaveAdmin0.size(); i++) { pStmt->SqlStatement(listSqlSaveAdmin0[i].toUtf8().data()); } pStmt->CommitTransaction(); pStmt->BeginTransaction(); for(int i=0; i < listSqlSaveAdmin1.size(); i++) { pStmt->SqlStatement(listSqlSaveAdmin1[i].toUtf8().data()); } pStmt->CommitTransaction(); } // delete temp table pStmt->SqlStatement("DROP TABLE temp;"); return true; }
bool vtVegLayer::OnLoad() { vtSpeciesList *plants = g_bld->GetSpeciesList(); if (plants->NumSpecies() == 0) { DisplayAndLog(_("You must specify a species file (plant list) to use when working with vegetation files.")); return false; } wxString fname = GetLayerFilename(); wxString ext = fname.Right(3); wxString dbfname = fname.Left(fname.Length() - 4); dbfname += _T(".dbf"); if (!ext.CmpNoCase(_T(".vf"))) { // read VF file SetVegType(VLT_Instances); GetPIA()->SetSpeciesList(plants); if (GetPIA()->ReadVF(fname.mb_str(wxConvUTF8))) { m_pSet->SetFilename((const char *)fname.mb_str(wxConvUTF8)); return true; } else { delete m_pSet; m_pSet = NULL; m_VLType = VLT_None; return false; } } else if (!ext.CmpNoCase(_T("shp"))) { // SHPOpen doesn't yet support utf-8 or wide filenames, so convert vtString fname_local = UTF8ToLocal(fname.mb_str(wxConvUTF8)); // Study this SHP file, look at what it might be int nElems, nShapeType; SHPHandle hSHP = SHPOpen(fname_local, "rb"); if (hSHP == NULL) return false; SHPGetInfo(hSHP, &nElems, &nShapeType, NULL, NULL); SHPClose(hSHP); if (nShapeType == SHPT_POINT) SetVegType(VLT_Instances); else if (nShapeType == SHPT_POLYGON) { // DBFOpen doesn't yet support utf-8 or wide filenames, so convert vtString fname_localdbf = UTF8ToLocal(dbfname.mb_str(wxConvUTF8)); DBFHandle db = DBFOpen(fname_localdbf, "rb"); if (db == NULL) return false; m_field_density = DBFGetFieldIndex(db, "Density"); m_field_biotype = DBFGetFieldIndex(db, "Biotype"); DBFClose(db); if (m_field_density != -1) SetVegType(VLT_Density); else if (m_field_biotype != -1) SetVegType(VLT_BioMap); else return false; } // OK, read the rest of the file return m_pSet->LoadFromSHP(fname.mb_str(wxConvUTF8)); } // don't know this file return false; }
int main( int argc, char ** argv ) { SHPHandle iSHP; DBFHandle iDBF; SHPHandle jSHP; DBFHandle jDBF; int i, j, k; int iEntities, jEntities; int iRecord, jRecord; int scanAhead; /* -------------------------------------------------------------------- */ /* Display a usage message. */ /* -------------------------------------------------------------------- */ if( argc != 3 ) { printf( "shpdiff original_shapefile comparison_shapefile\n" ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Open the passed shapefile parts */ /* -------------------------------------------------------------------- */ iSHP = SHPOpen( argv[1], "rb" ); if( iSHP == NULL ) { printf( "Unable to find shapefile \"%s\"\n", argv[1] ); exit( 1 ); } iDBF = DBFOpen( argv[1], "rb" ); if( iDBF == NULL ) { printf( "Unable to find shapefile \"%s\"\n", argv[1] ); exit( 1 ); } if( DBFGetFieldCount(iDBF) == 0 ) { printf( "There are no fields in table %s!\n", argv[1] ); exit( 3 ); } jSHP = SHPOpen( argv[2], "rb" ); if( jSHP == NULL ) { printf( "Unable to find shapefile \"%s\"\n", argv[2] ); exit( 1 ); } jDBF = DBFOpen( argv[2], "rb" ); if( jDBF == NULL ) { printf( "Unable to find shapefile \"%s\"\n", argv[2] ); exit( 1 ); } if( DBFGetFieldCount(jDBF) == 0 ) { printf( "There are no fields in table %s!\n", argv[2] ); exit( 3 ); } /* -------------------------------------------------------------------- */ /* Print out some useful data about each shapefile */ /* -------------------------------------------------------------------- */ printf("Original "); printHeader( iDBF, iSHP ); printf("Comparison "); printHeader( jDBF, jSHP ); printf("\n"); /* -------------------------------------------------------------------- */ /* Guess which column headering might best identify each record */ /* -------------------------------------------------------------------- */ identifyKey = DBFGetFieldIndex( iDBF, "NAME" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = DBFGetFieldIndex( iDBF, "STREET" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = DBFGetFieldIndex( iDBF, "TOWN" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = DBFGetFieldIndex( iDBF, "ID" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = DBFGetFieldIndex( iDBF, "STATION" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = DBFGetFieldIndex( iDBF, "LINE" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = DBFGetFieldIndex( iDBF, "TRAILNAME" ); if( identifyKey >= 0 ) goto gotkey; identifyKey = -1; gotkey: /* -------------------------------------------------------------------- */ /* Match up column indexes between the shapefiles */ /* -------------------------------------------------------------------- */ { int i, temp; int nWidth, nDecimals; char szTitle[12]; if(identifyKey) { DBFGetFieldInfo( iDBF, identifyKey, szTitle, &nWidth, &nDecimals ); printf("NOTE: Using column %s to identify records\n", szTitle); } for( i = 0; i < DBFGetFieldCount(iDBF); i++ ) { DBFGetFieldInfo( iDBF, i, szTitle, &nWidth, &nDecimals ); columnMatchArray[i] = DBFGetFieldIndex( jDBF, szTitle ); if( columnMatchArray[i] < 0 ) { printf("WARNING: Column %s deleted from original\n", szTitle); } } for( i = 0; i < DBFGetFieldCount(jDBF); i++ ) { DBFGetFieldInfo( jDBF, i, szTitle, &nWidth, &nDecimals ); if( DBFGetFieldIndex( iDBF, szTitle ) < 0 ) { printf("WARNING: Column \"%s\" was added\n", szTitle); } } // Eliminate certain columns from the comparison temp = DBFGetFieldIndex( jDBF, "LENGTH" ); if( temp >= 0 ) { columnMatchArray[temp] = -1; printf("WARNING: Ingoring column \"%s\"\n", "LENGTH"); } temp = DBFGetFieldIndex( jDBF, "FNODE_" ); if( temp >= 0 ) { columnMatchArray[temp] = -1; printf("WARNING: Ingoring column \"%s\"\n", "FNODE"); } temp = DBFGetFieldIndex( jDBF, "TNODE_" ); if( temp >= 0 ) { columnMatchArray[temp] = -1; printf("WARNING: Ingoring column \"%s\"\n", "TNODE_"); } temp = DBFGetFieldIndex( jDBF, "AREA" ); if( temp >= 0 ) { columnMatchArray[temp] = -1; printf("WARNING: Ingoring column \"%s\"\n", "AREA"); } } /* -------------------------------------------------------------------- */ /* Main loop */ /* -------------------------------------------------------------------- */ scanAhead= SCAN_AHEAD; iRecord = 0; jRecord = 0; iEntities = DBFGetRecordCount(iDBF); jEntities = DBFGetRecordCount(jDBF); while( (iRecord < iEntities) || (jRecord < jEntities) ) { int shpDiff; int dbfDiff; int keyDiff; //printf("iRecord %d jRecord %d\n", iRecord, jRecord); /* Print out any extra records at the end of either file */ if( iRecord == iEntities ) { while( jRecord < jEntities ) { printf("\nNew record %d found\n", jRecord); printf("-------------------------------"); printDBF(jDBF, jRecord); jRecord++; } goto end; } if( jRecord == jEntities ) { while( iRecord < iEntities ) { printf("\nRecord %d: deleted from original\n", iRecord); printf("--------------------------------"); printDBF(iDBF, iRecord); iRecord++; } goto end; } shpDiff = compareSHP (iSHP, iRecord, jSHP, jRecord, false); dbfDiff = compareDBF (iDBF, iRecord, jDBF, jRecord, false); keyDiff = compareDBFkey(iDBF, iRecord, jDBF, jRecord, false); //printf("Compare iRecord=%d jRecord=%d: shpDiff=%d dbfDiff=%d keyDiff=%d\n", // iRecord, jRecord, shpDiff, dbfDiff, keyDiff); /* If everything is the same, skip ahead */ if( !shpDiff && !dbfDiff && !keyDiff ) { iRecord++; jRecord++; goto end; } /* If the primary key record is different, * and the shape has also changed, scan ahead for a better match */ if ( keyDiff ) { for( i=1; (i<scanAhead) && (iRecord+i < iEntities); i++ ) { shpDiff = compareSHP (iSHP, iRecord+i, jSHP, jRecord, false); dbfDiff = compareDBF (iDBF, iRecord+i, jDBF, jRecord, false); keyDiff = compareDBFkey(iDBF, iRecord+i, jDBF, jRecord, false); //printf("Scan iRecord=%d jRecord=%d: shpDiff=%d dbfDiff=%d keyDiff=%d\n", // iRecord+i, jRecord, shpDiff, dbfDiff, keyDiff); if ( !shpDiff || !dbfDiff ) { for( j=0; j<i; j++ ) { printf("\nRecord %d: deleted from original\n", iRecord); printf("--------------------------------"); printDBF(iDBF, iRecord); iRecord++; } goto end; } } /* We can't find any match, call it a "new" record */ printf("\nNew record %d found\n", jRecord); printf("-------------------------------"); printDBF(jDBF, jRecord); jRecord++; goto end; } /* Either the shape or the primary key match exactly, show a change record */ printf("\nRecord %d:", iRecord); if( identifyKey ) printf(" (%s) ", DBFReadStringAttribute( iDBF, iRecord, identifyKey )); if( shpDiff ) printf("shape change\n"); else printf("\n"); if( dbfDiff ) { compareDBF(iDBF, iRecord, jDBF, jRecord, true); } iRecord++; jRecord++; end:; } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ SHPClose( iSHP ); DBFClose( iDBF ); SHPClose( jSHP ); DBFClose( jDBF ); #ifdef USE_DBMALLOC malloc_dump(2); #endif exit( 0 ); }
char* darxen_shapefiles_filter_shp(DarxenShapefile* shapefile, int dataLevel, const char* site, float latCenter, float lonCenter, float radius) { GSList* lstNewDBFs = NULL; GSList* lstNewSHPs = NULL; DBFHandle hDBF; SHPHandle hSHP; SHPHandle hNewSHP = NULL; DBFHandle hNewDBF = NULL; int pnEntities; int pnShapeType; int i; SHPObject *psObject = NULL; char* filteredPath; g_assert(shapefile->file); g_assert(!shapefile->dataLevels || shapefile->dataLevels->field); g_assert(!shapefile->dataLevels || (dataLevel >= 0 && dataLevel < g_slist_length(shapefile->dataLevels->levels))); gchar* gfilteredFile; if (shapefile->dataLevels) gfilteredFile = g_strdup_printf("%s_%s_%i", shapefile->file, site, dataLevel); else gfilteredFile = g_strdup_printf("%s_%s", shapefile->file, site); gchar* gfilteredPath = g_build_filename(darxen_file_support_get_app_path(), "shapefiles", "cache", gfilteredFile, NULL); filteredPath = strdup(gfilteredPath); g_free(gfilteredFile); g_free(gfilteredPath); //don't recreate the file, just return the path gchar* shpFile = g_strdup_printf("%s.shp", filteredPath); gchar* dbfFile = g_strdup_printf("%s.dbf", filteredPath); if (g_file_test(shpFile, G_FILE_TEST_EXISTS) && g_file_test(dbfFile, G_FILE_TEST_EXISTS)) { g_free(shpFile); g_free(dbfFile); return filteredPath; } g_free(shpFile); g_free(dbfFile); gchar* pathPart = g_strdup_printf("%s.shp", shapefile->file); gchar* pathPart2 = g_build_filename("shapefiles", pathPart, NULL); gchar* shapefilePath = darxen_file_support_get_overridable_file_path(pathPart2); //g_build_filename(darxen_file_support_get_app_path(), "shapefiles", shapefile->file, NULL); g_free(pathPart); g_free(pathPart2); g_assert(shapefilePath); shapefilePath[strlen(shapefilePath)-4] = '\0'; hSHP = SHPOpen(shapefilePath, "rb"); if (!hSHP) { g_free(shapefilePath); g_critical("Invalid shapefile path: %s", shapefile->file); return NULL; } hDBF = DBFOpen(shapefilePath, "rb"); if (!hDBF) { g_free(shapefilePath); g_critical("Invalid shapefile dbf path: %s", shapefile->file); return NULL; } g_free(shapefilePath); int dbfCount = DBFGetRecordCount(hDBF); SHPGetInfo(hSHP, &pnEntities, &pnShapeType, NULL, NULL); if (dbfCount != pnEntities) { g_critical("dbf and shp have a differing number of records!"); SHPClose(hSHP); DBFClose(hDBF); return NULL; } if (shapefile->dataLevels) { GSList* pLevel = shapefile->dataLevels->levels; i = 0; while (pLevel) { gfilteredFile = g_strdup_printf("%s_%s_%i", shapefile->file, site, i); gfilteredPath = g_build_filename(darxen_file_support_get_app_path(), "shapefiles", "cache", gfilteredFile, NULL); hNewDBF = DBFCreate(gfilteredPath); hNewSHP = SHPCreate(gfilteredPath, pnShapeType); if (!hNewDBF || !hNewSHP || !create_required_fields(shapefile, hDBF, hNewDBF)) { SHPClose(hSHP); DBFClose(hDBF); if (hNewDBF) DBFClose(hNewDBF); if (hNewSHP) SHPClose(hNewSHP); GSList* plstNewDBFs = lstNewDBFs; while (plstNewDBFs) { DBFClose((DBFHandle)plstNewDBFs->data); plstNewDBFs = plstNewDBFs->next; } g_slist_free(lstNewDBFs); GSList* plstNewSHPs = lstNewSHPs; while (plstNewSHPs) { SHPClose((SHPHandle)plstNewSHPs->data); plstNewSHPs = plstNewSHPs->next; } g_slist_free(lstNewSHPs); g_critical("Unable to create filtered shapefile lists: (level %i)", i); return NULL; } lstNewDBFs = g_slist_append(lstNewDBFs, hNewDBF); lstNewSHPs = g_slist_append(lstNewSHPs, hNewSHP); g_free(gfilteredPath); g_free(gfilteredFile); i++; pLevel = pLevel->next; } hNewDBF = NULL; hNewSHP = NULL; } else { hNewSHP = SHPCreate(filteredPath, pnShapeType); if (!hNewSHP) { SHPClose(hSHP); DBFClose(hDBF); g_critical("Unable to create filtered shapefile: %s", filteredPath); return NULL; } hNewDBF = DBFCreate(filteredPath); if (!hNewDBF || !create_required_fields(shapefile, hDBF, hNewDBF)) { SHPClose(hSHP); DBFClose(hDBF); SHPClose(hNewSHP); g_critical("Unable to create filtered dbf shapefile: %s", filteredPath); return NULL; } } float filterRegionX1 = lonCenter - radius; float filterRegionX2 = lonCenter + radius; float filterRegionY1 = latCenter - radius; float filterRegionY2 = latCenter + radius; for (i = 0; i < pnEntities; i++) { psObject = SHPReadObject(hSHP, i); if (((filterRegionX1 >= psObject->dfXMin && filterRegionX1 <= psObject->dfXMax) || (filterRegionX2 >= psObject->dfXMin && filterRegionX2 <= psObject->dfXMax) || (psObject->dfXMin >= filterRegionX1 && psObject->dfXMin <= filterRegionX2) || (psObject->dfXMax >= filterRegionX1 && psObject->dfXMax <= filterRegionX2)) && ((filterRegionY1 >= psObject->dfYMin && filterRegionY1 <= psObject->dfYMax) || (filterRegionY2 >= psObject->dfYMin && filterRegionY2 <= psObject->dfYMax) || (psObject->dfYMin >= filterRegionY1 && psObject->dfYMin <= filterRegionY2) || (psObject->dfYMax >= filterRegionY1 && psObject->dfYMax <= filterRegionY2))) { psObject->nShapeId = -1; if (shapefile->dataLevels) { int fieldIndex = DBFGetFieldIndex(hDBF, shapefile->dataLevels->field); GSList* pDataLevels = shapefile->dataLevels->levels; GSList* pLstNewSHPs = lstNewSHPs; GSList* pLstNewDBFs = lstNewDBFs; while (pDataLevels) { DarxenShapefileDataLevel* level = (DarxenShapefileDataLevel*)pDataLevels->data; hNewSHP = (SHPHandle)pLstNewSHPs->data; hNewDBF = (DBFHandle)pLstNewDBFs->data; double value = DBFReadDoubleAttribute(hDBF, i, fieldIndex); gboolean cond; switch (shapefile->dataLevels->comparisonType) { case DATALEVELS_COMPARISON_TYPE_MIN: cond = (level->value < value); break; case DATALEVELS_COMPARISON_TYPE_MAX: cond = (level->value > value); break; default: g_warning("Invalid comparison type: %i", shapefile->dataLevels->comparisonType); cond = TRUE; } if (cond) { int index = SHPWriteObject(hNewSHP, -1, psObject); write_fields(shapefile, i, index, hDBF, hNewDBF); break; } pDataLevels = pDataLevels->next; pLstNewDBFs = pLstNewDBFs->next; pLstNewSHPs = pLstNewSHPs->next; } hNewDBF = NULL; hNewSHP = NULL; } else { int index = SHPWriteObject(hNewSHP, -1, psObject); write_fields(shapefile, i, index, hDBF, hNewDBF); } } SHPDestroyObject(psObject); } SHPClose(hSHP); DBFClose(hDBF); if (hNewDBF) DBFClose(hNewDBF); if (hNewSHP) SHPClose(hNewSHP); GSList* plstNewDBFs = lstNewDBFs; while (plstNewDBFs) { DBFClose((DBFHandle)plstNewDBFs->data); plstNewDBFs = plstNewDBFs->next; } g_slist_free(lstNewDBFs); GSList* plstNewSHPs = lstNewSHPs; while (plstNewSHPs) { SHPClose((SHPHandle)plstNewSHPs->data); plstNewSHPs = plstNewSHPs->next; } g_slist_free(lstNewSHPs); // g_assert(g_file_test(filteredPath, G_FILE_TEST_EXISTS)); return filteredPath; }
shapefiles = g_list_reverse(shapefiles); xmlXPathFreeContext(xpath); xmlFreeDoc(doc); } static gboolean create_field(char* name, DBFHandle base, DBFHandle new) { int field; char fieldName[12]; int fieldWidth; int fieldDecimals; DBFFieldType fieldType; field = DBFGetFieldIndex(base, name); if (field < 0) { g_critical("Invalid shapefile field name: %s", name); return FALSE; } fieldType = DBFGetFieldInfo(base, field, fieldName, &fieldWidth, &fieldDecimals); DBFAddField(new, fieldName, fieldType, fieldWidth, fieldDecimals); return TRUE; } static gboolean create_required_fields(DarxenShapefile* shapefile, DBFHandle base, DBFHandle new) { if (shapefile->textLabels)
bool _curv_save_shp(const d_curv * contour, const char * filename) { if (!contour->getName()) writelog(LOG_MESSAGE,"saving curv to ERSI shape file %s", filename); else writelog(LOG_MESSAGE,"saving curv \"%s\" to ERSI shape file %s", contour->getName(), filename); if (!contour) { writelog(LOG_WARNING, "NULL pointer to curv."); return false; }; DBFHandle hDBF; SHPHandle hSHP; hSHP = SHPOpen( filename, "rb+" ); hDBF = DBFOpen( filename, "rb+" ); if (hSHP == NULL || hDBF == NULL) { if (hSHP) SHPClose( hSHP ); if (hDBF) DBFClose( hDBF ); hSHP = SHPCreate( filename, SHPT_ARC ); if( hSHP == NULL ) { writelog(LOG_ERROR, "Unable to create:%s", filename ); return false; } hDBF = DBFCreate( filename ); } int shpType; SHPGetInfo(hSHP, NULL, &shpType, NULL, NULL); if (shpType != SHPT_ARC) { writelog(LOG_ERROR, "%s : Wrong shape type! Should be SHPT_ARC.", filename); SHPClose( hSHP ); DBFClose( hDBF ); return false; } int name_field = DBFGetFieldIndex( hDBF, "NAME" ); if (name_field == -1) { if( DBFAddField( hDBF, "NAME", FTString, 50, 0 ) == -1 ) { writelog(LOG_ERROR, "DBFAddField(%s,FTString) failed.", "NAME"); SHPClose( hSHP ); DBFClose( hDBF ); return false; } name_field = DBFGetFieldIndex( hDBF, "NAME" ); }; std::vector<REAL> data_x(contour->size()); std::vector<REAL> data_y(contour->size()); std::copy(contour->X->begin(), contour->X->end(), data_x.begin()); std::copy(contour->Y->begin(), contour->Y->end(), data_y.begin()); SHPObject * psObject = SHPCreateObject(SHPT_ARC, -1, 0, NULL, NULL, contour->size(), &*(data_x.begin()), &*(data_y.begin()), NULL, NULL); SHPComputeExtents(psObject); int pos = SHPWriteObject(hSHP, -1, psObject); SHPDestroyObject(psObject); if (contour->getName()) DBFWriteStringAttribute(hDBF, pos, name_field, contour->getName() ); SHPClose( hSHP ); DBFClose( hDBF ); return true; };
bool _curv_load_shp(const char * filename, const char * curvname) { SHPHandle hSHP; DBFHandle hDBF; hSHP = SHPOpen(filename, "rb"); if( hSHP == NULL ) { writelog(LOG_ERROR, "Unable to open:%s", filename ); return false; } int shpType; int Entities; SHPGetInfo(hSHP, &Entities, &shpType, NULL, NULL); if (shpType != SHPT_ARC) { SHPClose( hSHP ); writelog(LOG_ERROR, "%s : Wrong shape type! Should be SHTP_ARC.", filename); return false; } hDBF = DBFOpen(filename, "rb"); if( hDBF == NULL ) { SHPClose(hSHP); writelog(LOG_ERROR, "Unable to open DBF for %s", filename ); return false; } int name_field = DBFGetFieldIndex( hDBF, "NAME" ); int dbf_records = DBFGetRecordCount( hDBF ); Entities = MIN(dbf_records, Entities); int i, j; for (i = 0; i < Entities; i++) { SHPObject * shpObject = SHPReadObject( hSHP, i ); if (shpObject->nParts != 1) { SHPDestroyObject(shpObject); continue; } const char * name = NULL; if (name_field != -1) name = DBFReadStringAttribute( hDBF, i, name_field ); if (curvname != NULL) { if ( StringMatch(curvname, name) == false ) continue; } writelog(LOG_MESSAGE,"loading curve \"%s\" from ESRI shape file %s", name?name:"noname",filename); vec * X = create_vec(shpObject->nVertices,0,0); vec * Y = create_vec(shpObject->nVertices,0,0); for (j = 0; j < shpObject->nVertices; j++) { (*X)(j) = *(shpObject->padfX + j); (*Y)(j) = *(shpObject->padfY + j); } d_curv * res = create_curv(X, Y, name); surfit_curvs->push_back(res); } DBFClose( hDBF ); SHPClose( hSHP ); return true; };
void dibSHP::procesFile(Document_Interface *doc) { int num_ent, st; double min_bound[4], max_bound[4]; currDoc = doc; QFileInfo fi = QFileInfo(fileedit->text()); if (fi.suffix() != "shp") { QMessageBox::critical ( this, "Shapefile", QString(tr("The file %1 not have extension .shp")).arg(fileedit->text()) ); return; } if (!fi.exists() ) { QMessageBox::critical ( this, "Shapefile", QString(tr("The file %1 not exist")).arg(fileedit->text()) ); return; } QString file = fi.canonicalFilePath (); SHPHandle sh = SHPOpen( file.toLocal8Bit(), "rb" ); SHPGetInfo( sh, &num_ent, &st, min_bound, max_bound ); DBFHandle dh = DBFOpen( file.toLocal8Bit(), "rb" ); if (radiolay1->isChecked()) { layerF = -1; attdata.layer = currDoc->getCurrentLayer(); } else { layerF = DBFGetFieldIndex( dh, (layerdata->currentText()).toLatin1().data() ); layerT = DBFGetFieldInfo( dh, layerF, NULL, NULL, NULL ); } if (radiocol1->isChecked()) colorF = -1; else { colorF = DBFGetFieldIndex( dh, (colordata->currentText()).toLatin1().data() ); colorT = DBFGetFieldInfo( dh, colorF, NULL, NULL, NULL ); } if (radioltype1->isChecked()) ltypeF = -1; else { ltypeF = DBFGetFieldIndex( dh, (ltypedata->currentText()).toLatin1().data() ); ltypeT = DBFGetFieldInfo( dh, ltypeF, NULL, NULL, NULL ); } if (radiolwidth1->isChecked()) lwidthF = -1; else { lwidthF = DBFGetFieldIndex( dh, (lwidthdata->currentText()).toLatin1().data() ); lwidthT = DBFGetFieldInfo( dh, lwidthF, NULL, NULL, NULL ); } if (radiopoint1->isChecked()) pointF = -1; else { pointF = DBFGetFieldIndex( dh, (pointdata->currentText()).toLatin1().data() ); pointT = DBFGetFieldInfo( dh, pointF, NULL, NULL, NULL ); } currlayer =currDoc->getCurrentLayer(); for( int i = 0; i < num_ent; i++ ) { sobject= NULL; sobject = SHPReadObject( sh, i ); if (sobject) { switch (sobject->nSHPType) { case SHPT_NULL: break; case SHPT_POINT: case SHPT_POINTM: //2d point with measure case SHPT_POINTZ: //3d point readPoint(dh, i); break; case SHPT_MULTIPOINT: case SHPT_MULTIPOINTM: case SHPT_MULTIPOINTZ: break; case SHPT_ARC: case SHPT_ARCM: case SHPT_ARCZ: readPolyline(dh, i); break; case SHPT_POLYGON: case SHPT_POLYGONM: case SHPT_POLYGONZ: readPolylineC(dh, i); case SHPT_MULTIPATCH: readMultiPolyline(dh, i); default: break; } SHPDestroyObject(sobject); } } SHPClose( sh ); DBFClose( dh ); currDoc->setLayer(currlayer); }
/** * Works when tree tops are being found in a partition of the original image because padding * isn't done. */ int checkPixelPart(float **gridded, float **orig, int i, int j, int wnd_size, int wnd_sqrd, double * mpsData, double ulEasting, double ulNorthing, SHPHandle hshp, DBFHandle hdbf) { int ii, jj, half, count = 0, maxi, maxj, nrecords; float max, height; height = gridded[i][j]; half = (wnd_size - 1)/2; for(ii = i - half; ii <= i + half; ii++) for(jj = j - half; jj <= j + half; jj++) if(gridded[ii][jj] < height) count++; if(count < wnd_sqrd-1) { // not the highest tree in the window return 1; } //find the highest point in the original data set maxi = i-1, maxj = j-1; max = orig[i-1][j-1]; for(jj = j - 1; jj <= j + 1; jj++) for(ii = i - 1; ii <= i + 1; ii++) if(orig[ii][jj] > max) { max = orig[ii][jj]; maxi = ii; maxj = jj; } // //Write point to shape file. // SHPObject * shape; double * xpts, * ypts, * zpts; xpts = (double *) malloc(sizeof(double)); ypts = (double *) malloc(sizeof(double)); zpts = (double *) malloc(sizeof(double)); xpts[0] = ulEasting + maxj * mpsData[0]; ypts[0] = ulNorthing - maxi * mpsData[1]; zpts[0] = (double)max; shape = SHPCreateSimpleObject(SHPT_POINT, 1, xpts, ypts, zpts); if(!shape){ PyErr_SetString(PyExc_Exception, "SHPCreateSimpleObject failed."); return 0; } SHPWriteObject(hshp, -1, shape); SHPGetInfo(hshp, &nrecords, NULL, NULL, NULL); DBFWriteDoubleAttribute( hdbf, nrecords-1, DBFGetFieldIndex(hdbf, "Height"), (double)max ); //DBFWriteNULLAttribute( // hdbf, // nrecords-1, // DBFGetFieldIndex(hdbf, "TC Index") //); SHPDestroyObject(shape); free(xpts);free(ypts); return 1; }
d_points * _pnts_load_shp(const char * filename, const char * pntsname, const char * param) { SHPHandle hSHP; DBFHandle hDBF; hSHP = SHPOpen(filename, "rb"); if( hSHP == NULL ) { writelog(LOG_ERROR, "Unable to open:%s", filename ); return NULL; } int shpType; int Entities; SHPGetInfo(hSHP, &Entities, &shpType, NULL, NULL); if (shpType != SHPT_POINT) { SHPClose( hSHP ); writelog(LOG_ERROR, "%s : Wrong shape type!", filename); return NULL; } hDBF = DBFOpen(filename, "rb"); if( hDBF == NULL ) { SHPClose(hSHP); writelog(LOG_ERROR, "Unable to open DBF for %s", filename ); return NULL; } int name_field = DBFGetFieldIndex( hDBF, "NAME" ); if (name_field == -1) writelog(LOG_WARNING,"can't find field named \"NAME\""); int val_field = DBFGetFieldIndex( hDBF, param ); if (val_field == -1) writelog(LOG_WARNING, "Cannot find parameter \"%s\" in DBF file", param); int dbf_records = DBFGetRecordCount( hDBF ); Entities = MIN(dbf_records, Entities); vec * X = create_vec(Entities, 0, 0); vec * Y = create_vec(Entities, 0, 0); int i; for (i = 0; i < Entities; i++) { SHPObject * shpObject = SHPReadObject( hSHP, i ); if (shpObject == NULL) continue; const char * name = NULL; if (name_field != -1) { name = DBFReadStringAttribute( hDBF, i, name_field ); if (pntsname != NULL) { if ( StringMatch(pntsname, name) == false ) continue; } } (*X)(i) = *(shpObject->padfX); (*Y)(i) = *(shpObject->padfY); SHPDestroyObject(shpObject); } vec * Z = create_vec(Entities, 0, 0); for (i = 0; i < Entities; i++) { if (val_field != -1) (*Z)(i) = DBFReadDoubleAttribute( hDBF, i, val_field ); else (*Z)(i) = 0; } DBFClose( hDBF ); SHPClose( hSHP ); char * fname = get_name(filename); d_points * res = create_points(X, Y, Z, fname); sstuff_free_char(fname); return res; };
bool _pnts_save_shp(const d_points * pnts, const char * filename) { if (!pnts) { writelog(LOG_WARNING, "NULL pointer to points."); return false; }; DBFHandle hDBF; SHPHandle hSHP; hSHP = SHPOpen( filename, "rb+" ); hDBF = DBFOpen( filename, "rb+" ); if (hSHP == NULL || hDBF == NULL) { if (hSHP) SHPClose( hSHP ); if (hDBF) DBFClose( hDBF ); hSHP = SHPCreate( filename, SHPT_POINT ); if( hSHP == NULL ) { writelog(LOG_ERROR, "Unable to create:%s", filename ); return false; } hDBF = DBFCreate( filename ); } int shpType; SHPGetInfo(hSHP, NULL, &shpType, NULL, NULL); if (shpType != SHPT_POINT) { writelog(LOG_ERROR, "%s : Wrong shape type!", filename); SHPClose( hSHP ); DBFClose( hDBF ); return false; } int name_field = DBFGetFieldIndex( hDBF, "NAME" ); int val_field = DBFGetFieldIndex( hDBF, "VALUE" ); if (name_field == -1) { if( DBFAddField( hDBF, "NAME", FTString, 50, 0 ) == -1 ) { writelog(LOG_ERROR, "DBFAddField(%s,FTString) failed.", "NAME"); SHPClose( hSHP ); DBFClose( hDBF ); return false; } name_field = DBFGetFieldIndex( hDBF, "NAME" ); } if (val_field == -1) { if( DBFAddField( hDBF, "VALUE", FTDouble, 50, 0 ) == -1 ) { writelog(LOG_ERROR, "DBFAddField(%s,FTString) failed.", "VALUE"); SHPClose( hSHP ); DBFClose( hDBF ); return false; } val_field = DBFGetFieldIndex( hDBF, "VALUE" ); } char buf[1024]; size_t i; for (i = 0; i < pnts->size(); i++) { double x = (*(pnts->X))(i); double y = (*(pnts->Y))(i); SHPObject * psObject = SHPCreateObject(SHPT_POINT, -1, 0, NULL, NULL, 1, &x, &y, NULL, NULL); SHPComputeExtents(psObject); int pos = SHPWriteObject(hSHP, -1, psObject); SHPDestroyObject(psObject); if (pnts->names) DBFWriteStringAttribute(hDBF, pos, name_field, (*(pnts->names))(i) ); else { sprintf(buf,"%d",(int)i); DBFWriteStringAttribute(hDBF, pos, name_field, buf ); } REAL val = (*(pnts->Z))(i); DBFWriteDoubleAttribute(hDBF, pos, val_field, val); } SHPClose( hSHP ); DBFClose( hDBF ); return true; };
int main(int argc, char *argv[]) { QCoreApplication myApp(argc, argv); // check input args QStringList inputArgs = myApp.arguments(); if(inputArgs.size() < 2) { qDebug() << "Error: No dbf directory: "; qDebug() << "Pass the dbf directory as an argument: "; qDebug() << "./dbf2sqlite /my/dbfdir"; return -1; } // filter shapefile types QStringList dbfFilterList; dbfFilterList << "*.dbf"; // check for all files QDir dbfDir = inputArgs[1]; QStringList dbfDirList = dbfDir.entryList(dbfFilterList, QDir::Files); // get all file paths QString fileDbf; for(int i=0; i < dbfDirList.size(); i++) { if(dbfDirList[i].contains(".dbf")) { fileDbf = dbfDir.absoluteFilePath(dbfDirList[i]); } } // open the database file DBFHandle hDBF = DBFOpen(fileDbf.toLocal8Bit().data(),"rb"); if(hDBF == NULL) { qDebug() << "Error: Could not open dbf file"; return -1; } // set fields to keep based on data type QStringList listFieldsToKeep; QString dbFileName; if(ADMIN0) { dbFileName = "admin0.sqlite"; listFieldsToKeep << "ADMIN" // administrative name of country << "ADM0_A3"; // 3 letter abbreviatesion of admin name } if(ADMIN1) { dbFileName = "admin1.sqlite"; listFieldsToKeep << "OBJECTID" << "NAME_1" // Admin1 region name << "VARNAME_1" // Admin1 alt name (not very reliable) << "NL_NAME_1" // Admin1 region name in national language (not reliable) << "Postal"; // 2 Letter Postal Code (not reliable) } // get number of fields in db size_t numRecords = 0; numRecords = DBFGetRecordCount(hDBF); if(numRecords > 0) { qDebug() << "Info: DBF file has" << numRecords << "records"; } else { qDebug() << "Error: DBF file has no records!"; return -1; } // create sqlite database qDebug() << "Info: Creating SQLite Database..."; Kompex::SQLiteDatabase * pDatabase = new Kompex::SQLiteDatabase(dbFileName.toStdString(), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,0); Kompex::SQLiteStatement * pStmt = new Kompex::SQLiteStatement(pDatabase); // create database schema (flat) if(ADMIN1) { qDebug() << "Info: Creating database schema for ADMIN1 profile"; pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS data(" "regionid INTEGER PRIMARY KEY NOT NULL UNIQUE," "name TEXT NOT NULL," "code TEXT);"); // regionid <-> internel shape/record id [integer] size_t idx_objectid = DBFGetFieldIndex(hDBF,"OBJECTID"); // name <-> NAME_1 [text] size_t idx_name = DBFGetFieldIndex(hDBF,"NAME_1"); // code <-> Postal [text] size_t idx_code = DBFGetFieldIndex(hDBF,"Postal"); qDebug() << "Info: Writing records to database..."; pStmt->BeginTransaction(); for(size_t i=0; i < numRecords; i++) { QString record_id = QString::number(i+1); QString record_name(DBFReadStringAttribute(hDBF,i,idx_name)); QString record_code(DBFReadStringAttribute(hDBF,i,idx_code)); QString inStmt = "INSERT INTO data(regionid,name,code) VALUES(\"" + record_id + "\",\"" +record_name + "\",\"" + record_code + "\");"; pStmt->SqlStatement(inStmt.toUtf8().data()); // qDebug() << record_name; if(i % 1000 == 0) { qDebug() << "Info: Wrote" << i+1 << "/" << numRecords << "records"; } } pStmt->CommitTransaction(); qDebug() << "Info: Done!"; } // close dbf file DBFClose(hDBF); // clean up database delete pStmt; delete pDatabase; return 0; }
OGRErr OGRShapeLayer::CreateField( OGRFieldDefn *poFieldDefn, int bApproxOK ) { CPLAssert( NULL != poFieldDefn ); int iNewField; if( !bUpdateAccess ) { CPLError( CE_Failure, CPLE_NotSupported, "Can't create fields on a read-only shapefile layer.\n"); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Normalize field name */ /* -------------------------------------------------------------------- */ char szNewFieldName[10 + 1]; char * pszTmp = NULL; int nRenameNum = 1; size_t nNameSize = strlen( poFieldDefn->GetNameRef() ); pszTmp = CPLScanString( poFieldDefn->GetNameRef(), MIN( nNameSize, 10) , TRUE, TRUE); strncpy(szNewFieldName, pszTmp, 10); szNewFieldName[10] = '\0'; if( !bApproxOK && ( DBFGetFieldIndex( hDBF, szNewFieldName ) >= 0 || !EQUAL(poFieldDefn->GetNameRef(),szNewFieldName) ) ) { CPLError( CE_Failure, CPLE_NotSupported, "Failed to add field named '%s'", poFieldDefn->GetNameRef() ); CPLFree( pszTmp ); return OGRERR_FAILURE; } while( DBFGetFieldIndex( hDBF, szNewFieldName ) >= 0 && nRenameNum < 10 ) sprintf( szNewFieldName, "%.8s_%.1d", pszTmp, nRenameNum++ ); while( DBFGetFieldIndex( hDBF, szNewFieldName ) >= 0 && nRenameNum < 100 ) sprintf( szNewFieldName, "%.8s%.2d", pszTmp, nRenameNum++ ); CPLFree( pszTmp ); pszTmp = NULL; if( DBFGetFieldIndex( hDBF, szNewFieldName ) >= 0 ) { CPLError( CE_Failure, CPLE_NotSupported, "Too many field names like '%s' when truncated to 10 letters " "for Shapefile format.", poFieldDefn->GetNameRef() );//One hundred similar field names!!? } if( !EQUAL(poFieldDefn->GetNameRef(),szNewFieldName) ) CPLError( CE_Warning, CPLE_NotSupported, "Normalized/laundered field name: '%s' to '%s'", poFieldDefn->GetNameRef(), szNewFieldName ); // Set field name with normalized value OGRFieldDefn oModFieldDefn(poFieldDefn); oModFieldDefn.SetName(szNewFieldName); /* -------------------------------------------------------------------- */ /* Add field to layer */ /* -------------------------------------------------------------------- */ if( oModFieldDefn.GetType() == OFTInteger ) { if( oModFieldDefn.GetWidth() == 0 ) iNewField = DBFAddField( hDBF, oModFieldDefn.GetNameRef(), FTInteger, 10,0); else iNewField = DBFAddField( hDBF, oModFieldDefn.GetNameRef(), FTInteger, oModFieldDefn.GetWidth(), 0 ); if( iNewField != -1 ) poFeatureDefn->AddFieldDefn( &oModFieldDefn ); } else if( oModFieldDefn.GetType() == OFTReal ) { if( oModFieldDefn.GetWidth() == 0 ) iNewField = DBFAddField( hDBF, oModFieldDefn.GetNameRef(), FTDouble, 24, 15 ); else iNewField = DBFAddField( hDBF, oModFieldDefn.GetNameRef(), FTDouble, oModFieldDefn.GetWidth(), oModFieldDefn.GetPrecision() ); if( iNewField != -1 ) poFeatureDefn->AddFieldDefn( &oModFieldDefn ); } else if( oModFieldDefn.GetType() == OFTString ) { if( oModFieldDefn.GetWidth() < 1 ) iNewField = DBFAddField( hDBF, oModFieldDefn.GetNameRef(), FTString, 80, 0 ); else iNewField = DBFAddField( hDBF, oModFieldDefn.GetNameRef(), FTString, oModFieldDefn.GetWidth(), 0 ); if( iNewField != -1 ) poFeatureDefn->AddFieldDefn( &oModFieldDefn ); } else if( oModFieldDefn.GetType() == OFTDate ) { iNewField = DBFAddNativeFieldType( hDBF, oModFieldDefn.GetNameRef(), 'D', 8, 0 ); if( iNewField != -1 ) poFeatureDefn->AddFieldDefn( &oModFieldDefn ); } else if( oModFieldDefn.GetType() == OFTDateTime ) { CPLError( CE_Warning, CPLE_NotSupported, "Field %s create as date field, though DateTime requested.\n", oModFieldDefn.GetNameRef() ); iNewField = DBFAddNativeFieldType( hDBF, oModFieldDefn.GetNameRef(), 'D', 8, 0 ); if( iNewField != -1 ) { oModFieldDefn.SetType( OFTDate ); poFeatureDefn->AddFieldDefn( &oModFieldDefn ); } } else { CPLError( CE_Failure, CPLE_NotSupported, "Can't create fields of type %s on shapefile layers.\n", OGRFieldDefn::GetFieldTypeName(oModFieldDefn.GetType()) ); return OGRERR_FAILURE; } if( iNewField != -1 ) { return OGRERR_NONE; } else { CPLError( CE_Failure, CPLE_AppDefined, "Can't create field %s in Shape DBF file, reason unknown.\n", oModFieldDefn.GetNameRef() ); return OGRERR_FAILURE; } }
/** * Create Delaunay shape files using Triangle. * @param argc is the number of arguments provided from the command line * (including the command name). * @param argv is an array of strings that contains the argc arguments. * @return An error code if something goes wrong or 0 if there was no error * during the conversion process. */ int main( int argc, char **argv ) { int error; char line[MAXLINE]; char wline[MAXLINE]; char *textpointer = NULL, *prev_textpointer = NULL; int nPolygons; int nShapeType, nEntities, nVertices, nParts, *panParts, i, j, iPart; int nNodes, nNodeRef; SHPObject *psCShape; int byRing = 1; char boolWriteShape; int nShapes = 0; double padfMinBound[4]; double padfMaxBound[4]; int nDcidIndex = -1; char *pDCID; /** * Vectors to calculate plane parameters */ double vector0[3]; double vector1[3]; /** * Plane parameters */ double a,b,c,d; /** * Slope of the plane */ double slope; /** * Elevation field (if provided) */ int nElevationField = -1; strcpy(vertex_line_name, ""); num_vertices = 0; /* parameter check */ if((((argc != 3)|| ((!str_is_shp(argv[1])||(!str_is_shp(argv[2]))))))&&((argc != 4)|| ((!str_is_shp(argv[1])||(!str_is_shp(argv[2])))))) { printf("shptriangle 0.1.0 (c) 2005,2006 Steffen Macke\n"); printf("usage: shptriangle input_shapefile delaunay_shapefile [elevationfield]\n"); exit(1); } remove_shp(argv[2]); hPointSHP = SHPOpen(argv[1], "rb" ); hPointDBF = DBFOpen(argv[1], "rb"); if(hPointSHP == NULL || hPointDBF == NULL ) { printf("FATAL ERROR: Unable to open input file:%s\n", argv[1] ); exit(1); } SHPGetInfo(hPointSHP, &nEntities, &nShapeType, padfMinBound, padfMaxBound); if(nShapeType != SHPT_POINT) { printf("FATAL ERROR: Input is not a point shapefile:%s\n", argv[1]); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } if(4 == argc) { nElevationField = DBFGetFieldIndex(hPointDBF, argv[3]); if(-1 == nElevationField) { printf("WARNING: Could not find elevation field '%s'.\n", argv[3]); } } if(nEntities > MAXNUMNODES) { printf("FATAL ERROR: Too many nodes. Please recompile.\n"); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } /** * \todo Dynamic filename */ hTextFile = fopen("shptriangle.node", "wt"); if(hTextFile == NULL) { printf("FATAL ERROR: Cannot open output file:%s\n", "shptriangle.node"); SHPClose(hPointSHP); DBFClose(hPointDBF); exit(1); } fprintf(hTextFile, "%d 2 0 0\n", nEntities); for(i=0; i<nEntities;i++) { psCShape = SHPReadObject(hPointSHP, i); fprintf(hTextFile, "%d %f %f\n", i+1, psCShape->dfXMin, psCShape->dfYMin); node_x[i] = psCShape->dfXMin; node_y[i] = psCShape->dfYMin; if(nElevationField > -1) { node_z[i] = DBFReadDoubleAttribute(hPointDBF, i, nElevationField); } else { node_z[i] = 0.0; } } fclose(hTextFile); SHPClose(hPointSHP); DBFClose(hPointDBF); system("triangle.exe -I shptriangle"); hTextFile = fopen("shptriangle.ele", "rt"); if(hTextFile == NULL) { printf("FATAL ERROR: Cannot open input file:%s\n", "shptriangle.ele"); exit(1); } if(fgets(line, MAXLINE, hTextFile) == NULL) { printf("FATAL ERROR: Reading first line of shptriangle.ele\n"); fclose(hTextFile); exit(1); } nPolygons = atoi(line); textpointer = strchr(line, ' '); num_vertices = atoi(textpointer); if(num_vertices != 3) { printf("FATAL ERROR: Wrong node count in first line of shptriangle.ele\n"); fclose(hTextFile); exit(1); } //printf("%s\n", line); if(num_vertices > MAXNUMNODES) { printf("FATAL ERROR: Too many nodes, please recompile: %d\n", num_vertices); fclose(hTextFile); exit(1); } //printf("%d nodes\n", num_vertices); //printf("%d polygons\n", nPolygons); hVoronoiSHP = SHPCreate(argv[2], SHPT_POLYGONZ); hVoronoiDBF = DBFCreate(argv[2]); hPointDBF = DBFOpen(argv[1], "rb"); if(hVoronoiSHP == NULL || hVoronoiDBF == NULL || hPointDBF == NULL) { fprintf(stderr, "FATAL ERROR: Unable to create file '%s'.\n", argv[2]); fclose(hTextFile); exit(1); } DBFAddField(hVoronoiDBF, "dc_id", FTString, 16, 0); DBFAddField(hVoronoiDBF, "slope", FTDouble, 16, 8); for(i=0; i < nPolygons; i++) { //printf("Polygon %d\n", i); if(fgets(line, MAXLINE, hTextFile) == NULL) { printf("FATAL ERROR: shptriangle.ele does not contain enough polygons.\n"); SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); exit(1); } nNodes = 0; textpointer = line; textpointer = strchr(strpbrk(line, "1234567890"), ' '); boolWriteShape = 1; for(j=0; j < num_vertices; j++) { textpointer = strpbrk(strchr(textpointer+1, ' '), "1234567890"); nNodes++; nNodeRef = atoi(textpointer); if((nNodeRef < 0)||(nNodeRef > nEntities)) { printf("FATAL ERROR: shptriangle.ele contains illegal node reference.\n"); SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); exit(1); } //printf("Node reference %d\n", nNodeRef); polygon_x[nNodes-1] = node_x[nNodeRef-1]; polygon_y[nNodes-1] = node_y[nNodeRef-1]; polygon_z[nNodes-1] = node_z[nNodeRef-1]; } if(boolWriteShape == 1) { nNodes++; polygon_x[nNodes-1] = polygon_x[0]; polygon_y[nNodes-1] = polygon_y[0]; polygon_z[nNodes-1] = polygon_z[0]; //printf("Polygon %d with %d nodes\n", i, nNodes); psCShape = SHPCreateSimpleObject( SHPT_POLYGONZ, nNodes, polygon_x, polygon_y, polygon_z ); SHPWriteObject(hVoronoiSHP, -1, psCShape); SHPDestroyObject(psCShape); DBFWriteStringAttribute(hVoronoiDBF, nShapes, 0, ""); /** * Calculate slope. * Plane equation 0 = a*x + b*y + c*z + d * Sea level plane 0 = 0*x + 0*y + 1*z - 0 */ vector0[0] = polygon_x[1] - polygon_x[0]; vector0[1] = polygon_y[1] - polygon_y[0]; vector0[2] = polygon_z[1] - polygon_z[0]; vector1[0] = polygon_x[2] - polygon_x[0]; vector1[1] = polygon_y[2] - polygon_y[0]; vector1[2] = polygon_z[2] - polygon_z[0]; /** * Use cross product to find plane equation. */ a = vector0[1] * vector1[2] - vector0[2] * vector1[1]; b = -(vector0[0] * vector1[2] - vector0[2] * vector1[0]); c = vector0[0] * vector1[1] - vector0[1] * vector1[0]; d = -(a * polygon_x[0] + b * polygon_y[0] + c * polygon_z[0]); /** * Calculate dihedral angle between sea level plane and triangle plane */ slope = acos(c/(sqrt(a*a+b*b+c*c)))/3.141592654*180; DBFWriteDoubleAttribute(hVoronoiDBF, nShapes, 1, slope); nShapes++; } } SHPClose(hVoronoiSHP); DBFClose(hVoronoiDBF); DBFClose(hPointDBF); fclose(hTextFile); }