Jump to content
  • Advertisement
Sign in to follow this  

Sorting polygon vertices clockwise

This topic is 4581 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, i got a problem with my vertex sorting in my polygons. I need to have clockwise ordered vertices for my triangulation code to work. So i assume the problem is within my sorting code. Maybe you can find the problem of my sorting code. If you have a simpler or better performing code for sorting polygons clockwise i would also appreciate to see it.
void	SortClockwise()
	// Get center of polygon
	CVector3D Center(GetCenter());

	for(unsigned int aktVert1 = 0; aktVert1 < Vertices.size() - 1; ++aktVert1)
		CVector3D	Pos1(Vertices[aktVert1].Position);
		CVector3D	A(Pos1 - Center);
		// Create a plane thru current vertex, center and normal of polygon
		CPlane		Plane(Pos1, Center, Center + Normal);

		float		SmallestAngle	= -1;
		int		Smallest	= -1;
		for(unsigned int aktVert2 = aktVert1 + 1; aktVert2 < Vertices.size(); ++aktVert2)
			CVector3D Pos2(Vertices[aktVert2].Position);
			// Test against plane if vert can be the next
			if(Plane.ClassifyPoint(Pos2) == CP_Front)
				CVector3D B(Pos2 - Center);

				float Angle = A.Dot(B);

				if(Angle > SmallestAngle)
					SmallestAngle	= Angle;
					Smallest	= aktVert2;
		// Vert with smallest angle is the next
		if(Smallest != -1)
			// Tauschen der Vertices
			CVertex			Temp(Vertices[aktVert1 + 1]);
			Vertices[aktVert1 + 1]	= Vertices[Smallest];
			Vertices[Smallest]	= Temp;
	// Reverse vertices if needed
	CVector3D P1(Vertices[0].Position);
	CVector3D P2(Vertices[1].Position);
	CVector3D P3(Vertices[(unsigned int)Vertices.size() - 1].Position);
	CVector3D AB(P2 - P1); 
	CVector3D BC(P3 - P1);        
	CVector3D Norm(AB.Cross(BC));
	if((Normal.Dot(Norm)) < 0)
		vector <CVertex>::iterator	B,E;
		B	= Vertices.begin();
		E	= Vertices.end();

		for(unsigned int i = 0; i < Vertices.size() / 2; ++i)
			CVertex TempV	= *E;
			*E				= *B;
			*B				= TempV;			

Thanks for any help

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!