Skip to content

Instantly share code, notes, and snippets.

@larsberg
Created March 23, 2016 17:51
Show Gist options
  • Save larsberg/d86c2620db241ea30db5 to your computer and use it in GitHub Desktop.
Save larsberg/d86c2620db241ea30db5 to your computer and use it in GitHub Desktop.
returns an edge to face map for a THREE geometry. make sure the vertices are merged before hand
'use strict'
var getWingedEdges = function( g ){
var edgeMap = {};
// find the edges
function getEdgeKey( i0, i1 ){
return Math.min(i0, i1) + '_' + Math.max(i0, i1);
}
function addEdge( i0, i1, faceIndex ){
var edgeKey = getEdgeKey( i0, i1 );
if(edgeMap[ edgeKey ] !== undefined){
edgeMap[ edgeKey ].f.push( faceIndex );
} else {
edgeMap[ edgeKey ] = {
v: [i0, i1],
f: [faceIndex],
normal: new THREE.Vector3()
}
}
return edgeKey;
}
g.faces.forEach( function( f, i ){
addEdge(f.a, f.b, i);
addEdge(f.b, f.c, i);
addEdge(f.c, f.a, i);
});
// compute edge normals
g.computeFaceNormals();
function normalFromTwoVector( v0, v1 ){
return v0.cross( v1 ).normalize();
}
var v = g.vertices;
for(var i in edgeMap){
var e = edgeMap[i];
if(e.f.length > 1){
// average the face normals
var n = e.normal.set(0,0,0);
e.f.forEach( function( i ){
n.add( g.faces[i].normal );
});
n.divideScalar( e.f.length );
} else {
var f = g.faces[ e.f[0] ];
var v0 = f.normal.normalize().clone();
var v1 = v[ e.v[0] ].clone().sub( v[ e.v[1] ] ).normalize();
e.normal.copy( normalFromTwoVector( v0, v1 ) );
}
}
return edgeMap
}
module.exports = getWingedEdges;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment