The website of the KaosCube
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

389 lines
11 KiB

  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:
  11. * Binary decoding ignores header. There doesn't seem to be much of a use for it.
  12. * There is perhaps some question as to how valid it is to always assume little-endian-ness.
  13. * ASCII decoding assumes file is UTF-8. Seems to work for the examples...
  14. *
  15. * Usage:
  16. * var loader = new THREE.STLLoader();
  17. * loader.addEventListener( 'load', function ( event ) {
  18. *
  19. * var geometry = event.content;
  20. * scene.add( new THREE.Mesh( geometry ) );
  21. *
  22. * } );
  23. * loader.load( './models/stl/slotted_disk.stl' );
  24. */
  25. THREE.STLLoader = function () {};
  26. THREE.STLLoader.prototype = {
  27. constructor: THREE.STLLoader,
  28. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  29. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  30. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  31. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
  32. };
  33. THREE.STLLoader.prototype.load = function (url, callback) {
  34. var scope = this;
  35. var xhr = new XMLHttpRequest();
  36. function onloaded( event ) {
  37. if ( event.target.status === 200 || event.target.status === 0 ) {
  38. var geometry = scope.parse( event.target.response || event.target.responseText );
  39. scope.dispatchEvent( { type: 'load', content: geometry } );
  40. if ( callback ) callback( geometry );
  41. } else {
  42. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']',
  43. response: event.target.responseText } );
  44. }
  45. }
  46. xhr.addEventListener( 'load', onloaded, false );
  47. xhr.addEventListener( 'progress', function ( event ) {
  48. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  49. }, false );
  50. xhr.addEventListener( 'error', function () {
  51. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  52. }, false );
  53. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  54. xhr.open( 'GET', url, true );
  55. xhr.responseType = "arraybuffer";
  56. xhr.send( null );
  57. };
  58. THREE.STLLoader.prototype.parse = function (data) {
  59. var isBinary = function () {
  60. var expect, face_size, n_faces, reader;
  61. reader = new DataView( binData );
  62. face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  63. n_faces = reader.getUint32(80,true);
  64. expect = 80 + (32 / 8) + (n_faces * face_size);
  65. return expect === reader.byteLength;
  66. };
  67. var binData = this.ensureBinary( data );
  68. return isBinary()
  69. ? this.parseBinary( binData )
  70. : this.parseASCII( this.ensureString( data ) );
  71. };
  72. THREE.STLLoader.prototype.parseBinary = function (data) {
  73. var face, geometry, n_faces, reader, length, normal, i, dataOffset, faceLength, start, vertexstart;
  74. reader = new DataView( data );
  75. n_faces = reader.getUint32(80,true);
  76. geometry = new THREE.Geometry();
  77. dataOffset = 84;
  78. faceLength = 12 * 4 + 2;
  79. for (face = 0; face < n_faces; face++) {
  80. start = dataOffset + face * faceLength;
  81. normal = new THREE.Vector3(
  82. reader.getFloat32(start,true),
  83. reader.getFloat32(start + 4,true),
  84. reader.getFloat32(start + 8,true)
  85. );
  86. for (i = 1; i <= 3; i++) {
  87. vertexstart = start + i * 12;
  88. geometry.vertices.push(
  89. new THREE.Vector3(
  90. reader.getFloat32(vertexstart,true),
  91. reader.getFloat32(vertexstart +4,true),
  92. reader.getFloat32(vertexstart + 8,true)
  93. )
  94. );
  95. }
  96. length = geometry.vertices.length;
  97. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  98. }
  99. //geometry.computeCentroids();
  100. geometry.computeBoundingSphere();
  101. return geometry;
  102. };
  103. THREE.STLLoader.prototype.parseASCII = function (data) {
  104. var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
  105. geometry = new THREE.Geometry();
  106. patternFace = /facet([\s\S]*?)endfacet/g;
  107. while (((result = patternFace.exec(data)) != null)) {
  108. text = result[0];
  109. 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;
  110. while (((result = patternNormal.exec(text)) != null)) {
  111. normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
  112. }
  113. 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;
  114. while (((result = patternVertex.exec(text)) != null)) {
  115. geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
  116. }
  117. length = geometry.vertices.length;
  118. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  119. }
  120. geometry.computeCentroids();
  121. geometry.computeBoundingBox();
  122. geometry.computeBoundingSphere();
  123. return geometry;
  124. };
  125. THREE.STLLoader.prototype.ensureString = function (buf) {
  126. if (typeof buf !== "string"){
  127. var array_buffer = new Uint8Array(buf);
  128. var str = '';
  129. for(var i = 0; i < buf.byteLength; i++) {
  130. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  131. }
  132. return str;
  133. } else {
  134. return buf;
  135. }
  136. };
  137. THREE.STLLoader.prototype.ensureBinary = function (buf) {
  138. if (typeof buf === "string"){
  139. var array_buffer = new Uint8Array(buf.length);
  140. for(var i = 0; i < buf.length; i++) {
  141. array_buffer[i] = buf.charCodeAt(i) & 0xff; // implicitly assumes little-endian
  142. }
  143. return array_buffer.buffer || array_buffer;
  144. } else {
  145. return buf;
  146. }
  147. };
  148. if ( typeof DataView === 'undefined'){
  149. DataView = function(buffer, byteOffset, byteLength){
  150. this.buffer = buffer;
  151. this.byteOffset = byteOffset || 0;
  152. this.byteLength = byteLength || buffer.byteLength || buffer.length;
  153. this._isString = typeof buffer === "string";
  154. }
  155. DataView.prototype = {
  156. _getCharCodes:function(buffer,start,length){
  157. start = start || 0;
  158. length = length || buffer.length;
  159. var end = start + length;
  160. var codes = [];
  161. for (var i = start; i < end; i++) {
  162. codes.push(buffer.charCodeAt(i) & 0xff);
  163. }
  164. return codes;
  165. },
  166. _getBytes: function (length, byteOffset, littleEndian) {
  167. var result;
  168. // Handle the lack of endianness
  169. if (littleEndian === undefined) {
  170. littleEndian = this._littleEndian;
  171. }
  172. // Handle the lack of byteOffset
  173. if (byteOffset === undefined) {
  174. byteOffset = this.byteOffset;
  175. } else {
  176. byteOffset = this.byteOffset + byteOffset;
  177. }
  178. if (length === undefined) {
  179. length = this.byteLength - byteOffset;
  180. }
  181. // Error Checking
  182. if (typeof byteOffset !== 'number') {
  183. throw new TypeError('DataView byteOffset is not a number');
  184. }
  185. if (length < 0 || byteOffset + length > this.byteLength) {
  186. throw new Error('DataView length or (byteOffset+length) value is out of bounds');
  187. }
  188. if (this.isString){
  189. result = this._getCharCodes(this.buffer, byteOffset, byteOffset + length);
  190. } else {
  191. result = this.buffer.slice(byteOffset, byteOffset + length);
  192. }
  193. if (!littleEndian && length > 1) {
  194. if (!(result instanceof Array)) {
  195. result = Array.prototype.slice.call(result);
  196. }
  197. result.reverse();
  198. }
  199. return result;
  200. },
  201. // Compatibility functions on a String Buffer
  202. getFloat64: function (byteOffset, littleEndian) {
  203. var b = this._getBytes(8, byteOffset, littleEndian),
  204. sign = 1 - (2 * (b[7] >> 7)),
  205. exponent = ((((b[7] << 1) & 0xff) << 3) | (b[6] >> 4)) - ((1 << 10) - 1),
  206. // Binary operators such as | and << operate on 32 bit values, using + and Math.pow(2) instead
  207. mantissa = ((b[6] & 0x0f) * Math.pow(2, 48)) + (b[5] * Math.pow(2, 40)) + (b[4] * Math.pow(2, 32)) +
  208. (b[3] * Math.pow(2, 24)) + (b[2] * Math.pow(2, 16)) + (b[1] * Math.pow(2, 8)) + b[0];
  209. if (exponent === 1024) {
  210. if (mantissa !== 0) {
  211. return NaN;
  212. } else {
  213. return sign * Infinity;
  214. }
  215. }
  216. if (exponent === -1023) { // Denormalized
  217. return sign * mantissa * Math.pow(2, -1022 - 52);
  218. }
  219. return sign * (1 + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent);
  220. },
  221. getFloat32: function (byteOffset, littleEndian) {
  222. var b = this._getBytes(4, byteOffset, littleEndian),
  223. sign = 1 - (2 * (b[3] >> 7)),
  224. exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127,
  225. mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0];
  226. if (exponent === 128) {
  227. if (mantissa !== 0) {
  228. return NaN;
  229. } else {
  230. return sign * Infinity;
  231. }
  232. }
  233. if (exponent === -127) { // Denormalized
  234. return sign * mantissa * Math.pow(2, -126 - 23);
  235. }
  236. return sign * (1 + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent);
  237. },
  238. getInt32: function (byteOffset, littleEndian) {
  239. var b = this._getBytes(4, byteOffset, littleEndian);
  240. return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
  241. },
  242. getUint32: function (byteOffset, littleEndian) {
  243. return this.getInt32(byteOffset, littleEndian) >>> 0;
  244. },
  245. getInt16: function (byteOffset, littleEndian) {
  246. return (this.getUint16(byteOffset, littleEndian) << 16) >> 16;
  247. },
  248. getUint16: function (byteOffset, littleEndian) {
  249. var b = this._getBytes(2, byteOffset, littleEndian);
  250. return (b[1] << 8) | b[0];
  251. },
  252. getInt8: function (byteOffset) {
  253. return (this.getUint8(byteOffset) << 24) >> 24;
  254. },
  255. getUint8: function (byteOffset) {
  256. return this._getBytes(1, byteOffset)[0];
  257. }
  258. };
  259. }