OBJLoader.js 19 KB

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