Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
THREE.js Flat Triangle Subdivide
// Triangle Subdivision based on http://wiki.unity3d.com/index.php?title=MeshHelper
// There is not smoothing of any sort, it will just divide the triangles
// hence the FlatSubdivide name
THREE.FlatSubdivide = function () {
};
// Applies the "modify" pattern
THREE.FlatSubdivide.prototype.modify = function ( geometry ) {
this.subdiv( geometry );
geometry.computeFaceNormals();
geometry.computeVertexNormals();
};
( function() {
THREE.FlatSubdivide.prototype.subdiv = function ( geometry ) {
var map = []
var newFaces = []
var vertices = geometry.vertices
var faces = geometry.faces
var numFaces = faces.length
for(var i=0; i < numFaces; ++i) {
var i1 = faces[i].a
var i2 = faces[i].b
var i3 = faces[i].c
var a = getNewVertex(i1,i2,map, vertices)
var b = getNewVertex(i2,i3,map, vertices)
var c = getNewVertex(i3,i1,map, vertices)
newFaces.push(new THREE.Face3(i1,a,c))
newFaces.push(new THREE.Face3(i2,b,a))
newFaces.push(new THREE.Face3(i3,c,b))
newFaces.push(new THREE.Face3(a,b,c))
}
geometry.faces = newFaces
};
function getEdgeKey(i1, i2) {
var vertexIndexA = Math.min( i1, i2 );
var vertexIndexB = Math.max( i1, i2 );
return vertexIndexA + "_" + vertexIndexB;
}
function GetMiddle(pointA, pointB) {
var middle = new THREE.Vector3()
middle.subVectors(pointB.clone() , pointA.clone())
middle.multiplyScalar( 0.5)
middle.subVectors(pointB.clone(), middle )
return middle.clone()
}
function getNewVertex(i1, i2, map, vertices) {
var newIndex = vertices.length
var edgeKey = getEdgeKey(i1, i2)
if(edgeKey in map ) {
return map[edgeKey];
}
// add new index
map[edgeKey] = newIndex
// get the middle of the edge
var middle = GetMiddle(vertices[i1], vertices[i2])
vertices.push(middle)
return newIndex
}
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.