Created
September 28, 2019 17:05
-
-
Save gnsx/16ce570c52311d4832ae1483a4ad22e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
//Point2D Structure | |
type Point2D struct { | |
x float64 | |
y float64 | |
} | |
func compute2DPolygonCentroid(vertices []Point2D, vertexCount int) Point2D { | |
centroid := Point2D{0, 0} | |
signedArea := 0.0 | |
x0 := 0.0 | |
y0 := 0.0 | |
x1 := 0.0 | |
y1 := 0.0 | |
a := 0.0 | |
// For all vertices except last | |
i := 0 | |
for i < vertexCount-1 { | |
x0 = vertices[i].x | |
y0 = vertices[i].y | |
x1 = vertices[i+1].x | |
y1 = vertices[i+1].y | |
a = x0*y1 - x1*y0 | |
signedArea += a | |
centroid.x += (x0 + x1) * a | |
centroid.y += (y0 + y1) * a | |
i++ | |
} | |
// Do last vertex separately to avoid performing an expensive | |
// modulus operation in each iteration. | |
x0 = vertices[i].x | |
y0 = vertices[i].y | |
x1 = vertices[0].x | |
y1 = vertices[0].y | |
a = x0*y1 - x1*y0 | |
signedArea += a | |
centroid.x += (x0 + x1) * a | |
centroid.y += (y0 + y1) * a | |
signedArea *= 0.5 | |
centroid.x /= (6.0 * signedArea) | |
centroid.y /= (6.0 * signedArea) | |
return centroid | |
} | |
func main() { | |
polygon := []Point2D{{0.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}, {10.0, 0.0}} | |
vertexCount := len(polygon) | |
fmt.Print("Centroid:", compute2DPolygonCentroid(polygon, vertexCount)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment