int CDbfFile::DBFAddRecord(CStringArray* psDBFFieldValList) { DBFHandle hDBF; int i; int iRecord; int iNumField; if (psDBFFieldValList == NULL) iNumField = 0; else iNumField = psDBFFieldValList->GetSize(); // Open/Create the database. hDBF = DBFOpen("r+b" ); if( hDBF == NULL ) { printf("DBFOpen failed: %s", _szDBFName); return 1; } // Do we have the correct number of arguments? if( DBFGetFieldCount( hDBF ) != iNumField ) { CString sMsg; sMsg.Format("Received %d field(s), but require %d field(s).",iNumField,DBFGetFieldCount(hDBF)); printf("%s\n",sMsg); int i, iWidth, iDecimals; char psName[257]; for (i=0; i<DBFGetFieldCount(hDBF); i++) { DBFGetFieldInfo(hDBF,i,psName,&iWidth,&iDecimals); sMsg.Format("%d of %d) FieldName: %s Width: %d Decimals: %d",i+1,DBFGetFieldCount(hDBF),psName,iWidth,iDecimals); printf("%s\n",sMsg); } return 1; } iRecord = DBFGetRecordCount( hDBF ); /* -------------------------------------------------------------------- */ /* Loop assigning the new field values. */ /* -------------------------------------------------------------------- */ for( i = 0; i < DBFGetFieldCount(hDBF); i++ ) { if( DBFGetFieldInfo( hDBF, i, NULL, NULL, NULL ) == FTString ) DBFWriteStringAttribute(hDBF, iRecord, i, psDBFFieldValList->GetAt(i) ); else DBFWriteDoubleAttribute(hDBF, iRecord, i, atof(psDBFFieldValList->GetAt(i)) ); } /* -------------------------------------------------------------------- */ /* Close and cleanup. */ /* -------------------------------------------------------------------- */ DBFClose( hDBF ); return 0; }
bool ShpFilter::DoubleField3D::save(DBFHandle handle, int xFieldIndex, int yFieldIndex, int zFieldIndex) const { if (!handle || xFieldIndex < 0 || yFieldIndex < 0 || zFieldIndex < 0) { assert(false); return false; } for (size_t i=0; i<values.size(); ++i) { DBFWriteDoubleAttribute(handle,static_cast<int>(i),xFieldIndex,values[i].x); DBFWriteDoubleAttribute(handle,static_cast<int>(i),yFieldIndex,values[i].y); DBFWriteDoubleAttribute(handle,static_cast<int>(i),zFieldIndex,values[i].z); } return true; }
int main( int argc, char ** argv ) { DBFHandle hDBF; int i, iRecord; /* -------------------------------------------------------------------- */ /* Display a usage message. */ /* -------------------------------------------------------------------- */ if( argc < 3 ) { printf( "dbfadd xbase_file field_values\n" ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Create the database. */ /* -------------------------------------------------------------------- */ hDBF = DBFOpen( argv[1], "r+b" ); if( hDBF == NULL ) { printf( "DBFOpen(%s,\"rb+\") failed.\n", argv[1] ); exit( 2 ); } /* -------------------------------------------------------------------- */ /* Do we have the correct number of arguments? */ /* -------------------------------------------------------------------- */ if( DBFGetFieldCount( hDBF ) != argc - 2 ) { printf( "Got %d fields, but require %d\n", argc - 2, DBFGetFieldCount( hDBF ) ); exit( 3 ); } iRecord = DBFGetRecordCount( hDBF ); /* -------------------------------------------------------------------- */ /* Loop assigning the new field values. */ /* -------------------------------------------------------------------- */ for( i = 0; i < DBFGetFieldCount(hDBF); i++ ) { if( strcmp( argv[i+2], "" ) == 0 ) DBFWriteNULLAttribute(hDBF, iRecord, i ); else if( DBFGetFieldInfo( hDBF, i, NULL, NULL, NULL ) == FTString ) DBFWriteStringAttribute(hDBF, iRecord, i, argv[i+2] ); else DBFWriteDoubleAttribute(hDBF, iRecord, i, atof(argv[i+2]) ); } /* -------------------------------------------------------------------- */ /* Close and cleanup. */ /* -------------------------------------------------------------------- */ DBFClose( hDBF ); return( 0 ); }
bool ShpFilter::DoubleField::save(DBFHandle handle, int fieldIndex) const { if (!handle || fieldIndex < 0) { assert(false); return false; } for (size_t i=0; i<values.size(); ++i) DBFWriteDoubleAttribute(handle,static_cast<int>(i),fieldIndex,values[i]); return true; }
int writePoint(JNIEnv * env, SHPHandle hSHP, DBFHandle hDBF, int index, double latitude, double longitude, jstring name, jdouble height, int apples) { SHPObject *oSHP = SHPCreateSimpleObject(SHPT_POINT, 1, &longitude, &latitude, NULL); SHPWriteObject(hSHP, -1, oSHP); const char *nativeName = (*env)->GetStringUTFChars(env, name, 0); DBFWriteStringAttribute(hDBF, index, 0, nativeName); (*env)->ReleaseStringUTFChars(env, name, nativeName); DBFWriteDoubleAttribute(hDBF, index, 1, height); DBFWriteIntegerAttribute(hDBF, index, 2, apples); SHPDestroyObject(oSHP); return 0; }
// A partir del trazo, genera y guarda el vector correspondiente en formato SHAPE void vect::agregarShape(vector<Point2f> trazo, int altura, SHPHandle sh, transformGeo *objGeo, Point pA, DBFHandle dbf) { vector<Point2f> l; for(vector<Point2f>::iterator it = trazo.begin(); it != trazo.end(); ++it) { Point2f p = *it; double xi = pA.x+p.x-1.0; double yi = pA.y+p.y-1.0; double xp= objGeo->getX(xi, yi); double yp = objGeo->getY(xi, yi); Point2f pi = Point2f(xp,yp); l.push_back(pi); } SHPObject *objShp = toArc(l, altura); int polyid = SHPWriteObject(sh, -1, objShp); DBFWriteDoubleAttribute(dbf, polyid, 0, 0.0); cout<<polyid<<".,,"<<endl; SHPDestroyObject(objShp); }
void surfaceVectorField::WriteShapePoint(double xpt, double ypt, double spd, long dir, long view_dir, long map_dir) { long NumRecord; double zpt=0; SHPObject *pSHP; pSHP=SHPCreateObject(SHPT_POINT, -1, 0, NULL, NULL, 1, &xpt, &ypt, &zpt, NULL); SHPWriteObject(hSHP, -1, pSHP); SHPDestroyObject(pSHP); NumRecord = DBFGetRecordCount(hDBF); // DBFWriteDoubleAttribute(hDBF, NumRecord, 0, xpt); // DBFWriteDoubleAttribute(hDBF, NumRecord, 1, ypt); // DBFWriteIntegerAttribute(hDBF, NumRecord, 2, spd); // DBFWriteIntegerAttribute(hDBF, NumRecord, 3, dir); DBFWriteDoubleAttribute(hDBF, NumRecord, 0, spd); DBFWriteIntegerAttribute(hDBF, NumRecord, 1, dir); DBFWriteIntegerAttribute(hDBF, NumRecord, 2, view_dir); DBFWriteIntegerAttribute(hDBF, NumRecord, 3, map_dir); }
// --------------------------------------------------------------------------- // // ----------- int bDBFTable::WriteVal(int o, int f, void* val){ _bTrace_("bDBFTable::WriteVal",false); if(o==CountRecords()+1){ o=CountRecords(); } else{ o--; } int sgn; (void)FieldSign(f,&sgn); f--; switch(sgn){ case _int: if(!DBFWriteIntegerAttribute(_dbf,o,f,(*(int*)val))){ //_te_("DBFWriteIntegerAttribute "+f); return(-2); } break; case _double: if(!DBFWriteDoubleAttribute(_dbf,o,f,(*(double*)val))){ //_te_("DBFWriteDoubleAttribute "+f); return(-2); } break; case _char: if(!DBFWriteStringAttribute(_dbf,o,f,(char*)val)){ //_te_("DBFWriteStringAttribute "+f); return(-2); } break; default: _te_("bad kind"); return(-1); } return(0); }
int save_table(int t) { int i, j, ncols, nrows, ret, field, rec; char name[2000], fname[20], element[100]; DBFHandle dbf; ROW *rows; VALUE *val; int dbftype, width, decimals; G_debug(2, "save_table %d", t); /* Note: because if driver is killed during the time the table is written, the process * is not completed and DATA ARE LOST. To minimize this, data are first written * to temporary file and then this file is renamed to 'database/table.dbf'. * Hopefully both file are on the same disk/partition */ if (!(db.tables[t].alive) || !(db.tables[t].updated)) return DB_OK; /* Construct our temp name because shapelib doesn't like '.' in name */ G__temp_element(element); sprintf(fname, "%d.dbf", getpid()); G_file_name(name, element, fname, G_mapset()); G_debug(2, "Write table to tempfile: '%s'", name); dbf = DBFCreate(name); if (dbf == NULL) return DB_FAILED; ncols = db.tables[t].ncols; rows = db.tables[t].rows; nrows = db.tables[t].nrows; for (i = 0; i < ncols; i++) { switch (db.tables[t].cols[i].type) { case DBF_INT: dbftype = FTInteger; break; case DBF_CHAR: dbftype = FTString; break; case DBF_DOUBLE: dbftype = FTDouble; break; } width = db.tables[t].cols[i].width; decimals = db.tables[t].cols[i].decimals; DBFAddField(dbf, db.tables[t].cols[i].name, dbftype, width, decimals); } G_debug(2, "Write %d rows", nrows); rec = 0; for (i = 0; i < nrows; i++) { if (rows[i].alive == FALSE) continue; for (j = 0; j < ncols; j++) { field = j; val = &(rows[i].values[j]); if (val->is_null) { DBFWriteNULLAttribute(dbf, rec, field); } else { switch (db.tables[t].cols[j].type) { case DBF_INT: ret = DBFWriteIntegerAttribute(dbf, rec, field, val->i); break; case DBF_CHAR: if (val->c != NULL) ret = DBFWriteStringAttribute(dbf, rec, field, val->c); else ret = DBFWriteStringAttribute(dbf, rec, field, ""); break; case DBF_DOUBLE: ret = DBFWriteDoubleAttribute(dbf, rec, field, val->d); break; } } } rec++; } G_debug(2, "Written %d records", rec); DBFClose(dbf); /* Copy */ if (G_rename_file(name, db.tables[t].file)) { append_error("Cannot move %s\nto %s\n", name, db.tables[t].file); return DB_FAILED; }; return DB_OK; }
/** * 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; }
static int FindGeoLocPosition( GDALGeoLocTransformInfo *psTransform, double dfGeoX, double dfGeoY, int nStartX, int nStartY, double *pdfFoundX, double *pdfFoundY ) { double adfPathX[5000], adfPathY[5000]; if( psTransform->padfGeoLocX == NULL ) return FALSE; int nXSize = psTransform->nGeoLocXSize; int nYSize = psTransform->nGeoLocYSize; int nStepCount = 0; // Start in center if we don't have any provided info. if( nStartX < 0 || nStartY < 0 || nStartX >= nXSize || nStartY >= nYSize ) { nStartX = nXSize / 2; nStartY = nYSize / 2; } nStartX = MIN(nStartX,nXSize-2); nStartY = MIN(nStartY,nYSize-2); int iX = nStartX, iY = nStartY; int iLastX = -1, iLastY = -1; int iSecondLastX = -1, iSecondLastY = -1; while( nStepCount < MAX(nXSize,nYSize) ) { int iXNext = -1, iYNext = -1; double dfDeltaXRight, dfDeltaYRight, dfDeltaXDown, dfDeltaYDown; double *padfThisX = psTransform->padfGeoLocX + iX + iY * nXSize; double *padfThisY = psTransform->padfGeoLocY + iX + iY * nXSize; double dfDeltaX = dfGeoX - *padfThisX; double dfDeltaY = dfGeoY - *padfThisY; if( iX == nXSize-1 ) { dfDeltaXRight = *(padfThisX) - *(padfThisX-1); dfDeltaYRight = *(padfThisY) - *(padfThisY-1); } else { dfDeltaXRight = *(padfThisX+1) - *padfThisX; dfDeltaYRight = *(padfThisY+1) - *padfThisY; } if( iY == nYSize - 1 ) { dfDeltaXDown = *(padfThisX) - *(padfThisX-nXSize); dfDeltaYDown = *(padfThisY) - *(padfThisY-nXSize); } else { dfDeltaXDown = *(padfThisX+nXSize) - *padfThisX; dfDeltaYDown = *(padfThisY+nXSize) - *padfThisY; } double dfRightProjection = (dfDeltaXRight * dfDeltaX + dfDeltaYRight * dfDeltaY) / (dfDeltaXRight*dfDeltaXRight + dfDeltaYRight*dfDeltaYRight); double dfDownProjection = (dfDeltaXDown * dfDeltaX + dfDeltaYDown * dfDeltaY) / (dfDeltaXDown*dfDeltaXDown + dfDeltaYDown*dfDeltaYDown); // Are we in our target cell? if( dfRightProjection >= 0.0 && dfRightProjection < 1.0 && dfDownProjection >= 0.0 && dfDownProjection < 1.0 ) { *pdfFoundX = iX + dfRightProjection; *pdfFoundY = iY + dfDownProjection; return TRUE; } if( ABS(dfRightProjection) > ABS(dfDownProjection) ) { // Do we want to move right? if( dfRightProjection > 1.0 && iX < nXSize-1 ) { iXNext = iX + MAX(1,(int)(dfRightProjection - nStepCount)/2); iYNext = iY; } // Do we want to move left? else if( dfRightProjection < 0.0 && iX > 0 ) { iXNext = iX - MAX(1,(int)(ABS(dfRightProjection) - nStepCount)/2); iYNext = iY; } // Do we want to move down. else if( dfDownProjection > 1.0 && iY < nYSize-1 ) { iXNext = iX; iYNext = iY + MAX(1,(int)(dfDownProjection - nStepCount)/2); } // Do we want to move up? else if( dfDownProjection < 0.0 && iY > 0 ) { iXNext = iX; iYNext = iY - MAX(1,(int)(ABS(dfDownProjection) - nStepCount)/2); } // We aren't there, and we have no where to go else { return FALSE; } } else { // Do we want to move down. if( dfDownProjection > 1.0 && iY < nYSize-1 ) { iXNext = iX; iYNext = iY + MAX(1,(int)(dfDownProjection - nStepCount)/2); } // Do we want to move up? else if( dfDownProjection < 0.0 && iY > 0 ) { iXNext = iX; iYNext = iY - MAX(1,(int)(ABS(dfDownProjection) - nStepCount)/2); } // Do we want to move right? else if( dfRightProjection > 1.0 && iX < nXSize-1 ) { iXNext = iX + MAX(1,(int)(dfRightProjection - nStepCount)/2); iYNext = iY; } // Do we want to move left? else if( dfRightProjection < 0.0 && iX > 0 ) { iXNext = iX - MAX(1,(int)(ABS(dfRightProjection) - nStepCount)/2); iYNext = iY; } // We aren't there, and we have no where to go else { return FALSE; } } adfPathX[nStepCount] = iX; adfPathY[nStepCount] = iY; nStepCount++; iX = MAX(0,MIN(iXNext,nXSize-1)); iY = MAX(0,MIN(iYNext,nYSize-1)); if( iX == iSecondLastX && iY == iSecondLastY ) { // Are we *near* our target cell? if( dfRightProjection >= -1.0 && dfRightProjection < 2.0 && dfDownProjection >= -1.0 && dfDownProjection < 2.0 ) { *pdfFoundX = iX + dfRightProjection; *pdfFoundY = iY + dfDownProjection; return TRUE; } #ifdef SHAPE_DEBUG if( hSHP != NULL ) { SHPObject *hObj; hObj = SHPCreateSimpleObject( SHPT_ARC, nStepCount, adfPathX, adfPathY, NULL ); SHPWriteObject( hSHP, -1, hObj ); SHPDestroyObject( hObj ); int iShape = DBFGetRecordCount( hDBF ); DBFWriteDoubleAttribute( hDBF, iShape, 0, dfGeoX ); DBFWriteDoubleAttribute( hDBF, iShape, 1, dfGeoY ); } #endif //CPLDebug( "GeoL", "Looping at step (%d) on search for %g,%g.", // nStepCount, dfGeoX, dfGeoY ); return FALSE; } iSecondLastX = iLastX; iSecondLastY = iLastY; iLastX = iX; iLastY = iY; } //CPLDebug( "GeoL", "Exceeded step count max (%d) on search for %g,%g.", // MAX(nXSize,nYSize), // dfGeoX, dfGeoY ); #ifdef SHAPE_DEBUG if( hSHP != NULL ) { SHPObject *hObj; hObj = SHPCreateSimpleObject( SHPT_ARC, nStepCount, adfPathX, adfPathY, NULL ); SHPWriteObject( hSHP, -1, hObj ); SHPDestroyObject( hObj ); int iShape = DBFGetRecordCount( hDBF ); DBFWriteDoubleAttribute( hDBF, iShape, 0, dfGeoX ); DBFWriteDoubleAttribute( hDBF, iShape, 1, dfGeoY ); } #endif return FALSE; }
static void write_shapefile (local_data_t *local_data) { guint npolys; char *shape_filename; SHPHandle shape_file = NULL; SHPObject *shape; double *vertex_x, *vertex_y; guint i, j; projUV p; char *dbf_filename; DBFHandle dbf_file = NULL; int nunits_field_index; int avg_ninfected_field_index; int avg_ndestroyed_field_index; int avg_nvaccinated_field_index; int avg_frinfected_field_index; int avg_frdestroyed_field_index; int avg_frvaccinated_field_index; #if DEBUG g_debug ("----- ENTER write_shapefile (%s)", MODEL_NAME); #endif vertex_x = g_new (double, local_data->max_nvertices); vertex_y = g_new (double, local_data->max_nvertices); /* We are going to write 2 files: the .shp file, containing the geometry of * the polygons, and the .dbf file, containing the numeric attributes * attached to the polygons. */ shape_filename = g_strdup_printf ("%s.shp", local_data->base_filename); #if DEBUG g_debug ("creating new shapefile \"%s\"", shape_filename); #endif shape_file = SHPCreate (shape_filename, SHPT_POLYGON); g_assert (shape_file != NULL); npolys = local_data->polys->len; for (i = 0; i < npolys; i++) { gpc_polygon *poly; gpc_vertex_list *contour; poly = (gpc_polygon *) g_ptr_array_index (local_data->polys, i); g_assert (poly->num_contours == 1); contour = &(poly->contour[0]); for (j = 0; j < contour->num_vertices; j++) { /* The polygon vertices are in x-y coordinates. We need to * "unproject" them back to lat-long. */ p.u = contour->vertex[j].x; p.v = contour->vertex[j].y; p = pj_inv (p, local_data->projection); vertex_x[j] = p.u * RAD_TO_DEG; vertex_y[j] = p.v * RAD_TO_DEG; } shape = SHPCreateSimpleObject (SHPT_POLYGON, j, vertex_x, vertex_y, NULL); SHPWriteObject (shape_file, -1, shape); SHPDestroyObject (shape); } if (shape_file != NULL) SHPClose (shape_file); g_free (shape_filename); /* Now the attribute file */ dbf_filename = g_strdup_printf ("%s.dbf", local_data->base_filename); #if DEBUG g_debug ("creating new attributes file \"%s\"", dbf_filename); #endif dbf_file = DBFCreate (dbf_filename); g_assert (dbf_file != NULL); /* Add attribute definitions. */ #if DEBUG g_debug ("adding field definitions to DBF file \"%s\": nunits, avgninf, avgndest, avgnvacc, avgfrinf, avgfrdest, avgfrvacc", dbf_filename); #endif /* 9-digit integers should be enough to count # of units in a polygon. */ nunits_field_index = DBFAddField (dbf_file, "nunits", FTInteger, 9, 0); /* 1 decimal place for average # of units infected or destroyed, 3 for * average fraction of units. */ avg_ninfected_field_index = DBFAddField (dbf_file, "avgninf", FTDouble, 9, 1); avg_ndestroyed_field_index = DBFAddField (dbf_file, "avgndest", FTDouble, 9, 1); avg_nvaccinated_field_index = DBFAddField (dbf_file, "avgnvacc", FTDouble, 9, 1); avg_frinfected_field_index = DBFAddField (dbf_file, "avgfrinf", FTDouble, 9, 3); avg_frdestroyed_field_index = DBFAddField (dbf_file, "avgfrdest", FTDouble, 9, 3); avg_frvaccinated_field_index = DBFAddField (dbf_file, "avgfrvacc", FTDouble, 9, 3); /* Write the attributes to the file. */ #if DEBUG g_debug ("writing attributes to \"%s\"", dbf_filename); #endif for (i = 0; i < npolys; i++) { guint nunits; /* Divide the counts by the number of runs to get the mean */ local_data->ninfected[i] /= local_data->nruns; local_data->ndestroyed[i] /= local_data->nruns; local_data->nvaccinated[i] /= local_data->nruns; nunits = local_data->unit_count[i]; DBFWriteIntegerAttribute (dbf_file, i, nunits_field_index, nunits); DBFWriteDoubleAttribute (dbf_file, i, avg_ninfected_field_index, local_data->ninfected[i]); DBFWriteDoubleAttribute (dbf_file, i, avg_ndestroyed_field_index, local_data->ndestroyed[i]); DBFWriteDoubleAttribute (dbf_file, i, avg_nvaccinated_field_index, local_data->nvaccinated[i]); DBFWriteDoubleAttribute (dbf_file, i, avg_frinfected_field_index, local_data->ninfected[i] / nunits); DBFWriteDoubleAttribute (dbf_file, i, avg_frdestroyed_field_index, local_data->ndestroyed[i] / nunits); DBFWriteDoubleAttribute (dbf_file, i, avg_frvaccinated_field_index, local_data->nvaccinated[i] / nunits); } if (dbf_file != NULL) DBFClose (dbf_file); g_free (dbf_filename); /* Clean up. */ g_free (vertex_y); g_free (vertex_x); #if DEBUG g_debug ("----- EXIT write_shapefile (%s)", MODEL_NAME); #endif return; }
bool vtStructureArray::WriteFootprintsToSHP(const char* filename) { SHPHandle hSHP = SHPCreate(filename, SHPT_POLYGON); if (!hSHP) return false; vtString dbfname = filename; dbfname = dbfname.Left(dbfname.GetLength() - 4); dbfname += ".dbf"; DBFHandle db = DBFCreate(dbfname); if (!db) return false; // Field 0: height in meters DBFAddField(db, "Height", FTDouble, 3, 2); // width, decimals uint i, j, count = GetSize(), record = 0; for (i = 0; i < count; i++) //for each coordinate { vtBuilding *bld = GetAt(i)->GetBuilding(); if (!bld) continue; const DLine2 &poly = bld->GetLevel(0)->GetOuterFootprint(); int total = poly.GetSize() + 1; double *dX = new double[total]; double *dY = new double[total]; int vert = 0; for (j=0; j < poly.GetSize(); j++) //for each vertex { DPoint2 pt = poly.GetAt(j); dX[vert] = pt.x; dY[vert] = pt.y; vert++; } // duplicate first vertex, it's just what SHP files do. DPoint2 pt = poly.GetAt(0); dX[vert] = pt.x; dY[vert] = pt.y; vert++; // Save to SHP SHPObject *obj = SHPCreateSimpleObject(SHPT_POLYGON, total, dX, dY, NULL); SHPWriteObject(hSHP, -1, obj); SHPDestroyObject(obj); delete [] dY; delete [] dX; // Save to DBF float h = bld->GetTotalHeight(); DBFWriteDoubleAttribute(db, record, 0, h); // Because not every structure may be a building, there may be fewer // records than structures. record++; } DBFClose(db); SHPClose(hSHP); return true; }
void Builder::print_shpObjects() { int dim = shpObjects.size(); int dimTexts = textObjects.size(); QgsDebugMsg( QString( "Number of primitives: %1" ).arg( dim ) ); QgsDebugMsg( QString( "Number of text fields: %1" ).arg( dimTexts ) ); SHPHandle hSHP; if ( fname.substr( fname.length() - 4 ).compare( ".shp" ) == 0 ) { outputdbf = fname; outputdbf = outputdbf.replace(( outputdbf.length() - 3 ), outputdbf.length(), "dbf" ); outputshp = fname; outputshp = outputshp.replace(( outputshp.length() - 3 ), outputshp.length(), "shp" ); outputtdbf = fname; outputtdbf = outputtdbf.replace(( outputtdbf.length() - 4 ), outputtdbf.length(), "_texts.dbf" ); outputtshp = fname; outputtshp = outputtshp.replace(( outputtshp.length() - 4 ), outputtshp.length(), "_texts.shp" ); } else { outputdbf = outputtdbf = fname + ".dbf"; outputshp = outputtshp = fname + ".shp"; } DBFHandle dbffile = DBFCreate( outputdbf.c_str() ); DBFAddField( dbffile, "myid", FTInteger, 10, 0 ); hSHP = SHPCreate( outputshp.c_str(), shapefileType ); QgsDebugMsg( "Writing to main shp file..." ); for ( int i = 0; i < dim; i++ ) { SHPWriteObject( hSHP, -1, shpObjects[i] ); SHPDestroyObject( shpObjects[i] ); DBFWriteIntegerAttribute( dbffile, i, 0, i ); } SHPClose( hSHP ); DBFClose( dbffile ); QgsDebugMsg( "Done!" ); if ( convertText && dimTexts > 0 ) { SHPHandle thSHP; DBFHandle Tdbffile = DBFCreate( outputtdbf.c_str() ); thSHP = SHPCreate( outputtshp.c_str(), SHPT_POINT ); DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "height", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "text", FTString, 50, 0 ); DBFAddField( Tdbffile, "style", FTString, 50, 0 ); DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 ); QgsDebugMsg( "Writing Texts' shp File..." ); for ( int i = 0; i < dimTexts; i++ ) { SHPObject *psObject; double x = textObjects[i].ipx; double y = textObjects[i].ipy; double z = textObjects[i].ipz; psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL ); SHPWriteObject( thSHP, -1, psObject ); DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects[i].ipx ); DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects[i].ipy ); DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects[i].ipz ); DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects[i].apx ); DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects[i].apy ); DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects[i].apz ); DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects[i].height ); DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects[i].xScaleFactor ); DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects[i].textGenerationFlags ); DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects[i].hJustification ); DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects[i].vJustification ); DBFWriteStringAttribute( Tdbffile, i, 11, textObjects[i].text.c_str() ); DBFWriteStringAttribute( Tdbffile, i, 12, textObjects[i].style.c_str() ); DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects[i].angle ); SHPDestroyObject( psObject ); } SHPClose( thSHP ); DBFClose( Tdbffile ); QgsDebugMsg( "Done!" ); } }
int main( int argc, char ** argv ) { DBFHandle hDBF; int *panWidth, i, iRecord; char szFormat[32], szField[1024]; char cTitle[32], nTitle[32]; int nWidth, nDecimals; int cnWidth, cnDecimals; DBFHandle cDBF; DBFFieldType hType,cType; int ci, ciRecord; char tfile[160]; int hflds, j, cflds; int verbose = 0; int force = 0; int mismatch = 0; int matches = 0; char fld_m[256]; int shift = 0; char type_names[4][15] = {"integer", "string", "double", "double"}; if( argc < 3 ) { printf( "dbfcat [-v] [-f] from_DBFfile to_DBFfile\n" ); exit( 1 ); } if ( strcmp ("-v", argv[1] ) == 0 ) { shift = 1; verbose = 1; } if ( strcmp ("-f", argv[1 + shift] ) == 0 ) { shift ++; force = 1; } if ( strcmp ("-v", argv[1 + shift] ) == 0 ) { shift ++; verbose = 1; } strcpy (tfile, argv[1 + shift]); strcat (tfile, ".dbf"); hDBF = DBFOpen( tfile, "rb" ); if( hDBF == NULL ) { printf( "DBFOpen(%s.dbf,\"r\") failed for From_DBF.\n", tfile ); exit( 2 ); } strcpy (tfile, argv[2 + shift]); strcat (tfile, ".dbf"); cDBF = DBFOpen( tfile, "rb+" ); if( cDBF == NULL ) { printf( "DBFOpen(%s.dbf,\"rb+\") failed for To_DBF.\n", tfile ); exit( 2 ); } if( DBFGetFieldCount(hDBF) == 0 ) { printf( "There are no fields in this table!\n" ); exit( 3 ); } hflds = DBFGetFieldCount(hDBF); cflds = DBFGetFieldCount(cDBF); matches = 0; for( i = 0; i < hflds; i++ ) { char szTitle[18]; char cname[18]; int j; hType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals ); fld_m[i] = -1; for ( j = 0; j < cflds; j ++ ) { cType = DBFGetFieldInfo( cDBF, j, cname, &cnWidth, &cnDecimals ); if ( strcmp (cname, szTitle) == 0 ) { if ( hType != cType ) { printf ("Incompatible fields %s(%s) != %s(%s),\n", type_names[hType],nTitle,type_names[cType],cTitle); mismatch = 1; } fld_m[i] = j; if ( verbose ) { printf("%s %s(%d,%d) <- %s %s(%d,%d)\n", cname, type_names[cType], cnWidth, cnDecimals, szTitle, type_names[hType], nWidth, nDecimals); } j = cflds; matches = 1; } } } if ( (matches == 0 ) && !force ) { printf ("ERROR: No field names match for tables, cannot proceed\n use -f to force processing using blank records\n"); exit(-1); } if ( mismatch && !force ) { printf ("ERROR: field type mismatch cannot proceed\n use -f to force processing using attempted conversions\n"); exit(-1); } for( iRecord = 0; iRecord < DBFGetRecordCount(hDBF); iRecord++ ) { ciRecord = DBFGetRecordCount( cDBF ); for ( i = 0; i < hflds;i ++ ) { double cf; ci = fld_m[i]; if ( ci != -1 ) { cType = DBFGetFieldInfo( cDBF, ci, cTitle, &cnWidth, &cnDecimals ); hType = DBFGetFieldInfo( hDBF, i, nTitle, &nWidth, &nDecimals ); switch( cType ) { case FTString: DBFWriteStringAttribute(cDBF, ciRecord, ci, (char *) DBFReadStringAttribute( hDBF, iRecord, i ) ); break; case FTInteger: DBFWriteIntegerAttribute(cDBF, ciRecord, ci, (int) DBFReadIntegerAttribute( hDBF, iRecord, i ) ); break; case FTDouble: /* cf = DBFReadDoubleAttribute( hDBF, iRecord, i ); printf ("%s <- %s (%f)\n", cTitle, nTitle, cf); */ DBFWriteDoubleAttribute(cDBF, ciRecord, ci, (double) DBFReadDoubleAttribute( hDBF, iRecord, i ) ); break; } } } /* fields names match */ } if ( verbose ) { printf (" %d records appended \n\n", iRecord); } DBFClose( hDBF ); DBFClose( cDBF ); return( 0 ); }
// Convert baseline to shape file void baseline2shape(int ii, struct base_pair *pairs, DBFHandle dbase, SHPHandle shape) { int vertices=4, off; char date[15]; double *lat, *lon; julian_date jd; ymd_date ymd; char *mon[13]= {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // Read coordinates of the vertices lat = (double *) MALLOC(sizeof(double)*(vertices+1)); lon = (double *) MALLOC(sizeof(double)*(vertices+1)); lat[0] = pairs->ns_lat; lon[0] = pairs->ns_lon; lat[1] = pairs->fs_lat; lon[1] = pairs->fs_lon; lat[2] = pairs->fe_lat; lon[2] = pairs->fe_lon; lat[3] = pairs->ne_lat; lon[3] = pairs->ne_lon; lat[vertices] = lat[0]; lon[vertices] = lon[0]; // Write information into database file if (strcmp_case(pairs->m_sensor, pairs->s_sensor) == 0) { DBFWriteStringAttribute(dbase, ii, 0, pairs->m_sensor); off = 0; } else { DBFWriteStringAttribute(dbase, ii, 0, pairs->m_sensor); DBFWriteStringAttribute(dbase, ii, 1, pairs->s_sensor); off = 1; } DBFWriteStringAttribute(dbase, ii, off+1, pairs->mode); DBFWriteIntegerAttribute(dbase, ii, off+2, pairs->frame); DBFWriteStringAttribute(dbase, ii, off+3, pairs->orbit_dir); DBFWriteIntegerAttribute(dbase, ii, off+4, pairs->master); sscanf(pairs->m_time, "%4d-%3dT", &jd.year, &jd.jd); date_jd2ymd(&jd, &ymd); sprintf(date, "%d-%s-%d", ymd.day, mon[ymd.month], ymd.year); DBFWriteStringAttribute(dbase, ii, off+5, date); DBFWriteIntegerAttribute(dbase, ii, off+6, pairs->slave); sscanf(pairs->s_time, "%4d-%3dT", &jd.year, &jd.jd); date_jd2ymd(&jd, &ymd); sprintf(date, "%d-%s-%d", ymd.day, mon[ymd.month], ymd.year); DBFWriteStringAttribute(dbase, ii, off+7, date); DBFWriteIntegerAttribute(dbase, ii, off+8, pairs->b_par); DBFWriteIntegerAttribute(dbase, ii, off+9, pairs->b_perp); DBFWriteIntegerAttribute(dbase, ii, off+10, pairs->b_temp); DBFWriteDoubleAttribute(dbase, ii, off+11, pairs->c_lat); DBFWriteDoubleAttribute(dbase, ii, off+12, pairs->c_lon); DBFWriteDoubleAttribute(dbase, ii, off+13, pairs->ns_lat); DBFWriteDoubleAttribute(dbase, ii, off+14, pairs->ns_lon); DBFWriteDoubleAttribute(dbase, ii, off+15, pairs->fs_lat); DBFWriteDoubleAttribute(dbase, ii, off+16, pairs->fs_lon); DBFWriteDoubleAttribute(dbase, ii, off+17, pairs->ne_lat); DBFWriteDoubleAttribute(dbase, ii, off+18, pairs->ne_lon); DBFWriteDoubleAttribute(dbase, ii, off+19, pairs->fe_lat); DBFWriteDoubleAttribute(dbase, ii, off+20, pairs->fe_lon); // Write shape object SHPObject *shapeObject=NULL; shapeObject = SHPCreateSimpleObject(SHPT_POLYGON, vertices+1, lon, lat, NULL); if (shapeObject == NULL) asfPrintError("Could not create shape object (%d)\n", ii); SHPWriteObject(shape, -1, shapeObject); SHPDestroyObject(shapeObject); FREE(lat); FREE(lon); }
inline static void apply(DBFHandle dbf, int row_index, int field_index, T const& value) { DBFWriteDoubleAttribute(dbf, row_index, field_index, value); }
bool TeExportQuerierToShapefile(TeQuerier* querier, const std::string& base) { // check initial conditions if (!querier) return false; if (!querier->loadInstances()) return false; // Get the list of attributes defined by the input querier bool onlyObjId = false; TeAttributeList qAttList = querier->getAttrList(); if (qAttList.empty()) { TeAttributeList qAttList; TeAttribute at; at.rep_.type_ = TeSTRING; at.rep_.numChar_ = 100; at.rep_.name_ = "ID"; at.rep_.isPrimaryKey_ = true; qAttList.push_back(at); onlyObjId = true; } // Handles to each type of geometries that will be created if necessary DBFHandle hDBFPol = 0; SHPHandle hSHPPol = 0; DBFHandle hDBFLin = 0; SHPHandle hSHPLin = 0; DBFHandle hDBFPt = 0; SHPHandle hSHPPt = 0; // Some auxiliary variables int totpoints; double* padfX; double* padfY; unsigned int nVertices; int* panPart; SHPObject *psObject; unsigned int posXY, npoints, nelem; int shpRes; // progress information if (TeProgress::instance()) TeProgress::instance()->setTotalSteps(querier->numElemInstances()); clock_t t0, t1, t2; t2 = clock(); t0 = t1 = t2; int dt = CLOCKS_PER_SEC/2; int dt2 = CLOCKS_PER_SEC; //* .000001; // Loop through the instances writting their geometries and attributes unsigned int iRecPol=0, iRecLin=0, iRecPt=0; unsigned int n, l, m; unsigned int nIProcessed = 0; TeSTInstance st; while(querier->fetchInstance(st)) { totpoints = 0; nVertices = 0; if (st.hasPolygons()) { TePolygonSet& polSet = st.getPolygons(); TePolygonSet::iterator itps; int nVerticesCount = 0; for (itps = polSet.begin(); itps != polSet.end(); ++itps) { nVertices = (*itps).size(); nVerticesCount += nVertices; for (n=0; n<nVertices;++n) totpoints += (*itps)[n].size(); } panPart = (int *) malloc(sizeof(int) * nVerticesCount); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; for (itps = polSet.begin(); itps != polSet.end(); ++itps) { TePolygon poly = *itps; for (l=0; l<poly.size(); ++l) { if (l==0) { if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) TeReverseLine(poly[l]); } else { if (TeOrientation(poly[l]) == TeCLOCKWISE) TeReverseLine(poly[l]); } npoints = poly[l].size(); panPart[nelem]=posXY; for (m=0; m<npoints; ++m) { padfX[posXY] = poly[l][m].x_; padfY[posXY] = poly[l][m].y_; posXY++; } nelem++; } } psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL, posXY, padfX, padfY, NULL, NULL); if (hSHPPol == 0) { string fname = base + "_pol.shp"; hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON); assert (hSHPPol != 0); } shpRes = SHPWriteObject(hSHPPol, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFPol == 0) { hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList); assert (hDBFPol != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str())); } } } ++iRecPol; } if (st.hasCells()) { TeCellSet& cellSet = st.getCells(); nVertices = cellSet.size(); totpoints = nVertices*5; panPart = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; TeCellSet::iterator itcs; for (itcs=cellSet.begin(); itcs!=cellSet.end(); ++itcs) { panPart[nelem]=posXY; padfX[posXY] = (*itcs).box().lowerLeft().x(); padfY[posXY] = (*itcs).box().lowerLeft().y(); posXY++; padfX[posXY] = (*itcs).box().upperRight().x(); padfY[posXY] = (*itcs).box().lowerLeft().y(); posXY++; padfX[posXY] = (*itcs).box().upperRight().x(); padfY[posXY] = (*itcs).box().upperRight().y(); posXY++; padfX[posXY] = (*itcs).box().lowerLeft().x(); padfY[posXY] = (*itcs).box().upperRight().y(); posXY++; padfX[posXY] = (*itcs).box().lowerLeft().x(); padfY[posXY] = (*itcs).box().lowerLeft().y(); ++posXY; ++nelem; } psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL,posXY, padfX, padfY, NULL, NULL); if (hSHPPol == 0) { string fname = base + "_pol.shp"; hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON); assert (hSHPPol != 0); } shpRes = SHPWriteObject(hSHPPol, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFPol == 0) { hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList); assert (hDBFPol != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str())); } } } ++iRecPol; } if (st.hasLines()) { TeLineSet& lineSet = st.getLines(); nVertices = lineSet.size(); TeLineSet::iterator itls; for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls) totpoints += (*itls).size(); panPart = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * totpoints); padfY = (double *) malloc(sizeof(double) * totpoints); posXY = 0; nelem = 0; for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls) { panPart[nelem]=posXY; for (l=0; l<(*itls).size(); ++l) { padfX[posXY] = (*itls)[l].x(); padfY[posXY] = (*itls)[l].y(); ++posXY; } ++nelem; } psObject = SHPCreateObject(SHPT_ARC, -1, nVertices, panPart, NULL, posXY, padfX, padfY, NULL, NULL); if (hSHPLin == 0) { string fname = base + "_lin.shp"; hSHPLin = SHPCreate(fname.c_str(), SHPT_ARC); assert (hSHPLin != 0); } shpRes = SHPWriteObject(hSHPLin, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFLin == 0) { hDBFLin = TeCreateDBFFile(base + "_lin.dbf", qAttList); assert (hDBFLin != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFLin, iRecLin, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFLin, iRecLin, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFLin, iRecLin, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFLin, iRecLin, n, atof(val.c_str())); } } } ++iRecLin; } if (st.hasPoints()) { TePointSet& pointSet = st.getPoints(); nVertices = pointSet.size(); panPart = (int *) malloc(sizeof(int) * nVertices); padfX = (double *) malloc(sizeof(double) * nVertices); padfY = (double *) malloc(sizeof(double) * nVertices); nelem = 0; TePointSet::iterator itpts; for (itpts=pointSet.begin(); itpts!=pointSet.end(); ++itpts) { panPart[nelem] = nelem; padfX[nelem] = (*itpts).location().x(); padfY[nelem] = (*itpts).location().y(); ++nelem; } psObject = SHPCreateObject(SHPT_POINT, -1, nVertices, panPart, NULL, nVertices, padfX, padfY, NULL, NULL ); if (hSHPPt == 0) { string fname = base + "_pt.shp"; hSHPPt = SHPCreate(fname.c_str(), SHPT_POINT); assert (hSHPPt != 0); } shpRes = SHPWriteObject(hSHPPt, -1, psObject); SHPDestroyObject(psObject); free(panPart); free(padfX); free(padfY); assert(shpRes != -1); if (hDBFPt == 0) { hDBFPt = TeCreateDBFFile(base + "_pt.dbf", qAttList); assert (hDBFPt != 0); } if (onlyObjId) { DBFWriteStringAttribute(hDBFPt, iRecPt, 0, st.objectId().c_str()); } else { string val; for (n=0; n<qAttList.size();++n) { st.getPropertyValue(val,n); if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME) { DBFWriteStringAttribute(hDBFPt, iRecPt, n, val.c_str()); } else if (qAttList[n].rep_.type_ == TeINT) { DBFWriteIntegerAttribute(hDBFPt, iRecPt, n, atoi(val.c_str())); } else if (qAttList[n].rep_.type_ == TeREAL) { DBFWriteDoubleAttribute(hDBFPt, iRecPt, n, atof(val.c_str())); } } } ++iRecPt; } ++nIProcessed; if (TeProgress::instance() && int(t2-t1) > dt) { t1 = t2; if(((int)(t2-t0) > dt2)) { if (TeProgress::instance()->wasCancelled()) break; else TeProgress::instance()->setProgress(nIProcessed); } } } if (hDBFPol != 0) DBFClose(hDBFPol); if (hSHPPol != 0) SHPClose(hSHPPol); if (hDBFLin != 0) DBFClose(hDBFLin); if (hSHPLin != 0) SHPClose(hSHPLin); if (hDBFPt != 0) DBFClose(hDBFPt); if (hSHPPt != 0) SHPClose(hSHPPt); if (TeProgress::instance()) TeProgress::instance()->reset(); return true; }
int main( int argc, char ** argv ) { /* -------------------------------------------------------------------- */ /* Check command line usage. */ /* -------------------------------------------------------------------- */ if( argc < 2 ) error(); strcpy(infile, argv[1]); if (argc > 2) { strcpy(outfile,argv[2]); if (strncasecmp2(outfile, "LIST",0) == 0) { ilist = TRUE; } if (strncasecmp2(outfile, "ALL",0) == 0) { iall = TRUE; } } if (ilist || iall || argc == 2 ) { setext(infile, "shp"); printf("DESCRIBE: %s\n",infile); strcpy(outfile,""); } /* -------------------------------------------------------------------- */ /* Look for other functions on the command line. (SELECT, UNIT) */ /* -------------------------------------------------------------------- */ for (i = 3; i < argc; i++) { if ((strncasecmp2(argv[i], "SEL",3) == 0) || (strncasecmp2(argv[i], "UNSEL",5) == 0)) { if (strncasecmp2(argv[i], "UNSEL",5) == 0) iunselect=TRUE; i++; if (i >= argc) error(); strcpy(selectitem,argv[i]); i++; if (i >= argc) error(); selcount=0; strcpy(temp,argv[i]); cpt=temp; tj = atoi(cpt); ti = 0; while (tj>0) { selectvalues[selcount] = tj; while( *cpt >= '0' && *cpt <= '9') cpt++; while( *cpt > '\0' && (*cpt < '0' || *cpt > '9') ) cpt++; tj=atoi(cpt); selcount++; } iselect=TRUE; } /*** End SEL & UNSEL ***/ else if ((strncasecmp2(argv[i], "CLIP",4) == 0) || (strncasecmp2(argv[i], "ERASE",5) == 0)) { if (strncasecmp2(argv[i], "ERASE",5) == 0) ierase=TRUE; i++; if (i >= argc) error(); strcpy(clipfile,argv[i]); sscanf(argv[i],"%lf",&cxmin); i++; if (i >= argc) error(); if (strncasecmp2(argv[i], "BOUND",5) == 0) { setext(clipfile, "shp"); hSHP = SHPOpen( clipfile, "rb" ); if( hSHP == NULL ) { printf( "ERROR: Unable to open the clip shape file:%s\n", clipfile ); exit( 1 ); } SHPGetInfo( hSHPappend, NULL, NULL, adfBoundsMin, adfBoundsMax ); cxmin = adfBoundsMin[0]; cymin = adfBoundsMin[1]; cxmax = adfBoundsMax[0]; cymax = adfBoundsMax[1]; printf("Theme Clip Boundary: (%lf,%lf) - (%lf,%lf)\n", cxmin, cymin, cxmax, cymax); ibound=TRUE; } else { /*** xmin,ymin,xmax,ymax ***/ sscanf(argv[i],"%lf",&cymin); i++; if (i >= argc) error(); sscanf(argv[i],"%lf",&cxmax); i++; if (i >= argc) error(); sscanf(argv[i],"%lf",&cymax); printf("Clip Box: (%lf,%lf) - (%lf,%lf)\n",cxmin, cymin, cxmax, cymax); } i++; if (i >= argc) error(); if (strncasecmp2(argv[i], "CUT",3) == 0) icut=TRUE; else if (strncasecmp2(argv[i], "TOUCH",5) == 0) itouch=TRUE; else if (strncasecmp2(argv[i], "INSIDE",6) == 0) iinside=TRUE; else error(); iclip=TRUE; } /*** End CLIP & ERASE ***/ else if (strncasecmp2(argv[i], "FACTOR",0) == 0) { i++; if (i >= argc) error(); infactor=findunit(argv[i]); if (infactor == 0) error(); iunit=TRUE; i++; if (i >= argc) error(); outfactor=findunit(argv[i]); if (outfactor == 0) { sscanf(argv[i],"%lf",&factor); if (factor == 0) error(); } if (factor == 0) { if (infactor ==0) { puts("ERROR: Input unit must be defined before output unit"); exit(1); } factor=infactor/outfactor; } printf("Output file coordinate values will be factored by %lg\n",factor); ifactor=(factor != 1); /* True if a valid factor */ } /*** End FACTOR ***/ else if (strncasecmp2(argv[i],"SHIFT",5) == 0) { i++; if (i >= argc) error(); sscanf(argv[i],"%lf",&xshift); i++; if (i >= argc) error(); sscanf(argv[i],"%lf",&yshift); iunit=TRUE; printf("X Shift: %lg Y Shift: %lg\n",xshift,yshift); } /*** End SHIFT ***/ else { printf("ERROR: Unknown function %s\n",argv[i]); error(); } } /* -------------------------------------------------------------------- */ /* If there is no data in this file let the user know. */ /* -------------------------------------------------------------------- */ openfiles(); /* Open the infile and the outfile for shape and dbf. */ if( DBFGetFieldCount(hDBF) == 0 ) { puts( "There are no fields in this table!" ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Print out the file bounds. */ /* -------------------------------------------------------------------- */ iRecord = DBFGetRecordCount( hDBF ); SHPGetInfo( hSHP, NULL, NULL, adfBoundsMin, adfBoundsMax ); printf( "Input Bounds: (%lg,%lg) - (%lg,%lg) Entities: %d DBF: %d\n", adfBoundsMin[0], adfBoundsMin[1], adfBoundsMax[0], adfBoundsMax[1], nEntities, iRecord ); if (strcmp(outfile,"") == 0) /* Describe the shapefile; No other functions */ { ti = DBFGetFieldCount( hDBF ); showitems(); exit(0); } if (iclip) check_theme_bnd(); jRecord = DBFGetRecordCount( hDBFappend ); SHPGetInfo( hSHPappend, NULL, NULL, adfBoundsMin, adfBoundsMax ); if (nEntitiesAppend == 0) puts("New Output File\n"); else printf( "Append Bounds: (%lg,%lg)-(%lg,%lg) Entities: %d DBF: %d\n", adfBoundsMin[0], adfBoundsMin[1], adfBoundsMax[0], adfBoundsMax[1], nEntitiesAppend, jRecord ); /* -------------------------------------------------------------------- */ /* Find matching fields in the append file or add new items. */ /* -------------------------------------------------------------------- */ mergefields(); /* -------------------------------------------------------------------- */ /* Find selection field if needed. */ /* -------------------------------------------------------------------- */ if (iselect) findselect(); /* -------------------------------------------------------------------- */ /* Read all the records */ /* -------------------------------------------------------------------- */ jRecord = DBFGetRecordCount( hDBFappend ); for( iRecord = 0; iRecord < nEntities; iRecord++) /** DBFGetRecordCount(hDBF) **/ { /* -------------------------------------------------------------------- */ /* SELECT for values if needed. (Can the record be skipped.) */ /* -------------------------------------------------------------------- */ if (iselect) if (selectrec() == 0) goto SKIP_RECORD; /** SKIP RECORD **/ /* -------------------------------------------------------------------- */ /* Read a Shape record */ /* -------------------------------------------------------------------- */ psCShape = SHPReadObject( hSHP, iRecord ); /* -------------------------------------------------------------------- */ /* Clip coordinates of shapes if needed. */ /* -------------------------------------------------------------------- */ if (iclip) if (clip_boundary() == 0) goto SKIP_RECORD; /** SKIP RECORD **/ /* -------------------------------------------------------------------- */ /* Read a DBF record and copy each field. */ /* -------------------------------------------------------------------- */ for( i = 0; i < DBFGetFieldCount(hDBF); i++ ) { /* -------------------------------------------------------------------- */ /* Store the record according to the type and formatting */ /* information implicit in the DBF field description. */ /* -------------------------------------------------------------------- */ if (pt[i] > -1) /* if the current field exists in output file */ { switch( DBFGetFieldInfo( hDBF, i, NULL, &iWidth, &iDecimals ) ) { case FTString: case FTLogical: DBFWriteStringAttribute(hDBFappend, jRecord, pt[i], (DBFReadStringAttribute( hDBF, iRecord, i )) ); break; case FTInteger: DBFWriteIntegerAttribute(hDBFappend, jRecord, pt[i], (DBFReadIntegerAttribute( hDBF, iRecord, i )) ); break; case FTDouble: DBFWriteDoubleAttribute(hDBFappend, jRecord, pt[i], (DBFReadDoubleAttribute( hDBF, iRecord, i )) ); break; case FTInvalid: break; } } } jRecord++; /* -------------------------------------------------------------------- */ /* Change FACTOR and SHIFT coordinates of shapes if needed. */ /* -------------------------------------------------------------------- */ if (iunit) { for( j = 0; j < psCShape->nVertices; j++ ) { psCShape->padfX[j] = psCShape->padfX[j] * factor + xshift; psCShape->padfY[j] = psCShape->padfY[j] * factor + yshift; } } /* -------------------------------------------------------------------- */ /* Write the Shape record after recomputing current extents. */ /* -------------------------------------------------------------------- */ SHPComputeExtents( psCShape ); SHPWriteObject( hSHPappend, -1, psCShape ); SKIP_RECORD: SHPDestroyObject( psCShape ); psCShape = NULL; j=0; } /* -------------------------------------------------------------------- */ /* Print out the # of Entities and the file bounds. */ /* -------------------------------------------------------------------- */ jRecord = DBFGetRecordCount( hDBFappend ); SHPGetInfo( hSHPappend, &nEntitiesAppend, &nShapeTypeAppend, adfBoundsMin, adfBoundsMax ); printf( "Output Bounds: (%lg,%lg) - (%lg,%lg) Entities: %d DBF: %d\n\n", adfBoundsMin[0], adfBoundsMin[1], adfBoundsMax[0], adfBoundsMax[1], nEntitiesAppend, jRecord ); /* -------------------------------------------------------------------- */ /* Close the both shapefiles. */ /* -------------------------------------------------------------------- */ SHPClose( hSHP ); SHPClose( hSHPappend ); DBFClose( hDBF ); DBFClose( hDBFappend ); if (nEntitiesAppend == 0) { puts("Remove the output files."); setext(outfile, "dbf"); remove(outfile); setext(outfile, "shp"); remove(outfile); setext(outfile, "shx"); remove(outfile); } return( 0 ); }
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; };
void output_saveSubcatchResults(double reportTime, FILE* file) // // Input: reportTime = elapsed simulation time (millisec) // file = ptr. to binary output file // Output: none // Purpose: writes computed subcatchment results to binary file. // { int j; double f; double area; REAL4 totalArea = 0.0f; DateTime reportDate = getDateTime(reportTime); FILE *fptr; // --- dbf variables DBFHandle hDBF; char fieldName[128]; int n; double f1,f0; double value; int numFields; // --- update reported rainfall at each rain gage for ( j=0; j<Nobjects[GAGE]; j++ ) { gage_setReportRainfall(j, reportDate); } // --- find where current reporting time lies between latest runoff times f = (reportTime - OldRunoffTime) / (NewRunoffTime - OldRunoffTime); f1 = 1.0 - f; f0 = f; // --- write subcatchment results to file for ( j=0; j<Nobjects[SUBCATCH]; j++) { // --- retrieve interpolated results for reporting time & write to file subcatch_getResults(j, f, SubcatchResults); if ( Subcatch[j].rptFlag ) fwrite(SubcatchResults, sizeof(REAL4), NsubcatchResults, file); // --- update system-wide results area = Subcatch[j].area * UCF(LANDAREA); totalArea += (REAL4)area; SysResults[SYS_RAINFALL] += (REAL4)(SubcatchResults[SUBCATCH_RAINFALL] * area); SysResults[SYS_SNOWDEPTH] += (REAL4)(SubcatchResults[SUBCATCH_SNOWDEPTH] * area); SysResults[SYS_EVAP] += (REAL4)(SubcatchResults[SUBCATCH_EVAP] * area); if ( Subcatch[j].groundwater ) SysResults[SYS_EVAP] += (REAL4)(Subcatch[j].groundwater->evapLoss * UCF(EVAPRATE) * area); SysResults[SYS_INFIL] += (REAL4)(SubcatchResults[SUBCATCH_INFIL] * area); SysResults[SYS_RUNOFF] += (REAL4)SubcatchResults[SUBCATCH_RUNOFF]; } // --- normalize system-wide results to catchment area if ( UnitSystem == SI ) f = (5./9.) * (Temp.ta - 32.0); else f = Temp.ta; SysResults[SYS_TEMPERATURE] = (REAL4)f; SysResults[SYS_EVAP] /= totalArea; SysResults[SYS_RAINFALL] /= totalArea; SysResults[SYS_SNOWDEPTH] /= totalArea; SysResults[SYS_INFIL] /= totalArea; // --- open DBF hDBF = DBFOpen(F2Dmesh.name, "r+b"); if( hDBF == NULL ) { //TODO //printf( "DBFOpen(%s,\"rb+\") failed.\n", argv[1] ); //exit( 2 ); } // --- create new field name n=sprintf (fieldName, "h_%07.0f", (reportTime / 1000.f)); if( DBFAddField( hDBF, fieldName, FTDouble, 12, 6 ) == -1 ) { //TODO //printf( "DBFAddField(%s,FTDouble,%d,%d) failed.\n", fieldName, 12, 3 ); //exit( 4 ); } n=sprintf (fieldName, "V_%07.0f", (reportTime / 1000.f)); if( DBFAddField( hDBF, fieldName, FTDouble, 12, 6 ) == -1 ) { //TODO //printf( "DBFAddField(%s,FTDouble,%d,%d) failed.\n", fieldName, 12, 3 ); //exit( 4 ); } // --- number of existing fields numFields = DBFGetFieldCount( hDBF ); // --- write subcatchment results to file for ( j=0; j<Nobjects[SUBCATCH]; j++) { if (Subcatch[j].isStreet) { value = ( f1 * Subcatch[j].oldGlobalDepth + f0 * Subcatch[j].newGlobalDepth ) * UCF(LENGTH); //Write value DBFWriteDoubleAttribute(hDBF, Subcatch[j].dbf_record, numFields - 2, value ); value = ( f1 * Subcatch[j].oldVel + f0 * Subcatch[j].newVel ) * UCF(LENGTH); //Write value DBFWriteDoubleAttribute(hDBF, Subcatch[j].dbf_record, numFields - 1, value ); } } //CLose DBFClose( hDBF ); // --- create file to print outflow fptr = fopen(F2Doutflow.name, "a+"); if (fptr == NULL) { printf("ERROR: Impossible to create Outflow.txt\n"); } else { fprintf(fptr, "%12.3f %12.3f\n", (reportTime / 1000.f), M2DControl.totalOutflow); fclose(fptr); } }
static void add_to_shape(DBFHandle dbase, SHPHandle shape, datapool_type_t *datapool, dbf_header_t *dbf, int nCols, int n, double *lat, double *lon) { int ii, field = 0; // Write fields into the database for (ii=0; ii<nCols; ii++) { if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->granule_name); field++; } else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->platform); field++; } else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->sensor); field++; } else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->beam_mode); field++; } else if (strcmp(dbf[ii].header, "Beam_Mode_Description") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->beam_mode_description); field++; } else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) { DBFWriteIntegerAttribute(dbase, n, field, datapool->orbit); field++; } else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) { DBFWriteIntegerAttribute(dbase, n, field, datapool->path_number); field++; } else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) { DBFWriteIntegerAttribute(dbase, n, field, datapool->frame_number); field++; } else if (strcmp(dbf[ii].header, "Acquisition_Date") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->acquisition_date); field++; } else if (strcmp(dbf[ii].header, "Processing_Date") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->processing_date); field++; } else if (strcmp(dbf[ii].header, "Processing_Level") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->processing_level); field++; } else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->start_time); field++; } else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->end_time); field++; } else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->center_lat); field++; } else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->center_lon); field++; } else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->near_start_lat); field++; } else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->near_start_lon); field++; } else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->far_start_lat); field++; } else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->far_start_lon); field++; } else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->near_end_lat); field++; } else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->near_end_lon); field++; } else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->far_end_lat); field++; } else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->far_end_lon); field++; } else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->faraday_rotation); field++; } else if (strcmp(dbf[ii].header, "Orbit_Direction") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->orbit_direction); field++; } else if (strcmp(dbf[ii].header, "Url") == 0 && dbf[ii].visible) { DBFWriteStringAttribute(dbase, n, field, datapool->url); field++; } else if (strcmp(dbf[ii].header, "Size") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->size); field++; } else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 && dbf[ii].visible) { DBFWriteDoubleAttribute(dbase, n, field, datapool->off_nadir_angle); field++; } } SHPObject *shapeObject=NULL; shapeObject = SHPCreateSimpleObject(SHPT_POLYGON, 5, lon, lat, NULL); SHPWriteObject(shape, -1, shapeObject); SHPDestroyObject(shapeObject); }
static void WriteAttrRecordToDBF( DBFHandle hDBF, int iRecord, SDTSTransfer * poTransfer, DDFField * poSR ) { /* -------------------------------------------------------------------- */ /* Process each subfield in the record. */ /* -------------------------------------------------------------------- */ DDFFieldDefn *poFDefn = poSR->GetFieldDefn(); for( int iSF=0; iSF < poFDefn->GetSubfieldCount(); iSF++ ) { DDFSubfieldDefn *poSFDefn = poFDefn->GetSubfield( iSF ); int iField; int nMaxBytes; const char * pachData = poSR->GetSubfieldData(poSFDefn, &nMaxBytes); /* -------------------------------------------------------------------- */ /* Identify the related DBF field, if any. */ /* -------------------------------------------------------------------- */ for( iField = 0; iField < hDBF->nFields; iField++ ) { if( EQUALN(poSFDefn->GetName(), hDBF->pszHeader+iField*32,10) ) break; } if( iField == hDBF->nFields ) iField = -1; /* -------------------------------------------------------------------- */ /* Handle each of the types. */ /* -------------------------------------------------------------------- */ switch( poSFDefn->GetType() ) { case DDFString: const char *pszValue; pszValue = poSFDefn->ExtractStringData(pachData, nMaxBytes, NULL); if( iField != -1 ) DBFWriteStringAttribute(hDBF, iRecord, iField, pszValue ); break; case DDFFloat: double dfValue; dfValue = poSFDefn->ExtractFloatData(pachData, nMaxBytes, NULL); if( iField != -1 ) DBFWriteDoubleAttribute( hDBF, iRecord, iField, dfValue ); break; case DDFInt: int nValue; nValue = poSFDefn->ExtractIntData(pachData, nMaxBytes, NULL); if( iField != -1 ) DBFWriteIntegerAttribute( hDBF, iRecord, iField, nValue ); break; default: break; } } /* next subfield */ }
/////////////////////////////////////////////////////////////////////////////// // Export eines Objektes HRESULT CArcViewLayer::ExportData ( GSTRUCT *pGS, MFELD *pMF, LPCSTR pcUIdent, CArcViewLayerAttributes *pMap) { OBJECTTYPE rgType = GetType(); int iShapeId = -1; int iObjTyp = pGS -> Typ; _ASSERTE(rgType == ObjType2OBJECTTYPE(pGS -> Typ, true)); // Objekttyp muß stimmen // Geometrie erzeugen if (OBJECTTYPE_Area == rgType) { // Anzahl der Konturen feststellen und Konturfeld zusammenbauen int iKCnt = 1; vector<int> Cnts(1); int iCurr = 0; Cnts[0] = 0; for (int i = 0; 0 != pGS -> cnt[i]; ++i) { if (i > 0) Cnts.push_back(iCurr); iCurr += pGS -> cnt[i]; } iKCnt = i; _ASSERTE(iKCnt > 0 && iKCnt == Cnts.size()); // Objekt erzeugen CArcViewObject Obj(SHPCreateObject(m_nShapeType, -1, iKCnt, Cnts.begin(), NULL, pGS -> GSize, pGS -> x, pGS -> y, NULL, NULL)); iShapeId = SHPWriteObject(m_hSHP, -1, Obj); } else { // Objekt erzeugen CArcViewObject Obj(SHPCreateSimpleObject(m_nShapeType, pGS -> GSize, pGS -> x, pGS -> y, NULL)); iShapeId = SHPWriteObject(m_hSHP, -1, Obj); } if (iShapeId == -1) return E_FAIL; // Attribute sicherstellen (bei TRiAS-Datenquellen jedesmal) if (!HasFields() || DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id))) { // sämtliche Attribute dieses Layers durchgehen und ggf. erzeugen for (CArcViewLayerAttributes::iterator it = pMap -> begin(); it != pMap -> end(); ++it) { // Feld in Datei erzeugen int iField = -1; CArcViewAttribute &rAttr = (*it).second; LPCSTR pcName = rAttr.GetName(); if (OBJECTTYPE_Text != m_rgType && !strcmp (pcName, g_cbLabelText)) continue; // Labeltext nur für Textobjekte if (FAILED(FieldExists (pcName, rAttr.GetTyp(), &iField))) { RETURN_FAILED_HRESULT(AddField(pcName, rAttr.GetTyp(), rAttr.GetLen(), rAttr.GetDecimals(), &iField)); } _ASSERTE(-1 != iField); // mehrerer Objekttypen eines Idents haben identischen Satz von Attributen _ASSERTE(-1 == (*it).second.GetField(iObjTyp) || (*it).second.GetField(iObjTyp) == iField || DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id))); // Feldnummer beim Attribut speichern (*it).second.SetField(iField, iObjTyp); } // Textlabel für Textobjekte if (OBJECTTYPE_Text == m_rgType) { pair<CArcViewLayerAttributes::iterator, bool> p = pMap -> insert (CArcViewLayerAttributes::value_type (-1, CArcViewAttribute(g_cbLabelText, 'a', _MAX_PATH))); if (p.second) { int iField = -1; it = p.first; if (FAILED(FieldExists (g_cbLabelText, FTString, &iField))) { RETURN_FAILED_HRESULT(AddField(g_cbLabelText, FTString, _MAX_PATH, 0, &iField)); } _ASSERTE(-1 != iField); (*it).second.SetField(iField, iObjTyp); } } SetHasFields(); } // Attributwerte schreiben if (NULL != pMF) { // nur, wenn mindestens ein Attribut ausgegeben werden soll for (MFELD *pMFT = pMF; 0 != pMFT -> MCode; ++pMFT) { if (NULL != pMap) { CArcViewLayerAttributes::iterator it = pMap -> find (pMFT -> MCode); _ASSERTE(it != pMap -> end()); // Attribut sollte (jetzt) existieren if (it != pMap -> end()) { // Feld muß bereits erzeugt worden sein und Typ muß mit DBF übereinstimmen int iField = (*it).second.GetField(iObjTyp); _ASSERTE(-1 != iField); _ASSERTE((*it).second.GetTyp() == DBFGetFieldInfo (m_hDBF, iField, NULL, NULL, NULL)); // Wert je nach Typ in die Datenbank schreiben switch ((*it).second.GetTyp()) { case FTString: { char cbBuffer[_MAX_PATH] = { '\0' }; if (NULL != pMFT -> MText) OemToCharBuff(pMFT -> MText, cbBuffer, min(MAX_DBASEFIELD_LEN, strlen(pMFT -> MText))+1); // '\0' mit konvertieren DBFWriteStringAttribute(m_hDBF, iShapeId, iField, cbBuffer); } break; case FTInteger: DBFWriteIntegerAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atol(pMFT -> MText) : 0); break; case FTDouble: DBFWriteDoubleAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atof(pMFT -> MText) : 0.0); break; } } } else { _ASSERTE(NULL != pMap); // eigentlich sollte eine Map da sein // keine Map, also erstmal leeren Datensatz schreiben int iCnt = DBFGetFieldCount(m_hDBF); for (int i = 0; i < iCnt; ++i) { switch (DBFGetFieldInfo(m_hDBF, i, NULL, NULL, NULL)) { case FTString: DBFWriteStringAttribute(m_hDBF, iShapeId, i, g_cbNil); break; case FTInteger: DBFWriteIntegerAttribute(m_hDBF, iShapeId, i, 0); break; case FTDouble: DBFWriteDoubleAttribute(m_hDBF, iShapeId, i, 0.0); break; } } } } } return S_OK; }
void Builder::print_shpObjects() { QgsDebugMsg( QString( "Number of primitives: %1" ).arg( shpObjects.size() ) ); QgsDebugMsg( QString( "Number of text fields: %1" ).arg( textObjects.size() ) ); QgsDebugMsg( QString( "Number of inserts fields: %1" ).arg( insertObjects.size() ) ); SHPHandle hSHP; if ( fname.endsWith( ".shp", Qt::CaseInsensitive ) ) { QString fn( fname.mid( fname.length() - 4 ) ); outputdbf = fn + ".dbf"; outputshp = fn + ".shp"; outputtdbf = fn + "_texts.dbf"; outputtshp = fn + "_texts.shp"; outputidbf = fn + "_inserts.dbf"; outputishp = fn + "_inserts.shp"; } else { outputdbf = outputtdbf = outputidbf = fname + ".dbf"; outputshp = outputtshp = outputishp = fname + ".shp"; } DBFHandle dbffile = DBFCreate( outputdbf.toUtf8() ); DBFAddField( dbffile, "myid", FTInteger, 10, 0 ); hSHP = SHPCreate( outputshp.toUtf8(), shapefileType ); QgsDebugMsg( "Writing to main shp file..." ); for ( int i = 0; i < shpObjects.size(); i++ ) { SHPWriteObject( hSHP, -1, shpObjects[i] ); SHPDestroyObject( shpObjects[i] ); DBFWriteIntegerAttribute( dbffile, i, 0, i ); } SHPClose( hSHP ); DBFClose( dbffile ); QgsDebugMsg( "Done!" ); if ( !textObjects.isEmpty() ) { SHPHandle thSHP; DBFHandle Tdbffile = DBFCreate( outputtdbf.toUtf8() ); thSHP = SHPCreate( outputtshp.toUtf8(), SHPT_POINT ); DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "height", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 ); DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 ); DBFAddField( Tdbffile, "text", FTString, 50, 0 ); DBFAddField( Tdbffile, "style", FTString, 50, 0 ); DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 ); QgsDebugMsg( "Writing Texts' shp File..." ); for ( int i = 0; i < textObjects.size(); i++ ) { SHPObject *psObject; double x = textObjects[i].ipx; double y = textObjects[i].ipy; double z = textObjects[i].ipz; psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL ); SHPWriteObject( thSHP, -1, psObject ); DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects[i].ipx ); DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects[i].ipy ); DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects[i].ipz ); DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects[i].apx ); DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects[i].apy ); DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects[i].apz ); DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects[i].height ); DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects[i].xScaleFactor ); DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects[i].textGenerationFlags ); DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects[i].hJustification ); DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects[i].vJustification ); DBFWriteStringAttribute( Tdbffile, i, 11, textObjects[i].text.c_str() ); DBFWriteStringAttribute( Tdbffile, i, 12, textObjects[i].style.c_str() ); DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects[i].angle ); SHPDestroyObject( psObject ); } SHPClose( thSHP ); DBFClose( Tdbffile ); QgsDebugMsg( "Done!" ); } if ( !insertObjects.isEmpty() ) { SHPHandle ihSHP; DBFHandle Idbffile = DBFCreate( outputidbf.toUtf8() ); ihSHP = SHPCreate( outputishp.toUtf8(), SHPT_POINT ); DBFAddField( Idbffile, "name", FTString, 200, 0 ); DBFAddField( Idbffile, "ipx", FTDouble, 20, 10 ); DBFAddField( Idbffile, "ipy", FTDouble, 20, 10 ); DBFAddField( Idbffile, "ipz", FTDouble, 20, 10 ); DBFAddField( Idbffile, "sx", FTDouble, 20, 10 ); DBFAddField( Idbffile, "sy", FTDouble, 20, 10 ); DBFAddField( Idbffile, "sz", FTDouble, 20, 10 ); DBFAddField( Idbffile, "angle", FTDouble, 20, 10 ); DBFAddField( Idbffile, "cols", FTInteger, 20, 0 ); DBFAddField( Idbffile, "rows", FTInteger, 20, 0 ); DBFAddField( Idbffile, "colsp", FTDouble, 20, 10 ); DBFAddField( Idbffile, "rowsp", FTDouble, 20, 10 ); QgsDebugMsg( "Writing Insert' shp File..." ); for ( int i = 0; i < insertObjects.size(); i++ ) { SHPObject *psObject; double &x = insertObjects[i].ipx; double &y = insertObjects[i].ipy; double &z = insertObjects[i].ipz; psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL ); SHPWriteObject( ihSHP, -1, psObject ); int c = 0; DBFWriteStringAttribute( Idbffile, i, c++, insertObjects[i].name.c_str() ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipx ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipy ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipz ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sx ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sy ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sz ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].angle ); DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].cols ); DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].rows ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].colSp ); DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].rowSp ); SHPDestroyObject( psObject ); } SHPClose( ihSHP ); DBFClose( Idbffile ); QgsDebugMsg( "Done!" ); } }
/** * 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); }