// ---------------------------------------------------------------------------
// Constructeur
// ------------
bDBFTable	::bDBFTable(	const char* path,
							const char* name,
							bool create, 
							double* reso,
							double* ox,
							double* oy,
							int* tsrid,
							int* asrid,
							int* status)
				:bStdTable(*reso,*ox,*oy,*tsrid,*asrid,status){
_bTrace_("bDBFTable::bDBFTable",false);

char	fpath[1024];
	
	sprintf(fpath,"%s%s",path,name);
	_dbf=DBFOpen(fpath,"rb+");
	if(!_dbf){
		_dbf=DBFOpen(fpath,"rb");	
	}
	if(_dbf){
		return;
	}
	if(!create){
		*status=-1;
_te_("table not found : "+fpath);
		return;
	}
	_dbf=DBFCreate(fpath);
	if(!_dbf){
_te_("creation failed for : "+fpath);
		*status=-1;
		return;
	}
	*status=0;
}
示例#2
0
bool surfaceVectorField::CreateShape()
{
	char 	DataBaseID[64]="";

	hSHP=SHPCreate(ShapeFileName.c_str(), SHPT_POINT);
	if(hSHP==NULL)
		return false;
	SHPClose( hSHP );
	// Create the database.
	hDBF=DBFCreate(DataBaseName.c_str());
	if(hDBF==NULL)
		return false;

     //sprintf(DataBaseID, "%s", "Xcoord");
    	//DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6);
     //sprintf(DataBaseID, "%s", "Ycoord");
    	//DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6);
     sprintf(DataBaseID, "%s", "Windspd");
    	DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6 );
     sprintf(DataBaseID, "%s", "Winddir");
    	DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0);
     sprintf(DataBaseID, "%s", "AV_dir");
    	DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0 );
     sprintf(DataBaseID, "%s", "AM_dir");
    	DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0 );
	DBFClose(hDBF);

     return true;
}
示例#3
0
文件: dbf.cpp 项目: bmfekete/TauDEM
DBFHandle DBFCloneEmpty(DBFHandle psDBF, const char * pszFilename ) 
{
    DBFHandle	newDBF;

   newDBF = DBFCreate ( pszFilename );
   if ( newDBF == NULL ) return ( NULL ); 
   
   newDBF->pszHeader = (char *) malloc ( 32 * psDBF->nFields );
   memcpy ( newDBF->pszHeader, psDBF->pszHeader, 32 * psDBF->nFields );
   
   newDBF->nFields = psDBF->nFields;
   newDBF->nRecordLength = psDBF->nRecordLength;
   newDBF->nHeaderLength = psDBF->nHeaderLength;
    
   newDBF->panFieldOffset = (int *) malloc ( sizeof(int) * psDBF->nFields ); 
   memcpy ( newDBF->panFieldOffset, psDBF->panFieldOffset, sizeof(int) * psDBF->nFields );
   newDBF->panFieldSize = (int *) malloc ( sizeof(int) * psDBF->nFields );
   memcpy ( newDBF->panFieldSize, psDBF->panFieldSize, sizeof(int) * psDBF->nFields );
   newDBF->panFieldDecimals = (int *) malloc ( sizeof(int) * psDBF->nFields );
   memcpy ( newDBF->panFieldDecimals, psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields );
   newDBF->pachFieldType = (char *) malloc ( sizeof(int) * psDBF->nFields );
   memcpy ( newDBF->pachFieldType, psDBF->pachFieldType, sizeof(int) * psDBF->nFields );

   newDBF->bNoHeader = TRUE;
   newDBF->bUpdated = TRUE;
   
   DBFWriteHeader ( newDBF );
   DBFClose ( newDBF );
   
   newDBF = DBFOpen ( pszFilename, "rb+" );

   return ( newDBF );
}
DBFHandle TeCreateDBFFile (const string& dbfFilename, TeAttributeList& attList)
{
	DBFHandle hDBF = DBFCreate( dbfFilename.c_str() );
	if( hDBF == 0 )
		return 0;
	
	int i =0;
	TeAttributeList::iterator it=attList.begin();

	while ( it != attList.end() )
	{
		TeAttribute at = (*it);
		string atName = at.rep_.name_;

		if (atName.size() > 10)
		{
			int extra = (int)(atName.size() - 10)/2;
			int middle = (int)(atName.size()/2);
			string str = atName.substr(0,middle-extra-1);
			str += atName.substr(middle+extra);
			atName = str;
		}
		if (at.rep_.type_ == TeSTRING )
		{
			if (DBFAddField( hDBF, atName.c_str(), FTString, at.rep_.numChar_, 0 ) == -1 )
				return 0;
		}
		else if (at.rep_.type_ == TeINT)
		{
			if (DBFAddField( hDBF, atName.c_str(), FTInteger, 32, 0 ) == -1 )
				return 0;
		}
		else if (at.rep_.type_ == TeREAL)
		{
			if (DBFAddField( hDBF, atName.c_str(), FTDouble, 40, 15 ) == -1 )
				return 0;
		}
		// OBS: shapelib doesn´t deal with xBase field type for Date 
		// we are transforming it to string
		else if (at.rep_.type_ == TeDATETIME)
		{
			if (DBFAddField( hDBF, atName.c_str(), FTDate, 8, 0 ) == -1 )
				return 0;
		}
		++i;
		++it;
	}
	return hDBF;
}
jboolean Java_org_maptools_shapelib_android_util_TestUtils_createShapefile(JNIEnv * env, jclass clazz,
                                                                jstring file, jobject listObject) {
    // create a shapefile and dbf (e.g. /sdcard/foo/bar)
    const char *fileStr = (*env)->GetStringUTFChars(env, file, 0);
    SHPHandle hSHP = SHPCreate(fileStr, SHPT_POINT);
    DBFHandle hDBF = DBFCreate(fileStr);

    // define the shapefile attributes
    DBFAddField(hDBF, "name", FTString, 25, 0);
    DBFAddField(hDBF, "height", FTDouble, 8, 8);
    DBFAddField(hDBF, "apples", FTInteger, 1, 0);

    process(env, hSHP, hDBF, file, listObject);

    SHPClose(hSHP);
    DBFClose(hDBF);
}
示例#6
0
            /**
             * Open and initialize all files belonging to shapefile (.shp/shx/dbf/prj/cpg).
             * Uses m_filename_base and m_sequence_number plus suffix to build filename.
             */
            void open() {
                std::ostringstream filename;
                filename << m_filename_base;
                if (m_sequence_number) {
                    filename << "_" << m_sequence_number;
                }

                m_shp_handle = SHPCreate(filename.str().c_str(), m_type);
                if (m_shp_handle == 0) {
                    throw std::runtime_error("Can't open shapefile: " + filename.str() + ".shp/shx");
                }
                m_dbf_handle = DBFCreate(filename.str().c_str());
                if (m_dbf_handle == 0) {
                    throw std::runtime_error("Can't open shapefile: " + filename.str() + ".dbf");
                }

                std::ofstream file;
                file.open((filename.str() + ".prj").c_str());
                if (file.fail()) {
                    throw std::runtime_error("Can't open shapefile: " + filename.str() + ".prj");
                }
                file << "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]" << std::endl;
                file.close();

                file.open((filename.str() + ".cpg").c_str());
                if (file.fail()) {
                    throw std::runtime_error("Can't open shapefile: " + filename.str() + ".cpg");
                }
                file << "UTF-8" << std::endl;
                file.close();

                // If any fields are defined already, add them here. This will do nothing if
                // called from the constructor.
                for (std::vector<Field>::const_iterator it = m_fields.begin(); it != m_fields.end(); ++it) {
                    DBFAddField(m_dbf_handle, it->name().c_str(), it->type(), it->width(), it->decimals());
                }
            }
OGRLayer *
OGRShapeDataSource::CreateLayer( const char * pszLayerName,
                                 OGRSpatialReference *poSRS,
                                 OGRwkbGeometryType eType,
                                 char ** papszOptions )

{
    SHPHandle   hSHP;
    DBFHandle   hDBF;
    int         nShapeType;

    /* -------------------------------------------------------------------- */
    /*      Verify we are in update mode.                                   */
    /* -------------------------------------------------------------------- */
    if( !bDSUpdate )
    {
        CPLError( CE_Failure, CPLE_NoWriteAccess,
                  "Data source %s opened read-only.\n"
                  "New layer %s cannot be created.\n",
                  pszName, pszLayerName );

        return NULL;
    }

    /* -------------------------------------------------------------------- */
    /*      Figure out what type of layer we need.                          */
    /* -------------------------------------------------------------------- */
    if( eType == wkbUnknown || eType == wkbLineString )
        nShapeType = SHPT_ARC;
    else if( eType == wkbPoint )
        nShapeType = SHPT_POINT;
    else if( eType == wkbPolygon )
        nShapeType = SHPT_POLYGON;
    else if( eType == wkbMultiPoint )
        nShapeType = SHPT_MULTIPOINT;
    else if( eType == wkbPoint25D )
        nShapeType = SHPT_POINTZ;
    else if( eType == wkbLineString25D )
        nShapeType = SHPT_ARCZ;
    else if( eType == wkbMultiLineString )
        nShapeType = SHPT_ARC;
    else if( eType == wkbMultiLineString25D )
        nShapeType = SHPT_ARCZ;
    else if( eType == wkbPolygon25D )
        nShapeType = SHPT_POLYGONZ;
    else if( eType == wkbMultiPolygon )
        nShapeType = SHPT_POLYGON;
    else if( eType == wkbMultiPolygon25D )
        nShapeType = SHPT_POLYGONZ;
    else if( eType == wkbMultiPoint25D )
        nShapeType = SHPT_MULTIPOINTZ;
    else if( eType == wkbNone )
        nShapeType = SHPT_NULL;
    else
        nShapeType = -1;

    /* -------------------------------------------------------------------- */
    /*      Has the application overridden this with a special creation     */
    /*      option?                                                         */
    /* -------------------------------------------------------------------- */
    const char *pszOverride = CSLFetchNameValue( papszOptions, "SHPT" );

    if( pszOverride == NULL )
        /* ignore */;
    else if( EQUAL(pszOverride,"POINT") )
    {
        nShapeType = SHPT_POINT;
        eType = wkbPoint;
    }
    else if( EQUAL(pszOverride,"ARC") )
    {
        nShapeType = SHPT_ARC;
        eType = wkbLineString;
    }
    else if( EQUAL(pszOverride,"POLYGON") )
    {
        nShapeType = SHPT_POLYGON;
        eType = wkbPolygon;
    }
    else if( EQUAL(pszOverride,"MULTIPOINT") )
    {
        nShapeType = SHPT_MULTIPOINT;
        eType = wkbMultiPoint;
    }
    else if( EQUAL(pszOverride,"POINTZ") )
    {
        nShapeType = SHPT_POINTZ;
        eType = wkbPoint25D;
    }
    else if( EQUAL(pszOverride,"ARCZ") )
    {
        nShapeType = SHPT_ARCZ;
        eType = wkbLineString25D;
    }
    else if( EQUAL(pszOverride,"POLYGONZ") )
    {
        nShapeType = SHPT_POLYGONZ;
        eType = wkbPolygon25D;
    }
    else if( EQUAL(pszOverride,"MULTIPOINTZ") )
    {
        nShapeType = SHPT_MULTIPOINTZ;
        eType = wkbMultiPoint25D;
    }
    else if( EQUAL(pszOverride,"NONE") )
    {
        nShapeType = SHPT_NULL;
    }
    else
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Unknown SHPT value of `%s' passed to Shapefile layer\n"
                  "creation.  Creation aborted.\n",
                  pszOverride );

        return NULL;
    }

    if( nShapeType == -1 )
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Geometry type of `%s' not supported in shapefiles.\n"
                  "Type can be overridden with a layer creation option\n"
                  "of SHPT=POINT/ARC/POLYGON/MULTIPOINT/POINTZ/ARCZ/POLYGONZ/MULTIPOINTZ.\n",
                  OGRGeometryTypeToName(eType) );
        return NULL;
    }

    /* -------------------------------------------------------------------- */
    /*      What filename do we use, excluding the extension?               */
    /* -------------------------------------------------------------------- */
    char *pszBasename;

    if( bSingleNewFile && nLayers == 0 )
    {
        char *pszPath = CPLStrdup(CPLGetPath(pszName));
        char *pszFBasename = CPLStrdup(CPLGetBasename(pszName));

        pszBasename = CPLStrdup(CPLFormFilename(pszPath, pszFBasename, NULL));

        CPLFree( pszFBasename );
        CPLFree( pszPath );
    }
    else if( bSingleNewFile )
    {
        char *pszPath = CPLStrdup(CPLGetPath(pszName));
        pszBasename = CPLStrdup(CPLFormFilename(pszPath,pszLayerName,NULL));
        CPLFree( pszPath );
    }
    else
        pszBasename = CPLStrdup(CPLFormFilename(pszName,pszLayerName,NULL));

    /* -------------------------------------------------------------------- */
    /*      Create the shapefile.                                           */
    /* -------------------------------------------------------------------- */
    char        *pszFilename;

    if( nShapeType != SHPT_NULL )
    {
        pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "shp" ));

        hSHP = SHPCreate( pszFilename, nShapeType );

        if( hSHP == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                      "Failed to open Shapefile `%s'.\n",
                      pszFilename );
            CPLFree( pszFilename );
            CPLFree( pszBasename );
            return NULL;
        }
        CPLFree( pszFilename );
    }
    else
        hSHP = NULL;

    /* -------------------------------------------------------------------- */
    /*      Create a DBF file.                                              */
    /* -------------------------------------------------------------------- */
    pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "dbf" ));

    hDBF = DBFCreate( pszFilename );

    if( hDBF == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Failed to open Shape DBF file `%s'.\n",
                  pszFilename );
        CPLFree( pszFilename );
        CPLFree( pszBasename );
        return NULL;
    }

    CPLFree( pszFilename );

    /* -------------------------------------------------------------------- */
    /*      Create the .prj file, if required.                              */
    /* -------------------------------------------------------------------- */
    if( poSRS != NULL )
    {
        char    *pszWKT = NULL;
        CPLString osPrjFile = CPLFormFilename( NULL, pszBasename, "prj");
        FILE    *fp;

        /* the shape layer needs it's own copy */
        poSRS = poSRS->Clone();
        poSRS->morphToESRI();

        if( poSRS->exportToWkt( &pszWKT ) == OGRERR_NONE
                && (fp = VSIFOpen( osPrjFile, "wt" )) != NULL )
        {
            VSIFWrite( pszWKT, strlen(pszWKT), 1, fp );
            VSIFClose( fp );
        }

        CPLFree( pszWKT );

        poSRS->morphFromESRI();
    }

    /* -------------------------------------------------------------------- */
    /*      Create the layer object.                                        */
    /* -------------------------------------------------------------------- */
    OGRShapeLayer       *poLayer;

    poLayer = new OGRShapeLayer( pszBasename, hSHP, hDBF, poSRS, TRUE,
                                 eType );

    poLayer->InitializeIndexSupport( pszBasename );

    CPLFree( pszBasename );

    /* -------------------------------------------------------------------- */
    /*      Add layer to data source layer list.                            */
    /* -------------------------------------------------------------------- */
    papoLayers = (OGRShapeLayer **)
                 CPLRealloc( papoLayers,  sizeof(OGRShapeLayer *) * (nLayers+1) );

    papoLayers[nLayers++] = poLayer;

    return poLayer;
}
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;
}
示例#9
0
/**
 * Vectoriza todos los trazos de una imagen binaria. Los trazos deben estar completamente adelgazados
 * @param imgBase Imagen binaria CV_8U
 * @param filename Nombre del archivo de salida (sin extensión)
 * @param deltaRDP Delta de reducción de puntos Ramen-Douglas-Peucker, entre más grande más agresivo, en 0 no se hace reducción de puntos (valores ejemplo: 0.5, 1, 2...)
 * @param suavizado Nivel de suavizado con interpolación spline Catmull-Rom, en 0 no se suavizan los trazos (valores ejemplo: 0, 1, 2, 4...)
 */
void vect::execVectorize(Mat &imgBase, const char *filename, float deltaRDP, short int suavizado, InfoMapa *iMapa) {
    SHPHandle sh = SHPCreate(filename, SHPT_ARC);
    DBFHandle dbf = DBFCreate(filename);
    int res = DBFAddField(dbf,"T_ALT", FTDouble, 12, 4);
    DBFClose(dbf);
    DBFHandle hDBF = DBFOpen(filename,"rb+");

    cout<<res<<",,,,,,,,,,,,,,,,,,,,,,,"<<endl;

    int imgAncho = imgBase.cols;
    int imgAlto = imgBase.rows;

    Point pA = Point(iMapa->recXmin,iMapa->recYmin);
    cout<<"XMIN"<<iMapa->recXmin<<endl;
    cout<<"YMIN"<<iMapa->recYmin<<endl;
/*
    Point pA = Point(492, 372);
    iMapa->setCoordsPuntosRef(1060000, 770000, 1075000, 770000, 1075000, 760000, 1060000, 760000);
    iMapa->setPosPuntosRef(522, 371,9957, 475, 9882, 6799, 453, 6701);
*/
    transformGeo *objGeo = new transformGeo();
    objGeo->setCoeficients(iMapa);
    // recorremos toda la imagen buscando puntos finales

    int altop = 0;
    vector<Point> punFinales;
    vect::puntosFinales(imgBase, punFinales);

    // para cada punto final, recorremos el trazo correspondiente y guardamos el vector
    Point pun;
    vector<Point2f> trazo;
    vector<Point2f> trazoSuave;
    for(vector<Point>::iterator it = punFinales.begin(); it != punFinales.end(); ++it) {
        pun = *it;
        cout << "recorrerTrazo() " << pun << endl;
        recorrerTrazo(imgBase, pun, trazo, false);

        if (trazo.size() > 1) {
            vec_RDP::reducirPuntos(trazo, deltaRDP); // aplicamos reducción de puntos Ramer-Douglas-Peucker
            catmull::interpolar(trazo, trazoSuave, suavizado);
            agregarShape(((suavizado > 0) ? trazoSuave : trazo), altop, sh, objGeo, pA, hDBF);
        }
    }

    // Buscamos en toda la imagen, si aún hay pixeles sin borrar, son de trayectos cerrados
    unsigned int x, y;
    uchar* fila;
    uchar intensidad;

    for (y = 1 ; y < (imgAlto - 1) ; ++y) {
        fila = imgBase.ptr<uchar>(y);
        for (x = 1 ; x < (imgAncho - 1) ; ++x) {
            intensidad = fila[x];
            if (intensidad == 0) {
                pun = Point(x, y);

                recorrerTrazo(imgBase, pun, trazo, true);

                if (trazo.size() > 1) {
                    vec_RDP::reducirPuntos(trazo, deltaRDP); // aplicamos reducción de puntos Ramer-Douglas-Peucker
                    catmull::interpolar(trazo, trazoSuave, suavizado);
                    agregarShape(((suavizado > 0) ? trazoSuave : trazo), imgAlto, sh, objGeo, pA, hDBF);
                }
            }
        }
    }
DBFClose(hDBF);
    SHPClose(sh);

}
示例#10
0
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!" );
  }
}
示例#11
0
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!" );
  }
}
示例#12
0
/**
 * 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);
}  
示例#13
0
static void WriteAttributeDBF( const char * pszShapefile,
                               SDTSTransfer * poTransfer,
                               const char * pszMODN )

{
    SDTSAttrReader      *poAttrReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    poAttrReader = (SDTSAttrReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poAttrReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poAttrReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );

/* -------------------------------------------------------------------- */
/*      Prepare the schema.                                             */
/* -------------------------------------------------------------------- */
    char        **papszMODNList = CSLAddString( NULL, pszMODN );

    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszMODNList );

    CSLDestroy( papszMODNList );
    
/* ==================================================================== */
/*      Process all the records in the module.                          */
/* ==================================================================== */
    SDTSAttrRecord *poRecord;
    int         iRecord = 0;

    while((poRecord = (SDTSAttrRecord*)poAttrReader->GetNextFeature()) != NULL)
    {
        DBFWriteIntegerAttribute( hDBF, iRecord, 0,
                                  poRecord->oModId.nRecord );

        WriteAttrRecordToDBF( hDBF, iRecord, poTransfer, poRecord->poATTR );

        if( !poAttrReader->IsIndexed() )
            delete poRecord;
        
        iRecord++;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
}    
示例#14
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;
};
示例#15
0
int main( int argc, char ** argv )

{
    DBFHandle	hDBF;
    int		i;

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc < 2 )
    {
	printf( "dbfcreate xbase_file [[-s field_name width],[-n field_name width decimals]]...\n" );

	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*	Create the database.						*/
/* -------------------------------------------------------------------- */
    hDBF = DBFCreate( argv[1] );
    if( hDBF == NULL )
    {
	printf( "DBFCreate(%s) failed.\n", argv[1] );
	exit( 2 );
    }
    
/* -------------------------------------------------------------------- */
/*	Loop over the field definitions adding new fields.	       	*/
/* -------------------------------------------------------------------- */
    for( i = 2; i < argc; i++ )
    {
	if( strcmp(argv[i],"-s") == 0 && i < argc-2 )
	{
	    if( DBFAddField( hDBF, argv[i+1], FTString, atoi(argv[i+2]), 0 )
                == -1 )
	    {
		printf( "DBFAddField(%s,FTString,%d,0) failed.\n",
		        argv[i+1], atoi(argv[i+2]) );
		exit( 4 );
	    }
	    i = i + 2;
	}
	else if( strcmp(argv[i],"-n") == 0 && i < argc-3 )
	{
	    if( DBFAddField( hDBF, argv[i+1], FTDouble, atoi(argv[i+2]), 
			      atoi(argv[i+3]) ) == -1 )
	    {
		printf( "DBFAddField(%s,FTDouble,%d,%d) failed.\n",
		        argv[i+1], atoi(argv[i+2]), atoi(argv[i+3]) );
		exit( 4 );
	    }
	    i = i + 3;
	}
	else
	{
	    printf( "Argument incomplete, or unrecognised:%s\n", argv[i] );
	    exit( 3 );
	}
    }

    DBFClose( hDBF );

    return( 0 );
}
示例#16
0
void shape_ursa_init(char *inFile, char *header)
{
  char *dbaseFile;
  DBFHandle dbase;
  SHPHandle shape;
  dbf_header_t *dbf;
  int ii, nCols, length=50;

  // Read configuration file
  read_header_config("URSA", &dbf, &nCols);

  // Open database for initialization
  dbaseFile = appendExt(inFile, ".dbf");
  dbase = DBFCreate(dbaseFile);
  if (!dbase)
    asfPrintError("Could not create database file '%s'\n", dbaseFile);

  // Add fields to database
  for (ii=0; ii<nCols; ii++) {
    if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "GRAN_NAME", FTString, length, 0) == -1)
        asfPrintError("Could not add GRAN_NAME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Granule_Type") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "GRAN_TYPE", FTString, length, 0) == -1)
        asfPrintError("Could not add GRAN_TYPE field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "PLATFORM", FTString, length, 0) == -1)
        asfPrintError("Could not add PLATFORM field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "SENSOR", FTString, length, 0) == -1)
        asfPrintError("Could not add SENSOR field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "ORBIT", FTInteger, 7, 0) == -1)
        asfPrintError("Could not add ORBIT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "BEAM_MODE", FTString, length, 0) == -1)
        asfPrintError("Could not add BEAM_MODE field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "OFF_NADIR", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add OFF_NADIR field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "START_TIME", FTString, length, 0) == -1)
        asfPrintError("Could not add START_TIME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "END_TIME", FTString, length, 0) == -1)
        asfPrintError("Could not add END_TIME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "NSTART_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add NSTART_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "NSTART_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add NSTART_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "FSTART_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add FSTART_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "FSTART_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add FSTART_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "N_END_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add N_END_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "N_END_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add N_END_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "F_END_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add F_END_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "F_END_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add F_END_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "CENTER_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add CENTER_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "CENTER_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add CENTER_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "PATH_NUM", FTInteger, 10, 0) == -1)
        asfPrintError("Could not add PATH_NUM field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "FRAME_NUM", FTInteger, 10, 0) == -1)
        asfPrintError("Could not add FRAME_NUM field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Cloud_Cover") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "CLOUDCOVER", FTInteger, 5, 0) == -1)
        asfPrintError("Could not add CLOUDCOVER field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "FARADAYROT", FTDouble, 16, 1) == -1)
        asfPrintError("Could not add FARADAYROT field to database file\n");
    }
  }

  // Close the database for initialization
  DBFClose(dbase);

  // Open shapefile for initialization
  shape = SHPCreate(inFile, SHPT_POLYGON);
  if (!shape)
    asfPrintError("Could not create shapefile '%s'\n", inFile);

  // Close shapefile for initialization
  SHPClose(shape);

  FREE(dbaseFile);

  return;
}
示例#17
0
void openfiles() {
/* -------------------------------------------------------------------- */
/*      Open the DBF file.                                              */
/* -------------------------------------------------------------------- */
    setext(infile, "dbf");
    hDBF = DBFOpen( infile, "rb" );
    if( hDBF == NULL )
    {
	printf( "ERROR: Unable to open the input DBF:%s\n", infile );
	exit( 1 );
    }
/* -------------------------------------------------------------------- */
/*      Open the append DBF file.                                       */
/* -------------------------------------------------------------------- */
    if (strcmp(outfile,"")) {
        setext(outfile, "dbf");
        hDBFappend = DBFOpen( outfile, "rb+" );
        newdbf=0;
        if( hDBFappend == NULL )
        {
            newdbf=1;
            hDBFappend = DBFCreate( outfile );
            if( hDBFappend == NULL )
            {
                printf( "ERROR: Unable to open the append DBF:%s\n", outfile );
                exit( 1 );
            }
        }
    }
/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    setext(infile, "shp");
    hSHP = SHPOpen( infile, "rb" );

    if( hSHP == NULL )
    {
	printf( "ERROR: Unable to open the input shape file:%s\n", infile );
	exit( 1 );
    }

    SHPGetInfo( hSHP, &nEntities, &nShapeType, NULL, NULL );

/* -------------------------------------------------------------------- */
/*      Open the passed append shapefile.                               */
/* -------------------------------------------------------------------- */
    if (strcmp(outfile,"")) {
        setext(outfile, "shp");
        hSHPappend = SHPOpen( outfile, "rb+" );

        if( hSHPappend == NULL )
        {
            hSHPappend = SHPCreate( outfile, nShapeType );
            if( hSHPappend == NULL )
            {
                printf( "ERROR: Unable to open the append shape file:%s\n",
                        outfile );
                exit( 1 );
            }
        }
        SHPGetInfo( hSHPappend, &nEntitiesAppend, &nShapeTypeAppend,
                    NULL, NULL );

        if (nShapeType != nShapeTypeAppend) 
        {
            puts( "ERROR: Input and Append shape files are of different types.");
            exit( 1 );
        }
    }
}
void shapefileClip::CreateShapeFile(vector<ossimPolygon> &polys, const char *shapeFilename)
{
	if (polys.empty())
	{
		cerr << "The polygons do not exist...cannot create shape file" << endl
		<< "Line: " << __LINE__ << " " << __FILE__ << endl;
		return;
	}

	SHPObject *psObject;
	SHPHandle hSHP;
	double *px, *py;
	vector<ossimPolygon>::iterator polyIter;
	vector<ossimDpt> vertices;
	vector<ossimDpt>::iterator vertIter;

	hSHP = SHPCreate(shapeFilename, SHPT_POLYGON);

	if( hSHP == NULL || shapeFilename == NULL)
	{
		cerr << "Unable to create: " << shapeFilename <<  endl
		<< "Line: " << __LINE__ << " " << __FILE__ << endl;
		exit(EXIT_FAILURE);
	}
	// Build DBF.
	DBFHandle hDBF;

	hDBF = DBFCreate(shapeFilename);
	if( hDBF == NULL)
	{
		cerr << "Unable to create: " << shapeFilename << " DBF File" <<  endl
		<< "Line: " << __LINE__ << " " << __FILE__ << endl;
		exit(EXIT_FAILURE);
	}


	// Add fields.
	DBFAddField(hDBF, "poly_num", FTString, 30, 0);

	polyIter = polys.begin();

	int arrayIndex;
	int poly_num = 0;
	while (polyIter != polys.end())
	{
		DBFWriteStringAttribute(hDBF, poly_num, 0, ossimString::toString(poly_num));
		vertices = (*polyIter).getVertexList();
		vertIter = vertices.begin();

		double *x = new double[vertices.size()];
		double *y = new double[vertices.size()];
		int *panParts = new int[vertices.size()];
		panParts[0] = 0;

		// SHPCreateObject deletes these
		px = &x[0];
		py = &y[0];

		arrayIndex = 0;
		while (vertIter != vertices.end())
		{
			x[arrayIndex] = (*vertIter).x;
			y[arrayIndex++] = (*vertIter).y;
			vertIter++;
		}

		psObject = SHPCreateObject( SHPT_POLYGON, -1, 1, panParts, NULL,
				vertices.size(), px, py, NULL, NULL );
		if (psObject != NULL)
		{
			SHPWriteObject( hSHP, -1, psObject );
			SHPDestroyObject( psObject );
		}
		else
		{
			cerr << "Shape object could not be written to file" << endl
			<< "Line: " << __LINE__ << " " << __FILE__ << endl;
			SHPClose(hSHP);
			delete []x;
			delete []y;
			delete [] panParts;
			exit(EXIT_FAILURE);
		}

		polyIter++;
		poly_num++;
		delete []x;
		delete []y;
		delete [] panParts;
	}
	DBFClose(hDBF);
	SHPClose( hSHP );
}
示例#19
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;
}
示例#20
0
void init_baseline_shape(char *inFile, int sensor_count)
{
    char *dbaseFile;
    DBFHandle dbase;
    SHPHandle shape;

    // Open database for initialization
    dbaseFile = (char *) MALLOC(sizeof(char)*(strlen(inFile)+5));
    sprintf(dbaseFile, "%s.dbf", inFile);
    dbase = DBFCreate(dbaseFile);
    if (!dbase)
        asfPrintError("Could not create database file '%s'\n", dbaseFile);

    // Add fields to database
    if (sensor_count == 1) {
        if (DBFAddField(dbase, "Sensor", FTString, 15, 0) == -1)
            asfPrintError("Could not add sensor field to database file\n");
    }
    else {
        if (DBFAddField(dbase, "Master_sensor", FTString, 15, 0) == -1)
            asfPrintError("Could not add sensor field to database file\n");
        if (DBFAddField(dbase, "Slave_sensor", FTString, 15, 0) == -1)
            asfPrintError("Could not add sensor field to database file\n");
    }
    if (DBFAddField(dbase, "Beam_mode", FTString, 5, 0) == -1)
        asfPrintError("Could not add beam mode to database file\n");
    if (DBFAddField(dbase, "Frame", FTInteger, 4, 0) == -1)
        asfPrintError("Could not add frame field to database file\n");
    if (DBFAddField(dbase, "Direction", FTString, 15, 0) == -1)
        asfPrintError("Could not add orbit direction field to database file\n");
    if (DBFAddField(dbase, "Master", FTInteger, 5, 0) == -1)
        asfPrintError("Could not add master field to database file\n");
    if (DBFAddField(dbase, "Master_date", FTString, 20, 0) == -1)
        asfPrintError("Could not add master acquisition date field"
                      " to database file\n");
    if (DBFAddField(dbase, "Slave", FTInteger, 5, 0) == -1)
        asfPrintError("Could not add slave field to database file\n");
    if (DBFAddField(dbase, "Slave_date", FTString, 20, 0) == -1)
        asfPrintError("Could not add slave acquisition date field"
                      " to database file\n");
    if (DBFAddField(dbase, "B_par", FTInteger, 5, 0) == -1)
        asfPrintError("Could not add parallel baseline field to database file\n");
    if (DBFAddField(dbase, "B_perp", FTInteger, 5, 0) == -1)
        asfPrintError("Could not add perpendicular baseline field"
                      " to database file\n");
    if (DBFAddField(dbase, "B_temp", FTInteger, 5, 0) == -1)
        asfPrintError("Could not add temporal baseline field to database file\n");
    if (DBFAddField(dbase, "Center_Lat", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add center latitude field to database file\n");
    if (DBFAddField(dbase, "Center_Lon", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add center longitude field to database file\n");
    if (DBFAddField(dbase, "Lat1", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add latitude field to database file\n");
    if (DBFAddField(dbase, "Lon1", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add longitude field to database file\n");
    if (DBFAddField(dbase, "Lat2", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add latitude field to database file\n");
    if (DBFAddField(dbase, "Lon2", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add longitude field to database file\n");
    if (DBFAddField(dbase, "Lat3", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add latitude field to database file\n");
    if (DBFAddField(dbase, "Lon3", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add longitude field to database file\n");
    if (DBFAddField(dbase, "Lat4", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add latitude field to database file\n");
    if (DBFAddField(dbase, "Lon4", FTDouble, 9, 4) == -1)
        asfPrintError("Could not add longitude field to database file\n");

    // Close the database for initialization
    DBFClose(dbase);

    // Open shapefile for initialization
    shape = SHPCreate(inFile, SHPT_POLYGON);
    if (!shape)
        asfPrintError("Could not create shapefile '%s'\n", inFile);

    // Close shapefile for initialization
    SHPClose(shape);

    FREE(dbaseFile);

    return;
}
示例#21
0
            panSuccess[i] = TRUE;
        }
    }

/* -------------------------------------------------------------------- */
/*      geox/geoy to pixel/line using search algorithm.                 */
/* -------------------------------------------------------------------- */
#ifdef notdef
    else
    {
        int i;
        int nStartX = -1, nStartY = -1;

#ifdef SHAPE_DEBUG
        hSHP = SHPCreate( "tracks.shp", SHPT_ARC );
        hDBF = DBFCreate( "tracks.dbf" );
        DBFAddField( hDBF, "GEOX", FTDouble, 10, 4 );
        DBFAddField( hDBF, "GEOY", FTDouble, 10, 4 );
#endif
        for( i = 0; i < nPointCount; i++ )
        {
            double dfGeoLocX, dfGeoLocY;

            if( padfX[i] == HUGE_VAL || padfY[i] == HUGE_VAL )
            {
                panSuccess[i] = FALSE;
                continue;
            }

            if( !FindGeoLocPosition( psTransform, padfX[i], padfY[i], 
                                     -1, -1, &dfGeoLocX, &dfGeoLocY ) )
示例#22
0
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;
}
示例#23
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;
}
示例#24
0
static void WriteLineShapefile( const char * pszShapefile,
                                SDTSTransfer * poTransfer,
                                const char * pszMODN )

{
/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    SDTSLineReader *poLineReader = (SDTSLineReader *)
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );

    if( poLineReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poLineReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_ARC );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nLeftPolyField, nRightPolyField;
    int         nStartNodeField, nEndNodeField, nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );
    nLeftPolyField = DBFAddField( hDBF, "LeftPoly", FTString, 12, 0 );
    nRightPolyField = DBFAddField( hDBF, "RightPoly", FTString, 12, 0 );
    nStartNodeField = DBFAddField( hDBF, "StartNode", FTString, 12, 0 );
    nEndNodeField = DBFAddField( hDBF, "EndNode", FTString, 12, 0 );

    char  **papszModRefs = poLineReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the line features in the module.                    */
/* ==================================================================== */
    SDTSRawLine *poRawLine = NULL;

    while( (poRawLine = poLineReader->GetNextLine()) != NULL )
    {
/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject *psShape =
            SHPCreateSimpleObject( SHPT_ARC, poRawLine->nVertices,
                                   poRawLine->padfX, poRawLine->padfY,
                                   poRawLine->padfZ );

        int iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        char    szID[13];

        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawLine->oModId.nRecord );

        sprintf( szID, "%s:%d",
                 poRawLine->oLeftPoly.szModule,
                 poRawLine->oLeftPoly.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nLeftPolyField, szID );

        sprintf( szID, "%s:%d",
                 poRawLine->oRightPoly.szModule,
                 poRawLine->oRightPoly.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nRightPolyField, szID );

        sprintf( szID, "%s:%d",
                 poRawLine->oStartNode.szModule,
                 poRawLine->oStartNode.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nStartNodeField, szID );

        sprintf( szID, "%s:%d",
                 poRawLine->oEndNode.szModule,
                 poRawLine->oEndNode.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nEndNodeField, szID );

        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawLine );

        if( !poLineReader->IsIndexed() )
            delete poRawLine;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}
示例#25
0
static void WritePointShapefile( const char * pszShapefile,
                                 SDTSTransfer * poTransfer,
                                 const char * pszMODN )

{
    SDTSPointReader     *poPointReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    poPointReader = (SDTSPointReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poPointReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poPointReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_POINT );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nAreaField, nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );
    nAreaField = DBFAddField( hDBF, "AreaId", FTString, 12, 0 );
    
    char  **papszModRefs = poPointReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the line features in the module.                    */
/* ==================================================================== */
    SDTSRawPoint        *poRawPoint;
        
    while( (poRawPoint = poPointReader->GetNextPoint()) != NULL )
    {
        int             iShape;
        
/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject       *psShape;

        psShape = SHPCreateSimpleObject( SHPT_POINT, 1,
                                         &(poRawPoint->dfX),
                                         &(poRawPoint->dfY),
                                         &(poRawPoint->dfZ) );

        iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        char    szID[13];

        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawPoint->oModId.nRecord );
        
        sprintf( szID, "%s:%ld",
                 poRawPoint->oAreaId.szModule,
                 poRawPoint->oAreaId.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nAreaField, szID );

        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoint );

        if( !poPointReader->IsIndexed() )
            delete poRawPoint;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}    
示例#26
0
void shape_datapool_init(char *inFile, char *header)
{
  char *dbaseFile;
  DBFHandle dbase;
  SHPHandle shape;
  dbf_header_t *dbf;
  int ii, nCols, length=32, length2=255;

  // Read configuration file
  read_header_config("DATAPOOL", &dbf, &nCols);

  // Open database for initialization
  dbaseFile = appendExt(inFile, ".dbf");
  dbase = DBFCreate(dbaseFile);
  if (!dbase)
    asfPrintError("Could not create database file '%s'\n", dbaseFile);

  // Add fields to database
  for (ii=0; ii<nCols; ii++) {
    if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "GRAN_NAME", FTString, length, 0) == -1)
        asfPrintError("Could not add GRAN_NAME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "PLATFORM", FTString, length, 0) == -1)
        asfPrintError("Could not add PLATFORM field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "SENSOR", FTString, length, 0) == -1)
        asfPrintError("Could not add SENSOR field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "BEAM_MODE", FTString, length2, 0) == -1)
        asfPrintError("Could not add BEAM_MODE field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode_Description") == 0 && 
	     dbf[ii].visible) {
      if (DBFAddField(dbase, "BEAM_MODE_D", FTString, length, 0) == -1)
        asfPrintError("Could not add BEAM_MODE_D field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "ORBIT", FTInteger, 7, 0) == -1)
        asfPrintError("Could not add ORBIT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "PATH_NUM", FTInteger, 10, 0) == -1)
        asfPrintError("Could not add PATH_NUM field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "FRAME_NUM", FTInteger, 10, 0) == -1)
        asfPrintError("Could not add FRAME_NUM field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Acquisition_Date") == 0 && 
	     dbf[ii].visible) {
      if (DBFAddField(dbase, "ACQ_DATE", FTString, length, 0) == -1)
        asfPrintError("Could not add ACQ_TIME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Processing_Date") == 0 && 
	     dbf[ii].visible) {
      if (DBFAddField(dbase, "PROC_DATE", FTString, length, 0) == -1)
        asfPrintError("Could not add PROC_TIME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Processing_Level") == 0 && 
	     dbf[ii].visible) {
      if (DBFAddField(dbase, "PROC_LEVEL", FTString, 10, 0) == -1)
        asfPrintError("Could not add PROC_LEVEL field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "START_TIME", FTString, length, 0) == -1)
        asfPrintError("Could not add START_TIME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "END_TIME", FTString, length, 0) == -1)
        asfPrintError("Could not add END_TIME field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "CENTER_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add CENTER_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "CENTER_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add CENTER_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "NSTART_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add NSTART_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "NSTART_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add NSTART_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "FSTART_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add FSTART_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "FSTART_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add FSTART_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "N_END_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add N_END_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "N_END_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add N_END_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "F_END_LAT", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add F_END_LAT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "F_END_LON", FTDouble, 16, 4) == -1)
        asfPrintError("Could not add F_END_LON field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "FARADAYROT", FTDouble, 16, 1) == -1)
        asfPrintError("Could not add FARADAYROT field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Orbit_Direction") == 0 && 
	     dbf[ii].visible) {
      if (DBFAddField(dbase, "ORBIT_DIR", FTString, length, 0) == -1)
        asfPrintError("Could not add ORBIT_DIR field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Url") == 0 && dbf[ii].visible) {
      if (DBFAddField(dbase, "URL", FTString, length2, 0) == -1)
        asfPrintError("Could not add URL field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Size") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "SIZE_MB", FTDouble, 16, 2) == -1)
        asfPrintError("Could not add SIZE_MB field to database file\n");
    }
    else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 &&
         dbf[ii].visible) {
      if (DBFAddField(dbase, "OFF_NADIR", FTDouble, 16, 2) == -1)
        asfPrintError("Could not add OFF_NADIR field to database file\n");
    }
  }

  // Close the database for initialization
  DBFClose(dbase);

  // Open shapefile for initialization
  shape = SHPCreate(inFile, SHPT_POLYGON);
  if (!shape)
    asfPrintError("Could not create shapefile '%s'\n", inFile);

  // Close shapefile for initialization
  SHPClose(shape);

  FREE(dbaseFile);

  return;
}
示例#27
0
static void WritePolygonShapefile( const char * pszShapefile,
                                   SDTSTransfer * poTransfer, 
                                   const char * pszMODN )

{
    SDTSPolygonReader *poPolyReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed polygon reader.                */
/* -------------------------------------------------------------------- */
    poPolyReader = (SDTSPolygonReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poPolyReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Assemble polygon geometries from all the line layers.           */
/* -------------------------------------------------------------------- */
    poPolyReader->AssembleRings( poTransfer, poTransfer->FindLayer(pszMODN) );
    
/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_POLYGON );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );

    char  **papszModRefs = poPolyReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the polygon features in the module.                 */
/* ==================================================================== */
    SDTSRawPolygon      *poRawPoly;

    poPolyReader->Rewind();
    while( (poRawPoly = (SDTSRawPolygon *) poPolyReader->GetNextFeature())
           != NULL )
    {
        int             iShape;

/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject       *psShape;

        psShape = SHPCreateObject( SHPT_POLYGON, -1, poRawPoly->nRings,
                                   poRawPoly->panRingStart, NULL,
                                   poRawPoly->nVertices,
                                   poRawPoly->padfX, 
                                   poRawPoly->padfY, 
                                   poRawPoly->padfZ,
                                   NULL );

        iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawPoly->oModId.nRecord );
        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoly );

        if( !poPolyReader->IsIndexed() )
            delete poRawPoly;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}    
示例#28
0
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;

};
示例#29
0
CC_FILE_ERROR ShpFilter::saveToFile(ccHObject* entity, const std::vector<GenericField*>& fields, QString filename)
{
	if (!entity)
		return CC_FERR_BAD_ENTITY_TYPE;
	
	//this filter only supports point clouds, meshes and polylines!
	ESRI_SHAPE_TYPE inputShapeType = SHP_NULL_SHAPE;
	ccHObject::Container toSave;
	GetSupportedShapes(entity,toSave,inputShapeType/*,m_closedPolylinesAsPolygons*/);

	if (inputShapeType == SHP_NULL_SHAPE || toSave.empty())
		return CC_FERR_BAD_ENTITY_TYPE;

	ESRI_SHAPE_TYPE outputShapeType = inputShapeType;
	if (m_closedPolylinesAsPolygons && (inputShapeType == SHP_POLYLINE || inputShapeType == SHP_POLYLINE_Z))
	{
		//check if all the polylines are closed!
		bool allAreClosed = true;
		for (size_t i=0; i<toSave.size() && allAreClosed; ++i)
		{
			if (!static_cast<ccPolyline*>(toSave[i])->isClosed())
				allAreClosed = false;
		}

		if (allAreClosed)
		{
			//promote 'polylines' to 'polygon'
			outputShapeType = SHP_POLYLINE ? SHP_POLYGON : SHP_POLYGON_Z;
		}
	}

	ccLog::Print("[SHP] Output type: " + ToString(outputShapeType));

	QFileInfo fi(filename);
	QString baseFileName = fi.path() + QString("/") + fi.completeBaseName();

	//the main file (suffix should be ".shp")
	QString shpFilename = baseFileName+QString(".shp");
	QFile file(shpFilename);
	if (!file.open(QIODevice::WriteOnly))
		return CC_FERR_WRITING;

	//index file (same base name + ".shx")
	QString indexFilename = baseFileName+QString(".shx");
	QFile indexFile(indexFilename);
	if (!indexFile.open(QIODevice::WriteOnly))
		return CC_FERR_WRITING;

	//build header (refer to ESRI Shapefile Technical Description)
	char header[100];
	memset(header,0,100);
	{
		/*** WARNING: the beginning of the header is written with big endianness! ***/
		char* _header = header;
		
		//Byte 0: SHP code
		const int32_t code = qToBigEndian<int32_t>(9994);
		memcpy(_header,(const char*)&code,4);
		_header += 4;

		//Byte 4: unused (20 bytes)
		_header += 20;

		//Byte 24: file length (will be written... later ;)
		_header += 4;

		/*** WARNING: from now on, we only write data with little endianness! ***/

		//Byte 28: file verion
		const int32_t version = qToLittleEndian<int32_t>(1000);
		memcpy(_header,(const char*)&version,4);
		_header += 4;

		//Byte 32: shape type
		int32_t shapeTypeInt = qToLittleEndian<int32_t>(outputShapeType);
		memcpy(_header,(const char*)&shapeTypeInt,4);
		_header += 4;

		ccBBox box = entity->getBB();
		assert(box.isValid());

		//X and Y bounaries
		double xMin = qToLittleEndian<double>(box.minCorner().x);
		double xMax = qToLittleEndian<double>(box.maxCorner().x);
		double yMin = qToLittleEndian<double>(box.minCorner().y);
		double yMax = qToLittleEndian<double>(box.maxCorner().y);
		//Byte 36: box X min
		memcpy(_header,(const char*)&xMin,8);
		_header += 8;
		//Byte 44: box Y min
		memcpy(_header,(const char*)&yMin,8);
		_header += 8;
		//Byte 52: box X max
		memcpy(_header,(const char*)&xMax,8);
		_header += 8;
		//Byte 60: box Y max
		memcpy(_header,(const char*)&yMax,8);
		_header += 8;

		//Z bounaries
		//Unused, with value 0.0, if not Measured or Z type
		double zMin = outputShapeType < SHP_POINT_Z ? 0.0 : qToLittleEndian<double>(box.minCorner().z);
		double zMax = outputShapeType < SHP_POINT_Z ? 0.0 : qToLittleEndian<double>(box.maxCorner().z);
		//Byte 68: box Z min
		memcpy(_header,(const char*)&zMin,8);
		_header += 8;
		//Byte 76: box Z max
		memcpy(_header,(const char*)&zMax,8);
		_header += 8;

		//M bounaries (M = measures)
		double mMin = ESRI_NO_DATA;
		double mMax = ESRI_NO_DATA;
		//Byte 84: M min
		memcpy(_header,(const char*)&mMin,8);
		_header += 8;
		//Byte 92: M max
		memcpy(_header,(const char*)&mMax,8);
		_header += 8;
	}

	//actually write the header
	if (!file.write(header,100))
		return CC_FERR_WRITING;
	if (!indexFile.write(header,100)) //exact same header for index file!
		return CC_FERR_WRITING;
	int32_t fileLength = 100;

	//save shapes
	unsigned shapeIndex = 0;
	for (unsigned i=0; i<toSave.size(); ++i)
	{
		ccHObject* child = toSave[i];
		
		//check entity elligibility
		if (child->isA(CC_TYPES::POLY_LINE))
		{
			if (static_cast<ccPolyline*>(child)->size() < 3)
			{
				ccLog::Warning(QString("Polyline '%1' is too small! It won't be saved...").arg(child->getName()));
				continue;
			}
		}

		int32_t recordSize = 0;
		qint64 recordStart = file.pos();
		//write shape record in main SHP file
		{
			//Byte 0: Record Number
			const int32_t recordNumber = qToBigEndian<int32_t>(++shapeIndex); //Record numbers begin at 1
			file.write((const char*)&recordNumber,4);
			//Byte 4: Content Length
			file.write((const char*)&recordSize,4); //will be updated later
		}
		fileLength += 8;

		CC_FILE_ERROR error = CC_FERR_NO_ERROR;
		switch (inputShapeType)
		{
		case SHP_POLYLINE:
		case SHP_POLYLINE_Z:
			assert(child->isKindOf(CC_TYPES::POLY_LINE));
			error = SavePolyline(static_cast<ccPolyline*>(child),file,recordSize,outputShapeType);
			break;
		case SHP_MULTI_POINT_Z:
			assert(child->isKindOf(CC_TYPES::POINT_CLOUD));
			error = SaveAsCloud(ccHObjectCaster::ToGenericPointCloud(child),file,recordSize);
			break;
		//case SHP_MULTI_PATCH:
		//	assert(child->isKindOf(CC_TYPES::MESH));
		//	error = SaveAsMesh(ccHObjectCaster::ToMesh(child),file,recordSize);
		//	break;
		default:
			assert(false);
			break;
		}

		if (error != CC_FERR_NO_ERROR)
			return error;

		fileLength += recordSize;

		//update record size
		{
			//backup current pos
			qint64 currentPos = file.pos();
			assert((qint64)fileLength == currentPos);
			//go backward
			file.seek(recordStart+4);
			int32_t recordSize16bits = qToBigEndian<int32_t>(recordSize/2); //recordSize is measured in 16-bit words
			file.write((const char*)&recordSize16bits,4);
			//restore last pos
			file.seek(currentPos);
		}

		//write corresponding entry in index SHX file
		{
			//Byte 0: Offset
			int32_t recordStart16bits = qToBigEndian<int32_t>(recordStart/2); //recordStart is measured in 16-bit words
			indexFile.write((const char*)&recordStart16bits,4);
			
			//Byte 4: Content Length
			int32_t recordSize16bits= qToBigEndian<int32_t>(recordSize/2); //recordSize is measured in 16-bit words
			indexFile.write((const char*)&recordSize16bits,4);
		}
	}

	//update main file length
	{
		file.seek(24);
		//Byte 24: file length (in 16-bit words)
		int32_t fileLength16bits = qToBigEndian<int32_t>(fileLength/2);
		file.write((const char*)&fileLength16bits,4);
	}
	file.close();

	//update idx file length
	{
		indexFile.seek(24);
		//Byte 24: file length (in 16-bit words)
		int32_t idxFileLength = (int32_t)indexFile.size();
		int32_t idxFileLength16bits = qToBigEndian<int32_t>(idxFileLength/2);
		indexFile.write((const char*)&idxFileLength16bits,4);
	}
	indexFile.close();

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;

	//eventually, we create the DB file (suffix should be ".dbf")
	QString dbfFilename = baseFileName+QString(".dbf");
	DBFHandle dbfHandle = DBFCreate(qPrintable(dbfFilename));
	if (dbfHandle)
	{
		while (true) //trick: we use 'while' to be able to break anytime
		{
			//always write an 'index' table
			{
				int fieldIdx = DBFAddField(dbfHandle,"local_idx",FTInteger,6,0);
				if (fieldIdx >= 0)
				{
					for (unsigned i=0; i<toSave.size(); ++i)
						DBFWriteIntegerAttribute(dbfHandle,static_cast<int>(i),fieldIdx,static_cast<int>(i)+1);
				}
				else
				{
					ccLog::Warning(QString("[ShpFilter::saveToFile] Failed to save field 'index' (default)"));
					result = CC_FERR_WRITING;
					break;
				}
			}

			//and write the other tables (specified by the user)
			for (std::vector<GenericField*>::const_iterator it = fields.begin(); it != fields.end(); ++it)
			{
				const GenericField* field = *it;
				if (field->is3D()) //3D case
				{
					int xFieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()+QString("_x")),field->type(),field->width(),field->decimal());
					int yFieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()+QString("_y")),field->type(),field->width(),field->decimal());
					int zFieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()+QString("_z")),field->type(),field->width(),field->decimal());
					if (xFieldIdx >= 0 && yFieldIdx >= 0 && zFieldIdx >= 0)
					{
						if (!(*it)->save(dbfHandle,xFieldIdx,yFieldIdx,zFieldIdx))
							xFieldIdx = -1;
					}

					if (xFieldIdx < 0)
					{
						ccLog::Warning(QString("[ShpFilter::saveToFile] Failed to save field '%1'").arg(field->name()));
						result = CC_FERR_WRITING;
						break;
					}
				}
				else //1D case
				{
					int fieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()),field->type(),field->width(),field->decimal());
					if (fieldIdx >= 0)
					{
						if (!(*it)->save(dbfHandle,fieldIdx))
							fieldIdx = -1;
					}

					if (fieldIdx < 0)
					{
						ccLog::Warning(QString("[ShpFilter::saveToFile] Failed to save field '%1'").arg(field->name()));
						result = CC_FERR_WRITING;
						break;
					}
				}
			}

			break;
		}

		DBFClose(dbfHandle);
	}
	else
	{
		result = CC_FERR_WRITING;
	}

	return result;
}
OGRLayer *
OGRShapeDataSource::CreateLayer( const char * pszLayerName,
                                 OGRSpatialReference *poSRS,
                                 OGRwkbGeometryType eType,
                                 char ** papszOptions )

{
    SHPHandle   hSHP;
    DBFHandle   hDBF;
    int         nShapeType;
    int         iLayer;

/* -------------------------------------------------------------------- */
/*      Check that the layer doesn't already exist.                     */
/* -------------------------------------------------------------------- */
    for( iLayer = 0; iLayer < nLayers; iLayer++ )
    {
        OGRLayer        *poLayer = papoLayers[iLayer];

        if( poLayer != NULL 
            && EQUAL(poLayer->GetLayerDefn()->GetName(),pszLayerName) )
        {
            CPLError( CE_Failure, CPLE_AppDefined, "Layer '%s' already exists",
                      pszLayerName);
            return NULL;
        }
    }

/* -------------------------------------------------------------------- */
/*      Verify we are in update mode.                                   */
/* -------------------------------------------------------------------- */
    if( !bDSUpdate )
    {
        CPLError( CE_Failure, CPLE_NoWriteAccess,
                  "Data source %s opened read-only.\n"
                  "New layer %s cannot be created.\n",
                  pszName, pszLayerName );

        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Figure out what type of layer we need.                          */
/* -------------------------------------------------------------------- */
    if( eType == wkbUnknown || eType == wkbLineString )
        nShapeType = SHPT_ARC;
    else if( eType == wkbPoint )
        nShapeType = SHPT_POINT;
    else if( eType == wkbPolygon )
        nShapeType = SHPT_POLYGON;
    else if( eType == wkbMultiPoint )
        nShapeType = SHPT_MULTIPOINT;
    else if( eType == wkbPoint25D )
        nShapeType = SHPT_POINTZ;
    else if( eType == wkbLineString25D )
        nShapeType = SHPT_ARCZ;
    else if( eType == wkbMultiLineString )
        nShapeType = SHPT_ARC;
    else if( eType == wkbMultiLineString25D )
        nShapeType = SHPT_ARCZ;
    else if( eType == wkbPolygon25D )
        nShapeType = SHPT_POLYGONZ;
    else if( eType == wkbMultiPolygon )
        nShapeType = SHPT_POLYGON;
    else if( eType == wkbMultiPolygon25D )
        nShapeType = SHPT_POLYGONZ;
    else if( eType == wkbMultiPoint25D )
        nShapeType = SHPT_MULTIPOINTZ;
    else if( eType == wkbNone )
        nShapeType = SHPT_NULL;
    else
        nShapeType = -1;

/* -------------------------------------------------------------------- */
/*      Has the application overridden this with a special creation     */
/*      option?                                                         */
/* -------------------------------------------------------------------- */
    const char *pszOverride = CSLFetchNameValue( papszOptions, "SHPT" );

    if( pszOverride == NULL )
        /* ignore */;
    else if( EQUAL(pszOverride,"POINT") )
    {
        nShapeType = SHPT_POINT;
        eType = wkbPoint;
    }
    else if( EQUAL(pszOverride,"ARC") )
    {
        nShapeType = SHPT_ARC;
        eType = wkbLineString;
    }
    else if( EQUAL(pszOverride,"POLYGON") )
    {
        nShapeType = SHPT_POLYGON;
        eType = wkbPolygon;
    }
    else if( EQUAL(pszOverride,"MULTIPOINT") )
    {
        nShapeType = SHPT_MULTIPOINT;
        eType = wkbMultiPoint;
    }
    else if( EQUAL(pszOverride,"POINTZ") )
    {
        nShapeType = SHPT_POINTZ;
        eType = wkbPoint25D;
    }
    else if( EQUAL(pszOverride,"ARCZ") )
    {
        nShapeType = SHPT_ARCZ;
        eType = wkbLineString25D;
    }
    else if( EQUAL(pszOverride,"POLYGONZ") )
    {
        nShapeType = SHPT_POLYGONZ;
        eType = wkbPolygon25D;
    }
    else if( EQUAL(pszOverride,"MULTIPOINTZ") )
    {
        nShapeType = SHPT_MULTIPOINTZ;
        eType = wkbMultiPoint25D;
    }
    else if( EQUAL(pszOverride,"NONE") )
    {
        nShapeType = SHPT_NULL;
    }
    else
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Unknown SHPT value of `%s' passed to Shapefile layer\n"
                  "creation.  Creation aborted.\n",
                  pszOverride );

        return NULL;
    }

    if( nShapeType == -1 )
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Geometry type of `%s' not supported in shapefiles.\n"
                  "Type can be overridden with a layer creation option\n"
                  "of SHPT=POINT/ARC/POLYGON/MULTIPOINT/POINTZ/ARCZ/POLYGONZ/MULTIPOINTZ.\n",
                  OGRGeometryTypeToName(eType) );
        return NULL;
    }
    
/* -------------------------------------------------------------------- */
/*      What filename do we use, excluding the extension?               */
/* -------------------------------------------------------------------- */
    char *pszBasename;

    if(  bSingleFileDataSource && nLayers == 0 )
    {
        char *pszPath = CPLStrdup(CPLGetPath(pszName));
        char *pszFBasename = CPLStrdup(CPLGetBasename(pszName));

        pszBasename = CPLStrdup(CPLFormFilename(pszPath, pszFBasename, NULL));

        CPLFree( pszFBasename );
        CPLFree( pszPath );
    }
    else if(  bSingleFileDataSource )
    {
        /* This is a very weird use case : the user creates/open a datasource */
        /* made of a single shapefile 'foo.shp' and wants to add a new layer */
        /* to it, 'bar'. So we create a new shapefile 'bar.shp' in the same */
        /* directory as 'foo.shp' */
        /* So technically, we will not be any longer a single file */
        /* datasource ... Ahem ahem */
        char *pszPath = CPLStrdup(CPLGetPath(pszName));
        pszBasename = CPLStrdup(CPLFormFilename(pszPath,pszLayerName,NULL));
        CPLFree( pszPath );
    }
    else
        pszBasename = CPLStrdup(CPLFormFilename(pszName,pszLayerName,NULL));

/* -------------------------------------------------------------------- */
/*      Create the shapefile.                                           */
/* -------------------------------------------------------------------- */
    char        *pszFilename;

    if( nShapeType != SHPT_NULL )
    {
        pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "shp" ));

        hSHP = SHPCreate( pszFilename, nShapeType );
        
        if( hSHP == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                      "Failed to open Shapefile `%s'.\n",
                      pszFilename );
            CPLFree( pszFilename );
            CPLFree( pszBasename );
            return NULL;
        }
        CPLFree( pszFilename );
    }
    else
        hSHP = NULL;

/* -------------------------------------------------------------------- */
/*      Has a specific LDID been specified by the caller?               */
/* -------------------------------------------------------------------- */
    const char *pszLDID = CSLFetchNameValue( papszOptions, "ENCODING" );

/* -------------------------------------------------------------------- */
/*      Create a DBF file.                                              */
/* -------------------------------------------------------------------- */
    pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "dbf" ));

    if( pszLDID != NULL )
        hDBF = DBFCreateEx( pszFilename, pszLDID );
    else
        hDBF = DBFCreate( pszFilename );

    if( hDBF == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Failed to open Shape DBF file `%s'.\n",
                  pszFilename );
        CPLFree( pszFilename );
        CPLFree( pszBasename );
        SHPClose(hSHP);
        return NULL;
    }

    CPLFree( pszFilename );

/* -------------------------------------------------------------------- */
/*      Create the .prj file, if required.                              */
/* -------------------------------------------------------------------- */
    if( poSRS != NULL )
    {
        char    *pszWKT = NULL;
        CPLString osPrjFile = CPLFormFilename( NULL, pszBasename, "prj");
        VSILFILE    *fp;

        /* the shape layer needs it's own copy */
        poSRS = poSRS->Clone();
        poSRS->morphToESRI();

        if( poSRS->exportToWkt( &pszWKT ) == OGRERR_NONE 
            && (fp = VSIFOpenL( osPrjFile, "wt" )) != NULL )
        {
            VSIFWriteL( pszWKT, strlen(pszWKT), 1, fp );
            VSIFCloseL( fp );
        }

        CPLFree( pszWKT );

        poSRS->morphFromESRI();
    }

/* -------------------------------------------------------------------- */
/*      Create the layer object.                                        */
/* -------------------------------------------------------------------- */
    OGRShapeLayer       *poLayer;

    poLayer = new OGRShapeLayer( pszBasename, hSHP, hDBF, poSRS, TRUE, TRUE,
                                 eType );
    
    poLayer->InitializeIndexSupport( pszBasename );

    CPLFree( pszBasename );

/* -------------------------------------------------------------------- */
/*      Add layer to data source layer list.                            */
/* -------------------------------------------------------------------- */
    papoLayers = (OGRShapeLayer **)
        CPLRealloc( papoLayers,  sizeof(OGRShapeLayer *) * (nLayers+1) );
    
    papoLayers[nLayers++] = poLayer;

    return poLayer;
}