Skip to main content
GameDev.net gamedev.net
🔒 Locked

'Squareing' a polygon

Started by Geeman Oct 19, 2003 at 1:21 PM 2 replies 600+ views
Original Post
Geeman
Geeman
Hi, I would like to make an ireguler 4 sided polygon perfectly square. To do this I have simply calculated the average length of the polygon sides. Then lined up the vertices to ''virtuals'' diagonals from the polygons center. My problem is, It only works with 2D. I need to take into account the orientation of the original polygon, so the resulting polygon is at the same angle the original polygon was. How can I go about this? my current code in pseudocode is:
// Calculated Edge lengths beforehand
...
// Get the average edge length
AverageEdge = (Edge1+Edge2+Edge3+Edge4) / 4;

// Get the Center of the polygon (v1,v2,v3,v4 are vectors)
Center = (v1+v2+v3+v4)/4;

// Use size to position the vertices in the correct place
Size = AverageEdge/2;

//move v1 to bottom-left of ''square''
v1 = Center;
v1.x -= Size;
v1.y -= Size

//move v2 to top-left of ''square''
v2 = Center;
v2.x -= Size;
v2.y += Size

//move v3 to top-right of ''square''
v3 = Center;
v3.x += Size;
v3.y += Size

//move v4 to bottom-right of ''square''
v4 = Center;
v4.x += Size;
v4.y -= Size
 
As you can see that is ok for 2D when the orientation isn''t important. Thanks
cowsarenotevil
cowsarenotevil
You could store the correct orientation of the polygon in a matrix, and then make it a square in 2D, and then orient it properly using the original matrix... I think.
-~-The Cow of Darkness-~-
Afaik
Afaik
If it''s just one poly, then sure it''s possible, but if this poly shares its
vertices with other polys, then you''re going to have a mess. Your errors will
just propagate through the model and get worse.
JonnyQuest
JonnyQuest
You could determine the surface vector of the polygon:
s = (edge1 x edge2 + edge4 x edge3) * 1/2
and the centre
c = (v1 + v2 + v3 + v4) * 1/4

where edge1..4 are the edge vectors and v1..4 are position vectors of the vertices. x is cross (vector) product.
If the vertices are coplanar, the magnitude of the surface vector is the area. If not, it''s slightly less, but in that case it''s quite hard to say what the correct area would be in the first place.
If you take the square root of the magnitude of the surface vector, you therefore get the length of a side of the resulting square.
a = sqrt(|s|)
To determine the orientation, you could average the diagonal directions:
d = (v1 - v3) / |v1 - v3| + (v2 - v4) / |v2 - v4|
e = (v1 - v3) / |v1 - v3| - (v2 - v4) / |v2 - v4|
and normalise
d = d / |d|
e = e / |e|
you can use these vectors together with the centre to find the vertices of the square:
v''1 = c - d * a/2 - e * a/2
v''2 = c + d * a/2 - e * a/2
v''3 = c + d * a/2 + e * a/2
v''4 = c - d * a/2 + e * a/2

Hope that helped.

- JQ
~phil

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.