Source: webgl-obj-loader.js

  1. /*
  2. MIT License
  3. Copyright (c) 2013 Aaron Boman and aaronboman.com
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. (/** @exports OBJ*/function (scope, undefined) {
  21. 'use strict';
  22. var OBJ = {};
  23. if (typeof module !== 'undefined') {
  24. module.exports = OBJ;
  25. } else {
  26. scope.OBJ = OBJ;
  27. }
  28. /**
  29. * @description
  30. * The main Mesh class. The constructor will parse through the OBJ file data
  31. * and collect the vertex, vertex normal, texture, and face information. This
  32. * information can then be used later on when creating your VBOs. See
  33. * OBJ.initMeshBuffers for an example of how to use the newly created Mesh.
  34. *
  35. * @memberOf module:OBJ
  36. * @constructor
  37. *
  38. * @param {String} objectData A string representation of an OBJ file with newlines preserved
  39. * @param name Name of the loaded OBJ file
  40. */
  41. OBJ.Mesh = function (objectData, name) {
  42. /*
  43. The OBJ file format does a sort of compression when saving a object in a
  44. program like Blender. There are at least 3 sections (4 including textures)
  45. within the file. Each line in a section begins with the same string:
  46. * 'v': indicates vertex section
  47. * 'vn': indicates vertex normal section
  48. * 'f': indicates the faces section
  49. * 'vt': indicates vertex texture section (if textures were used on the object)
  50. Each of the above sections (except for the faces section) is a list/set of
  51. unique vertices.
  52. Each line of the faces section contains a list of
  53. (vertex, [texture], normal) groups
  54. Some examples:
  55. // the texture index is optional, both formats are possible for models
  56. // without a texture applied
  57. f 1/25 18/46 12/31
  58. f 1//25 18//46 12//31
  59. // A 3 vertex face with texture indices
  60. f 16/92/11 14/101/22 1/69/1
  61. // A 4 vertex face
  62. f 16/92/11 40/109/40 38/114/38 14/101/22
  63. The first two lines are examples of a 3 vertex face without a texture applied.
  64. The second is an example of a 3 vertex face with a texture applied.
  65. The third is an example of a 4 vertex face. Note: a face can contain N
  66. number of vertices.
  67. Each number that appears in one of the groups is a 1-based index
  68. corresponding to an item from the other sections (meaning that indexing
  69. starts at one and *not* zero).
  70. For example:
  71. `f 16/92/11` is saying to
  72. - take the 16th element from the [v] vertex array
  73. - take the 92nd element from the [vt] texture array
  74. - take the 11th element from the [vn] normal array
  75. and together they make a unique vertex.
  76. Using all 3+ unique Vertices from the face line will produce a polygon.
  77. Now, you could just go through the OBJ file and create a new vertex for
  78. each face line and WebGL will draw what appears to be the same object.
  79. However, vertices will be overlapped and duplicated all over the place.
  80. Consider a cube in 3D space centered about the origin and each side is
  81. 2 units long. The front face (with the positive Z-axis pointing towards
  82. you) would have a Top Right vertex (looking orthogonal to its normal)
  83. mapped at (1,1,1) The right face would have a Top Left vertex (looking
  84. orthogonal to its normal) at (1,1,1) and the top face would have a Bottom
  85. Right vertex (looking orthogonal to its normal) at (1,1,1). Each face
  86. has a vertex at the same coordinates, however, three distinct vertices
  87. will be drawn at the same spot.
  88. To solve the issue of duplicate Vertices (the `(vertex, [texture], normal)`
  89. groups), while iterating through the face lines, when a group is encountered
  90. the whole group string ('16/92/11') is checked to see if it exists in the
  91. packed.hashindices object, and if it doesn't, the indices it specifies
  92. are used to look up each attribute in the corresponding attribute arrays
  93. already created. The values are then copied to the corresponding unpacked
  94. array (flattened to play nice with WebGL's ELEMENT_ARRAY_BUFFER indexing),
  95. the group string is added to the hashindices set and the current unpacked
  96. index is used as this hashindices value so that the group of elements can
  97. be reused. The unpacked index is incremented. If the group string already
  98. exists in the hashindices object, its corresponding value is the index of
  99. that group and is appended to the unpacked indices array.
  100. */
  101. var verts = [], vertNormals = [], textures = [], unpacked = {};
  102. // unpacking stuff
  103. unpacked.verts = [];
  104. unpacked.norms = [];
  105. unpacked.textures = [];
  106. unpacked.hashindices = {};
  107. unpacked.indices = [];
  108. unpacked.index = 0;
  109. // array of lines separated by the newline
  110. var lines = objectData.split('\n');
  111. var VERTEX_RE = /^v\s/;
  112. var NORMAL_RE = /^vn\s/;
  113. var TEXTURE_RE = /^vt\s/;
  114. var FACE_RE = /^f\s/;
  115. var WHITESPACE_RE = /\s+/;
  116. for (var i = 0; i < lines.length; i++) {
  117. var line = lines[i].trim();
  118. var elements = line.split(WHITESPACE_RE);
  119. elements.shift();
  120. if (VERTEX_RE.test(line)) {
  121. // if this is a vertex
  122. verts.push.apply(verts, elements);
  123. // writeLog("its a vertex");
  124. } else if (NORMAL_RE.test(line)) {
  125. // if this is a vertex normal
  126. vertNormals.push.apply(vertNormals, elements);
  127. } else if (TEXTURE_RE.test(line)) {
  128. // if this is a texture
  129. textures.push.apply(textures, elements);
  130. } else if (FACE_RE.test(line)) {
  131. // if this is a face
  132. /*
  133. split this face into an array of vertex groups
  134. for example:
  135. f 16/92/11 14/101/22 1/69/1
  136. becomes:
  137. ['16/92/11', '14/101/22', '1/69/1'];
  138. */
  139. var quad = false;
  140. for (var j = 0, eleLen = elements.length; j < eleLen; j++) {
  141. // Triangulating quads
  142. // quad: 'f v0/t0/vn0 v1/t1/vn1 v2/t2/vn2 v3/t3/vn3/'
  143. // corresponding triangles:
  144. // 'f v0/t0/vn0 v1/t1/vn1 v2/t2/vn2'
  145. // 'f v2/t2/vn2 v3/t3/vn3 v0/t0/vn0'
  146. if (j === 3 && !quad) {
  147. // add v2/t2/vn2 in again before continuing to 3
  148. j = 2;
  149. quad = true;
  150. }
  151. if (elements[j] in unpacked.hashindices) {
  152. unpacked.indices.push(unpacked.hashindices[elements[j]]);
  153. }
  154. else {
  155. /*
  156. Each element of the face line array is a vertex which has its
  157. attributes delimited by a forward slash. This will separate
  158. each attribute into another array:
  159. '19/92/11'
  160. becomes:
  161. vertex = ['19', '92', '11'];
  162. where
  163. vertex[0] is the vertex index
  164. vertex[1] is the texture index
  165. vertex[2] is the normal index
  166. Think of faces having Vertices which are comprised of the
  167. attributes location (v), texture (vt), and normal (vn).
  168. */
  169. var vertex = elements[j].split('/');
  170. /*
  171. The verts, textures, and vertNormals arrays each contain a
  172. flattend array of coordinates.
  173. Because it gets confusing by referring to vertex and then
  174. vertex (both are different in my descriptions) I will explain
  175. what's going on using the vertexNormals array:
  176. vertex[2] will contain the one-based index of the vertexNormals
  177. section (vn). One is subtracted from this index number to play
  178. nice with javascript's zero-based array indexing.
  179. Because vertexNormal is a flattened array of x, y, z values,
  180. simple pointer arithmetic is used to skip to the start of the
  181. vertexNormal, then the offset is added to get the correct
  182. component: +0 is x, +1 is y, +2 is z.
  183. This same process is repeated for verts and textures.
  184. */
  185. // vertex position
  186. unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + 0]);
  187. unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + 1]);
  188. unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + 2]);
  189. // vertex textures
  190. if (textures.length) {
  191. unpacked.textures.push(+textures[(vertex[1] - 1) * 2 + 0]);
  192. unpacked.textures.push(+textures[(vertex[1] - 1) * 2 + 1]);
  193. }
  194. // vertex normals
  195. unpacked.norms.push(+vertNormals[(vertex[2] - 1) * 3 + 0]);
  196. unpacked.norms.push(+vertNormals[(vertex[2] - 1) * 3 + 1]);
  197. unpacked.norms.push(+vertNormals[(vertex[2] - 1) * 3 + 2]);
  198. // add the newly created vertex to the list of indices
  199. unpacked.hashindices[elements[j]] = unpacked.index;
  200. unpacked.indices.push(unpacked.index);
  201. // increment the counter
  202. unpacked.index += 1;
  203. }
  204. if (j === 3 && quad) {
  205. // add v0/t0/vn0 onto the second triangle
  206. unpacked.indices.push(unpacked.hashindices[elements[0]]);
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * @description Array contains Vertex Position Coordinates (does not include w).
  213. * @type {Array}
  214. *
  215. */
  216. this.vertices = unpacked.verts;
  217. /**
  218. * @description Array contains the Vertex Normals.
  219. * @type {Array}
  220. *
  221. */
  222. this.vertexNormals = unpacked.norms;
  223. /**
  224. * @description Array contains the Texture Coordinates.
  225. * @type {Array}
  226. *
  227. */
  228. this.textures = unpacked.textures;
  229. /**
  230. * @description Array contains the indices of the faces.
  231. * @type {Array}
  232. *
  233. */
  234. this.indices = unpacked.indices;
  235. /**
  236. * @description Name of the Mesh.
  237. * @type {String}
  238. *
  239. */
  240. this.name = name;
  241. };
  242. /*
  243. function handleFileSelect(evt) {
  244. var reader = new FileReader();
  245. reader.onload = function(e) {
  246. console.log(reader.result);
  247. };
  248. reader.readAsText(this.files[0]);
  249. }
  250. $(document).ready(function () {
  251. $('#file').change(handleFileSelect);
  252. });
  253. */
  254. var loader = function () {
  255. var _this = this;
  256. this.request = new XMLHttpRequest();
  257. try {
  258. _this.request.responseType = 'text';
  259. } catch (e) {
  260. }
  261. this.get = function(url, callback) {
  262. _this.request.onreadystatechange = function () {
  263. if (_this.request.readyState === 4) {
  264. callback(_this.request.responseText, _this.request.status);
  265. }
  266. };
  267. _this.request.open("GET", url, true);
  268. _this.request.send();
  269. }
  270. };
  271. var Ajax = function () {
  272. // this is just a helper class to ease ajax calls
  273. var _this = this;
  274. this.xmlhttp = new XMLHttpRequest();
  275. this.get = function (url, callback) {
  276. _this.xmlhttp.onreadystatechange = function () {
  277. if (_this.xmlhttp.readyState === 4) {
  278. callback(_this.xmlhttp.responseText, _this.xmlhttp.status);
  279. }
  280. };
  281. _this.xmlhttp.open('GET', url, true);
  282. _this.xmlhttp.send();
  283. }
  284. };
  285. /**
  286. * @description
  287. * Takes in an object of 'mesh_name': 'src/object/[objectName].obj' pairs and a callback
  288. * function. Each OBJ file will be ajaxed in and automatically converted to
  289. * an OBJ.Mesh. When all files have successfully downloaded the callback
  290. * function provided will be called and passed in an object containing
  291. * the newly created meshes.
  292. *
  293. * <pre>
  294. * Note: Cross Origin Resource Sharing (CORS) is NOT enabled for loading objects. You can not download obj files from other domains.
  295. *
  296. * Note: In order to use this function as a way to download objects, a webserver of some sort must be used.
  297. *
  298. * The newly created Javascript-Arrays for each loaded Object are:
  299. * <pre>
  300. * Javascript-Array | Description
  301. * vertexNormals | contains the Vertex Normals
  302. * ___________________________________________________________________________________________________
  303. * textures | contains the Texture Coordinates
  304. * ___________________________________________________________________________________________________
  305. * vertices | contains the Vertex Position Coordinates (does not include w)
  306. * ___________________________________________________________________________________________________
  307. * indices | contains the indices of the faces
  308. * </pre>
  309. *
  310. * The URL path for loading objects provided by the Editor always begins with: 'src/object/[objectName].obj'. A list of all available objects within
  311. * the editor can be seen in the menu under sources -> object.
  312. *
  313. * @memberOf module:OBJ
  314. * @param {Object} nameAndURLs an object where the key is the name of the mesh and the value is the url to that mesh's OBJ file
  315. *
  316. * @param {Function} completionCallback should contain a function that will take one parameter: an object array where the keys will be the unique object name and the value will be a Mesh object
  317. *
  318. * @param {Object} meshes In case other meshes are loaded separately or if a previously declared variable is desired to be used, pass in a (possibly empty) json object of the pattern: { '< mesh_name >': OBJ.Mesh }
  319. *
  320. */
  321. OBJ.downloadMeshes = function (nameAndURLs, completionCallback, meshes) {
  322. _OBJisLoading = true;
  323. var target = document.getElementById('canvasBody');
  324. EDITOR._spinner.spin(target);
  325. // the total number of meshes. this is used to implement "blocking"
  326. var semaphore = Object.keys(nameAndURLs).length;
  327. // if error is true, an alert will given
  328. var error = false;
  329. // this is used to check if all meshes have been downloaded
  330. // if meshes is supplied, then it will be populated, otherwise
  331. // a new object is created. this will be passed into the completionCallback
  332. if (meshes === undefined) meshes = {};
  333. // loop over the mesh_name,url key,value pairs
  334. for (var mesh_name in nameAndURLs) {
  335. if (nameAndURLs.hasOwnProperty(mesh_name)) {
  336. new Ajax().get(nameAndURLs[mesh_name], (function (name) {
  337. writeLog("Loading mesh: " + name + ".");
  338. return function (data, status) {
  339. if (status === 200) {
  340. meshes[name] = new OBJ.Mesh(data, name);
  341. }
  342. else {
  343. error = true;
  344. EDITOR.writeError('An error has occurred and the mesh "' +
  345. name + '" could not be downloaded.');
  346. EDITOR._spinner.stop();
  347. }
  348. // the request has finished, decrement the counter
  349. semaphore--;
  350. if (semaphore === 0) {
  351. if (error) {
  352. // if an error has occurred, the user is notified here and the callback is not called
  353. EDITOR.writeError("The provided URL path may be wrong.");
  354. EDITOR.writeError("----------------------------------------------------------");
  355. EDITOR.writeError("The URL path for loading objects provided by the editor always begins with: './src/object/[objectName].obj'.");
  356. EDITOR.writeError("A list of all available objects within the editor can be seen in the menu.");
  357. EDITOR.writeError("----------------------------------------------------------");
  358. EDITOR.writeSystemMessage("Note: Cross Origin Resource Sharing (CORS) is NOT enabled.");
  359. EDITOR._spinner.stop();
  360. // throw '';
  361. }
  362. // checking for _OBJisLoading because if you smash the run button or going to quickly into fullscreen and back would cause a multiple requestAnimationFrame
  363. //FOLLOWING CODE WAS ADDED FOR THE WEBGL-EDITOR
  364. if (!EDITOR._error && !EDITOR._shaderError && EDITOR._run && _OBJisLoading) {
  365. EDITOR.writeCompletionMessage("Finished loading meshes.");
  366. for (var mesh_name in meshes) {
  367. writeLog("------------------------------------------------");
  368. writeLog("Mesh: " + meshes[mesh_name].name);
  369. writeLog("Vertices:" + meshes[mesh_name].vertices.length / 3);
  370. writeLog("Vertex normals:" + meshes[mesh_name].vertexNormals.length / 3);
  371. writeLog("Texture coordinates:" + meshes[mesh_name].textures.length / 2);
  372. writeLog("Indices:" + meshes[mesh_name].indices.length);
  373. }
  374. if (!_TEXisLoading) {
  375. EDITOR._spinner.stop();
  376. }
  377. // there haven't been any errors in retrieving the meshes
  378. // call the callback
  379. completionCallback(meshes);
  380. _OBJisLoading = false;
  381. /* if(!_TEXisLoading)
  382. renderLoop();*/
  383. } else {
  384. EDITOR._spinner.stop();
  385. }
  386. }
  387. }
  388. })(mesh_name));
  389. }
  390. }
  391. };
  392. var _buildBuffer = function (gl, type, data, itemSize) {
  393. var buffer = gl.createBuffer();
  394. var arrayView = type === gl.ARRAY_BUFFER ? Float32Array : Uint16Array;
  395. gl.bindBuffer(type, buffer);
  396. gl.bufferData(type, new arrayView(data), gl.STATIC_DRAW);
  397. buffer.itemSize = itemSize;
  398. buffer.numItems = data.length / itemSize;
  399. return buffer;
  400. };
  401. /**
  402. * @description
  403. * Takes in the WebGL context and a Mesh, then creates and appends the buffers
  404. * to the mesh object as attributes.
  405. *
  406. * The newly created mesh attributes are:
  407. *<pre>
  408. * Attribute | Description
  409. * normalBuffer | contains the Vertex Normals
  410. * normalBuffer.itemSize | set to 3 items
  411. * normalBuffer.numItems | the total number of vertex normals
  412. * ___________________________________________________________________________________________________
  413. * textureBuffer | contains the Texture Coordinates
  414. * textureBuffer.itemSize | set to 2 items
  415. * textureBuffer.numItems | the number of texture coordinates
  416. * ___________________________________________________________________________________________________
  417. * vertexBuffer | contains the Vertex Position Coordinates (does not include w)
  418. * vertexBuffer.itemSize | set to 3 items
  419. * vertexBuffer.numItems | the total number of vertices
  420. * ___________________________________________________________________________________________________
  421. * indexBuffer | contains the indices of the faces
  422. * indexBuffer.itemSize | is set to 1
  423. * indexBuffer.numItems | the total number of indices
  424. *</pre>
  425. * @memberOf module:OBJ
  426. * @param {WebGLRenderingContext} gl the 'canvas.getContext('webgl')' context instance
  427. * @param {Mesh} mesh a single 'OBJ.Mesh' instance
  428. */
  429. OBJ.initMeshBuffers = function (gl, mesh) {
  430. //FOLLOWING ERROR HANDLING WAS ADDED FOR THE WEBGL-EDITOR
  431. if (mesh === undefined) {
  432. EDITOR.writeError("Initalization of mesh buffers failed.");
  433. EDITOR.writeError("OBJ.initMeshBuffers(gl, undefined)");
  434. } else {
  435. mesh.normalBuffer = _buildBuffer(gl, gl.ARRAY_BUFFER, mesh.vertexNormals, 3);
  436. mesh.textureBuffer = _buildBuffer(gl, gl.ARRAY_BUFFER, mesh.textures, 2);
  437. mesh.vertexBuffer = _buildBuffer(gl, gl.ARRAY_BUFFER, mesh.vertices, 3);
  438. mesh.indexBuffer = _buildBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, mesh.indices, 1);
  439. }
  440. };
  441. /**
  442. * Takes in the WebGL context and a Mesh. Deletes the mesh's buffers,
  443. * which you would do when deleting an object from a scene so that you don't leak video memory.
  444. * Excessive buffer creation and deletion leads to video memory fragmentation. Beware.
  445. *
  446. * The deleted texture attributes are:
  447. *<pre>
  448. * Attribute | Description
  449. * normalBuffer | contains the Vertex Normals
  450. * normalBuffer.itemSize | set to 3 items
  451. * normalBuffer.numItems | the total number of vertex normals
  452. * ___________________________________________________________________________________________________
  453. * textureBuffer | contains the Texture Coordinates
  454. * textureBuffer.itemSize | set to 2 items
  455. * textureBuffer.numItems | the number of texture coordinates
  456. * ___________________________________________________________________________________________________
  457. * vertexBuffer | contains the Vertex Position Coordinates (does not include w)
  458. * vertexBuffer.itemSize | set to 3 items
  459. * vertexBuffer.numItems | the total number of vertices
  460. * ___________________________________________________________________________________________________
  461. * indexBuffer | contains the indices of the faces
  462. * indexBuffer.itemSize | is set to 1
  463. * indexBuffer.numItems | the total number of indices
  464. * </pre>
  465. *
  466. * @memberOf module:OBJ
  467. * @param {WebGLRenderingContext} gl the 'canvas.getContext('webgl')' context instance
  468. * @param {Mesh} mesh a single 'OBJ.Mesh' instance
  469. **/
  470. OBJ.deleteMeshBuffers = function (gl, mesh) {
  471. //FOLLOWING ERROR HANDLING WAS ADDED FOR THE WEBGL-EDITOR
  472. if (mesh === undefined) {
  473. EDITOR._error = true;
  474. EDITOR.writeError("Deletion of mesh buffers failed.");
  475. EDITOR.writeError("OBJ.deleteMeshBuffers(gl, undefined)");
  476. } else {
  477. gl.deleteBuffer(mesh.normalBuffer);
  478. gl.deleteBuffer(mesh.textureBuffer);
  479. gl.deleteBuffer(mesh.vertexBuffer);
  480. gl.deleteBuffer(mesh.indexBuffer);
  481. }
  482. };
  483. })(this);