STLExporter.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @author kovacsv / http://kovacsv.hu/
  3. */
  4. THREE.STLExporter = function () {
  5. this.stlContent = '';
  6. };
  7. THREE.STLExporter.prototype = {
  8. constructor: THREE.STLExporter,
  9. parse : function (scene) {
  10. return this.exportScene (scene);
  11. },
  12. exportScene : function (scene) {
  13. var meshes = [];
  14. var current;
  15. scene.traverse (function (current) {
  16. if (current instanceof THREE.Mesh) {
  17. meshes.push (current);
  18. }
  19. });
  20. return this.exportMeshes (meshes);
  21. },
  22. exportMesh : function (mesh) {
  23. return this.exportMeshes ([mesh]);
  24. },
  25. exportMeshes : function (meshes) {
  26. this.addLineToContent ('solid exported');
  27. var i, j, mesh, geometry, face, matrix, position;
  28. var normal, vertex1, vertex2, vertex3;
  29. for (i = 0; i < meshes.length; i++) {
  30. mesh = meshes[i];
  31. geometry = mesh.geometry;
  32. matrix = mesh.matrixWorld;
  33. position = mesh.position;
  34. for (j = 0; j < geometry.faces.length; j++) {
  35. face = geometry.faces[j];
  36. normal = face.normal;
  37. vertex1 = this.getTransformedPosition (geometry.vertices[face.a], matrix, position);
  38. vertex2 = this.getTransformedPosition (geometry.vertices[face.b], matrix, position);
  39. vertex3 = this.getTransformedPosition (geometry.vertices[face.c], matrix, position);
  40. this.addTriangleToContent (normal, vertex1, vertex2, vertex3);
  41. }
  42. };
  43. this.addLineToContent ('endsolid exported');
  44. return this.stlContent;
  45. },
  46. clearContent : function ()
  47. {
  48. this.stlContent = '';
  49. },
  50. addLineToContent : function (line) {
  51. this.stlContent += line + '\n';
  52. },
  53. addTriangleToContent : function (normal, vertex1, vertex2, vertex3) {
  54. this.addLineToContent ('\tfacet normal ' + normal.x + ' ' + normal.y + ' ' + normal.z);
  55. this.addLineToContent ('\t\touter loop');
  56. this.addLineToContent ('\t\t\tvertex ' + vertex1.x + ' ' + vertex1.y + ' ' + vertex1.z);
  57. this.addLineToContent ('\t\t\tvertex ' + vertex2.x + ' ' + vertex2.y + ' ' + vertex2.z);
  58. this.addLineToContent ('\t\t\tvertex ' + vertex3.x + ' ' + vertex3.y + ' ' + vertex3.z);
  59. this.addLineToContent ('\t\tendloop');
  60. this.addLineToContent ('\tendfacet');
  61. },
  62. getTransformedPosition : function (vertex, matrix, position) {
  63. var result = vertex.clone ();
  64. if (matrix !== undefined) {
  65. result.applyMatrix4 (matrix);
  66. }
  67. if (position !== undefined) {
  68. result.add (position);
  69. }
  70. return result;
  71. }
  72. };