Example #1
0
static void Test_WritePoints( int nSHPType, const char *pszFilename )

{
    SHPHandle	hSHPHandle;
    SHPObject	*psShape;
    double	x, y, z, m;

    hSHPHandle = SHPCreate( pszFilename, nSHPType );

    x = 1.0;
    y = 2.0;
    z = 3.0;
    m = 4.0;
    psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL,
                               1, &x, &y, &z, &m );
    SHPWriteObject( hSHPHandle, -1, psShape );
    SHPDestroyObject( psShape );
    
    x = 10.0;
    y = 20.0;
    z = 30.0;
    m = 40.0;
    psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL,
                               1, &x, &y, &z, &m );
    SHPWriteObject( hSHPHandle, -1, psShape );
    SHPDestroyObject( psShape );

    SHPClose( hSHPHandle );
}
Example #2
0
static void Test_WriteMultiPoints( int nSHPType, const char *pszFilename )

{
    SHPHandle	hSHPHandle;
    SHPObject	*psShape;
    double	x[4], y[4], z[4], m[4];
    int		i, iShape;

    hSHPHandle = SHPCreate( pszFilename, nSHPType );

    for( iShape = 0; iShape < 3; iShape++ )
    {
        for( i = 0; i < 4; i++ )
        {
            x[i] = iShape * 10 + i + 1.15;
            y[i] = iShape * 10 + i + 2.25;
            z[i] = iShape * 10 + i + 3.35;
            m[i] = iShape * 10 + i + 4.45;
        }
        
        psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL,
                                   4, x, y, z, m );
        SHPWriteObject( hSHPHandle, -1, psShape );
        SHPDestroyObject( psShape );
    }    

    SHPClose( hSHPHandle );
}
 // Returns: index in shapefile
 inline int AddShape(Geometry const& geometry)
 {
     // Note: we MIGHT design a small wrapper class which destroys in destructor
     ::SHPObject* obj = SHPCreateObject(geometry);
     int result = SHPWriteObject(m_shp, -1, obj );
     ::SHPDestroyObject( obj );
     return result;
 }
Example #4
0
 /**
  * Add a new geometry (shape object) to the Shapefile. You have to call
  * this first for every new shape. After that you call add_attribute()
  * for all the attributes.
  *
  * @param shp_object A pointer to the shape object to be added. The object
  *                   will be freed for you by calling SHPDestroyObject()!
  * @exception Osmium::Exception::IllegalGeometry If shp_object is NULL or
  *                   the type of geometry does not fit the type of the
  *                   shapefile.
  */
 void add_geometry(SHPObject* shp_object) {
     if (!shp_object || shp_object->nSHPType != m_shp_handle->nShapeType) {
         throw Osmium::Exception::IllegalGeometry();
     }
     m_current_shape = SHPWriteObject(m_shp_handle, -1, shp_object);
     if (m_current_shape == -1 && errno == EINVAL) {
         // second chance if likely cause is having reached the 2GB limit
         close();
         m_sequence_number++;
         open();
         m_current_shape = SHPWriteObject(m_shp_handle, -1, shp_object);
     }
     if (m_current_shape == -1) {
         throw std::runtime_error("error writing to shapefile");
     }
     SHPDestroyObject(shp_object);
 }
int writePoint(JNIEnv * env, SHPHandle hSHP, DBFHandle hDBF, int index, double latitude, double longitude, jstring name, jdouble height, int apples)
{
    SHPObject *oSHP = SHPCreateSimpleObject(SHPT_POINT, 1, &longitude, &latitude, NULL);
    SHPWriteObject(hSHP, -1, oSHP);
    const char *nativeName = (*env)->GetStringUTFChars(env, name, 0);
    DBFWriteStringAttribute(hDBF, index, 0, nativeName);
    (*env)->ReleaseStringUTFChars(env, name, nativeName);
    DBFWriteDoubleAttribute(hDBF, index, 1, height);
    DBFWriteIntegerAttribute(hDBF, index, 2, apples);

    SHPDestroyObject(oSHP);

    return 0;
}
Example #6
0
static void SplitCoastlines2( int show, struct source *arc, SHPHandle shp_arc_out, DBFHandle dbf_arc_out )
{
  int count = arc->shape_count;
  for( int i=0; i<count; i++ )
  {
    SHPObject *obj = source_get_shape( arc, i );
    int way_id = DBFReadIntegerAttribute( arc->dbf, i, 2 );
    
    if( obj->nVertices <= MAX_NODES_PER_ARC )
    {
      int new_id = SHPWriteObject( shp_arc_out, -1, obj );
      if( new_id < 0 ) { fprintf( stderr, "Output failure: %m\n"); exit(1); }
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 0, way_id );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 1, show );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 2, obj->nVertices < 4 );  /* Flag not real objects */
      source_release_shape(arc, obj);
      continue;
    }
    int arcs = (obj->nVertices / MAX_NODES_PER_ARC) + 1;
    int len = (obj->nVertices / arcs) + 1;
//    printf( "Splitting object with %d vertices, len=%d, arcs=%d\n", obj->nVertices, len, arcs );
    
    for( int j=0; j<arcs; j++ )
    {
      int this_len = (j==arcs-1)? obj->nVertices - (j*len): len+1;
//      printf( "Subobject start=%d, length=%d\n", j*len, this_len );
      SHPObject *new_obj = SHPCreateSimpleObject( SHPT_ARC, this_len, &obj->padfX[j*len], &obj->padfY[j*len], &obj->padfZ[j*len] );
      int new_id = SHPWriteObject( shp_arc_out, -1, new_obj );
      if( new_id < 0 ) { fprintf( stderr, "Output failure: %m\n"); exit(1); }
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 0, way_id );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 1, show );
      DBFWriteIntegerAttribute( dbf_arc_out, new_id, 2, 0 );
      SHPDestroyObject(new_obj);
    }
    source_release_shape(arc, obj);
  }
}
// ---------------------------------------------------------------------------
// 
// -----------
int	bSHPTable::WriteVal(int o, int f, void* val){
	if((o=CountRecords()+1)){
		o=0;
	}
SHPObject*	obj=vxs2shape(o-1,(*(ivertices**)val));
	if(!obj){
		return(-1);
	}
	if(SHPWriteObject(_shp,o-1,obj)){
	}
	else{
	}
	SHPDestroyObject(obj);
	return(0);
}
Example #8
0
// A partir del trazo, genera y guarda el vector correspondiente en formato SHAPE
void vect::agregarShape(vector<Point2f> trazo, int altura, SHPHandle sh, transformGeo *objGeo, Point pA, DBFHandle dbf) {
    vector<Point2f> l;
    for(vector<Point2f>::iterator it = trazo.begin(); it != trazo.end(); ++it)
    {
        Point2f p = *it;
        double xi = pA.x+p.x-1.0;
        double yi = pA.y+p.y-1.0;
        double xp= objGeo->getX(xi, yi);
        double yp = objGeo->getY(xi, yi);
        Point2f pi = Point2f(xp,yp);
        l.push_back(pi);
    }
    SHPObject *objShp = toArc(l, altura);
    int polyid = SHPWriteObject(sh, -1, objShp);
    DBFWriteDoubleAttribute(dbf, polyid, 0, 0.0);
    cout<<polyid<<".,,"<<endl;
    SHPDestroyObject(objShp);
}
void surfaceVectorField::WriteShapePoint(double xpt, double ypt, double spd, long dir, long view_dir, long map_dir)
{
     long NumRecord;
	double zpt=0;
     SHPObject *pSHP;

     pSHP=SHPCreateObject(SHPT_POINT, -1, 0, NULL, NULL, 1, &xpt, &ypt, &zpt, NULL);
     SHPWriteObject(hSHP, -1, pSHP);
     SHPDestroyObject(pSHP);

	NumRecord = DBFGetRecordCount(hDBF);
//	DBFWriteDoubleAttribute(hDBF, NumRecord, 0, xpt);
//   DBFWriteDoubleAttribute(hDBF, NumRecord, 1, ypt);
//	DBFWriteIntegerAttribute(hDBF, NumRecord, 2, spd);
//   DBFWriteIntegerAttribute(hDBF, NumRecord, 3, dir);
	DBFWriteDoubleAttribute(hDBF, NumRecord, 0, spd);
     DBFWriteIntegerAttribute(hDBF, NumRecord, 1, dir);
     DBFWriteIntegerAttribute(hDBF, NumRecord, 2, view_dir);
     DBFWriteIntegerAttribute(hDBF, NumRecord, 3, map_dir);
}
Example #10
0
int main( int argc, char ** argv )

{
    SHPHandle	hSHP, cSHP;
    int		nShapeType, i, nEntities, nShpInFile;
    SHPObject	*shape;

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc != 3 )
    {
	printf( "shpcat from_shpfile to_shpfile\n" );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( argv[1], "rb" );

    if( hSHP == NULL )
    {
	printf( "Unable to open:%s\n", argv[1] );
	exit( 1 );
    }
    
    SHPGetInfo( hSHP, &nEntities, &nShapeType, NULL, NULL );
    fprintf(stderr,"Opened From File %s, with %d shapes\n",argv[1],nEntities);

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    cSHP = SHPOpen( argv[2], "rb+" );

    if( cSHP == NULL )
    {
	printf( "Unable to open:%s\n", argv[2] );
	exit( 1 );
    }
    
    SHPGetInfo( cSHP, &nShpInFile, NULL, NULL, NULL );
    fprintf(stderr,"Opened to file %s with %d shapes, ready to add %d\n",
            argv[2],nShpInFile,nEntities);

/* -------------------------------------------------------------------- */
/*	Skim over the list of shapes, printing all the vertices.	*/
/* -------------------------------------------------------------------- */
    for( i = 0; i < nEntities; i++ )
    {
        shape = SHPReadObject( hSHP, i );
        SHPWriteObject( cSHP, -1, shape );
        SHPDestroyObject ( shape );

    }

    SHPClose( hSHP );
    SHPClose( cSHP );

    exit( 0 );
}
bool
TeExportQuerierToShapefile(TeQuerier* querier, const std::string& base)
{
	// check initial conditions
	if (!querier)
		return false;

	if (!querier->loadInstances())
		return false;

	// Get the list of attributes defined by the input querier
	bool onlyObjId = false;
	TeAttributeList qAttList = querier->getAttrList();
	if (qAttList.empty())
	{
		TeAttributeList qAttList;
		TeAttribute at;
		at.rep_.type_ = TeSTRING;               
		at.rep_.numChar_ = 100;
		at.rep_.name_ = "ID";
		at.rep_.isPrimaryKey_ = true;
		qAttList.push_back(at);
		onlyObjId = true;
	}

	// Handles to each type of geometries that will be created if necessary
	DBFHandle hDBFPol = 0;
	SHPHandle hSHPPol = 0;
	DBFHandle hDBFLin = 0;
	SHPHandle hSHPLin = 0;
	DBFHandle hDBFPt = 0;
	SHPHandle hSHPPt = 0;

	// Some auxiliary variables
    int totpoints;
    double*	padfX;
	double*	padfY;
    unsigned int nVertices;
    int* panPart;
    SHPObject *psObject;
    unsigned int posXY, npoints, nelem;
	int shpRes;

	// progress information
	if (TeProgress::instance())
		TeProgress::instance()->setTotalSteps(querier->numElemInstances());
	clock_t	t0, t1, t2;
	t2 = clock();
	t0 = t1 = t2;
	int dt = CLOCKS_PER_SEC/2;
	int dt2 = CLOCKS_PER_SEC; //* .000001;

	// Loop through the instances writting their geometries and attributes
	unsigned int iRecPol=0, iRecLin=0, iRecPt=0;
	unsigned int n, l, m;
	unsigned int nIProcessed = 0;
	TeSTInstance st;
	while(querier->fetchInstance(st))
	{
		totpoints = 0;
		nVertices = 0;
		if (st.hasPolygons())
		{
			TePolygonSet& polSet = st.getPolygons();
			TePolygonSet::iterator itps;
			int nVerticesCount = 0;
			for (itps = polSet.begin(); itps != polSet.end(); ++itps) 
			{
				nVertices = (*itps).size();
				nVerticesCount += nVertices;
				for (n=0; n<nVertices;++n) 
					totpoints += (*itps)[n].size();
			}

			panPart = (int *) malloc(sizeof(int) * nVerticesCount);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);

			posXY = 0;
			nelem = 0;
			for (itps = polSet.begin(); itps != polSet.end(); ++itps) 
			{
				TePolygon poly = *itps;
				for (l=0; l<poly.size(); ++l) 
				{
					if (l==0) 
					{
						if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) 
							TeReverseLine(poly[l]);
					}
					else 
					{
						if (TeOrientation(poly[l]) == TeCLOCKWISE)
							TeReverseLine(poly[l]);
					}
					npoints = poly[l].size();
					panPart[nelem]=posXY;
        
					for (m=0; m<npoints; ++m) 
					{
						padfX[posXY] = poly[l][m].x_;
						padfY[posXY] = poly[l][m].y_;
						posXY++;
					}
					nelem++;
				}
			}
			psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL, posXY, padfX, padfY, NULL, NULL);
			if (hSHPPol == 0)
			{
				string fname = base + "_pol.shp";
				hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON);
   				assert (hSHPPol != 0);
			}	
			shpRes = SHPWriteObject(hSHPPol, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);   
			if (hDBFPol == 0)
			{
				hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList);
				assert (hDBFPol != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str()));
					}
				}
			}
			++iRecPol;
		}
		if (st.hasCells())
		{
			TeCellSet& cellSet = st.getCells();
			nVertices = cellSet.size();
			totpoints = nVertices*5;
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);
			posXY = 0;
			nelem = 0;
			TeCellSet::iterator itcs;
			for (itcs=cellSet.begin(); itcs!=cellSet.end(); ++itcs)
			{
				panPart[nelem]=posXY;
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().upperRight().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().upperRight().x();
				padfY[posXY] = (*itcs).box().upperRight().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().upperRight().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				++posXY;	
				++nelem;
			} 
			psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL,posXY, padfX, padfY, NULL, NULL);
			if (hSHPPol == 0)
			{
				string fname = base + "_pol.shp";
				hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON);
   				assert (hSHPPol != 0);
			}	
			shpRes = SHPWriteObject(hSHPPol, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFPol == 0)
			{
				hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList);
				assert (hDBFPol != 0);
			}

			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str()));
					}
				}
			}
			++iRecPol;
		}
		if (st.hasLines())
		{
			TeLineSet& lineSet = st.getLines();
			nVertices = lineSet.size();
			TeLineSet::iterator itls;
			for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls)
				totpoints += (*itls).size();
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);
			posXY = 0;
			nelem = 0;
			for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls)
			{
				panPart[nelem]=posXY;
				for (l=0; l<(*itls).size(); ++l)
				{
					padfX[posXY] = (*itls)[l].x();
					padfY[posXY] = (*itls)[l].y();
					++posXY;
				}
				++nelem;
			}
			psObject = SHPCreateObject(SHPT_ARC, -1, nVertices, panPart, NULL,	posXY, padfX, padfY, NULL, NULL);
			if (hSHPLin == 0)
			{
				string fname = base + "_lin.shp"; 
				hSHPLin = SHPCreate(fname.c_str(), SHPT_ARC);
   				assert (hSHPLin != 0);
			}		
			shpRes = SHPWriteObject(hSHPLin, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFLin == 0)
			{
				hDBFLin = TeCreateDBFFile(base + "_lin.dbf", qAttList);
				assert (hDBFLin != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFLin, iRecLin, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFLin, iRecLin, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFLin, iRecLin, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFLin, iRecLin, n, atof(val.c_str()));
					}
				}
			}
			++iRecLin;
		}
		if (st.hasPoints())
		{
			TePointSet& pointSet = st.getPoints();
			nVertices = pointSet.size();
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * nVertices);
			padfY = (double *) malloc(sizeof(double) * nVertices);
			nelem = 0;
			TePointSet::iterator itpts;
			for (itpts=pointSet.begin(); itpts!=pointSet.end(); ++itpts)
			{
				panPart[nelem] = nelem;
				padfX[nelem] = (*itpts).location().x();
				padfY[nelem] = (*itpts).location().y();
				++nelem;
			}
			psObject = SHPCreateObject(SHPT_POINT, -1, nVertices, panPart, NULL, nVertices, padfX, padfY, NULL, NULL );
			if (hSHPPt == 0)
			{
				string fname = base + "_pt.shp";
				hSHPPt = SHPCreate(fname.c_str(), SHPT_POINT);
   				assert (hSHPPt != 0);
			}		
			shpRes = SHPWriteObject(hSHPPt, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFPt == 0)
			{
				hDBFPt = TeCreateDBFFile(base + "_pt.dbf", qAttList);
				assert (hDBFPt != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPt, iRecPt, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
						if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPt, iRecPt, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPt, iRecPt, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPt, iRecPt, n, atof(val.c_str()));
					}
				}
			}
			++iRecPt;
		}
		++nIProcessed;
		if (TeProgress::instance() && int(t2-t1) > dt)
		{
			t1 = t2;
			if(((int)(t2-t0) > dt2))
			{
				if (TeProgress::instance()->wasCancelled())
					break;
				else
					TeProgress::instance()->setProgress(nIProcessed);
			}
		}

	}
	if (hDBFPol != 0)
		DBFClose(hDBFPol);
	if (hSHPPol != 0)
        SHPClose(hSHPPol);
	if (hDBFLin != 0)
		DBFClose(hDBFLin);
	if (hSHPLin != 0)
        SHPClose(hSHPLin);
	if (hDBFPt != 0)
		DBFClose(hDBFPt);
	if (hSHPPt != 0)
        SHPClose(hSHPPt);

	if (TeProgress::instance())
		TeProgress::instance()->reset();
	return true;
}
Example #12
0
static int FindGeoLocPosition( GDALGeoLocTransformInfo *psTransform,
                               double dfGeoX, double dfGeoY,
                               int nStartX, int nStartY, 
                               double *pdfFoundX, double *pdfFoundY )

{
    double adfPathX[5000], adfPathY[5000];

    if( psTransform->padfGeoLocX == NULL )
        return FALSE;

    int nXSize = psTransform->nGeoLocXSize;
    int nYSize = psTransform->nGeoLocYSize;
    int nStepCount = 0;

    // Start in center if we don't have any provided info.
    if( nStartX < 0 || nStartY < 0 
        || nStartX >= nXSize || nStartY >= nYSize )
    {
        nStartX = nXSize / 2;
        nStartY = nYSize / 2;
    }

    nStartX = MIN(nStartX,nXSize-2);
    nStartY = MIN(nStartY,nYSize-2);

    int iX = nStartX, iY = nStartY;
    int iLastX = -1, iLastY = -1;
    int iSecondLastX = -1, iSecondLastY = -1;

    while( nStepCount < MAX(nXSize,nYSize) )
    {
        int iXNext = -1, iYNext = -1;
        double dfDeltaXRight, dfDeltaYRight, dfDeltaXDown, dfDeltaYDown;

        double *padfThisX = psTransform->padfGeoLocX + iX + iY * nXSize;
        double *padfThisY = psTransform->padfGeoLocY + iX + iY * nXSize;

        double dfDeltaX = dfGeoX - *padfThisX;
        double dfDeltaY = dfGeoY - *padfThisY;

        if( iX == nXSize-1 )
        {
            dfDeltaXRight = *(padfThisX) - *(padfThisX-1);
            dfDeltaYRight = *(padfThisY) - *(padfThisY-1);
        }
        else
        {
            dfDeltaXRight = *(padfThisX+1) - *padfThisX;
            dfDeltaYRight = *(padfThisY+1) - *padfThisY;
        }

        if( iY == nYSize - 1 )
        {
            dfDeltaXDown = *(padfThisX) - *(padfThisX-nXSize);
            dfDeltaYDown = *(padfThisY) - *(padfThisY-nXSize);
        }
        else
        {
            dfDeltaXDown = *(padfThisX+nXSize) - *padfThisX;
            dfDeltaYDown = *(padfThisY+nXSize) - *padfThisY;
        }

        double dfRightProjection = 
            (dfDeltaXRight * dfDeltaX + dfDeltaYRight * dfDeltaY) 
            / (dfDeltaXRight*dfDeltaXRight + dfDeltaYRight*dfDeltaYRight);

        double dfDownProjection = 
            (dfDeltaXDown * dfDeltaX + dfDeltaYDown * dfDeltaY) 
            / (dfDeltaXDown*dfDeltaXDown + dfDeltaYDown*dfDeltaYDown);

        // Are we in our target cell?
        if( dfRightProjection >= 0.0 && dfRightProjection < 1.0 
            && dfDownProjection >= 0.0 && dfDownProjection < 1.0 )
        {
            *pdfFoundX = iX + dfRightProjection;
            *pdfFoundY = iY + dfDownProjection;

            return TRUE;
        }
            
        if( ABS(dfRightProjection) > ABS(dfDownProjection) )
        {
            // Do we want to move right? 
            if( dfRightProjection > 1.0 && iX < nXSize-1 )
            {
                iXNext = iX + MAX(1,(int)(dfRightProjection - nStepCount)/2);
                iYNext = iY;
            }
            
            // Do we want to move left? 
            else if( dfRightProjection < 0.0 && iX > 0 )
            {
                iXNext = iX - MAX(1,(int)(ABS(dfRightProjection) - nStepCount)/2);
                iYNext = iY;
            }
            
            // Do we want to move down.
            else if( dfDownProjection > 1.0 && iY < nYSize-1 )
            {
                iXNext = iX;
                iYNext = iY + MAX(1,(int)(dfDownProjection - nStepCount)/2);
            }
            
            // Do we want to move up? 
            else if( dfDownProjection < 0.0 && iY > 0 )
            {
                iXNext = iX;
                iYNext = iY - MAX(1,(int)(ABS(dfDownProjection) - nStepCount)/2);
            }
            
            // We aren't there, and we have no where to go
            else
            {
                return FALSE;
            }
        }
        else
        {
            // Do we want to move down.
            if( dfDownProjection > 1.0 && iY < nYSize-1 )
            {
                iXNext = iX;
                iYNext = iY + MAX(1,(int)(dfDownProjection - nStepCount)/2);
            }
            
            // Do we want to move up? 
            else if( dfDownProjection < 0.0 && iY > 0 )
            {
                iXNext = iX;
                iYNext = iY - MAX(1,(int)(ABS(dfDownProjection) - nStepCount)/2);
            }
            
            // Do we want to move right? 
            else if( dfRightProjection > 1.0 && iX < nXSize-1 )
            {
                iXNext = iX + MAX(1,(int)(dfRightProjection - nStepCount)/2);
                iYNext = iY;
            }
            
            // Do we want to move left? 
            else if( dfRightProjection < 0.0 && iX > 0 )
            {
                iXNext = iX - MAX(1,(int)(ABS(dfRightProjection) - nStepCount)/2);
                iYNext = iY;
            }
            
            // We aren't there, and we have no where to go
            else
            {
                return FALSE;
            }
        }
                adfPathX[nStepCount] = iX;
        adfPathY[nStepCount] = iY;

        nStepCount++;
        iX = MAX(0,MIN(iXNext,nXSize-1));
        iY = MAX(0,MIN(iYNext,nYSize-1));

        if( iX == iSecondLastX && iY == iSecondLastY )
        {
            // Are we *near* our target cell?
            if( dfRightProjection >= -1.0 && dfRightProjection < 2.0
                && dfDownProjection >= -1.0 && dfDownProjection < 2.0 )
            {
                *pdfFoundX = iX + dfRightProjection;
                *pdfFoundY = iY + dfDownProjection;
                
                return TRUE;
            }

#ifdef SHAPE_DEBUG
            if( hSHP != NULL )
            {
                SHPObject *hObj;
                
                hObj = SHPCreateSimpleObject( SHPT_ARC, nStepCount,
                                              adfPathX, adfPathY, NULL );
                SHPWriteObject( hSHP, -1, hObj );
                SHPDestroyObject( hObj );
                
                int iShape = DBFGetRecordCount( hDBF );
                DBFWriteDoubleAttribute( hDBF, iShape, 0, dfGeoX );
                DBFWriteDoubleAttribute( hDBF, iShape, 1, dfGeoY );
            }
#endif             
            //CPLDebug( "GeoL", "Looping at step (%d) on search for %g,%g.", 
            //          nStepCount, dfGeoX, dfGeoY );
            return FALSE;
        }

        iSecondLastX = iLastX;
        iSecondLastY = iLastY;

        iLastX = iX;
        iLastY = iY;

    }

    //CPLDebug( "GeoL", "Exceeded step count max (%d) on search for %g,%g.", 
    //          MAX(nXSize,nYSize), 
    //          dfGeoX, dfGeoY );
    
#ifdef SHAPE_DEBUG
    if( hSHP != NULL )
    {
        SHPObject *hObj;

        hObj = SHPCreateSimpleObject( SHPT_ARC, nStepCount,
                                      adfPathX, adfPathY, NULL );
        SHPWriteObject( hSHP, -1, hObj );
        SHPDestroyObject( hObj );

        int iShape = DBFGetRecordCount( hDBF );
        DBFWriteDoubleAttribute( hDBF, iShape, 0, dfGeoX );
        DBFWriteDoubleAttribute( hDBF, iShape, 1, dfGeoY );
    }
#endif
              
    return FALSE;
}
bool TeExportPolygonSet2SHP( const TePolygonSet& ps,const std::string& base_file_name  )
{
    // creating files names
    std::string dbfFilename = base_file_name + ".dbf";
    std::string shpFilename = base_file_name + ".shp";

    // creating polygons attribute list ( max attribute size == 25 )
    TeAttributeList attList;
    TeAttribute at;
    at.rep_.type_ = TeSTRING;               //the id of the cell
    at.rep_.numChar_ = 25;
    at.rep_.name_ = "object_id_";
    at.rep_.isPrimaryKey_ = true;
	attList.push_back(at);
    
    /* DBF output file handle creation */
	DBFHandle hDBF = TeCreateDBFFile (dbfFilename, attList);
	if ( hDBF == 0 )
		return false;
    
    /* SHP output file handle creation */
    SHPHandle hSHP = SHPCreate( shpFilename.c_str(), SHPT_POLYGON );
    if( hSHP == 0 ) 
	{
      DBFClose( hDBF );
      return false;
    }
    
    /* Writing polygons */
    int iRecord = 0;
    int totpoints = 0;
    double  *padfX, *padfY;
    SHPObject       *psObject;
    int posXY, npoints, nelem;
    int nVertices;
    int* panParts;

    TePolygonSet::iterator itps;
    TePolygon poly;

    for (itps = ps.begin() ; itps != ps.end() ; itps++ ) {
      poly=(*itps);
      totpoints = 0;
      nVertices = poly.size();
      for (unsigned int n=0; n<poly.size();n++) {
        totpoints += poly[n].size();
      }

      panParts = (int *) malloc(sizeof(int) * nVertices);
      padfX = (double *) malloc(sizeof(double) * totpoints);
      padfY = (double *) malloc(sizeof(double) * totpoints);
      posXY = 0;
      nelem = 0;
      
      for (unsigned int l=0; l<poly.size(); ++l) {
        if (l==0) {
          if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) {
            TeReverseLine(poly[l]);
          }
        } else {
          if (TeOrientation(poly[l]) == TeCLOCKWISE) {
            TeReverseLine(poly[l]);
          }
        }
        
        npoints = poly[l].size();
        panParts[nelem]=posXY;
        
        for (int m=0; m<npoints; m++ ) {
          padfX[posXY] = poly[l][m].x_;
          padfY[posXY] = poly[l][m].y_;
          posXY++;
        }
        nelem++;
      }
                
      psObject = SHPCreateObject( SHPT_POLYGON, -1, nelem, panParts, NULL,
        posXY, padfX, padfY, NULL, NULL );
        
      int shpRes = SHPWriteObject( hSHP, -1, psObject );
      if (shpRes == -1 )
	  {
	      DBFClose( hDBF );
		  SHPClose( hSHP );
		  return false;
	  }
        
      SHPDestroyObject( psObject );
      free( panParts );
      free( padfX );
      free( padfY );

      // writing attributes - same creation order
      DBFWriteStringAttribute(hDBF, iRecord, 0, poly.objectId().c_str() );
            
      iRecord++;
    }
    
    DBFClose( hDBF );
    SHPClose( hSHP );
    return true;  
}
Example #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;
};
Example #15
0
int main( int argc, char ** argv )

{
    SHPHandle	hSHP;
    int		nShapeType, nVertices, nParts, *panParts, i, nVMax;
    double	*padfX, *padfY;
    SHPObject	*psObject;

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc < 2 )
    {
	printf( "shpadd shp_file [[x y] [+]]*\n" );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( argv[1], "r+b" );

    if( hSHP == NULL )
    {
	printf( "Unable to open:%s\n", argv[1] );
	exit( 1 );
    }

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

    if( argc == 2 )
        nShapeType = SHPT_NULL;

/* -------------------------------------------------------------------- */
/*	Build a vertex/part list from the command line arguments.	*/
/* -------------------------------------------------------------------- */
    nVMax = 1000;
    padfX = (double *) malloc(sizeof(double) * nVMax);
    padfY = (double *) malloc(sizeof(double) * nVMax);
    
    nVertices = 0;

    if( (panParts = (int *) malloc(sizeof(int) * 1000 )) == NULL )
    {
        printf( "Out of memory\n" );
        exit( 1 );
    }
    
    nParts = 1;
    panParts[0] = 0;

    for( i = 2; i < argc;  )
    {
	if( argv[i][0] == '+' )
	{
	    panParts[nParts++] = nVertices;
	    i++;
	}
	else if( i < argc-1 )
	{
            if( nVertices == nVMax )
            {
                nVMax = nVMax * 2;
                padfX = (double *) realloc(padfX,sizeof(double)*nVMax);
                padfY = (double *) realloc(padfY,sizeof(double)*nVMax);
            }

	    sscanf( argv[i], "%lg", padfX+nVertices );
	    sscanf( argv[i+1], "%lg", padfY+nVertices );
	    nVertices += 1;
	    i += 2;
	}
    }

/* -------------------------------------------------------------------- */
/*      Write the new entity to the shape file.                         */
/* -------------------------------------------------------------------- */
    psObject = SHPCreateObject( nShapeType, -1, nParts, panParts, NULL,
                                nVertices, padfX, padfY, NULL, NULL );
    SHPWriteObject( hSHP, -1, psObject );
    SHPDestroyObject( psObject );
    
    SHPClose( hSHP );

    free( panParts );
    free( padfX );
    free( padfY );

    return 0;
}
Example #16
0
int main( int argc, char ** argv )
{

/* -------------------------------------------------------------------- */
/*      Check command line usage.                                       */
/* -------------------------------------------------------------------- */
    if( argc < 2 ) error();
    strcpy(infile, argv[1]);
    if (argc > 2) {
        strcpy(outfile,argv[2]);
        if (strncasecmp2(outfile, "LIST",0) == 0) { ilist = TRUE; }
        if (strncasecmp2(outfile, "ALL",0) == 0)  { iall  = TRUE; }
    } 
    if (ilist || iall || argc == 2 ) {
        setext(infile, "shp");
        printf("DESCRIBE: %s\n",infile);
        strcpy(outfile,"");
    }
/* -------------------------------------------------------------------- */
/*	Look for other functions on the command line. (SELECT, UNIT)  	*/
/* -------------------------------------------------------------------- */
    for (i = 3; i < argc; i++)
    {
    	if ((strncasecmp2(argv[i],  "SEL",3) == 0) ||
            (strncasecmp2(argv[i],  "UNSEL",5) == 0))
    	{
            if (strncasecmp2(argv[i],  "UNSEL",5) == 0) iunselect=TRUE;
    	    i++;
    	    if (i >= argc) error();
    	    strcpy(selectitem,argv[i]);
    	    i++;
    	    if (i >= argc) error();
    	    selcount=0;
    	    strcpy(temp,argv[i]);
    	    cpt=temp;
    	    tj = atoi(cpt);
    	    ti = 0;
    	    while (tj>0) {
                selectvalues[selcount] = tj;
                while( *cpt >= '0' && *cpt <= '9')
                    cpt++; 
                while( *cpt > '\0' && (*cpt < '0' || *cpt > '9') )
                    cpt++; 
                tj=atoi(cpt);
                selcount++;
    	    }
    	    iselect=TRUE;
    	}  /*** End SEL & UNSEL ***/
    	else
            if ((strncasecmp2(argv[i], "CLIP",4) == 0) ||
                (strncasecmp2(argv[i],  "ERASE",5) == 0))
            {
                if (strncasecmp2(argv[i],  "ERASE",5) == 0) ierase=TRUE;
                i++;
                if (i >= argc) error();
                strcpy(clipfile,argv[i]);
                sscanf(argv[i],"%lf",&cxmin);
                i++;
                if (i >= argc) error();
                if (strncasecmp2(argv[i],  "BOUND",5) == 0) {
                    setext(clipfile, "shp");
                    hSHP = SHPOpen( clipfile, "rb" );
                    if( hSHP == NULL )
                    {
                        printf( "ERROR: Unable to open the clip shape file:%s\n", clipfile );
                        exit( 1 );
                    }
                    SHPGetInfo( hSHPappend, NULL, NULL,
                                adfBoundsMin, adfBoundsMax );
                    cxmin = adfBoundsMin[0];
                    cymin = adfBoundsMin[1];
                    cxmax = adfBoundsMax[0];
                    cymax = adfBoundsMax[1];
                    printf("Theme Clip Boundary: (%lf,%lf) - (%lf,%lf)\n",
                           cxmin, cymin, cxmax, cymax);
                    ibound=TRUE;
                } else {  /*** xmin,ymin,xmax,ymax ***/
                    sscanf(argv[i],"%lf",&cymin);
                    i++;
                    if (i >= argc) error();
                    sscanf(argv[i],"%lf",&cxmax);
                    i++;
                    if (i >= argc) error();
                    sscanf(argv[i],"%lf",&cymax);
                    printf("Clip Box: (%lf,%lf) - (%lf,%lf)\n",cxmin, cymin, cxmax, cymax);
                }
                i++;
                if (i >= argc) error();
                if      (strncasecmp2(argv[i], "CUT",3) == 0)    icut=TRUE;
                else if (strncasecmp2(argv[i], "TOUCH",5) == 0)  itouch=TRUE;
                else if (strncasecmp2(argv[i], "INSIDE",6) == 0) iinside=TRUE;
                else error();
                iclip=TRUE;
            } /*** End CLIP & ERASE ***/
            else if (strncasecmp2(argv[i],  "FACTOR",0) == 0)
            {
                i++;
    	        if (i >= argc) error();
    	        infactor=findunit(argv[i]);
    	        if (infactor == 0) error();
                iunit=TRUE;
                i++;
    	        if (i >= argc) error();
    	        outfactor=findunit(argv[i]);
    	        if (outfactor == 0)
    	        {
                    sscanf(argv[i],"%lf",&factor);
                    if (factor == 0) error();
                }
                if (factor == 0)
                {
                    if (infactor ==0)
                    { puts("ERROR: Input unit must be defined before output unit"); exit(1); }
                    factor=infactor/outfactor;
                }
                printf("Output file coordinate values will be factored by %lg\n",factor);
                ifactor=(factor != 1); /* True if a valid factor */
            } /*** End FACTOR ***/
            else if (strncasecmp2(argv[i],"SHIFT",5) == 0)
            {
                i++;
                if (i >= argc) error();
                sscanf(argv[i],"%lf",&xshift);
                i++;
                if (i >= argc) error();
                sscanf(argv[i],"%lf",&yshift);
                iunit=TRUE;
                printf("X Shift: %lg   Y Shift: %lg\n",xshift,yshift);
            } /*** End SHIFT ***/
            else {
                printf("ERROR: Unknown function %s\n",argv[i]);  error();
            }
    }
/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    openfiles();  /* Open the infile and the outfile for shape and dbf. */
    if( DBFGetFieldCount(hDBF) == 0 )
    {
	puts( "There are no fields in this table!" );
	exit( 1 );
    }
/* -------------------------------------------------------------------- */
/*      Print out the file bounds.                                      */
/* -------------------------------------------------------------------- */
    iRecord = DBFGetRecordCount( hDBF );
    SHPGetInfo( hSHP, NULL, NULL, adfBoundsMin, adfBoundsMax );

    printf( "Input Bounds:  (%lg,%lg) - (%lg,%lg)   Entities: %d   DBF: %d\n",
	    adfBoundsMin[0], adfBoundsMin[1],
            adfBoundsMax[0], adfBoundsMax[1],
            nEntities, iRecord );
	    
    if (strcmp(outfile,"") == 0) /* Describe the shapefile; No other functions */
    {
    	ti = DBFGetFieldCount( hDBF );
	showitems();
	exit(0);
    }
     
    if (iclip) check_theme_bnd();
    
    jRecord = DBFGetRecordCount( hDBFappend );
    SHPGetInfo( hSHPappend, NULL, NULL, adfBoundsMin, adfBoundsMax );
    if (nEntitiesAppend == 0)
        puts("New Output File\n");
    else
        printf( "Append Bounds: (%lg,%lg)-(%lg,%lg)   Entities: %d  DBF: %d\n",
                adfBoundsMin[0], adfBoundsMin[1],
                adfBoundsMax[0], adfBoundsMax[1],
                nEntitiesAppend, jRecord );
    
/* -------------------------------------------------------------------- */
/*	Find matching fields in the append file or add new items.       */
/* -------------------------------------------------------------------- */
    mergefields();
/* -------------------------------------------------------------------- */
/*	Find selection field if needed.                                 */
/* -------------------------------------------------------------------- */
    if (iselect)    findselect();

/* -------------------------------------------------------------------- */
/*  Read all the records 						*/
/* -------------------------------------------------------------------- */
    jRecord = DBFGetRecordCount( hDBFappend );
    for( iRecord = 0; iRecord < nEntities; iRecord++)  /** DBFGetRecordCount(hDBF) **/
    {
/* -------------------------------------------------------------------- */
/*      SELECT for values if needed. (Can the record be skipped.)       */
/* -------------------------------------------------------------------- */
        if (iselect)
            if (selectrec() == 0) goto SKIP_RECORD;   /** SKIP RECORD **/

/* -------------------------------------------------------------------- */
/*      Read a Shape record                                             */
/* -------------------------------------------------------------------- */
        psCShape = SHPReadObject( hSHP, iRecord );

/* -------------------------------------------------------------------- */
/*      Clip coordinates of shapes if needed.                           */
/* -------------------------------------------------------------------- */
        if (iclip)
            if (clip_boundary() == 0) goto SKIP_RECORD; /** SKIP RECORD **/

/* -------------------------------------------------------------------- */
/*      Read a DBF record and copy each field.                          */
/* -------------------------------------------------------------------- */
	for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
	{
/* -------------------------------------------------------------------- */
/*      Store the record according to the type and formatting           */
/*      information implicit in the DBF field description.              */
/* -------------------------------------------------------------------- */
            if (pt[i] > -1)  /* if the current field exists in output file */
            {
                switch( DBFGetFieldInfo( hDBF, i, NULL, &iWidth, &iDecimals ) )
                {
                  case FTString:
                  case FTLogical:
                    DBFWriteStringAttribute(hDBFappend, jRecord, pt[i],
                                            (DBFReadStringAttribute( hDBF, iRecord, i )) );
                    break;

                  case FTInteger:
                    DBFWriteIntegerAttribute(hDBFappend, jRecord, pt[i],
                                             (DBFReadIntegerAttribute( hDBF, iRecord, i )) );
                    break;

                  case FTDouble:
                    DBFWriteDoubleAttribute(hDBFappend, jRecord, pt[i],
                                            (DBFReadDoubleAttribute( hDBF, iRecord, i )) );
                    break;

                  case FTInvalid:
                    break;
                }
            }
	}
	jRecord++;
/* -------------------------------------------------------------------- */
/*      Change FACTOR and SHIFT coordinates of shapes if needed.        */
/* -------------------------------------------------------------------- */
        if (iunit)
        {
	    for( j = 0; j < psCShape->nVertices; j++ ) 
	    {
                psCShape->padfX[j] = psCShape->padfX[j] * factor + xshift;
                psCShape->padfY[j] = psCShape->padfY[j] * factor + yshift;
	    }
        }
        
/* -------------------------------------------------------------------- */
/*      Write the Shape record after recomputing current extents.       */
/* -------------------------------------------------------------------- */
        SHPComputeExtents( psCShape );
        SHPWriteObject( hSHPappend, -1, psCShape );

      SKIP_RECORD:
        SHPDestroyObject( psCShape );
        psCShape = NULL;
        j=0;
    }

/* -------------------------------------------------------------------- */
/*      Print out the # of Entities and the file bounds.                */
/* -------------------------------------------------------------------- */
    jRecord = DBFGetRecordCount( hDBFappend );
    SHPGetInfo( hSHPappend, &nEntitiesAppend, &nShapeTypeAppend,
                adfBoundsMin, adfBoundsMax );
    
    printf( "Output Bounds: (%lg,%lg) - (%lg,%lg)   Entities: %d  DBF: %d\n\n",
	    adfBoundsMin[0], adfBoundsMin[1],
            adfBoundsMax[0], adfBoundsMax[1],
            nEntitiesAppend, jRecord );

/* -------------------------------------------------------------------- */
/*      Close the both shapefiles.                                      */
/* -------------------------------------------------------------------- */
    SHPClose( hSHP );
    SHPClose( hSHPappend );
    DBFClose( hDBF );
    DBFClose( hDBFappend );
    if (nEntitiesAppend == 0) {
        puts("Remove the output files.");
        setext(outfile, "dbf");
        remove(outfile);
        setext(outfile, "shp");
        remove(outfile);
        setext(outfile, "shx");
        remove(outfile);
    }
    return( 0 );
}
Example #17
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 );
}    
Example #18
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!" );
  }
}
Example #19
0
static int shapelib_writeobject(lua_State *ls)
{
    SHPHandle shp = checkshphandle(ls);
    int index = (int)luaL_checknumber(ls, 2); 

    //verify index
    int entcount;
    int shptype; 
    SHPGetInfo(shp, &entcount, &shptype, 0, 0); 

    if (index != -1 || (index - 1) >= entcount) {
        return luaL_error(ls, "invalid index"); 
    }

    //verify vertices
    if (!lua_istable(ls, 3)) {
        return luaL_error(ls, "bad vertices");
    }

    int nvertices = lua_objlen(ls, 3);
    if (nvertices <= 0) {
        return luaL_error(ls, "bad vertices");
    }

    //allocate memory for vertices
    double *x = malloc(nvertices * sizeof(double));
    double *y = malloc(nvertices * sizeof(double));
    double *z = malloc(nvertices * sizeof(double));

    //extract vertices
    for (size_t i = 0; i < nvertices; ++i) {
        lua_pushnumber(ls, i + 1);
        lua_gettable(ls, 3);

        lua_pushstring(ls, "x");
        lua_gettable(ls, -2);
        x[i] = lua_tonumber(ls, -1); 
        lua_pop(ls, 1);

        lua_pushstring(ls, "y");
        lua_gettable(ls, -2);
        y[i] = lua_tonumber(ls, -1); 
        lua_pop(ls, 1);

        lua_pushstring(ls, "z");
        lua_gettable(ls, -2);
        z[i] = lua_tonumber(ls, -1); 
        lua_pop(ls, 1);

        lua_pop(ls, 1);
    }

    //create and write object
    SHPObject *obj = SHPCreateSimpleObject(shptype, nvertices, x, y, z);
    SHPWriteObject(shp, index == - 1? index : index - 1, obj); 

    //clean up
    SHPDestroyObject(obj); 
    free(x); 
    free(y); 
    free(z); 

    return 0;
}
Example #20
0
///////////////////////////////////////////////////////////////////////////////
// Export eines Objektes
HRESULT CArcViewLayer::ExportData (
	GSTRUCT *pGS, MFELD *pMF, LPCSTR pcUIdent, CArcViewLayerAttributes *pMap)
{
OBJECTTYPE rgType = GetType();
int iShapeId = -1;
int iObjTyp = pGS -> Typ;

	_ASSERTE(rgType == ObjType2OBJECTTYPE(pGS -> Typ, true));	// Objekttyp muß stimmen

// Geometrie erzeugen
	if (OBJECTTYPE_Area == rgType) {
	// Anzahl der Konturen feststellen und Konturfeld zusammenbauen
	int iKCnt = 1;
	vector<int> Cnts(1);
	int iCurr = 0;

		Cnts[0] = 0;
		for (int i = 0; 0 != pGS -> cnt[i]; ++i) {
			if (i > 0) 
				Cnts.push_back(iCurr);
			iCurr += pGS -> cnt[i];
		}
		iKCnt = i;

		_ASSERTE(iKCnt > 0 && iKCnt == Cnts.size());

	// Objekt erzeugen
	CArcViewObject Obj(SHPCreateObject(m_nShapeType, -1, iKCnt, Cnts.begin(), NULL,
						pGS -> GSize, pGS -> x, pGS -> y, NULL, NULL));

		iShapeId = SHPWriteObject(m_hSHP, -1, Obj);

	} else {
	// Objekt erzeugen
	CArcViewObject Obj(SHPCreateSimpleObject(m_nShapeType, pGS -> GSize, pGS -> x, pGS -> y, NULL));

		iShapeId = SHPWriteObject(m_hSHP, -1, Obj);
	}
	if (iShapeId == -1)
		return E_FAIL;

// Attribute sicherstellen (bei TRiAS-Datenquellen jedesmal)
	if (!HasFields() || DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id))) {
	// sämtliche Attribute dieses Layers durchgehen und ggf. erzeugen
		for (CArcViewLayerAttributes::iterator it = pMap -> begin(); it != pMap -> end(); ++it) {
		// Feld in Datei erzeugen
		int iField = -1;
		CArcViewAttribute &rAttr = (*it).second;
		LPCSTR pcName = rAttr.GetName();

			if (OBJECTTYPE_Text != m_rgType && !strcmp (pcName, g_cbLabelText))
				continue;		// Labeltext nur für Textobjekte
				
			if (FAILED(FieldExists (pcName, rAttr.GetTyp(), &iField))) 
			{
				RETURN_FAILED_HRESULT(AddField(pcName, rAttr.GetTyp(), rAttr.GetLen(), rAttr.GetDecimals(), &iField));
			}
			_ASSERTE(-1 != iField);

		// mehrerer Objekttypen eines Idents haben identischen Satz von Attributen
			_ASSERTE(-1 == (*it).second.GetField(iObjTyp) || 
					 (*it).second.GetField(iObjTyp) == iField ||
					 DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id)));

		// Feldnummer beim Attribut speichern
			(*it).second.SetField(iField, iObjTyp);
		}

	// Textlabel für Textobjekte
		if (OBJECTTYPE_Text == m_rgType) {
		pair<CArcViewLayerAttributes::iterator, bool> p = 
			pMap -> insert (CArcViewLayerAttributes::value_type (-1, CArcViewAttribute(g_cbLabelText, 'a', _MAX_PATH)));

			if (p.second) {
			int iField = -1;

				it = p.first;
				if (FAILED(FieldExists (g_cbLabelText, FTString, &iField))) 
				{
					RETURN_FAILED_HRESULT(AddField(g_cbLabelText, FTString, _MAX_PATH, 0, &iField));
				}
				
				_ASSERTE(-1 != iField);
				(*it).second.SetField(iField, iObjTyp);						
			}
		}
		SetHasFields();
	}
	
// Attributwerte schreiben
	if (NULL != pMF) {
	// nur, wenn mindestens ein Attribut ausgegeben werden soll
		for (MFELD *pMFT = pMF; 0 != pMFT -> MCode; ++pMFT) {
			if (NULL != pMap) {
			CArcViewLayerAttributes::iterator it = pMap -> find (pMFT -> MCode);

				_ASSERTE(it != pMap -> end());	// Attribut sollte (jetzt) existieren
				if (it != pMap -> end()) {
				// Feld muß bereits erzeugt worden sein und Typ muß mit DBF übereinstimmen
				int iField = (*it).second.GetField(iObjTyp);

					_ASSERTE(-1 != iField);
					_ASSERTE((*it).second.GetTyp() == DBFGetFieldInfo (m_hDBF, iField, NULL, NULL, NULL));

				// Wert je nach Typ in die Datenbank schreiben
					switch ((*it).second.GetTyp()) {
					case FTString:
						{
						char cbBuffer[_MAX_PATH] = { '\0' };

							if (NULL != pMFT -> MText)
								OemToCharBuff(pMFT -> MText, cbBuffer, min(MAX_DBASEFIELD_LEN, strlen(pMFT -> MText))+1);	// '\0' mit konvertieren
							DBFWriteStringAttribute(m_hDBF, iShapeId, iField, cbBuffer);
						}
						break;

					case FTInteger:
						DBFWriteIntegerAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atol(pMFT -> MText) : 0);
						break;

					case FTDouble:
						DBFWriteDoubleAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atof(pMFT -> MText) : 0.0);
						break;
					}
				}
			} else {
				_ASSERTE(NULL != pMap);		// eigentlich sollte eine Map da sein

			// keine Map, also erstmal leeren Datensatz schreiben
			int iCnt = DBFGetFieldCount(m_hDBF);

				for (int i = 0; i < iCnt; ++i) {
					switch (DBFGetFieldInfo(m_hDBF, i, NULL, NULL, NULL)) {
					case FTString:
						DBFWriteStringAttribute(m_hDBF, iShapeId, i, g_cbNil);
						break;

					case FTInteger:
						DBFWriteIntegerAttribute(m_hDBF, iShapeId, i, 0);
						break;

					case FTDouble:
						DBFWriteDoubleAttribute(m_hDBF, iShapeId, i, 0.0);
						break;
					}
				}
			}
		}
	}
	return S_OK;
}
Example #21
0
int main (int argc, char *argv[]) {

  SHPHandle  inSHP, outSHP;
  DBFHandle  inDBF, outDBF;
  int        len; 
  int        i;
  char       **fieldNames;
  char       **strOrder = 0;
  struct DataStruct *index;
  int        width;
  int        decimals;
  SHPObject  *feat;
  void       *tuple;

  if (argc < 4) {
    printf("USAGE: shpsort <infile> <outfile> <field[;...]> [<(ASCENDING|DESCENDING)[;...]>]\n");
    exit(EXIT_FAILURE);
  }

  inSHP = SHPOpen (argv[1], "rb");
  if (!inSHP) {
    fputs("Couldn't open shapefile for reading!\n", stderr);
    exit(EXIT_FAILURE);
  }
  SHPGetInfo(inSHP, &nShapes, &shpType, NULL, NULL);

  /* If we can open the inSHP, open its DBF */
  inDBF = DBFOpen (argv[1], "rb");
  if (!inDBF) {
    fputs("Couldn't open dbf file for reading!\n", stderr);
    exit(EXIT_FAILURE);
  }

  /* Parse fields and validate existence */
  fieldNames = split(argv[3], ";");
  if (!fieldNames) {
    fputs("ERROR: parsing field names!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (nFields = 0; fieldNames[nFields] ; nFields++) {
    continue;
  }

  fldIdx = malloc(sizeof *fldIdx * nFields);
  if (!fldIdx) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nFields; i++) {
    len = (int)strlen(fieldNames[i]);
    while(len > 0) {
      --len;
      fieldNames[i][len] = (char)toupper((unsigned char)fieldNames[i][len]); 
    }
    fldIdx[i] = DBFGetFieldIndex(inDBF, fieldNames[i]);
    if (fldIdx[i] < 0) {
      /* try "SHAPE" */
      if (strcmp(fieldNames[i], "SHAPE") == 0) {
	fldIdx[i] = -1;
      }
      else if (strcmp(fieldNames[i], "FID") == 0) {
	fldIdx[i] = -2;
      }
      else {
	fprintf(stderr, "ERROR: field '%s' not found!\n", fieldNames[i]);
	exit(EXIT_FAILURE);
      }
    }
  }


  /* set up field type array */
  fldType = malloc(sizeof *fldType * nFields);
  if (!fldType) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nFields; i++) {
    if (fldIdx[i] < 0) {
      fldType[i] = fldIdx[i];
    }
    else {
      fldType[i] = DBFGetFieldInfo(inDBF, fldIdx[i], NULL, &width, &decimals);
      if (fldType[i] == FTInvalid) {
	fputs("Unrecognized field type in dBASE file!\n", stderr);
	exit(EXIT_FAILURE);
      }
    }
  }


  /* set up field order array */
  fldOrder = malloc(sizeof *fldOrder * nFields);
  if (!fldOrder) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nFields; i++) {
    /* default to ascending order */
    fldOrder[i] = ASCENDING;
  }
  if (argc > 4) {
    strOrder = split(argv[4], ";");
    if (!strOrder) {
      fputs("ERROR: parsing fields ordering!\n", stderr);
      exit(EXIT_FAILURE);
    }
    for (i = 0; i < nFields && strOrder[i]; i++) {
      if (strcmp(strOrder[i], "DESCENDING") == 0) {
	fldOrder[i] = DESCENDING;
      }
    }
  }

  /* build the index */
  index = build_index (inSHP, inDBF);

  /* Create output shapefile */
  outSHP = SHPCreate(argv[2], shpType);
  if (!outSHP) {
    fprintf(stderr, "%s:%d: couldn't create output shapefile!\n",
	    __FILE__, __LINE__);
    exit(EXIT_FAILURE);
  }
  
  /* Create output dbf */
  outDBF = DBFCloneEmpty(inDBF, argv[2]);
  if (!outDBF) {
    fprintf(stderr, "%s:%d: couldn't create output dBASE file!\n",
	    __FILE__, __LINE__);
    exit(EXIT_FAILURE);
  }

  /* Copy projection file, if any */
  copy_related(argv[1], argv[2], ".shp", ".prj");

  /* Copy metadata file, if any */
  copy_related(argv[1], argv[2], ".shp", ".shp.xml");

  /* Write out sorted results */
  for (i = 0; i < nShapes; i++) {
    feat = SHPReadObject(inSHP, index[i].record);
    if (SHPWriteObject(outSHP, -1, feat) < 0) {
      fprintf(stderr, "%s:%d: error writing shapefile!\n", __FILE__, __LINE__);
      exit(EXIT_FAILURE);
    }
    tuple = (void *) DBFReadTuple(inDBF, index[i].record);
    if (DBFWriteTuple(outDBF, i, tuple) < 0) {
      fprintf(stderr, "%s:%d: error writing dBASE file!\n", __FILE__, __LINE__);
      exit(EXIT_FAILURE);
    }
  }
  SHPClose(inSHP);
  SHPClose(outSHP);
  DBFClose(inDBF);
  DBFClose(outDBF);

  return EXIT_SUCCESS;

}
Example #22
0
static void add_to_shape(DBFHandle dbase, SHPHandle shape, datapool_type_t *datapool,
			 dbf_header_t *dbf, int nCols, int n, 
			 double *lat, double *lon)
{
  int ii, field = 0;

  // Write fields into the database
  for (ii=0; ii<nCols; ii++) {
    if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->granule_name);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->platform);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->sensor);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->beam_mode);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode_Description") == 0 && 
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->beam_mode_description);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) {
      DBFWriteIntegerAttribute(dbase, n, field, datapool->orbit);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) {
      DBFWriteIntegerAttribute(dbase, n, field, datapool->path_number);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) {
      DBFWriteIntegerAttribute(dbase, n, field, datapool->frame_number);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Acquisition_Date") == 0 &&
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->acquisition_date);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Processing_Date") == 0 && 
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->processing_date);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Processing_Level") == 0 &&
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->processing_level);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->start_time);
      field++;
    }
    else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->end_time);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->center_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->center_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_start_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_start_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_start_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_start_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_end_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_end_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_end_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_end_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->faraday_rotation);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Orbit_Direction") == 0 && 
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->orbit_direction);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Url") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->url);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Size") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->size);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->off_nadir_angle);
      field++;
    }
  }

  SHPObject *shapeObject=NULL;
  shapeObject = SHPCreateSimpleObject(SHPT_POLYGON, 5, lon, lat, NULL);
  SHPWriteObject(shape, -1, shapeObject);
  SHPDestroyObject(shapeObject);
}
Example #23
0
static void Test_WriteArcPoly( int nSHPType, const char *pszFilename )

{
    SHPHandle	hSHPHandle;
    SHPObject	*psShape;
    double	x[100], y[100], z[100], m[100];
    int		anPartStart[100];
    int		anPartType[100], *panPartType;
    int		i, iShape;

    hSHPHandle = SHPCreate( pszFilename, nSHPType );

    if( nSHPType == SHPT_MULTIPATCH )
        panPartType = anPartType;
    else
        panPartType = NULL;

    for( iShape = 0; iShape < 3; iShape++ )
    {
        x[0] = 1.0;
        y[0] = 1.0+iShape*3;
        x[1] = 2.0;
        y[1] = 1.0+iShape*3;
        x[2] = 2.0;
        y[2] = 2.0+iShape*3;
        x[3] = 1.0;
        y[3] = 2.0+iShape*3;
        x[4] = 1.0;
        y[4] = 1.0+iShape*3;

        for( i = 0; i < 5; i++ )
        {
            z[i] = iShape * 10 + i + 3.35;
            m[i] = iShape * 10 + i + 4.45;
        }
        
        psShape = SHPCreateObject( nSHPType, -1, 0, NULL, NULL,
                                   5, x, y, z, m );
        SHPWriteObject( hSHPHandle, -1, psShape );
        SHPDestroyObject( psShape );
    }

/* -------------------------------------------------------------------- */
/*      Do a multi part polygon (shape).  We close it, and have two     */
/*      inner rings.                                                    */
/* -------------------------------------------------------------------- */
    x[0] = 0.0;
    y[0] = 0.0;
    x[1] = 0;
    y[1] = 100;
    x[2] = 100;
    y[2] = 100;
    x[3] = 100;
    y[3] = 0;
    x[4] = 0;
    y[4] = 0;

    x[5] = 10;
    y[5] = 20;
    x[6] = 30;
    y[6] = 20;
    x[7] = 30;
    y[7] = 40;
    x[8] = 10;
    y[8] = 40;
    x[9] = 10;
    y[9] = 20;

    x[10] = 60;
    y[10] = 20;
    x[11] = 90;
    y[11] = 20;
    x[12] = 90;
    y[12] = 40;
    x[13] = 60;
    y[13] = 40;
    x[14] = 60;
    y[14] = 20;

    for( i = 0; i < 15; i++ )
    {
        z[i] = i;
        m[i] = i*2;
    }

    anPartStart[0] = 0;
    anPartStart[1] = 5;
    anPartStart[2] = 10;

    anPartType[0] = SHPP_RING;
    anPartType[1] = SHPP_INNERRING;
    anPartType[2] = SHPP_INNERRING;
    
    psShape = SHPCreateObject( nSHPType, -1, 3, anPartStart, panPartType,
                               15, x, y, z, m );
    SHPWriteObject( hSHPHandle, -1, psShape );
    SHPDestroyObject( psShape );
    

    SHPClose( hSHPHandle );
}
Example #24
0
/*
 * Write the geometry for a set of polygons to a shape file
 * This needs to map between our internal structure for the
 * shape polygons and that expected by the shape file writer.
 */
int polyShapeWrite(PolyObject * poly /* set of polygons */ ,
                   char *name /* name of file to write to */ )
{
    SHPHandle hSHP;
    SHPObject *psObject;
    Vertex *v;
    PolyShape *ps;
    PolyShapeList *plist;
    static int v_size;
    static int p_size;
    int i, j, k, n;
    int np, nv;
    int nShapeType;
    int m;
    int nVertices;
    int *partsStart;
    double *vx, *vy;

    if(v_size == 0)
    {
        v_size = 1024;
                                                                                        
        /*
         * allocate space for each of the vertices
         */
        vx = (double *) malloc(2 * v_size * sizeof(double));
        if(vx == NULL)
        {
            WARN("Memory allocation error in polyShapeWrite");
            return 1;
        }
        vy = vx + v_size;
    }
    if(p_size == 0)
    {
        p_size = 1024;
        partsStart = (int *) malloc(p_size * sizeof(int));
        if(partsStart == NULL)
        {
            WARN("Memory allocation error in polyShapeWrite");
            return 1;
        }
    }
    nShapeType = poly->nSHPType;
    hSHP = SHPCreate(name, nShapeType);
                                                                                        
    if(hSHP == NULL)
    {
        WARN2("Unable to create ", name);
        return 1;
    }
    /*
     * make sure space is available for all vertices - if it gets full,
     * reallocate with double the size
     */
    n = poly->nObjects;
    plist = poly->plist;
    /*
     * loop over all polygons
     */
    for(i = 0; i < n; i++)
    {
        ps = plist->ps;
        /* debug code BDB */
        /*if(PolyArea(ps) < 0)
               printf("In polyShapeWrite area is negative for shape %d\n", i);
         */
        np = ps->num_contours;
        nVertices = 0;
        while(np > p_size)
        {
            p_size *= 2;
            partsStart = (int *) realloc(partsStart, 2 * p_size * sizeof(int));
            if(partsStart == NULL)
            {
                WARN("Memory allocation error in polyShapeWrite");
                return 1;
            }
        }
        partsStart[0] = 0;
        /*
         * population of parts field for ShapeFiles
         */
        for(j = 0; j < np; j++)
        {
            nv = ps->contour[j].num_vertices;
            nVertices += nv;
            partsStart[j + 1] = nVertices;
        }
        while(nVertices > v_size)
        {
            v_size *= 2;
                                                                                        
            vx = (double *) realloc(vx, 2 * v_size * sizeof(double));
            if(vx == NULL)
            {
                WARN("Memory allocation error in polyShapeWrite");
                return 1;
            }
            vy = vx + v_size;
        }
        /*
         * population of vertices field for ShapeFiles
         */
        m = 0;
        for(j = 0; j < np; j++)
        {
            nv = ps->contour[j].num_vertices;
            v = ps->contour[j].vertex;
            for(k = 0; k < nv; k++)
            {
                vx[m] = v[k].x;
                vy[m] = v[k].y;
                m++;
            }
        }
                                                                                        
        /*
         * write a polygon to the .shp file
         */
        psObject = SHPCreateObject(nShapeType, -1, np, partsStart, NULL,
                                   nVertices, vx, vy, NULL, NULL);
        SHPWriteObject(hSHP, -1, psObject);
        SHPDestroyObject(psObject);
        plist = plist->next;    /* go to next polygon */
    }                           /* end loop over polygons */
    SHPClose(hSHP);
    return 0;
}                               /* end of polyShapeWrite function */
Example #25
0
int main( int argc, char ** argv )
{
    SHPHandle	old_SHP, new_SHP;
    DBFHandle   old_DBF, new_DBF;
    int		nShapeType, nEntities, nVertices, nParts, *panParts, i, iPart, j;
    double	*padVertices, adBounds[4];
    const char 	*pszPlus;
    DBFFieldType  idfld_type;
    SHPObject	*psCShape;
    FILE	*ifp = NULL;
    int		idfld, nflds;
    char	kv[257] = "";
    char	idfldName[120] = "";
    char	fldName[120] = "";
    char	shpFileName[120] = "";
    char	dbfFileName[120] = "";
    char	prjFileName[120] = "";
    char	parg[1024];
    double	apeture[4];
    int		inarg, outarg;
    char	*DBFRow = NULL;

/* for testing only 
    char	*in_args[] = { "init=nad83:1002", "units=us-ft" };
    char	*out_args[] = { "proj=utm", "zone=16", "units=m" };
*/

    char	*in_args[16];
    char	*out_args[16];
    int		in_argc = 0 , out_argc = 0, outf_arg;
    char	*arglst;
    projPJ	orig_prj, new_prj;
    va_list	myargs, moargs;

    if( argc < 4)
    {
	printf( "shpproj shp_file new_shp ( -i=in_proj_file | -i=\"in_params\" | -i=geographic ) ( -o=out_info_file | -o=\"out_params\" | -o=geographic ) \n" );
	exit( 1 );
    }

    old_SHP = SHPOpen( argv[1], "rb" );
    old_DBF = DBFOpen( argv[1], "rb" );
    if( old_SHP == NULL || old_DBF == NULL )
    {
	printf( "Unable to open old files:%s\n", argv[1] );
	exit( 1 );
    }
    
   outf_arg = 2;
   inarg = 0;
   outarg = 0;
   for ( i = 3; i < argc; i++ ) {
     if ( !strncmp ("-i=", argv[i], 3 ))  inarg = i;
     if ( !strncmp ("-o=", argv[i], 3 ))  outarg = i;
    }


/* if shapefile has a prj component then use that 
   else try for a file then read args as list */

    if( inarg == 0 )
    {
        strcpy( prjFileName, argv[1] );
        ifp = fopen( asFileName ( prjFileName, "prj" ),"rt");
    }
    else
    {
        ifp = fopen( asFileName ( argv[inarg] + 3, "prj" ),"rt");
    }

    i = 0;
    if ( ifp ) {
        if( inarg == 0 )
            printf ("using default file proj params from <- %s\n",
                    asFileName ( prjFileName, "prj"  ) );
        else
            printf ("using file proj params from <- %s\n",
                    asFileName ( argv[inarg] + 3, "prj" ) );

       while( fscanf( ifp, "%s", parg) != EOF ) {
         in_args[i] = malloc ( strlen(parg)+1 );
         strcpy ( in_args[i], parg);
         i++;
       }

       in_argc = i;
       fclose (ifp);
      }
     else {
      if ( inarg > 0 ) {
       arglst = argv[inarg] + 3;
       j = 0;
       i = 0;
       while ( j < strlen (arglst) ) {    
         in_argc += sscanf ( arglst + j, "%s", parg);
        
         in_args[i] = malloc( strlen (parg)+1024); 
         strcpy (in_args[i], parg);
         i++;
         j += strlen (parg) +1;
         if ( arglst[j] + 1 == 0 ) j = strlen (argv[inarg]);  
       }
      }
     }  

    i = 0;
    if ( outarg > 0 ) ifp = fopen( asFileName ( argv[outarg] + 3, "prj" ),"rt");   
    if ( ifp ) {
       while( fscanf( ifp, "%s", parg) != EOF ) {
         out_args[i] = malloc ( strlen(parg));
         strcpy ( out_args[i], parg);
         i++;
       }
       out_argc = i;
       fclose (ifp);
     }
     else {
      if ( outarg > 0 ) {
       arglst = argv[outarg] + 3;
       j = 0;
       i = 0;
       while ( j < strlen (arglst) ) {    
         out_argc += sscanf ( arglst + j, "%s", parg);
         
         out_args[i] = malloc( strlen (parg)+1); 
         strcpy (out_args[i], parg);
         i++;
         j += strlen (parg) +1;
         if ( arglst[j] + 1 == 0 ) j = strlen (argv[outarg]);  
       }
      }
    }       
    
    if ( !strcmp( argv[inarg], "-i=geographic" )) in_argc = 0;
    if ( !strcmp( argv[outarg], "-o=geographic" )) out_argc = 0;
    
    orig_prj = SHPSetProjection ( in_argc, in_args );
    new_prj = SHPSetProjection ( out_argc, out_args );

    if ( !(( (!in_argc) || orig_prj) && ( (!out_argc) || new_prj) )) { 
      fprintf (stderr, "unable to process projection, exiting...\n");
      exit(1);
    }   


    SHPGetInfo( old_SHP, &nEntities, &nShapeType, NULL, NULL);
    new_SHP = SHPCreate ( argv[outf_arg], nShapeType ); 
    
    new_DBF = DBFCloneEmpty (old_DBF, argv[outf_arg]);
    if( new_SHP == NULL || new_DBF == NULL )
    {
	printf( "Unable to create new files:%s\n", argv[outf_arg] );
	exit( 1 );
    }

    DBFRow = (char *) malloc ( (old_DBF->nRecordLength) + 15 );
     
    for( i = 0; i < nEntities; i++ )
    {
	int		j;

	psCShape = SHPReadObject ( old_SHP, i );

	SHPProject (psCShape, orig_prj, new_prj );

	SHPWriteObject ( new_SHP, -1, psCShape );   
	SHPDestroyObject ( psCShape );

        memcpy ( DBFRow, DBFReadTuple ( old_DBF, i ), old_DBF->nRecordLength );
        DBFWriteTuple ( new_DBF, new_DBF->nRecords, DBFRow );

    }

    SHPFreeProjection ( orig_prj );
    SHPFreeProjection ( new_prj );

    /* store projection params into prj file */
    ifp = fopen( asFileName ( argv[outf_arg], "prj" ),"wt");   
    if ( ifp ) {

       if ( out_argc == 0 ) 
        { fprintf( ifp, "proj=geographic\n" ); }
       else
        { for ( i = 0; i < out_argc; i++ )
           fprintf( ifp, "%s\n", out_args[i]);
        }
       fclose (ifp);
    }
    
    SHPClose( old_SHP );
    SHPClose( new_SHP );
    DBFClose( old_DBF );
    DBFClose( new_DBF );
    printf ("\n");
}
Example #26
0
/**
 * Works when tree tops are being found in a partition of the original image because padding
 * isn't done.
 */
int checkPixelPart(float **gridded, float **orig, int i, int j, int wnd_size, int wnd_sqrd,
				double * mpsData, double ulEasting, double ulNorthing, SHPHandle hshp, DBFHandle hdbf)
{  
	int ii, jj, half, count = 0, maxi, maxj, nrecords;
	float max, height;
	
	height = gridded[i][j];
	half   = (wnd_size - 1)/2;
	
	for(ii = i - half; ii <= i + half; ii++)
	for(jj = j - half; jj <= j + half; jj++)
		if(gridded[ii][jj] < height)
			count++;
	
	if(count < wnd_sqrd-1)
	{	// not the highest tree in the window
		return 1;
	}
	
	//find the highest point in the original data set
	maxi = i-1, maxj = j-1;
	max  = orig[i-1][j-1];
	
	for(jj = j - 1; jj <= j + 1; jj++)
	for(ii = i - 1; ii <= i + 1; ii++)
		if(orig[ii][jj] > max)
		{
			max  = orig[ii][jj];
			maxi = ii;
			maxj = jj;
		}
		
	//
 	//Write point to shape file.
 	//
	SHPObject * shape;
	double * xpts, * ypts, * zpts;
	
	xpts = (double *) malloc(sizeof(double));
	ypts = (double *) malloc(sizeof(double));
	zpts = (double *) malloc(sizeof(double));
	
	xpts[0] = ulEasting + maxj * mpsData[0];
	ypts[0] = ulNorthing - maxi * mpsData[1];
	zpts[0] = (double)max;
	
	shape = SHPCreateSimpleObject(SHPT_POINT, 1, xpts, ypts, zpts);
	if(!shape){
		PyErr_SetString(PyExc_Exception, "SHPCreateSimpleObject failed.");
		return 0;
	}
	
	SHPWriteObject(hshp, -1, shape);
	SHPGetInfo(hshp, &nrecords, NULL, NULL, NULL);
	DBFWriteDoubleAttribute(
		hdbf, 
		nrecords-1, 
		DBFGetFieldIndex(hdbf, "Height"),
		(double)max
	);
	//DBFWriteNULLAttribute(
	//	hdbf, 
	//	nrecords-1, 
	//	DBFGetFieldIndex(hdbf, "TC Index")
	//);
	
	SHPDestroyObject(shape);
	free(xpts);free(ypts);
	
	return 1;
}
Example #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 );
}    
Example #28
0
int main( int argc, char ** argv )

{
    SHPHandle	old_SHP, new_SHP;
    DBFHandle   old_DBF, new_DBF;
    int		nShapeType, nEntities, nVertices, nParts, *panParts, i, iPart;
    double	*padVertices, adBounds[4];
    const char 	*pszPlus;
    DBFFieldType  idfld_type;
    int		idfld, nflds;
    char	kv[257] = "";
    char	idfldName[120] = "";
    char	fldName[120] = "";
    char	shpFileName[120] = "";
    char	dbfFileName[120] = "";
    double	apeture[4];
    char	*DBFRow = NULL;
    int		Cpan[2] = { 0,0 };
    int		byRing = 1;
    PT		Centrd;
    SHPObject	*psCShape, *cent_pt;


    if( argc < 3 )
    {
	printf( "shpcentrd shp_file new_shp_file\n" );
	exit( 1 );
    }
    
    old_SHP = SHPOpen (argv[1], "rb" );
    old_DBF = DBFOpen (argv[1], "rb");
    if( old_SHP == NULL || old_DBF == NULL )
    {
	printf( "Unable to open old files:%s\n", argv[1] );
	exit( 1 );
    }

    SHPGetInfo( old_SHP, &nEntities, &nShapeType, NULL, NULL );
    new_SHP = SHPCreate ( argv[2], SHPT_POINT ); 
    
    new_DBF = DBFCloneEmpty (old_DBF, argv[2]);
    if( new_SHP == NULL || new_DBF == NULL )
    {
	printf( "Unable to create new files:%s\n", argv[2] );
	exit( 1 );
    }

    DBFRow = (char *) malloc ( (old_DBF->nRecordLength) + 15 );


#ifdef 	DEBUG
    printf ("ShpCentrd using shpgeo \n");
#endif

    for( i = 0; i < nEntities; i++ )
    {
	int		res ;
 
	psCShape = SHPReadObject( old_SHP, i );

        if ( byRing == 1 ) {
          int 	ring;
          for ( ring = 0; ring < psCShape->nParts; ring ++ ) {
	    SHPObject 	*psO;
	    psO = SHPClone ( psCShape, ring,  ring + 1 );

            Centrd = SHPCentrd_2d ( psO ); 

            cent_pt = SHPCreateSimpleObject ( SHPT_POINT, 1, 
        	(double*) &(Centrd.x), (double*) &(Centrd.y), NULL ); 

            SHPWriteObject ( new_SHP, -1, cent_pt ); 
                        
            memcpy ( DBFRow, DBFReadTuple ( old_DBF, i ),
		 old_DBF->nRecordLength );
            DBFWriteTuple ( new_DBF, new_DBF->nRecords, DBFRow );            

            SHPDestroyObject ( cent_pt );

	    SHPDestroyObject ( psO );
           }

          }
        else {
        
          Centrd = SHPCentrd_2d ( psCShape ); 

          cent_pt = SHPCreateSimpleObject ( SHPT_POINT, 1, 
        	(double*) &(Centrd.x), (double*) &(Centrd.y), NULL ); 

          SHPWriteObject ( new_SHP, -1, cent_pt ); 
                        
          memcpy ( DBFRow, DBFReadTuple ( old_DBF, i ),
		 old_DBF->nRecordLength );
          DBFWriteTuple ( new_DBF, new_DBF->nRecords, DBFRow );            

          SHPDestroyObject ( cent_pt );
         }
    }

    SHPClose( old_SHP );
    SHPClose( new_SHP );
    DBFClose( old_DBF );
    DBFClose( new_DBF );
    printf ("\n");
}
Example #29
0
OGRErr OGRShapeLayer::Repack()

{
    if( !bUpdateAccess )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
            "The REPACK operation is not permitted on a read-only shapefile." );
        return OGRERR_FAILURE;
    }
    
    if( hDBF == NULL )
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "Attempt to repack a shapefile with no .dbf file not supported.");
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Build a list of records to be dropped.                          */
/* -------------------------------------------------------------------- */
    int *panRecordsToDelete = (int *) 
        CPLMalloc(sizeof(int)*(nTotalShapeCount+1));
    int nDeleteCount = 0;
    int iShape = 0;
    OGRErr eErr = OGRERR_NONE;

    for( iShape = 0; iShape < nTotalShapeCount; iShape++ )
    {
        if( DBFIsRecordDeleted( hDBF, iShape ) )
            panRecordsToDelete[nDeleteCount++] = iShape;
    }
    panRecordsToDelete[nDeleteCount] = -1;

/* -------------------------------------------------------------------- */
/*      If there are no records marked for deletion, we take no         */
/*      action.                                                         */
/* -------------------------------------------------------------------- */
    if( nDeleteCount == 0 )
    {
        CPLFree( panRecordsToDelete );
        return OGRERR_NONE;
    }

/* -------------------------------------------------------------------- */
/*      Find existing filenames with exact case (see #3293).            */
/* -------------------------------------------------------------------- */
    CPLString osDirname(CPLGetPath(pszFullName));
    CPLString osBasename(CPLGetBasename(pszFullName));
    
    CPLString osDBFName, osSHPName, osSHXName;
    char **papszCandidates = CPLReadDir( osDirname );
    int i = 0;
    while(papszCandidates != NULL && papszCandidates[i] != NULL)
    {
        CPLString osCandidateBasename = CPLGetBasename(papszCandidates[i]);
        CPLString osCandidateExtension = CPLGetExtension(papszCandidates[i]);
        if (osCandidateBasename.compare(osBasename) == 0)
        {
            if (EQUAL(osCandidateExtension, "dbf"))
                osDBFName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
            else if (EQUAL(osCandidateExtension, "shp"))
                osSHPName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
            else if (EQUAL(osCandidateExtension, "shx"))
                osSHXName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
        }
        
        i++;
    }
    CSLDestroy(papszCandidates);
    papszCandidates = NULL;
    
    if (osDBFName.size() == 0)
    {
        /* Should not happen, really */
        CPLFree( panRecordsToDelete );
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Cleanup any existing spatial index.  It will become             */
/*      meaningless when the fids change.                               */
/* -------------------------------------------------------------------- */
    if( CheckForQIX() )
        DropSpatialIndex();

/* -------------------------------------------------------------------- */
/*      Create a new dbf file, matching the old.                        */
/* -------------------------------------------------------------------- */
    DBFHandle hNewDBF = NULL;
    
    CPLString oTempFile(CPLFormFilename(osDirname, osBasename, NULL));
    oTempFile += "_packed.dbf";

    hNewDBF = DBFCloneEmpty( hDBF, oTempFile );
    if( hNewDBF == NULL )
    {
        CPLFree( panRecordsToDelete );

        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "Failed to create temp file %s.", 
                  oTempFile.c_str() );
        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Copy over all records that are not deleted.                     */
/* -------------------------------------------------------------------- */
    int iDestShape = 0;
    int iNextDeletedShape = 0;

    for( iShape = 0; 
         iShape < nTotalShapeCount && eErr == OGRERR_NONE; 
         iShape++ )
    {
        if( panRecordsToDelete[iNextDeletedShape] == iShape )
            iNextDeletedShape++;
        else
        {
            void *pTuple = (void *) DBFReadTuple( hDBF, iShape );
            if( pTuple == NULL )
                eErr = OGRERR_FAILURE;
            else if( !DBFWriteTuple( hNewDBF, iDestShape++, pTuple ) )
                eErr = OGRERR_FAILURE;
        }                           
    }

    if( eErr != OGRERR_NONE )
    {
        CPLFree( panRecordsToDelete );
        VSIUnlink( oTempFile );
        return eErr;
    }

/* -------------------------------------------------------------------- */
/*      Cleanup the old .dbf and rename the new one.                    */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    DBFClose( hNewDBF );
    hDBF = hNewDBF = NULL;
    
    VSIUnlink( osDBFName );
        
    if( VSIRename( oTempFile, osDBFName ) != 0 )
    {
        CPLDebug( "Shape", "Can not rename DBF file: %s", VSIStrerror( errno ) );
        CPLFree( panRecordsToDelete );
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Now create a shapefile matching the old one.                    */
/* -------------------------------------------------------------------- */
    if( hSHP != NULL )
    {
        SHPHandle hNewSHP = NULL;
        
        if (osSHPName.size() == 0 || osSHXName.size() == 0)
        {
            /* Should not happen, really */
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }

        oTempFile = CPLFormFilename(osDirname, osBasename, NULL);
        oTempFile += "_packed.shp";

        hNewSHP = SHPCreate( oTempFile, hSHP->nShapeType );
        if( hNewSHP == NULL )
        {
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }

/* -------------------------------------------------------------------- */
/*      Copy over all records that are not deleted.                     */
/* -------------------------------------------------------------------- */
        iNextDeletedShape = 0;

        for( iShape = 0; 
             iShape < nTotalShapeCount && eErr == OGRERR_NONE; 
             iShape++ )
        {
            if( panRecordsToDelete[iNextDeletedShape] == iShape )
                iNextDeletedShape++;
            else
            {
                SHPObject *hObject;

                hObject = SHPReadObject( hSHP, iShape );
                if( hObject == NULL )
                    eErr = OGRERR_FAILURE;
                else if( SHPWriteObject( hNewSHP, -1, hObject ) == -1 )
                    eErr = OGRERR_FAILURE;

                if( hObject )
                    SHPDestroyObject( hObject );
            }
        }

        if( eErr != OGRERR_NONE )
        {
            CPLFree( panRecordsToDelete );
            VSIUnlink( CPLResetExtension( oTempFile, "shp" ) );
            VSIUnlink( CPLResetExtension( oTempFile, "shx" ) );
            return eErr;
        }

/* -------------------------------------------------------------------- */
/*      Cleanup the old .shp/.shx and rename the new one.               */
/* -------------------------------------------------------------------- */
        SHPClose( hSHP );
        SHPClose( hNewSHP );
        hSHP = hNewSHP = NULL;

        VSIUnlink( osSHPName );
        VSIUnlink( osSHXName );

        oTempFile = CPLResetExtension( oTempFile, "shp" );
        if( VSIRename( oTempFile, osSHPName ) != 0 )
        {
            CPLDebug( "Shape", "Can not rename SHP file: %s", VSIStrerror( errno ) );
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }
    
        oTempFile = CPLResetExtension( oTempFile, "shx" );
        if( VSIRename( oTempFile, osSHXName ) != 0 )
        {
            CPLDebug( "Shape", "Can not rename SHX file: %s", VSIStrerror( errno ) );
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }
    }
    
    CPLFree( panRecordsToDelete );
    panRecordsToDelete = NULL;

/* -------------------------------------------------------------------- */
/*      Reopen the shapefile                                            */
/*                                                                      */
/* We do not need to reimplement OGRShapeDataSource::OpenFile() here    */  
/* with the fully featured error checking.                              */
/* If all operations above succeeded, then all necessery files are      */
/* in the right place and accessible.                                   */
/* -------------------------------------------------------------------- */
    CPLAssert( NULL == hSHP );
    CPLAssert( NULL == hDBF && NULL == hNewDBF );
    
    CPLPushErrorHandler( CPLQuietErrorHandler );
    
    const char* pszAccess = NULL;
    if( bUpdateAccess )
        pszAccess = "r+";
    else
        pszAccess = "r";
    
    hSHP = SHPOpen ( CPLResetExtension( pszFullName, "shp" ) , pszAccess );
    hDBF = DBFOpen ( CPLResetExtension( pszFullName, "dbf" ) , pszAccess );
    
    CPLPopErrorHandler();
    
    if( NULL == hSHP || NULL == hDBF )
    {
        CPLString osMsg(CPLGetLastErrorMsg());
        CPLError( CE_Failure, CPLE_OpenFailed, "%s", osMsg.c_str() );

        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Update total shape count.                                       */
/* -------------------------------------------------------------------- */
    nTotalShapeCount = hDBF->nRecords;

    return OGRERR_NONE;
}
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;
}