STLLoader.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /**
  2. * @author aleeper / http://adamleeper.com/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author gero3 / https://github.com/gero3
  5. * @author Mugen87 / https://github.com/Mugen87
  6. *
  7. * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
  8. *
  9. * Supports both binary and ASCII encoded files, with automatic detection of type.
  10. *
  11. * The loader returns a non-indexed buffer geometry.
  12. *
  13. * Limitations:
  14. * Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
  15. * There is perhaps some question as to how valid it is to always assume little-endian-ness.
  16. * ASCII decoding assumes file is UTF-8.
  17. *
  18. * Usage:
  19. * var loader = new THREE.STLLoader();
  20. * loader.load( './models/stl/slotted_disk.stl', function ( geometry ) {
  21. * scene.add( new THREE.Mesh( geometry ) );
  22. * });
  23. *
  24. * For binary STLs geometry might contain colors for vertices. To use it:
  25. * // use the same code to load STL as above
  26. * if (geometry.hasColors) {
  27. * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
  28. * } else { .... }
  29. * var mesh = new THREE.Mesh( geometry, material );
  30. */
  31. THREE.STLLoader = function ( manager ) {
  32. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33. };
  34. THREE.STLLoader.prototype = {
  35. constructor: THREE.STLLoader,
  36. load: function ( url, onLoad, onProgress, onError ) {
  37. var scope = this;
  38. var loader = new THREE.FileLoader( scope.manager );
  39. loader.setPath( scope.path );
  40. loader.setResponseType( 'arraybuffer' );
  41. loader.load( url, function ( text ) {
  42. try {
  43. onLoad( scope.parse( text ) );
  44. } catch ( exception ) {
  45. if ( onError ) {
  46. onError( exception );
  47. }
  48. }
  49. }, onProgress, onError );
  50. },
  51. setPath: function ( value ) {
  52. this.path = value;
  53. return this;
  54. },
  55. parse: function ( data ) {
  56. function isBinary( data ) {
  57. var expect, face_size, n_faces, reader;
  58. reader = new DataView( data );
  59. face_size = ( 32 / 8 * 3 ) + ( ( 32 / 8 * 3 ) * 3 ) + ( 16 / 8 );
  60. n_faces = reader.getUint32( 80, true );
  61. expect = 80 + ( 32 / 8 ) + ( n_faces * face_size );
  62. if ( expect === reader.byteLength ) {
  63. return true;
  64. }
  65. // An ASCII STL data must begin with 'solid ' as the first six bytes.
  66. // However, ASCII STLs lacking the SPACE after the 'd' are known to be
  67. // plentiful. So, check the first 5 bytes for 'solid'.
  68. // Several encodings, such as UTF-8, precede the text with up to 5 bytes:
  69. // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
  70. // Search for "solid" to start anywhere after those prefixes.
  71. // US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd'
  72. var solid = [ 115, 111, 108, 105, 100 ];
  73. for ( var off = 0; off < 5; off ++ ) {
  74. // If "solid" text is matched to the current offset, declare it to be an ASCII STL.
  75. if ( matchDataViewAt ( solid, reader, off ) ) return false;
  76. }
  77. // Couldn't find "solid" text at the beginning; it is binary STL.
  78. return true;
  79. }
  80. function matchDataViewAt( query, reader, offset ) {
  81. // Check if each byte in query matches the corresponding byte from the current offset
  82. for ( var i = 0, il = query.length; i < il; i ++ ) {
  83. if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
  84. }
  85. return true;
  86. }
  87. function parseBinary( data ) {
  88. var reader = new DataView( data );
  89. var faces = reader.getUint32( 80, true );
  90. var r, g, b, hasColors = false, colors;
  91. var defaultR, defaultG, defaultB, alpha;
  92. // process STL header
  93. // check for default color in header ("COLOR=rgba" sequence).
  94. for ( var index = 0; index < 80 - 10; index ++ ) {
  95. if ( ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ ) &&
  96. ( reader.getUint8( index + 4 ) == 0x52 /*'R'*/ ) &&
  97. ( reader.getUint8( index + 5 ) == 0x3D /*'='*/ ) ) {
  98. hasColors = true;
  99. colors = [];
  100. defaultR = reader.getUint8( index + 6 ) / 255;
  101. defaultG = reader.getUint8( index + 7 ) / 255;
  102. defaultB = reader.getUint8( index + 8 ) / 255;
  103. alpha = reader.getUint8( index + 9 ) / 255;
  104. }
  105. }
  106. var dataOffset = 84;
  107. var faceLength = 12 * 4 + 2;
  108. var geometry = new THREE.BufferGeometry();
  109. var vertices = [];
  110. var normals = [];
  111. for ( var face = 0; face < faces; face ++ ) {
  112. var start = dataOffset + face * faceLength;
  113. var normalX = reader.getFloat32( start, true );
  114. var normalY = reader.getFloat32( start + 4, true );
  115. var normalZ = reader.getFloat32( start + 8, true );
  116. if ( hasColors ) {
  117. var packedColor = reader.getUint16( start + 48, true );
  118. if ( ( packedColor & 0x8000 ) === 0 ) {
  119. // facet has its own unique color
  120. r = ( packedColor & 0x1F ) / 31;
  121. g = ( ( packedColor >> 5 ) & 0x1F ) / 31;
  122. b = ( ( packedColor >> 10 ) & 0x1F ) / 31;
  123. } else {
  124. r = defaultR;
  125. g = defaultG;
  126. b = defaultB;
  127. }
  128. }
  129. for ( var i = 1; i <= 3; i ++ ) {
  130. var vertexstart = start + i * 12;
  131. vertices.push( reader.getFloat32( vertexstart, true ) );
  132. vertices.push( reader.getFloat32( vertexstart + 4, true ) );
  133. vertices.push( reader.getFloat32( vertexstart + 8, true ) );
  134. normals.push( normalX, normalY, normalZ );
  135. if ( hasColors ) {
  136. colors.push( r, g, b );
  137. }
  138. }
  139. }
  140. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
  141. geometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );
  142. if ( hasColors ) {
  143. geometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( colors ), 3 ) );
  144. geometry.hasColors = true;
  145. geometry.alpha = alpha;
  146. }
  147. return geometry;
  148. }
  149. function parseASCII( data ) {
  150. var geometry = new THREE.BufferGeometry();
  151. var patternFace = /facet([\s\S]*?)endfacet/g;
  152. var faceCounter = 0;
  153. var patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
  154. var patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' );
  155. var patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' );
  156. var vertices = [];
  157. var normals = [];
  158. var normal = new THREE.Vector3();
  159. var result;
  160. while ( ( result = patternFace.exec( data ) ) !== null ) {
  161. var vertexCountPerFace = 0;
  162. var normalCountPerFace = 0;
  163. var text = result[ 0 ];
  164. while ( ( result = patternNormal.exec( text ) ) !== null ) {
  165. normal.x = parseFloat( result[ 1 ] );
  166. normal.y = parseFloat( result[ 2 ] );
  167. normal.z = parseFloat( result[ 3 ] );
  168. normalCountPerFace ++;
  169. }
  170. while ( ( result = patternVertex.exec( text ) ) !== null ) {
  171. vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
  172. normals.push( normal.x, normal.y, normal.z );
  173. vertexCountPerFace ++;
  174. }
  175. // every face have to own ONE valid normal
  176. if ( normalCountPerFace !== 1 ) {
  177. console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
  178. }
  179. // each face have to own THREE valid vertices
  180. if ( vertexCountPerFace !== 3 ) {
  181. console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
  182. }
  183. faceCounter ++;
  184. }
  185. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  186. geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  187. return geometry;
  188. }
  189. function ensureString( buffer ) {
  190. if ( typeof buffer !== 'string' ) {
  191. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer ) );
  192. }
  193. return buffer;
  194. }
  195. function ensureBinary( buffer ) {
  196. if ( typeof buffer === 'string' ) {
  197. var array_buffer = new Uint8Array( buffer.length );
  198. for ( var i = 0; i < buffer.length; i ++ ) {
  199. array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
  200. }
  201. return array_buffer.buffer || array_buffer;
  202. } else {
  203. return buffer;
  204. }
  205. }
  206. // start
  207. var binData = ensureBinary( data );
  208. return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
  209. }
  210. };