Created
January 16, 2014 09:42
-
-
Save kishalmi/8452247 to your computer and use it in GitHub Desktop.
three.js - split a (loaded) model into mesh parts by material index
This file contains hidden or 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
/** | |
* split a (loaded) model into mesh parts by material index | |
* @param {THREE.Geometry} geometry | |
* @param {Array<THREE.Material>} materials | |
* @returns {Array<THREE.Mesh>} | |
*/ | |
var splitByMaterial = function(geometry,materials) { | |
var parts = [], | |
geo, vMap, iMat, | |
addPart = function() { | |
var mat = materials[iMat]; | |
mat.side = THREE.DoubleSide; | |
parts.push(new THREE.Mesh(geo,mat)); | |
}; | |
geometry.faces.forEach(function(face) { | |
if( face.materialIndex != iMat ) { | |
if( iMat !== undefined ) | |
addPart(); | |
geo = new THREE.Geometry(); | |
vMap = {}; | |
iMat = face.materialIndex; | |
} | |
var f = face.clone(); | |
['a','b','c'].forEach(function(p) { | |
var iv = face[p]; | |
if( !vMap.hasOwnProperty(iv) ) | |
vMap[iv] = geo.vertices.push(geometry.vertices[iv]) - 1; | |
f[p] = vMap[iv]; | |
}); | |
geo.faces.push(f); | |
}); | |
addPart(); | |
return parts; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment