STLLoader.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /**
  2. * @author aleeper / http://adamleeper.com/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author gero3 / https://github.com/gero3
  5. *
  6. * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
  7. *
  8. * Supports both binary and ASCII encoded files, with automatic detection of type.
  9. *
  10. * Limitations: Binary decoding ignores header. There doesn't seem to be much of a use for it.
  11. * There is perhaps some question as to how valid it is to always assume little-endian-ness.
  12. * ASCII decoding assumes file is UTF-8. Seems to work for the examples...
  13. *
  14. * Usage:
  15. * var loader = new THREE.STLLoader();
  16. * loader.addEventListener( 'load', function ( event ) {
  17. *
  18. * var geometry = event.content;
  19. * scene.add( new THREE.Mesh( geometry ) );
  20. *
  21. * } );
  22. * loader.load( './models/stl/slotted_disk.stl' );
  23. */
  24. THREE.STLLoader = function () {};
  25. THREE.STLLoader.prototype = {
  26. constructor: THREE.STLLoader,
  27. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  28. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  29. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  30. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
  31. };
  32. THREE.STLLoader.prototype.load = function (url) {
  33. var scope = this;
  34. console.log("Attempting to load URL: [" + url + "]");
  35. var xhr = new XMLHttpRequest();
  36. function onloaded( event ) {
  37. if ( event.target.status === 200 || event.target.status === 0 ) {
  38. var data = event.target.responseText;
  39. return scope.dispatchEvent({
  40. type: 'load',
  41. content: scope.parse(data)
  42. });
  43. } else {
  44. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']',
  45. response: event.target.responseText } );
  46. }
  47. }
  48. xhr.addEventListener( 'load', onloaded, false );
  49. xhr.addEventListener( 'progress', function ( event ) {
  50. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  51. }, false );
  52. xhr.addEventListener( 'error', function () {
  53. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  54. }, false );
  55. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  56. xhr.open( 'GET', url, true );
  57. xhr.send( null );
  58. };
  59. THREE.STLLoader.prototype.parse = function (data) {
  60. var isBinary = function (data) {
  61. var expect, face_size, n_faces, reader;
  62. reader = new THREE.STLLoader.BinaryReader(data);
  63. reader.seek(80);
  64. face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  65. n_faces = reader.readUInt32();
  66. expect = 80 + (32 / 8) + (n_faces * face_size);
  67. return expect === reader.getSize();
  68. };
  69. if (isBinary(data)) {
  70. return this.parseBinary(data);
  71. } else {
  72. return this.parseASCII(data);
  73. }
  74. };
  75. THREE.STLLoader.prototype.parseBinary = function (data) {
  76. var face, geometry, n_faces, reader, length, normal, i;
  77. reader = new THREE.STLLoader.BinaryReader(data);
  78. reader.seek(80);
  79. n_faces = reader.readUInt32();
  80. geometry = new THREE.Geometry();
  81. for (face = 0; face < n_faces; face++) {
  82. normal = new THREE.Vector3(reader.readFloat(),reader.readFloat(),reader.readFloat());
  83. for (i = 1; i <= 3; i++) {
  84. geometry.vertices.push(new THREE.Vector3(reader.readFloat(),reader.readFloat(),reader.readFloat()));
  85. }
  86. reader.readUInt16(); // attr doesn't get used yet.
  87. length = geometry.vertices.length;
  88. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  89. }
  90. geometry.computeCentroids();
  91. geometry.computeBoundingBox();
  92. geometry.computeBoundingSphere();
  93. return geometry;
  94. };
  95. THREE.STLLoader.prototype.parseASCII = function (data) {
  96. var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
  97. geometry = new THREE.Geometry();
  98. patternFace = /facet([\s\S]*?)endfacet/g;
  99. while (((result = patternFace.exec(data)) != null)) {
  100. text = result[0];
  101. patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  102. while (((result = patternNormal.exec(text)) != null)) {
  103. normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
  104. }
  105. patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  106. while (((result = patternVertex.exec(text)) != null)) {
  107. geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
  108. }
  109. length = geometry.vertices.length;
  110. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  111. }
  112. geometry.computeCentroids();
  113. geometry.computeBoundingBox();
  114. geometry.computeBoundingSphere();
  115. return geometry;
  116. };
  117. THREE.STLLoader.BinaryReader = function (data) {
  118. this._buffer = data;
  119. this._pos = 0;
  120. };
  121. THREE.STLLoader.BinaryReader.prototype = {
  122. /* Public */
  123. readInt8: function (){ return this._decodeInt(8, true); },
  124. readUInt8: function (){ return this._decodeInt(8, false); },
  125. readInt16: function (){ return this._decodeInt(16, true); },
  126. readUInt16: function (){ return this._decodeInt(16, false); },
  127. readInt32: function (){ return this._decodeInt(32, true); },
  128. readUInt32: function (){ return this._decodeInt(32, false); },
  129. readFloat: function (){ return this._decodeFloat(23, 8); },
  130. readDouble: function (){ return this._decodeFloat(52, 11); },
  131. readChar: function () { return this.readString(1); },
  132. readString: function (length) {
  133. this._checkSize(length * 8);
  134. var result = this._buffer.substr(this._pos, length);
  135. this._pos += length;
  136. return result;
  137. },
  138. seek: function (pos) {
  139. this._pos = pos;
  140. this._checkSize(0);
  141. },
  142. getPosition: function () {
  143. return this._pos;
  144. },
  145. getSize: function () {
  146. return this._buffer.length;
  147. },
  148. /* Private */
  149. _decodeFloat: function(precisionBits, exponentBits){
  150. var length = precisionBits + exponentBits + 1;
  151. var size = length >> 3;
  152. this._checkSize(length);
  153. var bias = Math.pow(2, exponentBits - 1) - 1;
  154. var signal = this._readBits(precisionBits + exponentBits, 1, size);
  155. var exponent = this._readBits(precisionBits, exponentBits, size);
  156. var significand = 0;
  157. var divisor = 2;
  158. // var curByte = length + (-precisionBits >> 3) - 1;
  159. var curByte = 0;
  160. do {
  161. var byteValue = this._readByte(++curByte, size);
  162. var startBit = precisionBits % 8 || 8;
  163. var mask = 1 << startBit;
  164. while (mask >>= 1) {
  165. if (byteValue & mask) {
  166. significand += 1 / divisor;
  167. }
  168. divisor *= 2;
  169. }
  170. } while (precisionBits -= startBit);
  171. this._pos += size;
  172. return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
  173. : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
  174. : Math.pow(2, exponent - bias) * (1 + significand) : 0);
  175. },
  176. _decodeInt: function(bits, signed){
  177. var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
  178. var result = signed && x >= max / 2 ? x - max : x;
  179. this._pos += bits / 8;
  180. return result;
  181. },
  182. //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
  183. _shl: function (a, b){
  184. for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
  185. return a;
  186. },
  187. _readByte: function (i, size) {
  188. return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff;
  189. },
  190. _readBits: function (start, length, size) {
  191. var offsetLeft = (start + length) % 8;
  192. var offsetRight = start % 8;
  193. var curByte = size - (start >> 3) - 1;
  194. var lastByte = size + (-(start + length) >> 3);
  195. var diff = curByte - lastByte;
  196. var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
  197. if (diff && offsetLeft) {
  198. sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
  199. }
  200. while (diff) {
  201. sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight);
  202. }
  203. return sum;
  204. },
  205. _checkSize: function (neededBits) {
  206. if (!(this._pos + Math.ceil(neededBits / 8) < this._buffer.length)) {
  207. throw new Error("Index out of bound");
  208. }
  209. }
  210. };