OBJLoader.js 19 KB

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