STLLoader.js 10 KB

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