split.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <html>
  2. <title>Split STL mesh</title>
  3. <body>
  4. <p>This is a simple piece of javascript (licensed under the MIT license) by
  5. <a href="http://www.thingiverse.com/arpruss/">Alexander Pruss</a> that splits an STL mesh file that contains multiple parts into
  6. those multiple parts.</p>
  7. <p>This may well fail if the mesh is defective and has points that are meant to be coincident
  8. but are merely close together.</p>
  9. <p>All the processing is done in your browser--your STL is not uploaded to any server.</p>
  10. <p><b>Warning:</b> If an object has a cavity surrounded by material on all sides, you will get one mesh for the outer surface
  11. and an inside-out mesh for the cavity. Solving this problem would require significant coding.</p>
  12. <input type="file" id="file" name="file" />
  13. <ul id="console">
  14. </ul>
  15. <p id="progress">
  16. </p>
  17. <script>
  18. var TRIANGLE_SIZE = (3+3*3)*4+2;
  19. var ASCII_MODE = true;
  20. var allSplitMeshes = [];
  21. var baseFilaname = "";
  22. function getString(view, position, length) {
  23. var out = "";
  24. for (var i=0; i<length; i++) {
  25. var b = view.getUint8(position + i);
  26. out += String.fromCharCode(b);
  27. }
  28. return out;
  29. }
  30. // For hashing during splitting, ASCII mode is used, where vectors are stored
  31. // as strings. From a binary STL, the vectors are stored as hex strings, and
  32. // from an ASCII STL, they are stored as directly extracted ASCII.
  33. function getVector(view, position) {
  34. if (ASCII_MODE) {
  35. function fixZero(a) {
  36. return a == 0x80000000 ? 0 : a;
  37. }
  38. x = fixZero(view.getUint32(position, true));
  39. y = fixZero(view.getUint32(position+4, true));
  40. z = fixZero(view.getUint32(position+8, true));
  41. return x.toString(16)+":"+y.toString(16)+":"+z.toString(16);
  42. }
  43. x = view.getFloat32(position, true);
  44. y = view.getFloat32(position+4, true);
  45. z = view.getFloat32(position+8, true);
  46. return [x,y,z]; // x.toString()+","+y.toString()+","+z.toString(); //[x,y,z];
  47. }
  48. function parseVector(vector) {
  49. if (typeof vector === "string") {
  50. var data = vector.split(":");
  51. var buf = new ArrayBuffer(4);
  52. var view = new DataView(buf);
  53. function parse(s) {
  54. view.setUint32(0, parseInt(s,16));
  55. return view.getFloat32(0);
  56. }
  57. return [parse(data[0]),parse(data[1]),parse(data[2])];
  58. }
  59. else {
  60. return vector;
  61. }
  62. }
  63. function setVector(view, position, vector) {
  64. if (typeof vector === "string") {
  65. var data = vector.split(":");
  66. view.setUint32(position, parseInt(data[0],16), true);
  67. view.setUint32(position+4, parseInt(data[1],16), true);
  68. view.setUint32(position+8, parseInt(data[2],16), true);
  69. }
  70. else {
  71. view.setFloat32(position, vector[0], true);
  72. view.setFloat32(position+4, vector[1], true);
  73. view.setFloat32(position+8, vector[2], true);
  74. }
  75. }
  76. function getVectorFromText(line, position) {
  77. var data = line.substr(position).split(/[\s,]+/);
  78. if (data.length < 3)
  79. throw 'Invalid vector';
  80. if (ASCII_MODE) {
  81. var buf = new ArrayBuffer(4);
  82. var view = new DataView(buf);
  83. function toHex32(number) {
  84. view.setFloat32(0, parseFloat(number));
  85. return view.getUint32(0).toString(16);
  86. }
  87. return toHex32(data[0])+":"+toHex32(data[1])+":"+toHex32(data[2]);
  88. }
  89. return [parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])];
  90. }
  91. function message(text) {
  92. document.getElementById('console').innerHTML += '<li>'+text+'</li>';
  93. }
  94. function getASCIISTL(text) {
  95. var triangles = [];
  96. var triangle = [];
  97. var normal = [0,0,0];
  98. var lines = text.split(/[\r\n]+/);
  99. message(lines.length+" lines of data");
  100. for (var i = 0 ; i < lines.length ; i++ ) {
  101. l = lines[i].trim().toLowerCase();
  102. if (l == 'endfacet') {
  103. if (triangle.length != 3)
  104. throw 'invalid triangle';
  105. triangles.push([triangle[0],triangle[1],triangle[2],normal]);
  106. triangle = [];
  107. normal = [0,0,0];
  108. }
  109. else if (l.startsWith('facet')) {
  110. if (l.length > 6) {
  111. if (l.substr(6).startsWith('normal'))
  112. normal = getVectorFromText(l, 13);
  113. }
  114. }
  115. else if (l.startsWith('vertex')) {
  116. if (l.length > 7)
  117. triangle.push(getVectorFromText(l, 7));
  118. }
  119. }
  120. message(String(triangles.length) + " triangles");
  121. return triangles;
  122. }
  123. function getBinarySTL(view) {
  124. var triangles = [];
  125. var numTriangles = view.getUint32(80, true);
  126. message(String(numTriangles) + " triangles");
  127. for (var i = 0 ; i < numTriangles ; i++) {
  128. position = 84 + TRIANGLE_SIZE*i;
  129. normal = getVector(view, position);
  130. v1 = getVector(view, position+12);
  131. v2 = getVector(view, position+12*2);
  132. v3 = getVector(view, position+12*3);
  133. triangles.push( [v1,v2,v3,normal] );
  134. }
  135. return triangles;
  136. }
  137. var splitMeshIndex;
  138. var meshes;
  139. function splitMesh(triangles) {
  140. meshes = [];
  141. splitMeshIndex = 0;
  142. function process() {
  143. var i = splitMeshIndex;
  144. var t0 = Date.now();
  145. document.getElementById('progress').innerHTML = "Splitting "+(i/triangles.length*100).toFixed(1)+'% done ('+(meshes.length)+' parts found)';
  146. for (; i<triangles.length; i++) {
  147. var t = triangles[i];
  148. var matches = [];
  149. for (var j = 0 ; j < 3 ; j++) {
  150. for (var k = 0 ; k < meshes.length; k++) {
  151. if (matches.indexOf(k) == -1 && t[j] in meshes[k].points) {
  152. matches.push(k);
  153. }
  154. }
  155. }
  156. matches.sort((x,y)=>(x<y ? -1 : (x>y ? 1 : 0)));
  157. var m;
  158. if (matches.length == 0) {
  159. m = {points:{}, triangles:[]};
  160. meshes.push(m);
  161. }
  162. else {
  163. m = meshes[matches[0]];
  164. for (var j = matches.length - 1 ; j >= 1 ; j--) {
  165. mm = meshes[matches[j]];
  166. console.log(mm);
  167. for (var key in mm.points) {
  168. if (mm.points.hasOwnProperty(key))
  169. m.points[key] = true;
  170. }
  171. for (var k = 0 ; k < mm.triangles.length; k++) {
  172. m.triangles.push(mm.triangles[k]);
  173. }
  174. meshes.splice(matches[j], 1);
  175. }
  176. }
  177. for (var k = 0 ; k < 3 ; k++) {
  178. m.points[t[k]] = true;
  179. }
  180. m.triangles.push(t);
  181. if (Date.now() >= t0 + 500) {
  182. setTimeout(process, 0);
  183. splitMeshIndex = i+1;
  184. return;
  185. }
  186. }
  187. for (var i = 0 ; i < meshes.length ; i++) {
  188. var bounds = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY,
  189. Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY ];
  190. for (var key in meshes[i].points) {
  191. if (meshes[i].points.hasOwnProperty(key)) {
  192. var v = parseVector(key);
  193. for (var k=0; k<3; k++) {
  194. bounds[k] = Math.min(bounds[k], v[k]);
  195. bounds[3+k] = Math.max(bounds[3+k], v[k]);
  196. }
  197. }
  198. }
  199. meshes[i].bounds = bounds;
  200. delete meshes[i].points;
  201. }
  202. function compareByBounds(m,mm) {
  203. for (var i=0; i<6; i++) {
  204. if (m.bounds[i] < mm.bounds[i])
  205. return -1;
  206. else if (mm.bounds[i] < m.bounds[i])
  207. return 1;
  208. }
  209. return 0;
  210. }
  211. meshes.sort(compareByBounds);
  212. if (meshes.length == 1) {
  213. message("No splitting done: Only one mesh in file.");
  214. }
  215. else if (meshes.length == 0) {
  216. message("No mesh found in file.");
  217. }
  218. else {
  219. message(String(meshes.length)+" meshes extracted");
  220. allSplitMeshes = [];
  221. for (var i=0; i<meshes.length; i++) {
  222. allSplitMeshes.push(meshes[i].triangles);
  223. message("<a href='#' onclick='downloadMesh("+i+");'>Download mesh part "+(i+1)+"</a> "+describeBounds(meshes[i].bounds));
  224. }
  225. }
  226. document.getElementById('progress').innerHTML = '';
  227. document.getElementById('file').disabled = false;
  228. }
  229. process();
  230. }
  231. function downloadBlob(name,blob) {
  232. var link = document.createElement('a');
  233. document.body.appendChild(link);
  234. link.download = name;
  235. link.href = window.URL.createObjectURL(blob);
  236. link.onclick = function(e) {
  237. setTimeout(function() {
  238. window.URL.revokeObjectURL(link.href);
  239. }, 1600);
  240. };
  241. link.click();
  242. try {
  243. link.remove();
  244. }
  245. catch(err) {}
  246. try {
  247. document.body.removeChild(link);
  248. }
  249. catch(err) {}
  250. }
  251. function makeMeshByteArray(triangles) {
  252. data = new ArrayBuffer(84 + triangles.length * TRIANGLE_SIZE);
  253. view = new DataView(data);
  254. view.setUint32(80, triangles.length, true);
  255. for (var i=0; i<triangles.length; i++) {
  256. var offset = 84 + i*TRIANGLE_SIZE;
  257. setVector(view, offset, triangles[i][3]); // normal
  258. setVector(view, offset+12, triangles[i][0]); // v1
  259. setVector(view, offset+12*2, triangles[i][1]); // v2
  260. setVector(view, offset+12*3, triangles[i][2]); // v3
  261. }
  262. return view.buffer;
  263. }
  264. function downloadMesh(i) {
  265. downloadBlob(baseFilename+"-"+(i+1)+".stl", new Blob([makeMeshByteArray(allSplitMeshes[i])], {type: "application/octet-stream"}));
  266. }
  267. function describeBounds(bounds) {
  268. return "("+bounds[0].toFixed(2)+", "+bounds[1].toFixed(2)+", "+bounds[2].toFixed(2)+") - ("+
  269. bounds[3].toFixed(2)+", "+bounds[4].toFixed(2)+", "+bounds[5].toFixed(2)+")";
  270. }
  271. function processSTL(data) {
  272. length = data.byteLength;
  273. view = new DataView(data);
  274. var header = getString(view, 0, 5);
  275. var binary = true;
  276. var text;
  277. if (header == "solid") {
  278. // probably ASCII
  279. text = getString(view, 0, length);
  280. if (text.includes("endfacet")) {
  281. binary = false;
  282. }
  283. }
  284. message(binary ? "binary STL" : "ASCII STL");
  285. triangles = binary ? getBinarySTL(view) : getASCIISTL(text);
  286. message("data successfully read");
  287. splitMesh(triangles);
  288. }
  289. function handleFileSelect(evt) {
  290. var e = document.getElementById('file');
  291. e.disabled = true;
  292. document.getElementById('console').innerHTML = '';
  293. var f = evt.target.files[0];
  294. message( "reading "+ String(f.size) + ' bytes');
  295. var n = f.name.split(/[/\\]+/);
  296. baseFilename = f.name.replace(/.*[/\\]/, "").replace(/\.[sS][tT][lL]$/, "");
  297. var reader = new FileReader();
  298. reader.onload = function(event) {
  299. try {
  300. processSTL(event.target.result);
  301. }
  302. catch(err) {
  303. message( "Error: "+err);
  304. var e = document.getElementById('file');
  305. e.disabled = false;
  306. }
  307. }
  308. reader.readAsArrayBuffer(f);
  309. }
  310. document.getElementById('file').addEventListener('change', handleFileSelect, false);
  311. </script>
  312. </body>
  313. </html>