STLLoader.js 9.6 KB

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