STLLoader.js 8.6 KB

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