objFileLoader.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. import { Nullable, FloatArray, IndicesArray } from "babylonjs/types";
  2. import { Vector3, Vector2, Color3, Color4 } from "babylonjs/Maths/math";
  3. import { Tools } from "babylonjs/Misc/tools";
  4. import { VertexData } from "babylonjs/Meshes/mesh.vertexData";
  5. import { Geometry } from "babylonjs/Meshes/geometry";
  6. import { AnimationGroup } from "babylonjs/Animations/animationGroup";
  7. import { Skeleton } from "babylonjs/Bones/skeleton";
  8. import { IParticleSystem } from "babylonjs/Particles/IParticleSystem";
  9. import { Texture } from "babylonjs/Materials/Textures/texture";
  10. import { StandardMaterial } from "babylonjs/Materials/standardMaterial";
  11. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  12. import { Mesh } from "babylonjs/Meshes/mesh";
  13. import { SceneLoader, ISceneLoaderPluginAsync, SceneLoaderProgressEvent, ISceneLoaderPluginFactory, ISceneLoaderPlugin } from "babylonjs/Loading/sceneLoader";
  14. import { AssetContainer } from "babylonjs/assetContainer";
  15. import { Scene } from "babylonjs/scene";
  16. import { WebRequest } from 'babylonjs/Misc/webRequest';
  17. /**
  18. * Class reading and parsing the MTL file bundled with the obj file.
  19. */
  20. export class MTLFileLoader {
  21. /**
  22. * All material loaded from the mtl will be set here
  23. */
  24. public materials: StandardMaterial[] = [];
  25. /**
  26. * This function will read the mtl file and create each material described inside
  27. * This function could be improve by adding :
  28. * -some component missing (Ni, Tf...)
  29. * -including the specific options available
  30. *
  31. * @param scene defines the scene the material will be created in
  32. * @param data defines the mtl data to parse
  33. * @param rootUrl defines the rooturl to use in order to load relative dependencies
  34. */
  35. public parseMTL(scene: Scene, data: string | ArrayBuffer, rootUrl: string): void {
  36. if (data instanceof ArrayBuffer) {
  37. return;
  38. }
  39. //Split the lines from the file
  40. var lines = data.split('\n');
  41. //Space char
  42. var delimiter_pattern = /\s+/;
  43. //Array with RGB colors
  44. var color: number[];
  45. //New material
  46. var material: Nullable<StandardMaterial> = null;
  47. //Look at each line
  48. for (var i = 0; i < lines.length; i++) {
  49. var line = lines[i].trim();
  50. // Blank line or comment
  51. if (line.length === 0 || line.charAt(0) === '#') {
  52. continue;
  53. }
  54. //Get the first parameter (keyword)
  55. var pos = line.indexOf(' ');
  56. var key = (pos >= 0) ? line.substring(0, pos) : line;
  57. key = key.toLowerCase();
  58. //Get the data following the key
  59. var value: string = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  60. //This mtl keyword will create the new material
  61. if (key === "newmtl") {
  62. //Check if it is the first material.
  63. // Materials specifications are described after this keyword.
  64. if (material) {
  65. //Add the previous material in the material array.
  66. this.materials.push(material);
  67. }
  68. //Create a new material.
  69. // value is the name of the material read in the mtl file
  70. material = new StandardMaterial(value, scene);
  71. } else if (key === "kd" && material) {
  72. // Diffuse color (color under white light) using RGB values
  73. //value = "r g b"
  74. color = <number[]>value.split(delimiter_pattern, 3).map(parseFloat);
  75. //color = [r,g,b]
  76. //Set tghe color into the material
  77. material.diffuseColor = Color3.FromArray(color);
  78. } else if (key === "ka" && material) {
  79. // Ambient color (color under shadow) using RGB values
  80. //value = "r g b"
  81. color = <number[]>value.split(delimiter_pattern, 3).map(parseFloat);
  82. //color = [r,g,b]
  83. //Set tghe color into the material
  84. material.ambientColor = Color3.FromArray(color);
  85. } else if (key === "ks" && material) {
  86. // Specular color (color when light is reflected from shiny surface) using RGB values
  87. //value = "r g b"
  88. color = <number[]>value.split(delimiter_pattern, 3).map(parseFloat);
  89. //color = [r,g,b]
  90. //Set the color into the material
  91. material.specularColor = Color3.FromArray(color);
  92. } else if (key === "ke" && material) {
  93. // Emissive color using RGB values
  94. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95. material.emissiveColor = Color3.FromArray(color);
  96. } else if (key === "ns" && material) {
  97. //value = "Integer"
  98. material.specularPower = parseFloat(value);
  99. } else if (key === "d" && material) {
  100. //d is dissolve for current material. It mean alpha for BABYLON
  101. material.alpha = parseFloat(value);
  102. //Texture
  103. //This part can be improved by adding the possible options of texture
  104. } else if (key === "map_ka" && material) {
  105. // ambient texture map with a loaded image
  106. //We must first get the folder of the image
  107. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  108. } else if (key === "map_kd" && material) {
  109. // Diffuse texture map with a loaded image
  110. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  111. } else if (key === "map_ks" && material) {
  112. // Specular texture map with a loaded image
  113. //We must first get the folder of the image
  114. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  115. } else if (key === "map_ns") {
  116. //Specular
  117. //Specular highlight component
  118. //We must first get the folder of the image
  119. //
  120. //Not supported by BABYLON
  121. //
  122. // continue;
  123. } else if (key === "map_bump" && material) {
  124. //The bump texture
  125. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  126. } else if (key === "map_d" && material) {
  127. // The dissolve of the material
  128. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  129. //Options for illumination
  130. } else if (key === "illum") {
  131. //Illumination
  132. if (value === "0") {
  133. //That mean Kd == Kd
  134. } else if (value === "1") {
  135. //Color on and Ambient on
  136. } else if (value === "2") {
  137. //Highlight on
  138. } else if (value === "3") {
  139. //Reflection on and Ray trace on
  140. } else if (value === "4") {
  141. //Transparency: Glass on, Reflection: Ray trace on
  142. } else if (value === "5") {
  143. //Reflection: Fresnel on and Ray trace on
  144. } else if (value === "6") {
  145. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  146. } else if (value === "7") {
  147. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  148. } else if (value === "8") {
  149. //Reflection on and Ray trace off
  150. } else if (value === "9") {
  151. //Transparency: Glass on, Reflection: Ray trace off
  152. } else if (value === "10") {
  153. //Casts shadows onto invisible surfaces
  154. }
  155. } else {
  156. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  157. }
  158. }
  159. //At the end of the file, add the last material
  160. if (material) {
  161. this.materials.push(material);
  162. }
  163. }
  164. /**
  165. * Gets the texture for the material.
  166. *
  167. * If the material is imported from input file,
  168. * We sanitize the url to ensure it takes the textre from aside the material.
  169. *
  170. * @param rootUrl The root url to load from
  171. * @param value The value stored in the mtl
  172. * @return The Texture
  173. */
  174. private static _getTexture(rootUrl: string, value: string, scene: Scene): Nullable<Texture> {
  175. if (!value) {
  176. return null;
  177. }
  178. var url = rootUrl;
  179. // Load from input file.
  180. if (rootUrl === "file:") {
  181. var lastDelimiter = value.lastIndexOf("\\");
  182. if (lastDelimiter === -1) {
  183. lastDelimiter = value.lastIndexOf("/");
  184. }
  185. if (lastDelimiter > -1) {
  186. url += value.substr(lastDelimiter + 1);
  187. }
  188. else {
  189. url += value;
  190. }
  191. }
  192. // Not from input file.
  193. else {
  194. url += value;
  195. }
  196. return new Texture(url, scene);
  197. }
  198. }
  199. type MeshObject = {
  200. name: string;
  201. indices?: Array<number>;
  202. positions?: Array<number>;
  203. normals?: Array<number>;
  204. colors?: Array<number>;
  205. uvs?: Array<number>;
  206. materialName: string;
  207. };
  208. /**
  209. * Options for loading OBJ/MTL files
  210. */
  211. type MeshLoadOptions = {
  212. /**
  213. * Defines if UVs are optimized by default during load.
  214. */
  215. OptimizeWithUV: boolean,
  216. /**
  217. * Invert model on y-axis (does a model scaling inversion)
  218. */
  219. InvertY: boolean,
  220. /**
  221. * Include in meshes the vertex colors available in some OBJ files. This is not part of OBJ standard.
  222. */
  223. ImportVertexColors: boolean,
  224. /**
  225. * Compute the normals for the model, even if normals are present in the file.
  226. */
  227. ComputeNormals: boolean,
  228. /**
  229. * Skip loading the materials even if defined in the OBJ file (materials are ignored).
  230. */
  231. SkipMaterials: boolean,
  232. /**
  233. * When a material fails to load OBJ loader will silently fail and onSuccess() callback will be triggered.
  234. */
  235. MaterialLoadingFailsSilently: boolean
  236. };
  237. /**
  238. * OBJ file type loader.
  239. * This is a babylon scene loader plugin.
  240. */
  241. export class OBJFileLoader implements ISceneLoaderPluginAsync, ISceneLoaderPluginFactory {
  242. /**
  243. * Defines if UVs are optimized by default during load.
  244. */
  245. public static OPTIMIZE_WITH_UV = false;
  246. /**
  247. * Invert model on y-axis (does a model scaling inversion)
  248. */
  249. public static INVERT_Y = false;
  250. /**
  251. * Include in meshes the vertex colors available in some OBJ files. This is not part of OBJ standard.
  252. */
  253. public static IMPORT_VERTEX_COLORS = false;
  254. /**
  255. * Compute the normals for the model, even if normals are present in the file.
  256. */
  257. public static COMPUTE_NORMALS = false;
  258. /**
  259. * Skip loading the materials even if defined in the OBJ file (materials are ignored).
  260. */
  261. public static SKIP_MATERIALS = false;
  262. /**
  263. * When a material fails to load OBJ loader will silently fail and onSuccess() callback will be triggered.
  264. *
  265. * Defaults to true for backwards compatibility.
  266. */
  267. public static MATERIAL_LOADING_FAILS_SILENTLY = true;
  268. /**
  269. * Defines the name of the plugin.
  270. */
  271. public name = "obj";
  272. /**
  273. * Defines the extension the plugin is able to load.
  274. */
  275. public extensions = ".obj";
  276. /** @hidden */
  277. public obj = /^o/;
  278. /** @hidden */
  279. public group = /^g/;
  280. /** @hidden */
  281. public mtllib = /^mtllib /;
  282. /** @hidden */
  283. public usemtl = /^usemtl /;
  284. /** @hidden */
  285. public smooth = /^s /;
  286. /** @hidden */
  287. public vertexPattern = /v( +[\d|\.|\+|\-|e|E]+){3,7}/;
  288. // vn float float float
  289. /** @hidden */
  290. public normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  291. // vt float float
  292. /** @hidden */
  293. public uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  294. // f vertex vertex vertex ...
  295. /** @hidden */
  296. public facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  297. // f vertex/uvs vertex/uvs vertex/uvs ...
  298. /** @hidden */
  299. public facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  300. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  301. /** @hidden */
  302. public facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  303. // f vertex//normal vertex//normal vertex//normal ...
  304. /** @hidden */
  305. public facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  306. // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...
  307. /** @hidden */
  308. public facePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;
  309. private _meshLoadOptions: MeshLoadOptions;
  310. /**
  311. * Creates loader for .OBJ files
  312. *
  313. * @param meshLoadOptions options for loading and parsing OBJ/MTL files.
  314. */
  315. constructor(meshLoadOptions?: MeshLoadOptions) {
  316. this._meshLoadOptions = meshLoadOptions || OBJFileLoader.currentMeshLoadOptions;
  317. }
  318. private static get currentMeshLoadOptions(): MeshLoadOptions {
  319. return {
  320. ComputeNormals: OBJFileLoader.COMPUTE_NORMALS,
  321. ImportVertexColors: OBJFileLoader.IMPORT_VERTEX_COLORS,
  322. InvertY: OBJFileLoader.INVERT_Y,
  323. MaterialLoadingFailsSilently: OBJFileLoader.MATERIAL_LOADING_FAILS_SILENTLY,
  324. OptimizeWithUV: OBJFileLoader.OPTIMIZE_WITH_UV,
  325. SkipMaterials: OBJFileLoader.SKIP_MATERIALS
  326. };
  327. }
  328. /**
  329. * Calls synchronously the MTL file attached to this obj.
  330. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  331. * Without this function materials are not displayed in the first frame (but displayed after).
  332. * In consequence it is impossible to get material information in your HTML file
  333. *
  334. * @param url The URL of the MTL file
  335. * @param rootUrl
  336. * @param onSuccess Callback function to be called when the MTL file is loaded
  337. * @private
  338. */
  339. private _loadMTL(url: string, rootUrl: string, onSuccess: (response: string | ArrayBuffer, responseUrl?: string) => any, onFailure: (pathOfFile: string, exception?: any) => void) {
  340. //The complete path to the mtl file
  341. var pathOfFile = Tools.BaseUrl + rootUrl + url;
  342. // Loads through the babylon tools to allow fileInput search.
  343. Tools.LoadFile(
  344. pathOfFile,
  345. onSuccess,
  346. undefined,
  347. undefined,
  348. false,
  349. (request?: WebRequest | undefined, exception?: any) => {
  350. onFailure(pathOfFile, exception);
  351. }
  352. );
  353. }
  354. /**
  355. * Instantiates a OBJ file loader plugin.
  356. * @returns the created plugin
  357. */
  358. createPlugin(): ISceneLoaderPluginAsync | ISceneLoaderPlugin {
  359. return new OBJFileLoader(OBJFileLoader.currentMeshLoadOptions);
  360. }
  361. /**
  362. * If the data string can be loaded directly.
  363. *
  364. * @param data string containing the file data
  365. * @returns if the data can be loaded directly
  366. */
  367. public canDirectLoad(data: string): boolean {
  368. return false;
  369. }
  370. /**
  371. * Imports one or more meshes from the loaded OBJ data and adds them to the scene
  372. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  373. * @param scene the scene the meshes should be added to
  374. * @param data the OBJ data to load
  375. * @param rootUrl root url to load from
  376. * @param onProgress event that fires when loading progress has occured
  377. * @param fileName Defines the name of the file to load
  378. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  379. */
  380. public importMeshAsync(meshesNames: any, scene: Scene, data: any, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<{ meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], animationGroups: AnimationGroup[] }> {
  381. //get the meshes from OBJ file
  382. return this._parseSolid(meshesNames, scene, data, rootUrl).then((meshes) => {
  383. return {
  384. meshes,
  385. particleSystems: [],
  386. skeletons: [],
  387. animationGroups: []
  388. };
  389. });
  390. }
  391. /**
  392. * Imports all objects from the loaded OBJ data and adds them to the scene
  393. * @param scene the scene the objects should be added to
  394. * @param data the OBJ data to load
  395. * @param rootUrl root url to load from
  396. * @param onProgress event that fires when loading progress has occured
  397. * @param fileName Defines the name of the file to load
  398. * @returns a promise which completes when objects have been loaded to the scene
  399. */
  400. public loadAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<void> {
  401. //Get the 3D model
  402. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(() => {
  403. // return void
  404. });
  405. }
  406. /**
  407. * Load into an asset container.
  408. * @param scene The scene to load into
  409. * @param data The data to import
  410. * @param rootUrl The root url for scene and resources
  411. * @param onProgress The callback when the load progresses
  412. * @param fileName Defines the name of the file to load
  413. * @returns The loaded asset container
  414. */
  415. public loadAssetContainerAsync(scene: Scene, data: string, rootUrl: string, onProgress?: (event: SceneLoaderProgressEvent) => void, fileName?: string): Promise<AssetContainer> {
  416. return this.importMeshAsync(null, scene, data, rootUrl).then((result) => {
  417. var container = new AssetContainer(scene);
  418. result.meshes.forEach((mesh) => container.meshes.push(mesh));
  419. result.meshes.forEach((mesh) => {
  420. var material = mesh.material;
  421. if (material) {
  422. // Materials
  423. if (container.materials.indexOf(material) == -1) {
  424. container.materials.push(material);
  425. // Textures
  426. var textures = material.getActiveTextures();
  427. textures.forEach((t) => {
  428. if (container.textures.indexOf(t) == -1) {
  429. container.textures.push(t);
  430. }
  431. });
  432. }
  433. }
  434. });
  435. container.removeAllFromScene();
  436. return container;
  437. });
  438. }
  439. /**
  440. * Read the OBJ file and create an Array of meshes.
  441. * Each mesh contains all information given by the OBJ and the MTL file.
  442. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  443. *
  444. * @param meshesNames
  445. * @param scene Scene The scene where are displayed the data
  446. * @param data String The content of the obj file
  447. * @param rootUrl String The path to the folder
  448. * @returns Array<AbstractMesh>
  449. * @private
  450. */
  451. private _parseSolid(meshesNames: any, scene: Scene, data: string, rootUrl: string): Promise<Array<AbstractMesh>> {
  452. var positions: Array<Vector3> = []; //values for the positions of vertices
  453. var normals: Array<Vector3> = []; //Values for the normals
  454. var uvs: Array<Vector2> = []; //Values for the textures
  455. var colors: Array<Color4> = [];
  456. var meshesFromObj: Array<MeshObject> = []; //[mesh] Contains all the obj meshes
  457. var handledMesh: MeshObject; //The current mesh of meshes array
  458. var indicesForBabylon: Array<number> = []; //The list of indices for VertexData
  459. var wrappedPositionForBabylon: Array<Vector3> = []; //The list of position in vectors
  460. var wrappedUvsForBabylon: Array<Vector2> = []; //Array with all value of uvs to match with the indices
  461. var wrappedColorsForBabylon: Array<Color4> = []; // Array with all color values to match with the indices
  462. var wrappedNormalsForBabylon: Array<Vector3> = []; //Array with all value of normals to match with the indices
  463. var tuplePosNorm: Array<{ normals: Array<number>; idx: Array<number>; uv: Array<number> }> = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  464. var curPositionInIndices = 0;
  465. var hasMeshes: Boolean = false; //Meshes are defined in the file
  466. var unwrappedPositionsForBabylon: Array<number> = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  467. var unwrappedColorsForBabylon: Array<number> = []; // Value of colorForBabylon w/o Color4() [r,g,b,a]
  468. var unwrappedNormalsForBabylon: Array<number> = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  469. var unwrappedUVForBabylon: Array<number> = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  470. var triangles: Array<string> = []; //Indices from new triangles coming from polygons
  471. var materialNameFromObj: string = ""; //The name of the current material
  472. var fileToLoad: string = ""; //The name of the mtlFile to load
  473. var materialsFromMTLFile: MTLFileLoader = new MTLFileLoader();
  474. var objMeshName: string = ""; //The name of the current obj mesh
  475. var increment: number = 1; //Id for meshes created by the multimaterial
  476. var isFirstMaterial: boolean = true;
  477. var grayColor = new Color4(0.5, 0.5, 0.5, 1);
  478. /**
  479. * Search for obj in the given array.
  480. * This function is called to check if a couple of data already exists in an array.
  481. *
  482. * If found, returns the index of the founded tuple index. Returns -1 if not found
  483. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  484. * @param obj Array<number>
  485. * @returns {boolean}
  486. */
  487. var isInArray = (arr: Array<{ normals: Array<number>; idx: Array<number> }>, obj: Array<number>) => {
  488. if (!arr[obj[0]]) { arr[obj[0]] = { normals: [], idx: [] }; }
  489. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  490. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  491. };
  492. var isInArrayUV = (arr: Array<{ normals: Array<number>; idx: Array<number>; uv: Array<number> }>, obj: Array<number>) => {
  493. if (!arr[obj[0]]) { arr[obj[0]] = { normals: [], idx: [], uv: [] }; }
  494. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  495. if (idx != 1 && (obj[2] === arr[obj[0]].uv[idx])) {
  496. return arr[obj[0]].idx[idx];
  497. }
  498. return -1;
  499. };
  500. /**
  501. * This function set the data for each triangle.
  502. * Data are position, normals and uvs
  503. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  504. * If the tuple already exist, add only their indice
  505. *
  506. * @param indicePositionFromObj Integer The index in positions array
  507. * @param indiceUvsFromObj Integer The index in uvs array
  508. * @param indiceNormalFromObj Integer The index in normals array
  509. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  510. * @param textureVectorFromOBJ Vector3 The value of uvs
  511. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  512. */
  513. var setData = (indicePositionFromObj: number, indiceUvsFromObj: number, indiceNormalFromObj: number, positionVectorFromOBJ: Vector3, textureVectorFromOBJ: Vector2, normalsVectorFromOBJ: Vector3, positionColorsFromOBJ?: Color4) => {
  514. //Check if this tuple already exists in the list of tuples
  515. var _index: number;
  516. if (this._meshLoadOptions.OptimizeWithUV) {
  517. _index = isInArrayUV(
  518. tuplePosNorm,
  519. [
  520. indicePositionFromObj,
  521. indiceNormalFromObj,
  522. indiceUvsFromObj
  523. ]
  524. );
  525. }
  526. else {
  527. _index = isInArray(
  528. tuplePosNorm,
  529. [
  530. indicePositionFromObj,
  531. indiceNormalFromObj
  532. ]
  533. );
  534. }
  535. //If it not exists
  536. if (_index === -1) {
  537. //Add an new indice.
  538. //The array of indices is only an array with his length equal to the number of triangles - 1.
  539. //We add vertices data in this order
  540. indicesForBabylon.push(wrappedPositionForBabylon.length);
  541. //Push the position of vertice for Babylon
  542. //Each element is a Vector3(x,y,z)
  543. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  544. //Push the uvs for Babylon
  545. //Each element is a Vector3(u,v)
  546. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  547. //Push the normals for Babylon
  548. //Each element is a Vector3(x,y,z)
  549. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  550. if (positionColorsFromOBJ !== undefined) {
  551. //Push the colors for Babylon
  552. //Each element is a BABYLON.Color4(r,g,b,a)
  553. wrappedColorsForBabylon.push(positionColorsFromOBJ);
  554. }
  555. //Add the tuple in the comparison list
  556. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  557. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  558. if (this._meshLoadOptions.OptimizeWithUV) { tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj); }
  559. } else {
  560. //The tuple already exists
  561. //Add the index of the already existing tuple
  562. //At this index we can get the value of position, normal, color and uvs of vertex
  563. indicesForBabylon.push(_index);
  564. }
  565. };
  566. /**
  567. * Transform Vector() and BABYLON.Color() objects into numbers in an array
  568. */
  569. var unwrapData = () => {
  570. //Every array has the same length
  571. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  572. //Push the x, y, z values of each element in the unwrapped array
  573. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  574. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  575. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  576. }
  577. if (this._meshLoadOptions.ImportVertexColors === true) {
  578. //Push the r, g, b, a values of each element in the unwrapped array
  579. unwrappedColorsForBabylon.push(wrappedColorsForBabylon[l].r, wrappedColorsForBabylon[l].g, wrappedColorsForBabylon[l].b, wrappedColorsForBabylon[l].a);
  580. }
  581. // Reset arrays for the next new meshes
  582. wrappedPositionForBabylon = [];
  583. wrappedNormalsForBabylon = [];
  584. wrappedUvsForBabylon = [];
  585. wrappedColorsForBabylon = [];
  586. tuplePosNorm = [];
  587. curPositionInIndices = 0;
  588. };
  589. /**
  590. * Create triangles from polygons by recursion
  591. * The best to understand how it works is to draw it in the same time you get the recursion.
  592. * It is important to notice that a triangle is a polygon
  593. * We get 5 patterns of face defined in OBJ File :
  594. * facePattern1 = ["1","2","3","4","5","6"]
  595. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  596. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  597. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  598. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  599. * Each pattern is divided by the same method
  600. * @param face Array[String] The indices of elements
  601. * @param v Integer The variable to increment
  602. */
  603. var getTriangles = (face: Array<string>, v: number) => {
  604. //Work for each element of the array
  605. if (v + 1 < face.length) {
  606. //Add on the triangle variable the indexes to obtain triangles
  607. triangles.push(face[0], face[v], face[v + 1]);
  608. //Incrementation for recursion
  609. v += 1;
  610. //Recursion
  611. getTriangles(face, v);
  612. }
  613. //Result obtained after 2 iterations:
  614. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  615. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  616. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  617. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  618. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  619. };
  620. /**
  621. * Create triangles and push the data for each polygon for the pattern 1
  622. * In this pattern we get vertice positions
  623. * @param face
  624. * @param v
  625. */
  626. var setDataForCurrentFaceWithPattern1 = (face: Array<string>, v: number) => {
  627. //Get the indices of triangles for each polygon
  628. getTriangles(face, v);
  629. //For each element in the triangles array.
  630. //This var could contains 1 to an infinity of triangles
  631. for (var k = 0; k < triangles.length; k++) {
  632. // Set position indice
  633. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  634. setData(
  635. indicePositionFromObj,
  636. 0, 0, //In the pattern 1, normals and uvs are not defined
  637. positions[indicePositionFromObj], //Get the vectors data
  638. Vector2.Zero(), Vector3.Up(), //Create default vectors
  639. this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined
  640. );
  641. }
  642. //Reset variable for the next line
  643. triangles = [];
  644. };
  645. /**
  646. * Create triangles and push the data for each polygon for the pattern 2
  647. * In this pattern we get vertice positions and uvsu
  648. * @param face
  649. * @param v
  650. */
  651. var setDataForCurrentFaceWithPattern2 = (face: Array<string>, v: number) => {
  652. //Get the indices of triangles for each polygon
  653. getTriangles(face, v);
  654. for (var k = 0; k < triangles.length; k++) {
  655. //triangle[k] = "1/1"
  656. //Split the data for getting position and uv
  657. var point = triangles[k].split("/"); // ["1", "1"]
  658. //Set position indice
  659. var indicePositionFromObj = parseInt(point[0]) - 1;
  660. //Set uv indice
  661. var indiceUvsFromObj = parseInt(point[1]) - 1;
  662. setData(
  663. indicePositionFromObj,
  664. indiceUvsFromObj,
  665. 0, //Default value for normals
  666. positions[indicePositionFromObj], //Get the values for each element
  667. uvs[indiceUvsFromObj],
  668. Vector3.Up(), //Default value for normals
  669. this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined
  670. );
  671. }
  672. //Reset variable for the next line
  673. triangles = [];
  674. };
  675. /**
  676. * Create triangles and push the data for each polygon for the pattern 3
  677. * In this pattern we get vertice positions, uvs and normals
  678. * @param face
  679. * @param v
  680. */
  681. var setDataForCurrentFaceWithPattern3 = (face: Array<string>, v: number) => {
  682. //Get the indices of triangles for each polygon
  683. getTriangles(face, v);
  684. for (var k = 0; k < triangles.length; k++) {
  685. //triangle[k] = "1/1/1"
  686. //Split the data for getting position, uv, and normals
  687. var point = triangles[k].split("/"); // ["1", "1", "1"]
  688. // Set position indice
  689. var indicePositionFromObj = parseInt(point[0]) - 1;
  690. // Set uv indice
  691. var indiceUvsFromObj = parseInt(point[1]) - 1;
  692. // Set normal indice
  693. var indiceNormalFromObj = parseInt(point[2]) - 1;
  694. setData(
  695. indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj,
  696. positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  697. );
  698. }
  699. //Reset variable for the next line
  700. triangles = [];
  701. };
  702. /**
  703. * Create triangles and push the data for each polygon for the pattern 4
  704. * In this pattern we get vertice positions and normals
  705. * @param face
  706. * @param v
  707. */
  708. var setDataForCurrentFaceWithPattern4 = (face: Array<string>, v: number) => {
  709. getTriangles(face, v);
  710. for (var k = 0; k < triangles.length; k++) {
  711. //triangle[k] = "1//1"
  712. //Split the data for getting position and normals
  713. var point = triangles[k].split("//"); // ["1", "1"]
  714. // We check indices, and normals
  715. var indicePositionFromObj = parseInt(point[0]) - 1;
  716. var indiceNormalFromObj = parseInt(point[1]) - 1;
  717. setData(
  718. indicePositionFromObj,
  719. 1, //Default value for uv
  720. indiceNormalFromObj,
  721. positions[indicePositionFromObj], //Get each vector of data
  722. Vector2.Zero(),
  723. normals[indiceNormalFromObj],
  724. this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined
  725. );
  726. }
  727. //Reset variable for the next line
  728. triangles = [];
  729. };
  730. /**
  731. * Create triangles and push the data for each polygon for the pattern 3
  732. * In this pattern we get vertice positions, uvs and normals
  733. * @param face
  734. * @param v
  735. */
  736. var setDataForCurrentFaceWithPattern5 = (face: Array<string>, v: number) => {
  737. //Get the indices of triangles for each polygon
  738. getTriangles(face, v);
  739. for (var k = 0; k < triangles.length; k++) {
  740. //triangle[k] = "-1/-1/-1"
  741. //Split the data for getting position, uv, and normals
  742. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  743. // Set position indice
  744. var indicePositionFromObj = positions.length + parseInt(point[0]);
  745. // Set uv indice
  746. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  747. // Set normal indice
  748. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  749. setData(
  750. indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj,
  751. positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj], //Set the vector for each component
  752. this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined
  753. );
  754. }
  755. //Reset variable for the next line
  756. triangles = [];
  757. };
  758. var addPreviousObjMesh = () => {
  759. //Check if it is not the first mesh. Otherwise we don't have data.
  760. if (meshesFromObj.length > 0) {
  761. //Get the previous mesh for applying the data about the faces
  762. //=> in obj file, faces definition append after the name of the mesh
  763. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  764. //Set the data into Array for the mesh
  765. unwrapData();
  766. // Reverse tab. Otherwise face are displayed in the wrong sens
  767. indicesForBabylon.reverse();
  768. //Set the information for the mesh
  769. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  770. handledMesh.indices = indicesForBabylon.slice();
  771. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  772. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  773. handledMesh.uvs = unwrappedUVForBabylon.slice();
  774. if (this._meshLoadOptions.ImportVertexColors === true) {
  775. handledMesh.colors = unwrappedColorsForBabylon.slice();
  776. }
  777. //Reset the array for the next mesh
  778. indicesForBabylon = [];
  779. unwrappedPositionsForBabylon = [];
  780. unwrappedColorsForBabylon = [];
  781. unwrappedNormalsForBabylon = [];
  782. unwrappedUVForBabylon = [];
  783. }
  784. };
  785. //Main function
  786. //Split the file into lines
  787. var lines = data.split('\n');
  788. //Look at each line
  789. for (var i = 0; i < lines.length; i++) {
  790. var line = lines[i].trim();
  791. var result;
  792. //Comment or newLine
  793. if (line.length === 0 || line.charAt(0) === '#') {
  794. continue;
  795. //Get information about one position possible for the vertices
  796. } else if (this.vertexPattern.test(line)) {
  797. result = line.match(/[^ ]+/g)!; // match will return non-null due to passing regex pattern
  798. // Value of result with line: "v 1.0 2.0 3.0"
  799. // ["v", "1.0", "2.0", "3.0"]
  800. // Create a Vector3 with the position x, y, z
  801. positions.push(new Vector3(
  802. parseFloat(result[1]),
  803. parseFloat(result[2]),
  804. parseFloat(result[3])
  805. ));
  806. if (this._meshLoadOptions.ImportVertexColors === true) {
  807. if (result.length >= 7) {
  808. // TODO: if these numbers are > 1 we can use Color4.FromInts(r,g,b,a)
  809. colors.push(new Color4(
  810. parseFloat(result[4]),
  811. parseFloat(result[5]),
  812. parseFloat(result[6]),
  813. (result.length === 7 || result[7] === undefined) ? 1 : parseFloat(result[7])
  814. ));
  815. } else {
  816. // TODO: maybe push NULL and if all are NULL to skip (and remove grayColor var).
  817. colors.push(grayColor);
  818. }
  819. }
  820. } else if ((result = this.normalPattern.exec(line)) !== null) {
  821. //Create a Vector3 with the normals x, y, z
  822. //Value of result
  823. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  824. //Add the Vector in the list of normals
  825. normals.push(new Vector3(
  826. parseFloat(result[1]),
  827. parseFloat(result[2]),
  828. parseFloat(result[3])
  829. ));
  830. } else if ((result = this.uvPattern.exec(line)) !== null) {
  831. //Create a Vector2 with the normals u, v
  832. //Value of result
  833. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  834. //Add the Vector in the list of uvs
  835. uvs.push(new Vector2(
  836. parseFloat(result[1]),
  837. parseFloat(result[2])
  838. ));
  839. //Identify patterns of faces
  840. //Face could be defined in different type of pattern
  841. } else if ((result = this.facePattern3.exec(line)) !== null) {
  842. //Value of result:
  843. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  844. //Set the data for this face
  845. setDataForCurrentFaceWithPattern3(
  846. result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  847. 1
  848. );
  849. } else if ((result = this.facePattern4.exec(line)) !== null) {
  850. //Value of result:
  851. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  852. //Set the data for this face
  853. setDataForCurrentFaceWithPattern4(
  854. result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  855. 1
  856. );
  857. } else if ((result = this.facePattern5.exec(line)) !== null) {
  858. //Value of result:
  859. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  860. //Set the data for this face
  861. setDataForCurrentFaceWithPattern5(
  862. result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  863. 1
  864. );
  865. } else if ((result = this.facePattern2.exec(line)) !== null) {
  866. //Value of result:
  867. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  868. //Set the data for this face
  869. setDataForCurrentFaceWithPattern2(
  870. result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  871. 1
  872. );
  873. } else if ((result = this.facePattern1.exec(line)) !== null) {
  874. //Value of result
  875. //["f 1 2 3", "1 2 3"...]
  876. //Set the data for this face
  877. setDataForCurrentFaceWithPattern1(
  878. result[1].trim().split(" "), // ["1", "2", "3"]
  879. 1
  880. );
  881. //Define a mesh or an object
  882. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  883. } else if (this.group.test(line) || this.obj.test(line)) {
  884. //Create a new mesh corresponding to the name of the group.
  885. //Definition of the mesh
  886. var objMesh: MeshObject = {
  887. name: line.substring(2).trim(), //Set the name of the current obj mesh
  888. indices: undefined,
  889. positions: undefined,
  890. normals: undefined,
  891. uvs: undefined,
  892. colors: undefined,
  893. materialName: ""
  894. };
  895. addPreviousObjMesh();
  896. //Push the last mesh created with only the name
  897. meshesFromObj.push(objMesh);
  898. //Set this variable to indicate that now meshesFromObj has objects defined inside
  899. hasMeshes = true;
  900. isFirstMaterial = true;
  901. increment = 1;
  902. //Keyword for applying a material
  903. } else if (this.usemtl.test(line)) {
  904. //Get the name of the material
  905. materialNameFromObj = line.substring(7).trim();
  906. //If this new material is in the same mesh
  907. if (!isFirstMaterial) {
  908. //Set the data for the previous mesh
  909. addPreviousObjMesh();
  910. //Create a new mesh
  911. var objMesh: MeshObject =
  912. //Set the name of the current obj mesh
  913. {
  914. name: objMeshName + "_mm" + increment.toString(), //Set the name of the current obj mesh
  915. indices: undefined,
  916. positions: undefined,
  917. normals: undefined,
  918. uvs: undefined,
  919. colors: undefined,
  920. materialName: materialNameFromObj
  921. };
  922. increment++;
  923. //If meshes are already defined
  924. meshesFromObj.push(objMesh);
  925. }
  926. //Set the material name if the previous line define a mesh
  927. if (hasMeshes && isFirstMaterial) {
  928. //Set the material name to the previous mesh (1 material per mesh)
  929. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  930. isFirstMaterial = false;
  931. }
  932. //Keyword for loading the mtl file
  933. } else if (this.mtllib.test(line)) {
  934. //Get the name of mtl file
  935. fileToLoad = line.substring(7).trim();
  936. //Apply smoothing
  937. } else if (this.smooth.test(line)) {
  938. // smooth shading => apply smoothing
  939. //Today I don't know it work with babylon and with obj.
  940. //With the obj file an integer is set
  941. } else {
  942. //If there is another possibility
  943. console.log("Unhandled expression at line : " + line);
  944. }
  945. }
  946. //At the end of the file, add the last mesh into the meshesFromObj array
  947. if (hasMeshes) {
  948. //Set the data for the last mesh
  949. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  950. //Reverse indices for displaying faces in the good sense
  951. indicesForBabylon.reverse();
  952. //Get the good array
  953. unwrapData();
  954. //Set array
  955. handledMesh.indices = indicesForBabylon;
  956. handledMesh.positions = unwrappedPositionsForBabylon;
  957. handledMesh.normals = unwrappedNormalsForBabylon;
  958. handledMesh.uvs = unwrappedUVForBabylon;
  959. if (this._meshLoadOptions.ImportVertexColors === true) {
  960. handledMesh.colors = unwrappedColorsForBabylon;
  961. }
  962. }
  963. //If any o or g keyword found, create a mesh with a random id
  964. if (!hasMeshes) {
  965. // reverse tab of indices
  966. indicesForBabylon.reverse();
  967. //Get positions normals uvs
  968. unwrapData();
  969. //Set data for one mesh
  970. meshesFromObj.push({
  971. name: Geometry.RandomId(),
  972. indices: indicesForBabylon,
  973. positions: unwrappedPositionsForBabylon,
  974. colors: unwrappedColorsForBabylon,
  975. normals: unwrappedNormalsForBabylon,
  976. uvs: unwrappedUVForBabylon,
  977. materialName: materialNameFromObj
  978. });
  979. }
  980. //Create a Mesh list
  981. var babylonMeshesArray: Array<Mesh> = []; //The mesh for babylon
  982. var materialToUse = new Array<string>();
  983. //Set data for each mesh
  984. for (var j = 0; j < meshesFromObj.length; j++) {
  985. //check meshesNames (stlFileLoader)
  986. if (meshesNames && meshesFromObj[j].name) {
  987. if (meshesNames instanceof Array) {
  988. if (meshesNames.indexOf(meshesFromObj[j].name) === -1) {
  989. continue;
  990. }
  991. }
  992. else {
  993. if (meshesFromObj[j].name !== meshesNames) {
  994. continue;
  995. }
  996. }
  997. }
  998. //Get the current mesh
  999. //Set the data with VertexBuffer for each mesh
  1000. handledMesh = meshesFromObj[j];
  1001. //Create a Mesh with the name of the obj mesh
  1002. var babylonMesh = new Mesh(meshesFromObj[j].name, scene);
  1003. //Push the name of the material to an array
  1004. //This is indispensable for the importMesh function
  1005. materialToUse.push(meshesFromObj[j].materialName);
  1006. var vertexData: VertexData = new VertexData(); //The container for the values
  1007. //Set the data for the babylonMesh
  1008. vertexData.uvs = handledMesh.uvs as FloatArray;
  1009. vertexData.indices = handledMesh.indices as IndicesArray;
  1010. vertexData.positions = handledMesh.positions as FloatArray;
  1011. if (this._meshLoadOptions.ComputeNormals === true) {
  1012. let normals: Array<number> = new Array<number>();
  1013. VertexData.ComputeNormals(handledMesh.positions, handledMesh.indices, normals);
  1014. vertexData.normals = normals;
  1015. } else {
  1016. vertexData.normals = handledMesh.normals as FloatArray;
  1017. }
  1018. if (this._meshLoadOptions.ImportVertexColors === true) {
  1019. vertexData.colors = handledMesh.colors as FloatArray;
  1020. }
  1021. //Set the data from the VertexBuffer to the current Mesh
  1022. vertexData.applyToMesh(babylonMesh);
  1023. if (this._meshLoadOptions.InvertY) {
  1024. babylonMesh.scaling.y *= -1;
  1025. }
  1026. //Push the mesh into an array
  1027. babylonMeshesArray.push(babylonMesh);
  1028. }
  1029. let mtlPromises: Array<Promise<any>> = [];
  1030. //load the materials
  1031. //Check if we have a file to load
  1032. if (fileToLoad !== "" && this._meshLoadOptions.SkipMaterials === false) {
  1033. //Load the file synchronously
  1034. mtlPromises.push(new Promise((resolve, reject) => {
  1035. this._loadMTL(fileToLoad, rootUrl, (dataLoaded) => {
  1036. try {
  1037. //Create materials thanks MTLLoader function
  1038. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  1039. //Look at each material loaded in the mtl file
  1040. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  1041. //Three variables to get all meshes with the same material
  1042. var startIndex = 0;
  1043. var _indices = [];
  1044. var _index;
  1045. //The material from MTL file is used in the meshes loaded
  1046. //Push the indice in an array
  1047. //Check if the material is not used for another mesh
  1048. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  1049. _indices.push(_index);
  1050. startIndex = _index + 1;
  1051. }
  1052. //If the material is not used dispose it
  1053. if (_index === -1 && _indices.length === 0) {
  1054. //If the material is not needed, remove it
  1055. materialsFromMTLFile.materials[n].dispose();
  1056. } else {
  1057. for (var o = 0; o < _indices.length; o++) {
  1058. //Apply the material to the Mesh for each mesh with the material
  1059. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  1060. }
  1061. }
  1062. }
  1063. resolve();
  1064. } catch (e) {
  1065. Tools.Warn(`Error processing MTL file: '${fileToLoad}'`);
  1066. if (this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1067. resolve();
  1068. } else {
  1069. reject(e);
  1070. }
  1071. }
  1072. }, (pathOfFile: string, exception?: any) => {
  1073. Tools.Warn(`Error downloading MTL file: '${fileToLoad}'`);
  1074. if (this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1075. resolve();
  1076. } else {
  1077. reject(exception);
  1078. }
  1079. });
  1080. }));
  1081. }
  1082. //Return an array with all Mesh
  1083. return Promise.all(mtlPromises).then(() => {
  1084. return babylonMeshesArray;
  1085. });
  1086. }
  1087. }
  1088. if (SceneLoader) {
  1089. //Add this loader into the register plugin
  1090. SceneLoader.RegisterPlugin(new OBJFileLoader());
  1091. }