OBJLoader.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.OBJLoader = function ( manager ) {
  5. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6. this.materials = null;
  7. this.regexp = {
  8. // v float float float
  9. vertex_pattern : /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  10. // vn float float float
  11. normal_pattern : /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  12. // vt float float
  13. uv_pattern : /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  14. // f vertex vertex vertex
  15. face_vertex : /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
  16. // f vertex/uv vertex/uv vertex/uv
  17. face_vertex_uv : /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
  18. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  19. face_vertex_uv_normal : /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
  20. // f vertex//normal vertex//normal vertex//normal
  21. face_vertex_normal : /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
  22. // o object_name | g group_name
  23. object_pattern : /^[og]\s*(.+)?/,
  24. // s boolean
  25. smoothing_pattern : /^s\s+(\d+|on|off)/,
  26. // mtllib file_reference
  27. material_library_pattern : /^mtllib /,
  28. // usemtl material_name
  29. material_use_pattern : /^usemtl /
  30. };
  31. };
  32. THREE.OBJLoader.prototype = {
  33. constructor: THREE.OBJLoader,
  34. load: function ( url, onLoad, onProgress, onError ) {
  35. var scope = this;
  36. var loader = new THREE.XHRLoader( scope.manager );
  37. loader.setPath( this.path );
  38. loader.load( url, function ( text ) {
  39. onLoad( scope.parse( text ) );
  40. }, onProgress, onError );
  41. },
  42. setPath: function ( value ) {
  43. this.path = value;
  44. },
  45. setMaterials: function ( materials ) {
  46. this.materials = materials;
  47. },
  48. _createParserState : function () {
  49. var state = {
  50. objects : [],
  51. object : {},
  52. vertices : [],
  53. normals : [],
  54. uvs : [],
  55. materialLibraries : [],
  56. startObject: function ( name, fromDeclaration ) {
  57. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  58. // file. We need to use it for the first parsed g/o to keep things in sync.
  59. if ( this.object && this.object.fromDeclaration === false ) {
  60. this.object.name = name;
  61. this.object.fromDeclaration = ( fromDeclaration !== false );
  62. return;
  63. }
  64. if ( this.object && typeof this.object._finalize === 'function' ) {
  65. this.object._finalize();
  66. }
  67. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  68. this.object = {
  69. name : name || '',
  70. fromDeclaration : ( fromDeclaration !== false ),
  71. geometry : {
  72. vertices : [],
  73. normals : [],
  74. uvs : []
  75. },
  76. materials : [],
  77. smooth : true,
  78. startMaterial : function( name, libraries ) {
  79. var previous = this._finalize( false );
  80. // New usemtl declaration overwrites an inherited material, except if faces were declared
  81. // after the material, then it must be preserved for proper MultiMaterial continuation.
  82. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  83. this.materials.splice( previous.index, 1 );
  84. }
  85. var material = {
  86. index : this.materials.length,
  87. name : name || '',
  88. mtllib : ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  89. smooth : ( previous !== undefined ? previous.smooth : this.smooth ),
  90. groupStart : ( previous !== undefined ? previous.groupEnd : 0 ),
  91. groupEnd : -1,
  92. groupCount : -1,
  93. inherited : false,
  94. clone : function( index ) {
  95. return {
  96. index : ( typeof index === 'number' ? index : this.index ),
  97. name : this.name,
  98. mtllib : this.mtllib,
  99. smooth : this.smooth,
  100. groupStart : this.groupEnd,
  101. groupEnd : -1,
  102. groupCount : -1,
  103. inherited : false
  104. };
  105. }
  106. };
  107. this.materials.push( material );
  108. return material;
  109. },
  110. currentMaterial : function() {
  111. if ( this.materials.length > 0 ) {
  112. return this.materials[ this.materials.length - 1 ];
  113. }
  114. return undefined;
  115. },
  116. _finalize : function( end ) {
  117. var lastMultiMaterial = this.currentMaterial();
  118. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === -1 ) {
  119. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  120. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  121. lastMultiMaterial.inherited = false;
  122. }
  123. // Guarantee at least one empty material, this makes the creation later more straight forward.
  124. if ( end !== false && this.materials.length === 0 ) {
  125. this.materials.push({
  126. name : '',
  127. smooth : this.smooth
  128. });
  129. }
  130. return lastMultiMaterial;
  131. }
  132. };
  133. // Inherit previous objects material.
  134. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  135. // If a usemtl declaration is encountered while this new object is being parsed, it will
  136. // overwrite the inherited material. Exception being that there was already face declarations
  137. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  138. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function" ) {
  139. var declared = previousMaterial.clone( 0 );
  140. declared.inherited = true;
  141. this.object.materials.push( declared );
  142. }
  143. this.objects.push( this.object );
  144. },
  145. finalize : function() {
  146. if ( this.object && typeof this.object._finalize === 'function' ) {
  147. this.object._finalize();
  148. }
  149. },
  150. parseVertexIndex: function ( value, len ) {
  151. var index = parseInt( value, 10 );
  152. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  153. },
  154. parseNormalIndex: function ( value, len ) {
  155. var index = parseInt( value, 10 );
  156. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  157. },
  158. parseUVIndex: function ( value, len ) {
  159. var index = parseInt( value, 10 );
  160. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  161. },
  162. addVertex: function ( a, b, c ) {
  163. var src = this.vertices;
  164. var dst = this.object.geometry.vertices;
  165. dst.push( src[ a + 0 ] );
  166. dst.push( src[ a + 1 ] );
  167. dst.push( src[ a + 2 ] );
  168. dst.push( src[ b + 0 ] );
  169. dst.push( src[ b + 1 ] );
  170. dst.push( src[ b + 2 ] );
  171. dst.push( src[ c + 0 ] );
  172. dst.push( src[ c + 1 ] );
  173. dst.push( src[ c + 2 ] );
  174. },
  175. addVertexLine: function ( a ) {
  176. var src = this.vertices;
  177. var dst = this.object.geometry.vertices;
  178. dst.push( src[ a + 0 ] );
  179. dst.push( src[ a + 1 ] );
  180. dst.push( src[ a + 2 ] );
  181. },
  182. addNormal : function ( a, b, c ) {
  183. var src = this.normals;
  184. var dst = this.object.geometry.normals;
  185. dst.push( src[ a + 0 ] );
  186. dst.push( src[ a + 1 ] );
  187. dst.push( src[ a + 2 ] );
  188. dst.push( src[ b + 0 ] );
  189. dst.push( src[ b + 1 ] );
  190. dst.push( src[ b + 2 ] );
  191. dst.push( src[ c + 0 ] );
  192. dst.push( src[ c + 1 ] );
  193. dst.push( src[ c + 2 ] );
  194. },
  195. addUV: function ( a, b, c ) {
  196. var src = this.uvs;
  197. var dst = this.object.geometry.uvs;
  198. dst.push( src[ a + 0 ] );
  199. dst.push( src[ a + 1 ] );
  200. dst.push( src[ b + 0 ] );
  201. dst.push( src[ b + 1 ] );
  202. dst.push( src[ c + 0 ] );
  203. dst.push( src[ c + 1 ] );
  204. },
  205. addUVLine: function ( a ) {
  206. var src = this.uvs;
  207. var dst = this.object.geometry.uvs;
  208. dst.push( src[ a + 0 ] );
  209. dst.push( src[ a + 1 ] );
  210. },
  211. addFace: function ( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  212. var vLen = this.vertices.length;
  213. var ia = this.parseVertexIndex( a, vLen );
  214. var ib = this.parseVertexIndex( b, vLen );
  215. var ic = this.parseVertexIndex( c, vLen );
  216. var id;
  217. if ( d === undefined ) {
  218. this.addVertex( ia, ib, ic );
  219. } else {
  220. id = this.parseVertexIndex( d, vLen );
  221. this.addVertex( ia, ib, id );
  222. this.addVertex( ib, ic, id );
  223. }
  224. if ( ua !== undefined ) {
  225. var uvLen = this.uvs.length;
  226. ia = this.parseUVIndex( ua, uvLen );
  227. ib = this.parseUVIndex( ub, uvLen );
  228. ic = this.parseUVIndex( uc, uvLen );
  229. if ( d === undefined ) {
  230. this.addUV( ia, ib, ic );
  231. } else {
  232. id = this.parseUVIndex( ud, uvLen );
  233. this.addUV( ia, ib, id );
  234. this.addUV( ib, ic, id );
  235. }
  236. }
  237. if ( na !== undefined ) {
  238. // Normals are many times the same. If so, skip function call and parseInt.
  239. var nLen = this.normals.length;
  240. ia = this.parseNormalIndex( na, nLen );
  241. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  242. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  243. if ( d === undefined ) {
  244. this.addNormal( ia, ib, ic );
  245. } else {
  246. id = this.parseNormalIndex( nd, nLen );
  247. this.addNormal( ia, ib, id );
  248. this.addNormal( ib, ic, id );
  249. }
  250. }
  251. },
  252. addLineGeometry: function ( vertices, uvs ) {
  253. this.object.geometry.type = 'Line';
  254. var vLen = this.vertices.length;
  255. var uvLen = this.uvs.length;
  256. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  257. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  258. }
  259. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  260. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  261. }
  262. }
  263. };
  264. state.startObject( '', false );
  265. return state;
  266. },
  267. parse: function ( text ) {
  268. console.time( 'OBJLoader' );
  269. var state = this._createParserState();
  270. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  271. // This is faster than String.split with regex that splits on both
  272. text = text.replace( '\r\n', '\n' );
  273. }
  274. var lines = text.split( '\n' );
  275. var line = '', lineFirstChar = '', lineSecondChar = '';
  276. var lineLength = 0;
  277. var result = [];
  278. // Faster to just trim left side of the line. Use if available.
  279. var trimLeft = ( typeof ''.trimLeft === 'function' );
  280. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  281. line = lines[ i ];
  282. line = trimLeft ? line.trimLeft() : line.trim();
  283. lineLength = line.length;
  284. if ( lineLength === 0 ) continue;
  285. lineFirstChar = line.charAt( 0 );
  286. // @todo invoke passed in handler if any
  287. if ( lineFirstChar === '#' ) continue;
  288. if ( lineFirstChar === 'v' ) {
  289. lineSecondChar = line.charAt( 1 );
  290. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  291. // 0 1 2 3
  292. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  293. state.vertices.push(
  294. parseFloat( result[ 1 ] ),
  295. parseFloat( result[ 2 ] ),
  296. parseFloat( result[ 3 ] )
  297. );
  298. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  299. // 0 1 2 3
  300. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  301. state.normals.push(
  302. parseFloat( result[ 1 ] ),
  303. parseFloat( result[ 2 ] ),
  304. parseFloat( result[ 3 ] )
  305. );
  306. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  307. // 0 1 2
  308. // ["vt 0.1 0.2", "0.1", "0.2"]
  309. state.uvs.push(
  310. parseFloat( result[ 1 ] ),
  311. parseFloat( result[ 2 ] )
  312. );
  313. } else {
  314. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'" );
  315. }
  316. } else if ( lineFirstChar === "f" ) {
  317. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  318. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  319. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  320. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  321. state.addFace(
  322. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  323. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  324. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  325. );
  326. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  327. // f vertex/uv vertex/uv vertex/uv
  328. // 0 1 2 3 4 5 6 7 8
  329. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  330. state.addFace(
  331. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  332. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  333. );
  334. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  335. // f vertex//normal vertex//normal vertex//normal
  336. // 0 1 2 3 4 5 6 7 8
  337. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  338. state.addFace(
  339. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  340. undefined, undefined, undefined, undefined,
  341. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  342. );
  343. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  344. // f vertex vertex vertex
  345. // 0 1 2 3 4
  346. // ["f 1 2 3", "1", "2", "3", undefined]
  347. state.addFace(
  348. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  349. );
  350. } else {
  351. throw new Error( "Unexpected face line: '" + line + "'" );
  352. }
  353. } else if ( lineFirstChar === "l" ) {
  354. var lineParts = line.substring( 1 ).trim().split( " " );
  355. var lineVertices = [], lineUVs = [];
  356. if ( line.indexOf( "/" ) === - 1 ) {
  357. lineVertices = lineParts;
  358. } else {
  359. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  360. var parts = lineParts[ li ].split( "/" );
  361. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  362. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  363. }
  364. }
  365. state.addLineGeometry( lineVertices, lineUVs );
  366. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  367. // o object_name
  368. // or
  369. // g group_name
  370. var name = result[ 0 ].substr( 1 ).trim();
  371. state.startObject( name );
  372. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  373. // material
  374. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  375. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  376. // mtl file
  377. state.materialLibraries.push( line.substring( 7 ).trim() );
  378. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  379. // smooth shading
  380. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  381. // but does not define a usemtl for each face set.
  382. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  383. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  384. // where explicit usemtl defines geometry groups.
  385. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  386. var value = result[ 1 ].trim().toLowerCase();
  387. state.object.smooth = ( value === '1' || value === 'on' );
  388. var material = state.object.currentMaterial();
  389. if ( material ) {
  390. material.smooth = state.object.smooth;
  391. }
  392. } else {
  393. // Handle null terminated files without exception
  394. if ( line === '\0' ) continue;
  395. throw new Error( "Unexpected line: '" + line + "'" );
  396. }
  397. }
  398. state.finalize();
  399. var container = new THREE.Group();
  400. container.materialLibraries = [].concat( state.materialLibraries );
  401. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  402. var object = state.objects[ i ];
  403. var geometry = object.geometry;
  404. var materials = object.materials;
  405. var isLine = ( geometry.type === 'Line' );
  406. // Skip o/g line declarations that did not follow with any faces
  407. if ( geometry.vertices.length === 0 ) continue;
  408. var buffergeometry = new THREE.BufferGeometry();
  409. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  410. if ( geometry.normals.length > 0 ) {
  411. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  412. } else {
  413. buffergeometry.computeVertexNormals();
  414. }
  415. if ( geometry.uvs.length > 0 ) {
  416. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  417. }
  418. // Create materials
  419. var createdMaterials = [];
  420. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  421. var sourceMaterial = materials[mi];
  422. var material = undefined;
  423. if ( this.materials !== null ) {
  424. material = this.materials.create( sourceMaterial.name );
  425. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  426. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  427. var materialLine = new THREE.LineBasicMaterial();
  428. materialLine.copy( material );
  429. material = materialLine;
  430. }
  431. }
  432. if ( ! material ) {
  433. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  434. material.name = sourceMaterial.name;
  435. }
  436. material.shading = sourceMaterial.smooth ? THREE.SmoothShading : THREE.FlatShading;
  437. createdMaterials.push(material);
  438. }
  439. // Create mesh
  440. var mesh;
  441. if ( createdMaterials.length > 1 ) {
  442. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  443. var sourceMaterial = materials[mi];
  444. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  445. }
  446. var multiMaterial = new THREE.MultiMaterial( createdMaterials );
  447. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, multiMaterial ) : new THREE.LineSegments( buffergeometry, multiMaterial ) );
  448. } else {
  449. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  450. }
  451. mesh.name = object.name;
  452. container.add( mesh );
  453. }
  454. console.timeEnd( 'OBJLoader' );
  455. return container;
  456. }
  457. };