OBJLoader.js 19 KB

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