STLLoader.js 9.6 KB

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