OBJMTLLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /**
  2. * Loads a Wavefront .obj file with materials
  3. *
  4. * @author mrdoob / http://mrdoob.com/
  5. * @author angelxuanchang
  6. */
  7. THREE.OBJMTLLoader = function ( ) {
  8. THREE.EventTarget.call( this );
  9. };
  10. THREE.OBJMTLLoader.prototype = {
  11. constructor: THREE.OBJMTLLoader,
  12. /**
  13. * Load a Wavefront OBJ file with materials (MTL file)
  14. *
  15. * Loading progress is indicated by the following events:
  16. * "load" event (successful loading): type = 'load', content = THREE.Object3D
  17. * "error" event (error loading): type = 'load', message
  18. * "progress" event (progress loading): type = 'progress', loaded, total
  19. *
  20. * If the MTL file cannot be loaded, then a MeshLambertMaterial is used as a default
  21. * @param url - Location of OBJ file to load
  22. * @param mtlfileurl - MTL file to load (optional, if not specified, attempts to use MTL specified in OBJ file)
  23. * @param options - Options on how to interpret the material (see THREE.MTLLoader.MaterialCreator )
  24. *
  25. */
  26. load: function ( url, mtlfileurl, options ) {
  27. var scope = this;
  28. var xhr = new XMLHttpRequest();
  29. var mtlDone; // Is the MTL done (true if no MTL, error loading MTL, or MTL actually loaded)
  30. var obj3d; // Loaded model (from obj file)
  31. var materialsCreator; // Material creator is created when MTL file is loaded
  32. // Loader for MTL
  33. var mtlLoader = new THREE.MTLLoader(url.substr(0,url.lastIndexOf("/")+1), options);
  34. mtlLoader.addEventListener( 'load', waitReady );
  35. mtlLoader.addEventListener( 'error', waitReady );
  36. // Try to load mtlfile
  37. if (mtlfileurl) {
  38. mtlLoader.load(mtlfileurl);
  39. mtlDone = false;
  40. } else {
  41. mtlDone = true;
  42. }
  43. function waitReady(event) {
  44. if (event.type === 'load') {
  45. if (event.content instanceof THREE.MTLLoader.MaterialCreator) {
  46. // MTL file is loaded
  47. mtlDone = true;
  48. materialsCreator = event.content;
  49. materialsCreator.preload();
  50. } else {
  51. // OBJ file is loaded
  52. if (event.target.status == 200 || event.target.status == 0) {
  53. var objContent = event.target.responseText;
  54. if (mtlfileurl) {
  55. // Parse with passed in MTL file
  56. obj3d = scope.parse(objContent);
  57. } else {
  58. // No passed in MTL file, look for mtlfile in obj file
  59. obj3d = scope.parse(objContent, function(mtlfile) {
  60. mtlDone = false;
  61. mtlLoader.load(mtlLoader.baseUrl + mtlfile);
  62. });
  63. }
  64. } else {
  65. // Error loading OBJ file....
  66. scope.dispatchEvent( {
  67. type: 'error',
  68. message: 'Couldn\'t load URL [' + url + ']',
  69. response: event.target.responseText } );
  70. }
  71. }
  72. } else if (event.type === 'error') {
  73. // MTL failed to load -- oh well, we will just not have material...
  74. mtlDone = true;
  75. }
  76. if (mtlDone && obj3d) {
  77. // MTL file is loaded and OBJ file is loaded
  78. // Apply materials to model
  79. if (materialsCreator) {
  80. THREE.SceneUtils.traverseHierarchy(
  81. obj3d, function(node) {
  82. if (node instanceof THREE.Mesh) {
  83. if (node.material.name) {
  84. var material = materialsCreator.create(node.material.name);
  85. if (material) node.material = material;
  86. }
  87. }
  88. }
  89. )
  90. }
  91. // Notify listeners
  92. scope.dispatchEvent( { type: 'load', content: obj3d } );
  93. }
  94. }
  95. xhr.addEventListener( 'load', waitReady, false );
  96. xhr.addEventListener( 'progress', function ( event ) {
  97. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  98. }, false );
  99. xhr.addEventListener( 'error', function () {
  100. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  101. }, false );
  102. xhr.open( 'GET', url, true );
  103. xhr.send( null );
  104. },
  105. /**
  106. * Parses loaded .obj file
  107. * @param data - content of .obj file
  108. * @param mtllibCallback - callback to handle mtllib declaration (optional)
  109. * @return {THREE.Object3D} - Object3D (with default material)
  110. */
  111. parse: function ( data, mtllibCallback ) {
  112. function vector( x, y, z ) {
  113. return new THREE.Vector3( x, y, z );
  114. }
  115. function uv( u, v ) {
  116. return new THREE.UV( u, v );
  117. }
  118. function face3( a, b, c, normals ) {
  119. return new THREE.Face3( a, b, c, normals );
  120. }
  121. function face4( a, b, c, d, normals ) {
  122. return new THREE.Face4( a, b, c, d, normals );
  123. }
  124. function finalize_mesh( group, mesh_info ) {
  125. mesh_info.geometry.computeCentroids();
  126. mesh_info.geometry.computeFaceNormals();
  127. mesh_info.geometry.computeBoundingSphere();
  128. group.add( new THREE.Mesh( mesh_info.geometry, mesh_info.material ) );
  129. }
  130. var vertices = [];
  131. var normals = [];
  132. var uvs = [];
  133. // v float float float
  134. var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/;
  135. // vn float float float
  136. var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/;
  137. // vt float float
  138. var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( [\d|\.|\+|\-|e]+)/;
  139. // f vertex vertex vertex ...
  140. var face_pattern1 = /f( +[\d]+)( [\d]+)( [\d]+)( [\d]+)?/;
  141. // f vertex/uv vertex/uv vertex/uv ...
  142. var face_pattern2 = /f( +([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))( ([\d]+)\/([\d]+))?/;
  143. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal ...
  144. var face_pattern3 = /f( +([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))( ([\d]+)\/([\d]+)\/([\d]+))?/;
  145. // f vertex//normal vertex//normal vertex//normal ...
  146. var face_pattern4 = /f( +([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))( ([\d]+)\/\/([\d]+))?/;
  147. var final_model = new THREE.Object3D();
  148. var geometry = new THREE.Geometry();
  149. geometry.vertices = vertices;
  150. var cur_mesh = {
  151. material: new THREE.MeshLambertMaterial(),
  152. geometry: geometry
  153. };
  154. var lines = data.split("\n");
  155. for (var i = 0; i < lines.length; i++) {
  156. var line = lines[i];
  157. line = $.trim(line);
  158. // temporary variable storing pattern matching result
  159. var result;
  160. if (line.length === 0 || line.charAt(0) === '#') {
  161. continue;
  162. } else if ((result = vertex_pattern.exec(line)) != null) {
  163. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  164. vertices.push( vector(
  165. parseFloat( result[ 1 ] ),
  166. parseFloat( result[ 2 ] ),
  167. parseFloat( result[ 3 ] )
  168. ) );
  169. } else if ((result = normal_pattern.exec(line)) != null) {
  170. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  171. normals.push( vector(
  172. parseFloat( result[ 1 ] ),
  173. parseFloat( result[ 2 ] ),
  174. parseFloat( result[ 3 ] )
  175. ) );
  176. } else if (( result = uv_pattern.exec(line)) != null) {
  177. // ["vt 0.1 0.2", "0.1", "0.2"]
  178. uvs.push( uv(
  179. parseFloat( result[ 1 ] ),
  180. parseFloat( result[ 2 ] )
  181. ) );
  182. } else if (( result = face_pattern1.exec( line ) ) != null ) {
  183. // ["f 1 2 3", "1", "2", "3", undefined]
  184. if ( result[ 4 ] === undefined ) {
  185. geometry.faces.push( face3(
  186. parseInt( result[ 1 ] ) - 1,
  187. parseInt( result[ 2 ] ) - 1,
  188. parseInt( result[ 3 ] ) - 1
  189. ) );
  190. } else {
  191. geometry.faces.push( face4(
  192. parseInt( result[ 1 ] ) - 1,
  193. parseInt( result[ 2 ] ) - 1,
  194. parseInt( result[ 3 ] ) - 1,
  195. parseInt( result[ 4 ] ) - 1
  196. ) );
  197. }
  198. } else if ( ( result = face_pattern2.exec( line ) ) != null ) {
  199. // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined]
  200. if ( result[ 10 ] === undefined ) {
  201. geometry.faces.push( face3(
  202. parseInt( result[ 2 ] ) - 1,
  203. parseInt( result[ 5 ] ) - 1,
  204. parseInt( result[ 8 ] ) - 1
  205. ) );
  206. geometry.faceVertexUvs[ 0 ].push( [
  207. uvs[ parseInt( result[ 3 ] ) - 1 ],
  208. uvs[ parseInt( result[ 6 ] ) - 1 ],
  209. uvs[ parseInt( result[ 9 ] ) - 1 ]
  210. ] );
  211. } else {
  212. geometry.faces.push( face4(
  213. parseInt( result[ 2 ] ) - 1,
  214. parseInt( result[ 5 ] ) - 1,
  215. parseInt( result[ 8 ] ) - 1,
  216. parseInt( result[ 11 ] ) - 1
  217. ) );
  218. geometry.faceVertexUvs[ 0 ].push( [
  219. uvs[ parseInt( result[ 3 ] ) - 1 ],
  220. uvs[ parseInt( result[ 6 ] ) - 1 ],
  221. uvs[ parseInt( result[ 9 ] ) - 1 ],
  222. uvs[ parseInt( result[ 12 ] ) - 1 ]
  223. ] );
  224. }
  225. } else if ( ( result = face_pattern3.exec( line ) ) != null ) {
  226. // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined]
  227. if ( result[ 13 ] === undefined ) {
  228. geometry.faces.push( face3(
  229. parseInt( result[ 2 ] ) - 1,
  230. parseInt( result[ 6 ] ) - 1,
  231. parseInt( result[ 10 ] ) - 1,
  232. [
  233. normals[ parseInt( result[ 4 ] ) - 1 ],
  234. normals[ parseInt( result[ 8 ] ) - 1 ],
  235. normals[ parseInt( result[ 12 ] ) - 1 ]
  236. ]
  237. ) );
  238. geometry.faceVertexUvs[ 0 ].push( [
  239. uvs[ parseInt( result[ 3 ] ) - 1 ],
  240. uvs[ parseInt( result[ 7 ] ) - 1 ],
  241. uvs[ parseInt( result[ 11 ] ) - 1 ]
  242. ] );
  243. } else {
  244. geometry.faces.push( face4(
  245. parseInt( result[ 2 ] ) - 1,
  246. parseInt( result[ 6 ] ) - 1,
  247. parseInt( result[ 10 ] ) - 1,
  248. parseInt( result[ 14 ] ) - 1,
  249. [
  250. normals[ parseInt( result[ 4 ] ) - 1 ],
  251. normals[ parseInt( result[ 8 ] ) - 1 ],
  252. normals[ parseInt( result[ 12 ] ) - 1 ],
  253. normals[ parseInt( result[ 16 ] ) - 1 ]
  254. ]
  255. ) );
  256. geometry.faceVertexUvs[ 0 ].push( [
  257. uvs[ parseInt( result[ 3 ] ) - 1 ],
  258. uvs[ parseInt( result[ 7 ] ) - 1 ],
  259. uvs[ parseInt( result[ 11 ] ) - 1 ],
  260. uvs[ parseInt( result[ 15 ] ) - 1 ]
  261. ] );
  262. }
  263. } else if ( ( result = face_pattern4.exec( line ) ) != null ) {
  264. // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined]
  265. if ( result[ 10 ] === undefined ) {
  266. geometry.faces.push( face3(
  267. parseInt( result[ 2 ] ) - 1,
  268. parseInt( result[ 5 ] ) - 1,
  269. parseInt( result[ 8 ] ) - 1,
  270. [
  271. normals[ parseInt( result[ 3 ] ) - 1 ],
  272. normals[ parseInt( result[ 6 ] ) - 1 ],
  273. normals[ parseInt( result[ 9 ] ) - 1 ]
  274. ]
  275. ) );
  276. } else {
  277. geometry.faces.push( face4(
  278. parseInt( result[ 2 ] ) - 1,
  279. parseInt( result[ 5 ] ) - 1,
  280. parseInt( result[ 8 ] ) - 1,
  281. parseInt( result[ 11 ] ) - 1,
  282. [
  283. normals[ parseInt( result[ 3 ] ) - 1 ],
  284. normals[ parseInt( result[ 6 ] ) - 1 ],
  285. normals[ parseInt( result[ 9 ] ) - 1 ],
  286. normals[ parseInt( result[ 12 ] ) - 1 ]
  287. ]
  288. ) );
  289. }
  290. } else if (line.startsWith("usemtl ")) {
  291. var material_name = line.substring(7);
  292. material_name = $.trim(material_name);
  293. var material = new THREE.MeshLambertMaterial();
  294. material.name = material_name;
  295. if (geometry.faces.length > 0) {
  296. // Finalize previous geometry and add to model
  297. finalize_mesh(final_model, cur_mesh);
  298. geometry = new THREE.Geometry();
  299. geometry.vertices = vertices;
  300. cur_mesh = {
  301. geometry: geometry
  302. };
  303. }
  304. cur_mesh.material = material;
  305. //material_index = materialsCreator.getIndex(material_name);
  306. } else if (line.startsWith("g ")) {
  307. // Polygon group for object
  308. var group_name = line.substring(2);
  309. group_name = $.trim(group_name);
  310. } else if (line.startsWith("o ")) {
  311. // Object
  312. var object_name = line.substring(2);
  313. object_name = $.trim(object_name);
  314. } else if (line.startsWith("s ")) {
  315. // Smooth shading
  316. } else if (line.startsWith("mtllib ")) {
  317. // mtl file
  318. if (mtllibCallback) {
  319. var mtlfile = line.substring(7);
  320. mtlfile = $.trim(mtlfile);
  321. mtllibCallback(mtlfile);
  322. }
  323. } else {
  324. console.error("Unhandled line " + line);
  325. }
  326. }
  327. finalize_mesh(final_model, cur_mesh);
  328. return final_model;
  329. }
  330. };
  331. if (typeof String.prototype.startsWith != 'function') {
  332. String.prototype.startsWith = function (str){
  333. return this.slice(0, str.length) == str;
  334. };
  335. }