Generate mesh faces for vertices in THREE.js

I'm not sure the answer should be dazzlingly obvious, but it eludes me. I am making a 3D Graphics class on Udacity that uses three.js. I am at the point where 3d mesh generation is required.

I have the correct vertices, but I am stuck in creating faces for them. I can't think of an obvious way to automatically create faces that don't overlap. I searched and searched on the Internet, but I can not find any information about this. I'm not sure if this is something stupidly obvious or just not very documented. Here is the code:

function PolygonGeometry(sides) { var geo = new THREE.Geometry(); // generate vertices for ( var pt = 0 ; pt < sides; pt++ ) { // Add 90 degrees so we start at +Y axis, rotate counterclockwise around var angle = (Math.PI/2) + (pt / sides) * 2 * Math.PI; var x = Math.cos( angle ); var y = Math.sin( angle ); // YOUR CODE HERE //Save the vertex location - fill in the code geo.vertices.push( new THREE.Vector3(x, y, 0) ); } // YOUR CODE HERE // Write the code to generate minimum number of faces for the polygon. // Return the geometry object return geo; } 

I know that the basic formula for the minimum number of faces is n-2. But I just can't think of a way to do this without crossing faces. I don’t want anyone to do my work for me, I want to understand as much as I can. But is there anyone who can point me in the right direction or give me a formula or something else?

+6
source share
2 answers

Assuming you create your vertices in a concave way and counterclockwise, then if you have 3 sides (triangle), you connect vertex 0 to 1 with 2. If you have 4 sides (four), you connect vertex 0 to 1 s 2 (first triangle) and then with vertex 0 s 2 s 3. If you have 5 sides (pentagon), you connect vertex 0 with 1 s 2 (first triangle) and then vertex 0 with 2 s 3 (second triangle and then vertex 0 s 3 s 4. I think you get a pattern.

+3
source

You can automate triangulation

For large polygons, it can be quite difficult to manually add faces. You can automate the process of adding faces to Mesh using the triangulateShape method in THREE.Shape.Utils as follows:

 var vertices = [your vertices array] var holes = []; var triangles, mesh; var geometry = new THREE.Geometry(); var material = new THREE.MeshBasicMaterial(); geometry.vertices = vertices; triangles = THREE.Shape.Utils.triangulateShape ( vertices, holes ); for( var i = 0; i < triangles.length; i++ ){ geometry.faces.push( new THREE.Face3( triangles[i][0], triangles[i][1], triangles[i][2] )); } mesh = new THREE.Mesh( geometry, material ); 

Where vertices is your array of vertices and holes you can define holes in your polygon.

Note. Be careful if your polygon self-intersects, it throws an error. Make sure your vertex array represents a valid (disjoint) polygon.

+9
source

All Articles