Exemple #1
0
void freePolygonList(PolygonList& list) {
  PolygonList::iterator begin = list.begin(), end=list.end();
  for(; begin != end; begin++)
    delete *begin;

  list.clear();
}
Exemple #2
0
void polygonList2File(PolygonList & p, ftFile ff)
{
	ff.write("");
	for (auto it = p.begin(); it != p.end(); ++it) {
                polygon2File(*it, ff);
	}
}
void LevelDesignerController::alignToGrid(void) {
  PolygonList polygonList = _model->getPolygonList();
  for (int k = 0; k < _model->rowCount(); ++k) {
    TreeItem* polygonItem = _model->getItem(_model->index(k, 0));
    std::vector<Point2d> vertices = polygonList.at(k).getVertices();
    for (int i = 0; i < polygonItem->childCount(); ++i) {
      Point2d currVertex = vertices.at(i);

      int oldX = currVertex.getX();
      int oldY = currVertex.getY();

      int extraX = static_cast<int>(oldX)%50;
      int extraY = static_cast<int>(oldY)%50;

      int newX = oldX;
      int newY = oldY;

      if (extraY < 50/3)
        newY = oldY - extraY;// + 5;
      else if (extraY > 50 - 50/3)
        newY = oldY + (50 - extraY);// + 5;

      if (extraX < 50/3)
        newX = oldX - extraX;// + 5;
      else if (extraX > 50 - 50/3)
        newX = oldX + (50 - extraX);// + 5;

      if (oldX != newX || oldY != newY)
        moveVertex(k, i, oldX, oldY, newX, newY);
    }
  }
}
bool COpenGLStaticMesh::GenerateDisplayListFromMesh(const CStaticMeshBase& staticMesh)
{
	bool							bListGeneratedSuccessfully = false;


	//Obtain a list of polygons from the mesh...
	PolygonList						meshPolyList = staticMesh.GetPolygonList();	

	if (!meshPolyList.empty()) {
		//Number of display lists to generate.
		const QuantityType			kNumDisplayLists = 1;

		//Obtain a display list reference...
		const displayListReference = ::glGenLists(kNumDisplayLists);

		//Create a display list (GL_COMPILE indicates that the list will
		//be created, but not rendered immediately).
		::glNewList(displayListReference, GL_COMPILE);

		// Create texture(s) and bind the texture(s), allowing the texture/
		// textures to be used.
		::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		GLuint						textureID;
		::glGenTextures(1, &textureID);

		// Store the texture reference/identifier.
		this->AddTextureLayerReference(textureID);

		::glBindTexture(GL_TEXTURE_2D, textureID);

		::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);


		const CTextureCollection&	textureCollection = staticMesh.GetTextureCollection();
		const CBaseTextureData*		pTextureInformation = textureCollection.GetTextureLayer(0);

		if (pTextureInformation) {
			const void*				pRawTextureData = pTextureInformation->GetTextureData();

			if (pRawTextureData) {
				::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pTextureInformation->GetTextureWidth(),
					pTextureInformation->GetTextureHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, pRawTextureData);
			}

			::glBindTexture(GL_TEXTURE_2D, textureID);
		}

		//Iterate through the list of mesh polygons, adding the polygons
		//to the created OpenGL display list.
		for(PolygonList::iterator polylistIterator = meshPolyList.begin();
			polylistIterator != meshPolyList.end(); polylistIterator++)
		{
			//Obtain the vertex list from the current polygon...
			CFloatPolygon::VertexList	
									vertexList  = polylistIterator->GetVertexList();

			//Create an OpenGl polygon.
			::glBegin(GL_POLYGON);
			for(CFloatPolygon::VertexList::iterator vertexListIterator = vertexList.begin();
				vertexListIterator != vertexList.end(); vertexListIterator++)
			{
				//Set the material properties (basic lighting model interactions -
				//ambient, diffuse, specular, emissive) for the polygon..

				const ScalarType	kMaxSpecularExponent = 128.0;

				//Ambient color.
				CFloatColor			ambientColor =
					polylistIterator->GetLightShading(eShadeAmbient);
				GLfloat				ambientMaterial[] = { ambientColor.GetRedValue(),
					ambientColor.GetGreenValue(), ambientColor.GetBlueValue(), 1.0 };
				glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambientMaterial);

				//Diffuse color.
				CFloatColor			diffuseColor =
					polylistIterator->GetLightShading(eShadeDiffuse);
				GLfloat				diffuseMaterial[] = { diffuseColor.GetRedValue(),
					diffuseColor.GetGreenValue(), diffuseColor.GetBlueValue(), 1.0 };
				glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuseMaterial);

				//Emissive color.
				CFloatColor			emissiveColor =
					polylistIterator->GetLightShading(eShadeEmissive);
				GLfloat				emissiveMaterial[] = { emissiveColor.GetRedValue(),
					emissiveColor.GetGreenValue(), emissiveColor.GetBlueValue(), 1.0 };
				glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissiveMaterial);			

				//Specular color.
				CFloatColor			specularColor =
					polylistIterator->GetLightShading(eShadeSpecular);
				GLfloat				specularMaterial[] = { specularColor.GetRedValue(), 
					specularColor.GetGreenValue(), specularColor.GetBlueValue(), 1.0 };
				glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularMaterial);
				glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS,
					kMaxSpecularExponent * polylistIterator->GetSpecularity());
				
				//Retrieve the vertex normal.
				CVector				vertexNormal = vertexListIterator->GetNormal();

				//Store the color/alpha information.
				CFloatColor			vertexColor = vertexListIterator->GetColor();
				::glColor4d(vertexColor.GetRedValue(), vertexColor.GetGreenValue(),
					vertexColor.GetBlueValue(), vertexColor.GetAlphaValue());
				//Store the normal.
				::glNormal3d(vertexNormal.GetXComponent(), vertexNormal.GetYComponent(),
					vertexNormal.GetZComponent());

				//Texture coordinates
				ScalarType			uTextureCoordinate = 0.0;
				ScalarType			vTextureCoordinate = 0.0;
				vertexListIterator->GetTextureCoordinates(uTextureCoordinate, vTextureCoordinate);
				::glTexCoord2f(uTextureCoordinate, vTextureCoordinate);

				//Store the vertex coordinates.
				::glVertex3d(vertexListIterator->GetXCoord(), 
					vertexListIterator->GetYCoord(),
					vertexListIterator->GetZCoord());
			}
			::glEnd();

		#if RENDER_VERTEX_NORMALS
			for(CFloatPolygon::VertexList::iterator vertexNormIterator = vertexList.begin();
				vertexNormIterator != vertexList.end(); vertexNormIterator++)
			{
				//Retrieve the vertex normal.
				CVector				vertexNormal = vertexNormIterator->GetNormal();
				::glBegin(GL_LINES);
				//Render the normal vector (debugging purposes only).
				::glVertex3d(vertexNormIterator->GetXCoord(), 
					vertexNormIterator->GetYCoord(),
					vertexNormIterator->GetZCoord());
				::glVertex3d(vertexNormIterator->GetXCoord() + vertexNormal.GetXComponent(), 
					vertexNormIterator->GetYCoord() + vertexNormal.GetYComponent(),
					vertexNormIterator->GetZCoord() + vertexNormal.GetZComponent());
				::glEnd();
			}
		#endif	//#if RENDER_VERTEX_NORMALS
		}

		// Unbind any texture objects.
		::glBindTexture(GL_TEXTURE_2D, 0);

		//Complete the display list.
		::glEndList();

		//Store the display list reference number.
		this->SetDisplayListReference(displayListReference);

		//Indicate a success condition. 
		bListGeneratedSuccessfully = true;
	}


	//Set the validity flag of the display list reference to
	//correspond to the display list creation result flag.
	this->mbDisplayListReferenceSet = bListGeneratedSuccessfully;

	return(bListGeneratedSuccessfully);
}
void SpatiaLiteDB::queryGeometry(
		std::string table,
		std::string geometry_col,
		double left,
		double bottom,
		double right,
		double top,
		std::string label_col) {

	_pointlist.clear();
	_linestringlist.clear();
	_polygonlist.clear();
	bool getLabel = label_col.size() != 0;

	// Search for geometry and name

	// The query will be either
	//
	// SELECT Geometry FROM  table WHERE MbrWithin(Column, BuildMbr(left, bottom, right, top));
	//    or
	// SELECT Geometry,Label FROM  table WHERE MbrWithin(Column, BuildMbr(left, bottom, right, top));
	//
	// where Geometry is the geometry column name and Label is the column containing a name or label.
	std::string label;
	if (getLabel) {
		label = "," + label_col;
	}
	std::stringstream s;
	s <<
		 "SELECT "           <<
		 geometry_col        <<
		 label               <<
		 " FROM "            <<
		 table               <<
		 " WHERE  MbrIntersects(" <<
		 geometry_col        <<
		 ", BuildMbr("         <<
		 left                <<
		 ","                 <<
		 bottom              <<
		 ","                 <<
		 right               <<
		 ","                 <<
		 top                 <<
		 "));";

	// prepare the query
	prepare(s.str());

	// fetch the next result row
	while (step()) {
		// get the geometry
		gaiaGeomCollPtr geom = Geom(0);
		// get the label, if we asked for it
		std::string label;
		if (getLabel) {
			label = Text(1);
		}
		// the following will create lists for points, lines and polygons found in
		// a single geometry. In practice it seems that only one of those types
		// exists for a given geometry, but it's not clear if this is a requirement
		// or just occurs in the sample databases we have been working with.
		PointList points = point_list(geom, label);
		for (PointList::iterator i = points.begin(); i != points.end(); i++) {
			_pointlist.push_back(*i);
		}
		LinestringList lines = linestring_list(geom, label);
		for (LinestringList::iterator i = lines.begin(); i != lines.end(); i++) {
			_linestringlist.push_back(*i);
		}
		PolygonList polys = polygon_list(geom, label);
		for (PolygonList::iterator i = polys.begin(); i != polys.end(); i++) {
			_polygonlist.push_back(*i);
		}
	}

	// finish with this query
	finalize();
}
int main(int argc, char* argv[])
{
/*
mySF gg;
test(&myF);
test(gg);
*/
    PolygonList plygnList;
    PolygonParser plygnPrsr("polygon.txt");
    if (plygnPrsr.init())
    {
        Polygon tmpPlygn;
        DataTrans tmp(tmpPlygn);
        while (plygnPrsr.hasNext())
        {
            //tmpPlygn.clear();
            tmp.getData().clear();
            plygnPrsr.getPointVec(tmp,tmp);
            plygnList.push_back(tmp.getData());
        }
    }

    VerSegCntnr tmpCntnr;
    STD::vector<VerSegCntnr> segInfoVec;
    GraphLib::IdType invalidId(STD::numeric_limits<int>::max());
    PolygonLinkRec linkRec;
    LinkRecList linkRecList;
    size_t verSegCnt = 0;
    size_t totalVerSegCnt = 0;
    for (STD::list<Polygon>::iterator it=plygnList.begin();
         it != plygnList.end(); ++it )
    {
        assert(0 == (*it).size() % 1 && 4 <= (*it).size() );
        if (!(0==(*it).size() %1 && 4<= (*it).size()) ) continue;
        linkRecList.push_back( STD::make_pair(&(*it), invalidId) );

        verSegCnt = (*it).size() >> 2;
        totalVerSegCnt += verSegCnt;
        tmpCntnr.linkRecPtr_ = &(linkRecList.back());

        //assume the first point is the most lowerleft point
        //O(n) complexity
        //the trap is: itA+=2 could be an action of 2,not as simple as adding.
        Polygon::const_iterator itA = (*it).begin()+1;
        Polygon::const_iterator itB = itA+1; 
        for (;itA != (*it).end() && itB != (*it).end();
              itA+=2,itB+=2)
        {
            tmpCntnr.seg_.head_ = ((*itA).y_<=(*itB).y_) ? (*itA) : (*itB);
            tmpCntnr.seg_.tail_ = ((*itA).y_<=(*itB).y_) ? (*itB) : (*itA);
            printf("PUSH (%d,%d)-(%d,%d)\n", tmpCntnr.seg_.head_.x_,tmpCntnr.seg_.head_.y_,tmpCntnr.seg_.tail_.x_,tmpCntnr.seg_.tail_.y_);
            segInfoVec.push_back(tmpCntnr);
        }
        itB = (*it).begin();
        tmpCntnr.seg_.head_ = ((*itA).y_<=(*itB).y_) ? (*itA) : (*itB);
        tmpCntnr.seg_.tail_ = ((*itA).y_<=(*itB).y_) ? (*itB) : (*itA);
        printf("PUSH (%d,%d)-(%d,%d)\n", tmpCntnr.seg_.head_.x_,tmpCntnr.seg_.head_.y_,tmpCntnr.seg_.tail_.x_,tmpCntnr.seg_.tail_.y_);
        segInfoVec.push_back(tmpCntnr);
    }

    //sort reversely
    STD::sort(segInfoVec.begin(), segInfoVec.end(),sortVerSegByRevX);

    StNodePtrVec treeNodePtrVec(2,static_cast<StNodePtrVec::value_type>(NULL));
    //Collector collector(treeNodePtrVec);
    SegmentTree st; 
    CnstrntGraph graph;
    PolygonLinkRec *leftRecPtr = NULL, *rightRecPtr = NULL, *middleRecPtr = NULL;
    for(size_t idx = 0; idx < segInfoVec.size(); ++idx )
    {
        //collect overlapped datas
        treeNodePtrVec.clear();
        Collector collector(treeNodePtrVec,segInfoVec[idx].linkRecPtr_,segInfoVec[idx].seg_.head_.x_);
        st.getOverlap(segInfoVec[idx].seg_.head_.y_,segInfoVec[idx].seg_.tail_.y_, collector);
        //use the collected datas to build contraints
        if ( treeNodePtrVec[0] || treeNodePtrVec[1] )
        {
            middleRecPtr = segInfoVec[idx].linkRecPtr_;
            if (invalidId == middleRecPtr->second )
                middleRecPtr->second = graph.addNode(Gnode(middleRecPtr));

            printf("Ref:%d %d %d \n", segInfoVec[idx].seg_.head_.y_, segInfoVec[idx].seg_.tail_.y_,segInfoVec[idx].seg_.tail_.x_);
            if (treeNodePtrVec[0])
            {
                printf("left:%d,%d,%d\n", treeNodePtrVec[0]->getStartCoord(), treeNodePtrVec[0]->getEndCoord(), treeNodePtrVec[0]->getRefCoord());         
                leftRecPtr = static_cast<PolygonLinkRec*>(treeNodePtrVec[0]->getId());
                if ( invalidId == leftRecPtr->second )
                    leftRecPtr->second = graph.addNode(Gnode(leftRecPtr));

                SegCoord diff =  segInfoVec[idx].seg_.head_.x_ - treeNodePtrVec[idx]->getRefCoord();
                GraphLib::IdType edgeId;
                //My personal constraint: only one constraint
                if (graph.beginNodeIter(leftRecPtr->second) == graph.endNodeIter(leftRecPtr->second))
                    edgeId = graph.addEdge(leftRecPtr->second, middleRecPtr->second, diff);
                else
                    edgeId = graph.getEdgeId(leftRecPtr->second,middleRecPtr->second);

                if (graph.getEdgeData(edgeId).userData_ > diff) 
                {
                    graph.getEdgeData(edgeId).userData_ = diff;
                }
            }
            if (treeNodePtrVec[1])
            {
                printf("right:%d,%d,%d\n", treeNodePtrVec[1]->getStartCoord(), treeNodePtrVec[1]->getEndCoord(), treeNodePtrVec[1]->getRefCoord());
                rightRecPtr = static_cast<PolygonLinkRec*>(treeNodePtrVec[1]->getId()); 
                if ( invalidId == rightRecPtr->second )
                    rightRecPtr->second = graph.addNode(Gnode(rightRecPtr)); 

                SegCoord diff =  treeNodePtrVec[1]->getRefCoord() - segInfoVec[idx].seg_.head_.x_;
printf("diff:%d\n",diff);
                GraphLib::IdType edgeId;
                //My personal constraint: only one edge
                if (graph.beginNodeIter(middleRecPtr->second) == graph.endNodeIter(middleRecPtr->second))
                    edgeId = graph.addEdge(middleRecPtr->second, rightRecPtr->second, diff);
                else
                    edgeId = graph.getEdgeId(middleRecPtr->second, rightRecPtr->second);

                if (graph.getEdgeData(edgeId).userData_ > diff) 
                {
                    graph.getEdgeData(edgeId).userData_ = diff;
                    graph.getEdgeData(edgeId).toId_ = rightRecPtr->second;
                }
            }
        }

        st.insert_equal( SegmentTreeNode(segInfoVec[idx].seg_.head_.y_, 
                                         segInfoVec[idx].seg_.tail_.y_,
                                         segInfoVec[idx].seg_.head_.x_,
                                         (void*)(segInfoVec[idx].linkRecPtr_)));

        treeNodePtrVec.assign(2,static_cast<StNodePtrVec::value_type>(NULL));
    } 

    printf("NodeCount:%d EdgeCount:%d\n", graph.nodeCount(),graph.edgeCount());
    CnstrntGraph::EdgeIdGen edgeIdGenObj(graph);
    while(edgeIdGenObj.hasNext()) 
    {
        CnstrntGraph::EdgeType& edge = graph.getEdgeData(edgeIdGenObj.getNext());
        CnstrntGraph::NodeType& from = graph.getNodeData(edge.fromId_);
        CnstrntGraph::NodeType& to = graph.getNodeData(edge.toId_);
       
        printf("edge Value:%d shape1:size:%d x:%d, shape2:size:%d x:%d\n",
                edge.userData_, 
                ((Polygon*)(from.userData_.getLinkRecPtr()->first))->size(),
                ((Polygon*)(from.userData_.getLinkRecPtr()->first))->front().x_,
                ((Polygon*)(to.userData_.getLinkRecPtr()->first))->size(),
                ((Polygon*)(to.userData_.getLinkRecPtr()->first))->front().x_
              );
    }

#if 0
// this code snippet is testing that if all the posotion of polygons are all
// altered after the constraint grah is built, this solving system can get
// all the polygons back to where it is such that the constraints are 
// satisfied.
    int shift = 10;
    for (PolygonList::iterator iter = ++plygnList.begin(); iter != plygnList.end(); ++iter)
    {
        for ( Polygon::iterator iter2 = (*iter).begin(); iter2 != (*iter).end(); ++iter2)
        {
            (*iter2).x_ = (*iter2).x_ + shift;
            (*iter2).y_ = (*iter2).y_ + shift;
        }
        shift+=10;
    }
#endif
    //add a fake source
    GraphLib::IdType source = graph.addNode(Gnode(NULL));
    graph.addEdge(source, linkRecList.front().second, 0);

    //longest path
    edgeIdGenObj.init();
    int dist[ graph.nodeCount() ];
    memset(dist,-1,sizeof(dist));
    int parent[graph.nodeCount()];
    dist[source] = 0;
    parent[source] = source;
    for (int count = 0; count < graph.nodeCount(); ++count )
    {
        while (edgeIdGenObj.hasNext())
        {
            CnstrntGraph::EdgeType& edge = graph.getEdgeData(edgeIdGenObj.getNext());
            if ( dist[edge.toId_] < dist[edge.fromId_] + edge.userData_ )
            {
                dist[edge.toId_] = dist[edge.fromId_] + edge.userData_;
                parent[edge.toId_] = edge.fromId_;
            }

        }
        edgeIdGenObj.init();
    }

    edgeIdGenObj.init();
    while (edgeIdGenObj.hasNext())
    {
        CnstrntGraph::EdgeType& edge = graph.getEdgeData(edgeIdGenObj.getNext());
        printf("from:%d dist:%d to:%d dist:%d\n",
                edge.fromId_.val(), dist[edge.fromId_],
                edge.toId_.val(), dist[edge.toId_]
              );
    }

    //for verification
    printf("Start printing result for verification\n");
    dfsPrint(graph,source,dist);    
    printf("End printing result for verification\n");
     
#if 0 
    for (STD::list<Polygon>::const_iterator it=plygnList.begin();
         it != plygnList.end();
         ++it
        )
    {
        for (STD::vector<Point>::const_iterator it2=(*it).begin();
             it2 != (*it).end();
             ++it2
            )
        {
            printf(" (%d %d)-", (*it2).x_, (*it2).y_);
        }
        printf("\n");
    }
#endif
    return EXIT_SUCCESS;
}