STLLoader.js 10 KB

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