OBJLoader.js 19 KB

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