OBJMTLLoader.js 12 KB

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