1 module beziermeshmaker.datastructures.input.polygon;
2 
3 import beziermeshmaker.datastructures.vec3;
4 
5 class Polygon {
6 	vec3[] vertices;
7 	vec3 centroid;
8 
9 	//Used to carry forward information from the initial polygons to the output surfaces
10 	string[string] metadata;
11 
12 	this(float[3][] vertices) {
13 		foreach (float[3] coords ; vertices) {
14 			this.vertices ~= new vec3(coords[0], coords[1], coords[2]);
15 		}
16 
17 		centroid = getCentroid();
18 	}
19 
20 	//Algorithm is from https://bell0bytes.eu/centroid-convex/
21 	private vec3 getCentroid() {
22 		vec3 weightedCenterSum = new vec3(0, 0, 0);
23 		float totalWeight = 0;
24 
25 		//We're not doing anything special with the triangulation here since the polygons are supposed to be convex.
26 		vec3 root = vertices[0];
27 		for (int i = 0; i < vertices.length - 2; i++) {
28 			vec3 a = vertices[i+1];
29 			vec3 b = vertices[i+2];
30 
31 			vec3 center = (root + a + b) / 3;
32 			float weight = 0.5 * (a - root).cross(b - root).length();
33 
34 			weightedCenterSum = weightedCenterSum + (center * weight);
35 			totalWeight += weight;
36 		}
37 
38 		return weightedCenterSum / totalWeight;
39 	}
40 }