OBJLoader.js 19 KB

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