stlFileLoader.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { Tools } from "@babylonjs/core/Misc/tools.js";
  2. import { VertexBuffer } from "@babylonjs/core/Buffers/buffer.js";
  3. import { Mesh } from "@babylonjs/core/Meshes/mesh.js";
  4. import { SceneLoader } from "@babylonjs/core/Loading/sceneLoader.js";
  5. import { AssetContainer } from "@babylonjs/core/assetContainer.js";
  6. /**
  7. * STL file type loader.
  8. * This is a babylon scene loader plugin.
  9. */
  10. export class STLFileLoader {
  11. constructor() {
  12. /** @internal */
  13. this.solidPattern = /solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g;
  14. /** @internal */
  15. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  16. /** @internal */
  17. this.normalPattern = /normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g;
  18. /** @internal */
  19. this.vertexPattern = /vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g;
  20. /**
  21. * Defines the name of the plugin.
  22. */
  23. this.name = "stl";
  24. /**
  25. * Defines the extensions the stl loader is able to load.
  26. * force data to come in as an ArrayBuffer
  27. * we'll convert to string if it looks like it's an ASCII .stl
  28. */
  29. this.extensions = {
  30. ".stl": { isBinary: true },
  31. };
  32. }
  33. /**
  34. * Import meshes into a scene.
  35. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  36. * @param scene The scene to import into
  37. * @param data The data to import
  38. * @param rootUrl The root url for scene and resources
  39. * @param meshes The meshes array to import into
  40. * @returns True if successful or false otherwise
  41. */
  42. importMesh(meshesNames, scene, data, rootUrl, meshes) {
  43. let matches;
  44. if (typeof data !== "string") {
  45. if (this._isBinary(data)) {
  46. // binary .stl
  47. const babylonMesh = new Mesh("stlmesh", scene);
  48. this._parseBinary(babylonMesh, data);
  49. if (meshes) {
  50. meshes.push(babylonMesh);
  51. }
  52. return true;
  53. }
  54. // ASCII .stl
  55. // convert to string
  56. data = new TextDecoder().decode(new Uint8Array(data));
  57. }
  58. //if arrived here, data is a string, containing the STLA data.
  59. while ((matches = this.solidPattern.exec(data))) {
  60. let meshName = matches[1];
  61. const meshNameFromEnd = matches[3];
  62. if (meshNameFromEnd && meshName != meshNameFromEnd) {
  63. Tools.Error("Error in STL, solid name != endsolid name");
  64. return false;
  65. }
  66. // check meshesNames
  67. if (meshesNames && meshName) {
  68. if (meshesNames instanceof Array) {
  69. if (!meshesNames.indexOf(meshName)) {
  70. continue;
  71. }
  72. }
  73. else {
  74. if (meshName !== meshesNames) {
  75. continue;
  76. }
  77. }
  78. }
  79. // stl mesh name can be empty as well
  80. meshName = meshName || "stlmesh";
  81. const babylonMesh = new Mesh(meshName, scene);
  82. this._parseASCII(babylonMesh, matches[2]);
  83. if (meshes) {
  84. meshes.push(babylonMesh);
  85. }
  86. }
  87. return true;
  88. }
  89. /**
  90. * Load into a scene.
  91. * @param scene The scene to load into
  92. * @param data The data to import
  93. * @param rootUrl The root url for scene and resources
  94. * @returns true if successful or false otherwise
  95. */
  96. load(scene, data, rootUrl) {
  97. const result = this.importMesh(null, scene, data, rootUrl, null);
  98. return result;
  99. }
  100. /**
  101. * Load into an asset container.
  102. * @param scene The scene to load into
  103. * @param data The data to import
  104. * @param rootUrl The root url for scene and resources
  105. * @returns The loaded asset container
  106. */
  107. loadAssetContainer(scene, data, rootUrl) {
  108. const container = new AssetContainer(scene);
  109. scene._blockEntityCollection = true;
  110. this.importMesh(null, scene, data, rootUrl, container.meshes);
  111. scene._blockEntityCollection = false;
  112. return container;
  113. }
  114. _isBinary(data) {
  115. // check if file size is correct for binary stl
  116. const reader = new DataView(data);
  117. // A Binary STL header is 80 bytes, if the data size is not great than
  118. // that then it's not a binary STL.
  119. if (reader.byteLength <= 80) {
  120. return false;
  121. }
  122. const faceSize = (32 / 8) * 3 + (32 / 8) * 3 * 3 + 16 / 8;
  123. const nFaces = reader.getUint32(80, true);
  124. if (80 + 32 / 8 + nFaces * faceSize === reader.byteLength) {
  125. return true;
  126. }
  127. // US-ASCII begin with 's', 'o', 'l', 'i', 'd'
  128. const ascii = [115, 111, 108, 105, 100];
  129. for (let off = 0; off < 5; off++) {
  130. if (reader.getUint8(off) !== ascii[off]) {
  131. return true;
  132. }
  133. }
  134. return false;
  135. }
  136. _parseBinary(mesh, data) {
  137. const reader = new DataView(data);
  138. const faces = reader.getUint32(80, true);
  139. const dataOffset = 84;
  140. const faceLength = 12 * 4 + 2;
  141. let offset = 0;
  142. const positions = new Float32Array(faces * 3 * 3);
  143. const normals = new Float32Array(faces * 3 * 3);
  144. const indices = new Uint32Array(faces * 3);
  145. let indicesCount = 0;
  146. for (let face = 0; face < faces; face++) {
  147. const start = dataOffset + face * faceLength;
  148. const normalX = reader.getFloat32(start, true);
  149. const normalY = reader.getFloat32(start + 4, true);
  150. const normalZ = reader.getFloat32(start + 8, true);
  151. for (let i = 1; i <= 3; i++) {
  152. const vertexstart = start + i * 12;
  153. // ordering is intentional to match ascii import
  154. positions[offset] = reader.getFloat32(vertexstart, true);
  155. normals[offset] = normalX;
  156. if (!STLFileLoader.DO_NOT_ALTER_FILE_COORDINATES) {
  157. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  158. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  159. normals[offset + 2] = normalY;
  160. normals[offset + 1] = normalZ;
  161. }
  162. else {
  163. positions[offset + 1] = reader.getFloat32(vertexstart + 4, true);
  164. positions[offset + 2] = reader.getFloat32(vertexstart + 8, true);
  165. normals[offset + 1] = normalY;
  166. normals[offset + 2] = normalZ;
  167. }
  168. offset += 3;
  169. }
  170. if (STLFileLoader.DO_NOT_ALTER_FILE_COORDINATES) {
  171. indices[indicesCount] = indicesCount;
  172. indices[indicesCount + 1] = indicesCount + 2;
  173. indices[indicesCount + 2] = indicesCount + 1;
  174. indicesCount += 3;
  175. }
  176. else {
  177. indices[indicesCount] = indicesCount++;
  178. indices[indicesCount] = indicesCount++;
  179. indices[indicesCount] = indicesCount++;
  180. }
  181. }
  182. mesh.setVerticesData(VertexBuffer.PositionKind, positions);
  183. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  184. mesh.setIndices(indices);
  185. mesh.computeWorldMatrix(true);
  186. }
  187. _parseASCII(mesh, solidData) {
  188. const positions = [];
  189. const normals = [];
  190. const indices = [];
  191. let indicesCount = 0;
  192. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  193. let matches;
  194. while ((matches = this.facetsPattern.exec(solidData))) {
  195. const facet = matches[1];
  196. //one normal per face
  197. const normalMatches = this.normalPattern.exec(facet);
  198. this.normalPattern.lastIndex = 0;
  199. if (!normalMatches) {
  200. continue;
  201. }
  202. const normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  203. let vertexMatch;
  204. while ((vertexMatch = this.vertexPattern.exec(facet))) {
  205. if (!STLFileLoader.DO_NOT_ALTER_FILE_COORDINATES) {
  206. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  207. normals.push(normal[0], normal[1], normal[2]);
  208. }
  209. else {
  210. positions.push(Number(vertexMatch[1]), Number(vertexMatch[3]), Number(vertexMatch[5]));
  211. // Flipping the second and third component because inverted
  212. // when normal was declared.
  213. normals.push(normal[0], normal[2], normal[1]);
  214. }
  215. }
  216. if (STLFileLoader.DO_NOT_ALTER_FILE_COORDINATES) {
  217. indices.push(indicesCount, indicesCount + 2, indicesCount + 1);
  218. indicesCount += 3;
  219. }
  220. else {
  221. indices.push(indicesCount++, indicesCount++, indicesCount++);
  222. }
  223. this.vertexPattern.lastIndex = 0;
  224. }
  225. this.facetsPattern.lastIndex = 0;
  226. mesh.setVerticesData(VertexBuffer.PositionKind, positions);
  227. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  228. mesh.setIndices(indices);
  229. mesh.computeWorldMatrix(true);
  230. }
  231. }
  232. /**
  233. * Defines if Y and Z axes are swapped or not when loading an STL file.
  234. * The default is false to maintain backward compatibility. When set to
  235. * true, coordinates from the STL file are used without change.
  236. */
  237. STLFileLoader.DO_NOT_ALTER_FILE_COORDINATES = false;
  238. if (SceneLoader) {
  239. SceneLoader.RegisterPlugin(new STLFileLoader());
  240. }
  241. //# sourceMappingURL=stlFileLoader.js.map