STLLoader.js 10.0 KB

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