STLLoader.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. }
  85. // An ASCII STL data must begin with 'solid ' as the first six bytes.
  86. // However, ASCII STLs lacking the SPACE after the 'd' are known to be
  87. // plentiful. So, check the first 5 bytes for 'solid'.
  88. // Several encodings, such as UTF-8, precede the text with up to 5 bytes:
  89. // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
  90. // Search for "solid" to start anywhere after those prefixes.
  91. // US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd'
  92. const solid = [ 115, 111, 108, 105, 100 ];
  93. for ( let off = 0; off < 5; off ++ ) {
  94. // If "solid" text is matched to the current offset, declare it to be an ASCII STL.
  95. if ( matchDataViewAt( solid, reader, off ) ) return false;
  96. }
  97. // Couldn't find "solid" text at the beginning; it is binary STL.
  98. return true;
  99. }
  100. function matchDataViewAt( query, reader, offset ) {
  101. // Check if each byte in query matches the corresponding byte from the current offset
  102. for ( let i = 0, il = query.length; i < il; i ++ ) {
  103. if ( query[ i ] !== reader.getUint8( offset + i ) ) return false;
  104. }
  105. return true;
  106. }
  107. function parseBinary( data ) {
  108. const reader = new DataView( data );
  109. const faces = reader.getUint32( 80, true );
  110. let r,
  111. g,
  112. b,
  113. hasColors = false,
  114. colors;
  115. let defaultR, defaultG, defaultB, alpha;
  116. // process STL header
  117. // check for default color in header ("COLOR=rgba" sequence).
  118. for ( let index = 0; index < 80 - 10; index ++ ) {
  119. if ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ && reader.getUint8( index + 4 ) == 0x52 /*'R'*/ && reader.getUint8( index + 5 ) == 0x3D /*'='*/ ) {
  120. hasColors = true;
  121. colors = new Float32Array( faces * 3 * 3 );
  122. defaultR = reader.getUint8( index + 6 ) / 255;
  123. defaultG = reader.getUint8( index + 7 ) / 255;
  124. defaultB = reader.getUint8( index + 8 ) / 255;
  125. alpha = reader.getUint8( index + 9 ) / 255;
  126. }
  127. }
  128. const dataOffset = 84;
  129. const faceLength = 12 * 4 + 2;
  130. const geometry = new THREE.BufferGeometry();
  131. const vertices = new Float32Array( faces * 3 * 3 );
  132. const normals = new Float32Array( faces * 3 * 3 );
  133. for ( let face = 0; face < faces; face ++ ) {
  134. const start = dataOffset + face * faceLength;
  135. const normalX = reader.getFloat32( start, true );
  136. const normalY = reader.getFloat32( start + 4, true );
  137. const normalZ = reader.getFloat32( start + 8, true );
  138. if ( hasColors ) {
  139. const packedColor = reader.getUint16( start + 48, true );
  140. if ( ( packedColor & 0x8000 ) === 0 ) {
  141. // facet has its own unique color
  142. r = ( packedColor & 0x1F ) / 31;
  143. g = ( packedColor >> 5 & 0x1F ) / 31;
  144. b = ( packedColor >> 10 & 0x1F ) / 31;
  145. } else {
  146. r = defaultR;
  147. g = defaultG;
  148. b = defaultB;
  149. }
  150. }
  151. for ( let i = 1; i <= 3; i ++ ) {
  152. const vertexstart = start + i * 12;
  153. const componentIdx = face * 3 * 3 + ( i - 1 ) * 3;
  154. vertices[ componentIdx ] = reader.getFloat32( vertexstart, true );
  155. vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true );
  156. vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true );
  157. normals[ componentIdx ] = normalX;
  158. normals[ componentIdx + 1 ] = normalY;
  159. normals[ componentIdx + 2 ] = normalZ;
  160. if ( hasColors ) {
  161. colors[ componentIdx ] = r;
  162. colors[ componentIdx + 1 ] = g;
  163. colors[ componentIdx + 2 ] = b;
  164. }
  165. }
  166. }
  167. geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  168. geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  169. if ( hasColors ) {
  170. geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  171. geometry.hasColors = true;
  172. geometry.alpha = alpha;
  173. }
  174. return geometry;
  175. }
  176. function parseASCII( data ) {
  177. const geometry = new THREE.BufferGeometry();
  178. const patternSolid = /solid([\s\S]*?)endsolid/g;
  179. const patternFace = /facet([\s\S]*?)endfacet/g;
  180. let faceCounter = 0;
  181. const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
  182. const patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' );
  183. const patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' );
  184. const vertices = [];
  185. const normals = [];
  186. const normal = new THREE.Vector3();
  187. let result;
  188. let groupCount = 0;
  189. let startVertex = 0;
  190. let endVertex = 0;
  191. while ( ( result = patternSolid.exec( data ) ) !== null ) {
  192. startVertex = endVertex;
  193. const solid = result[ 0 ];
  194. while ( ( result = patternFace.exec( solid ) ) !== null ) {
  195. let vertexCountPerFace = 0;
  196. let normalCountPerFace = 0;
  197. const text = result[ 0 ];
  198. while ( ( result = patternNormal.exec( text ) ) !== null ) {
  199. normal.x = parseFloat( result[ 1 ] );
  200. normal.y = parseFloat( result[ 2 ] );
  201. normal.z = parseFloat( result[ 3 ] );
  202. normalCountPerFace ++;
  203. }
  204. while ( ( result = patternVertex.exec( text ) ) !== null ) {
  205. vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
  206. normals.push( normal.x, normal.y, normal.z );
  207. vertexCountPerFace ++;
  208. endVertex ++;
  209. }
  210. // every face have to own ONE valid normal
  211. if ( normalCountPerFace !== 1 ) {
  212. console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
  213. }
  214. // each face have to own THREE valid vertices
  215. if ( vertexCountPerFace !== 3 ) {
  216. console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
  217. }
  218. faceCounter ++;
  219. }
  220. const start = startVertex;
  221. const count = endVertex - startVertex;
  222. geometry.addGroup( start, count, groupCount );
  223. groupCount ++;
  224. }
  225. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  226. geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  227. return geometry;
  228. }
  229. function ensureString( buffer ) {
  230. if ( typeof buffer !== 'string' ) {
  231. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer ) );
  232. }
  233. return buffer;
  234. }
  235. function ensureBinary( buffer ) {
  236. if ( typeof buffer === 'string' ) {
  237. const array_buffer = new Uint8Array( buffer.length );
  238. for ( let i = 0; i < buffer.length; i ++ ) {
  239. array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
  240. }
  241. return array_buffer.buffer || array_buffer;
  242. } else {
  243. return buffer;
  244. }
  245. }
  246. // start
  247. const binData = ensureBinary( data );
  248. return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
  249. }
  250. }
  251. THREE.STLLoader = STLLoader;
  252. } )();