Skip to content

Instantly share code, notes, and snippets.

@kjlubick
Last active September 8, 2024 16:49
Show Gist options
  • Save kjlubick/fb6ba9c51df63ba0951f to your computer and use it in GitHub Desktop.
Save kjlubick/fb6ba9c51df63ba0951f to your computer and use it in GitHub Desktop.
Exports a THREE.js scene mesh to STL, making it suitable for 3d printing
The MIT License
Copyright © 2010-2016 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
/**
* Based on https://github.com/mrdoob/three.js/blob/a72347515fa34e892f7a9bfa66a34fdc0df55954/examples/js/exporters/STLExporter.js
* Tested on r68 and r70
* @author kjlubick / https://github.com/kjlubick
* @author kovacsv / http://kovacsv.hu/
* @author mrdoob / http://mrdoob.com/
*/
THREE.STLExporter = function () {};
THREE.STLExporter.prototype = {
constructor: THREE.STLExporter,
parse: ( function () {
var vector = new THREE.Vector3();
var normalMatrixWorld = new THREE.Matrix3();
return function ( scene ) {
var output = '';
output += 'solid exported\n';
scene.traverse( function ( object ) {
if ( object instanceof THREE.Mesh ) {
var geometry = object.geometry;
var matrixWorld = object.matrixWorld;
var mesh = object;
if ( geometry instanceof THREE.Geometry ) {
var vertices = geometry.vertices;
var faces = geometry.faces;
normalMatrixWorld.getNormalMatrix( matrixWorld );
for ( var i = 0, l = faces.length; i < l; i ++ ) {
var face = faces[ i ];
vector.copy( face.normal ).applyMatrix3( normalMatrixWorld ).normalize();
output += '\tfacet normal ' + vector.x + ' ' + vector.y + ' ' + vector.z + '\n';
output += '\t\touter loop\n';
var indices = [ face.a, face.b, face.c ];
for ( var j = 0; j < 3; j ++ ) {
var vertexIndex = indices[ j ];
if (mesh.geometry.skinIndices.length == 0) {
vector.copy( vertices[ vertexIndex ] ).applyMatrix4( matrixWorld );
output += '\t\t\tvertex ' + vector.x + ' ' + vector.y + ' ' + vector.z + '\n';
} else {
vector.copy( vertices[ vertexIndex ] ); //.applyMatrix4( matrixWorld );
// see https://github.com/mrdoob/three.js/issues/3187
boneIndices = [];
boneIndices[0] = mesh.geometry.skinIndices[vertexIndex].x;
boneIndices[1] = mesh.geometry.skinIndices[vertexIndex].y;
boneIndices[2] = mesh.geometry.skinIndices[vertexIndex].z;
boneIndices[3] = mesh.geometry.skinIndices[vertexIndex].w;
weights = [];
weights[0] = mesh.geometry.skinWeights[vertexIndex].x;
weights[1] = mesh.geometry.skinWeights[vertexIndex].y;
weights[2] = mesh.geometry.skinWeights[vertexIndex].z;
weights[3] = mesh.geometry.skinWeights[vertexIndex].w;
inverses = [];
inverses[0] = mesh.skeleton.boneInverses[ boneIndices[0] ];
inverses[1] = mesh.skeleton.boneInverses[ boneIndices[1] ];
inverses[2] = mesh.skeleton.boneInverses[ boneIndices[2] ];
inverses[3] = mesh.skeleton.boneInverses[ boneIndices[3] ];
skinMatrices = [];
skinMatrices[0] = mesh.skeleton.bones[ boneIndices[0] ].matrixWorld;
skinMatrices[1] = mesh.skeleton.bones[ boneIndices[1] ].matrixWorld;
skinMatrices[2] = mesh.skeleton.bones[ boneIndices[2] ].matrixWorld;
skinMatrices[3] = mesh.skeleton.bones[ boneIndices[3] ].matrixWorld;
var finalVector = new THREE.Vector4();
for(var k = 0; k<4; k++) {
var tempVector = new THREE.Vector4(vector.x, vector.y, vector.z);
tempVector.multiplyScalar(weights[k]);
//the inverse takes the vector into local bone space
tempVector.applyMatrix4(inverses[k])
//which is then transformed to the appropriate world space
.applyMatrix4(skinMatrices[k]);
finalVector.add(tempVector);
}
output += '\t\t\tvertex ' + finalVector.x + ' ' + finalVector.y + ' ' + finalVector.z + '\n';
}
}
output += '\t\tendloop\n';
output += '\tendfacet\n';
}
}
}
} );
output += 'endsolid exported\n';
return output;
};
}() )
};
// Use FileSaver.js 'saveAs' function to save the string
function saveSTL( scene, name ){
var exporter = new THREE.STLExporter();
var stlString = exporter.parse( scene );
var blob = new Blob([stlString], {type: 'text/plain'});
saveAs(blob, name + '.stl');
}
@jcarletto27
Copy link

Kevin, thanks for this! Any chance you found a way to apply morphs in this fashion as well? I'm pulling my hair out trying to adapt your code.

@jcarletto27
Copy link

Hi Kevin, I finally updated your code to include morphTarget data. you can find it here for your reference.
https://gist.github.com/jcarletto27/e271bbb7639c4bed2427

@atnartur
Copy link

atnartur commented Aug 3, 2016

Hi! I updated your code. I include support of BufferGeometry and support of AMD, common.js and ES6 modules. Also I published npm package and added you to contributors in package.json. https://github.com/atnartur/three-STLexporter

@jloffredo
Copy link

Hi Kevin!, thanks for this script. Could you possibly update for r83? I can't make it work. atnartur's works but the model is not correctly exported. looses posture and such (humanoid model in my case).

Thanks!

@dav-m85
Copy link

dav-m85 commented Jan 6, 2017

Nice gist, would be a fine addition to @joostn work on OpenJSCAD https://github.com/joostn/OpenJsCad/blob/gh-pages/src/formats.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment