OBJLoader.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Group,
  6. LineBasicMaterial,
  7. LineSegments,
  8. Loader,
  9. Material,
  10. Mesh,
  11. MeshPhongMaterial,
  12. Points,
  13. PointsMaterial,
  14. Vector3,
  15. Color,
  16. SRGBColorSpace
  17. } from 'three';
  18. // o object_name | g group_name
  19. const _object_pattern = /^[og]\s*(.+)?/;
  20. // mtllib file_reference
  21. const _material_library_pattern = /^mtllib /;
  22. // usemtl material_name
  23. const _material_use_pattern = /^usemtl /;
  24. // usemap map_name
  25. const _map_use_pattern = /^usemap /;
  26. const _face_vertex_data_separator_pattern = /\s+/;
  27. const _vA = new Vector3();
  28. const _vB = new Vector3();
  29. const _vC = new Vector3();
  30. const _ab = new Vector3();
  31. const _cb = new Vector3();
  32. const _color = new Color();
  33. function ParserState() {
  34. const state = {
  35. objects: [],
  36. object: {},
  37. vertices: [],
  38. normals: [],
  39. colors: [],
  40. uvs: [],
  41. materials: {},
  42. materialLibraries: [],
  43. startObject: function ( name, fromDeclaration ) {
  44. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  45. // file. We need to use it for the first parsed g/o to keep things in sync.
  46. if ( this.object && this.object.fromDeclaration === false ) {
  47. this.object.name = name;
  48. this.object.fromDeclaration = ( fromDeclaration !== false );
  49. return;
  50. }
  51. const previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  52. if ( this.object && typeof this.object._finalize === 'function' ) {
  53. this.object._finalize( true );
  54. }
  55. this.object = {
  56. name: name || '',
  57. fromDeclaration: ( fromDeclaration !== false ),
  58. geometry: {
  59. vertices: [],
  60. normals: [],
  61. colors: [],
  62. uvs: [],
  63. hasUVIndices: false
  64. },
  65. materials: [],
  66. smooth: true,
  67. startMaterial: function ( name, libraries ) {
  68. const previous = this._finalize( false );
  69. // New usemtl declaration overwrites an inherited material, except if faces were declared
  70. // after the material, then it must be preserved for proper MultiMaterial continuation.
  71. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  72. this.materials.splice( previous.index, 1 );
  73. }
  74. const material = {
  75. index: this.materials.length,
  76. name: name || '',
  77. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  78. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  79. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  80. groupEnd: - 1,
  81. groupCount: - 1,
  82. inherited: false,
  83. clone: function ( index ) {
  84. const cloned = {
  85. index: ( typeof index === 'number' ? index : this.index ),
  86. name: this.name,
  87. mtllib: this.mtllib,
  88. smooth: this.smooth,
  89. groupStart: 0,
  90. groupEnd: - 1,
  91. groupCount: - 1,
  92. inherited: false
  93. };
  94. cloned.clone = this.clone.bind( cloned );
  95. return cloned;
  96. }
  97. };
  98. this.materials.push( material );
  99. return material;
  100. },
  101. currentMaterial: function () {
  102. if ( this.materials.length > 0 ) {
  103. return this.materials[ this.materials.length - 1 ];
  104. }
  105. return undefined;
  106. },
  107. _finalize: function ( end ) {
  108. const lastMultiMaterial = this.currentMaterial();
  109. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  110. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  111. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  112. lastMultiMaterial.inherited = false;
  113. }
  114. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  115. if ( end && this.materials.length > 1 ) {
  116. for ( let mi = this.materials.length - 1; mi >= 0; mi -- ) {
  117. if ( this.materials[ mi ].groupCount <= 0 ) {
  118. this.materials.splice( mi, 1 );
  119. }
  120. }
  121. }
  122. // Guarantee at least one empty material, this makes the creation later more straight forward.
  123. if ( end && this.materials.length === 0 ) {
  124. this.materials.push( {
  125. name: '',
  126. smooth: this.smooth
  127. } );
  128. }
  129. return lastMultiMaterial;
  130. }
  131. };
  132. // Inherit previous objects material.
  133. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  134. // If a usemtl declaration is encountered while this new object is being parsed, it will
  135. // overwrite the inherited material. Exception being that there was already face declarations
  136. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  137. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  138. const declared = previousMaterial.clone( 0 );
  139. declared.inherited = true;
  140. this.object.materials.push( declared );
  141. }
  142. this.objects.push( this.object );
  143. },
  144. finalize: function () {
  145. if ( this.object && typeof this.object._finalize === 'function' ) {
  146. this.object._finalize( true );
  147. }
  148. },
  149. parseVertexIndex: function ( value, len ) {
  150. const index = parseInt( value, 10 );
  151. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  152. },
  153. parseNormalIndex: function ( value, len ) {
  154. const index = parseInt( value, 10 );
  155. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  156. },
  157. parseUVIndex: function ( value, len ) {
  158. const index = parseInt( value, 10 );
  159. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  160. },
  161. addVertex: function ( a, b, c ) {
  162. const src = this.vertices;
  163. const dst = this.object.geometry.vertices;
  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. addVertexPoint: function ( a ) {
  169. const src = this.vertices;
  170. const dst = this.object.geometry.vertices;
  171. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  172. },
  173. addVertexLine: function ( a ) {
  174. const src = this.vertices;
  175. const dst = this.object.geometry.vertices;
  176. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  177. },
  178. addNormal: function ( a, b, c ) {
  179. const src = this.normals;
  180. const dst = this.object.geometry.normals;
  181. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  182. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  183. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  184. },
  185. addFaceNormal: function ( a, b, c ) {
  186. const src = this.vertices;
  187. const dst = this.object.geometry.normals;
  188. _vA.fromArray( src, a );
  189. _vB.fromArray( src, b );
  190. _vC.fromArray( src, c );
  191. _cb.subVectors( _vC, _vB );
  192. _ab.subVectors( _vA, _vB );
  193. _cb.cross( _ab );
  194. _cb.normalize();
  195. dst.push( _cb.x, _cb.y, _cb.z );
  196. dst.push( _cb.x, _cb.y, _cb.z );
  197. dst.push( _cb.x, _cb.y, _cb.z );
  198. },
  199. addColor: function ( a, b, c ) {
  200. const src = this.colors;
  201. const dst = this.object.geometry.colors;
  202. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  203. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  204. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  205. },
  206. addUV: function ( a, b, c ) {
  207. const src = this.uvs;
  208. const dst = this.object.geometry.uvs;
  209. dst.push( src[ a + 0 ], src[ a + 1 ] );
  210. dst.push( src[ b + 0 ], src[ b + 1 ] );
  211. dst.push( src[ c + 0 ], src[ c + 1 ] );
  212. },
  213. addDefaultUV: function () {
  214. const dst = this.object.geometry.uvs;
  215. dst.push( 0, 0 );
  216. dst.push( 0, 0 );
  217. dst.push( 0, 0 );
  218. },
  219. addUVLine: function ( a ) {
  220. const src = this.uvs;
  221. const dst = this.object.geometry.uvs;
  222. dst.push( src[ a + 0 ], src[ a + 1 ] );
  223. },
  224. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  225. const vLen = this.vertices.length;
  226. let ia = this.parseVertexIndex( a, vLen );
  227. let ib = this.parseVertexIndex( b, vLen );
  228. let ic = this.parseVertexIndex( c, vLen );
  229. this.addVertex( ia, ib, ic );
  230. this.addColor( ia, ib, ic );
  231. // normals
  232. if ( na !== undefined && na !== '' ) {
  233. const nLen = this.normals.length;
  234. ia = this.parseNormalIndex( na, nLen );
  235. ib = this.parseNormalIndex( nb, nLen );
  236. ic = this.parseNormalIndex( nc, nLen );
  237. this.addNormal( ia, ib, ic );
  238. } else {
  239. this.addFaceNormal( ia, ib, ic );
  240. }
  241. // uvs
  242. if ( ua !== undefined && ua !== '' ) {
  243. const uvLen = this.uvs.length;
  244. ia = this.parseUVIndex( ua, uvLen );
  245. ib = this.parseUVIndex( ub, uvLen );
  246. ic = this.parseUVIndex( uc, uvLen );
  247. this.addUV( ia, ib, ic );
  248. this.object.geometry.hasUVIndices = true;
  249. } else {
  250. // add placeholder values (for inconsistent face definitions)
  251. this.addDefaultUV();
  252. }
  253. },
  254. addPointGeometry: function ( vertices ) {
  255. this.object.geometry.type = 'Points';
  256. const vLen = this.vertices.length;
  257. for ( let vi = 0, l = vertices.length; vi < l; vi ++ ) {
  258. const index = this.parseVertexIndex( vertices[ vi ], vLen );
  259. this.addVertexPoint( index );
  260. this.addColor( index );
  261. }
  262. },
  263. addLineGeometry: function ( vertices, uvs ) {
  264. this.object.geometry.type = 'Line';
  265. const vLen = this.vertices.length;
  266. const uvLen = this.uvs.length;
  267. for ( let vi = 0, l = vertices.length; vi < l; vi ++ ) {
  268. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  269. }
  270. for ( let uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  271. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  272. }
  273. }
  274. };
  275. state.startObject( '', false );
  276. return state;
  277. }
  278. /**
  279. * A loader for the OBJ format.
  280. *
  281. * The [OBJ format]{@link https://en.wikipedia.org/wiki/Wavefront_.obj_file} is a simple data-format that
  282. * represents 3D geometry in a human readable format as the position of each vertex, the UV position of
  283. * each texture coordinate vertex, vertex normals, and the faces that make each polygon defined as a list
  284. * of vertices, and texture vertices.
  285. *
  286. * ```js
  287. * const loader = new OBJLoader();
  288. * const object = await loader.loadAsync( 'models/monster.obj' );
  289. * scene.add( object );
  290. * ```
  291. *
  292. * @augments Loader
  293. */
  294. class OBJLoader extends Loader {
  295. /**
  296. * Constructs a new OBJ loader.
  297. *
  298. * @param {LoadingManager} [manager] - The loading manager.
  299. */
  300. constructor( manager ) {
  301. super( manager );
  302. /**
  303. * A reference to a material creator.
  304. *
  305. * @type {?MaterialCreator}
  306. * @default null
  307. */
  308. this.materials = null;
  309. }
  310. /**
  311. * Starts loading from the given URL and passes the loaded OBJ asset
  312. * to the `onLoad()` callback.
  313. *
  314. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  315. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  316. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  317. * @param {onErrorCallback} onError - Executed when errors occur.
  318. */
  319. load( url, onLoad, onProgress, onError ) {
  320. const scope = this;
  321. const loader = new FileLoader( this.manager );
  322. loader.setPath( this.path );
  323. loader.setRequestHeader( this.requestHeader );
  324. loader.setWithCredentials( this.withCredentials );
  325. loader.load( url, function ( text ) {
  326. try {
  327. onLoad( scope.parse( text ) );
  328. } catch ( e ) {
  329. if ( onError ) {
  330. onError( e );
  331. } else {
  332. console.error( e );
  333. }
  334. scope.manager.itemError( url );
  335. }
  336. }, onProgress, onError );
  337. }
  338. /**
  339. * Sets the material creator for this OBJ. This object is loaded via {@link MTLLoader}.
  340. *
  341. * @param {MaterialCreator} materials - An object that creates the materials for this OBJ.
  342. * @return {OBJLoader} A reference to this loader.
  343. */
  344. setMaterials( materials ) {
  345. this.materials = materials;
  346. return this;
  347. }
  348. /**
  349. * Parses the given OBJ data and returns the resulting group.
  350. *
  351. * @param {string} text - The raw OBJ data as a string.
  352. * @return {Group} The parsed OBJ.
  353. */
  354. parse( text ) {
  355. const state = new ParserState();
  356. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  357. // This is faster than String.split with regex that splits on both
  358. text = text.replace( /\r\n/g, '\n' );
  359. }
  360. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  361. // join lines separated by a line continuation character (\)
  362. text = text.replace( /\\\n/g, '' );
  363. }
  364. const lines = text.split( '\n' );
  365. let result = [];
  366. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  367. const line = lines[ i ].trimStart();
  368. if ( line.length === 0 ) continue;
  369. const lineFirstChar = line.charAt( 0 );
  370. // @todo invoke passed in handler if any
  371. if ( lineFirstChar === '#' ) continue; // skip comments
  372. if ( lineFirstChar === 'v' ) {
  373. const data = line.split( _face_vertex_data_separator_pattern );
  374. switch ( data[ 0 ] ) {
  375. case 'v':
  376. state.vertices.push(
  377. parseFloat( data[ 1 ] ),
  378. parseFloat( data[ 2 ] ),
  379. parseFloat( data[ 3 ] )
  380. );
  381. if ( data.length >= 7 ) {
  382. _color.setRGB(
  383. parseFloat( data[ 4 ] ),
  384. parseFloat( data[ 5 ] ),
  385. parseFloat( data[ 6 ] ),
  386. SRGBColorSpace
  387. );
  388. state.colors.push( _color.r, _color.g, _color.b );
  389. } else {
  390. // if no colors are defined, add placeholders so color and vertex indices match
  391. state.colors.push( undefined, undefined, undefined );
  392. }
  393. break;
  394. case 'vn':
  395. state.normals.push(
  396. parseFloat( data[ 1 ] ),
  397. parseFloat( data[ 2 ] ),
  398. parseFloat( data[ 3 ] )
  399. );
  400. break;
  401. case 'vt':
  402. state.uvs.push(
  403. parseFloat( data[ 1 ] ),
  404. parseFloat( data[ 2 ] )
  405. );
  406. break;
  407. }
  408. } else if ( lineFirstChar === 'f' ) {
  409. const lineData = line.slice( 1 ).trim();
  410. const vertexData = lineData.split( _face_vertex_data_separator_pattern );
  411. const faceVertices = [];
  412. // Parse the face vertex data into an easy to work with format
  413. for ( let j = 0, jl = vertexData.length; j < jl; j ++ ) {
  414. const vertex = vertexData[ j ];
  415. if ( vertex.length > 0 ) {
  416. const vertexParts = vertex.split( '/' );
  417. faceVertices.push( vertexParts );
  418. }
  419. }
  420. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  421. const v1 = faceVertices[ 0 ];
  422. for ( let j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  423. const v2 = faceVertices[ j ];
  424. const v3 = faceVertices[ j + 1 ];
  425. state.addFace(
  426. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  427. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  428. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  429. );
  430. }
  431. } else if ( lineFirstChar === 'l' ) {
  432. const lineParts = line.substring( 1 ).trim().split( ' ' );
  433. let lineVertices = [];
  434. const lineUVs = [];
  435. if ( line.indexOf( '/' ) === - 1 ) {
  436. lineVertices = lineParts;
  437. } else {
  438. for ( let li = 0, llen = lineParts.length; li < llen; li ++ ) {
  439. const parts = lineParts[ li ].split( '/' );
  440. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  441. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  442. }
  443. }
  444. state.addLineGeometry( lineVertices, lineUVs );
  445. } else if ( lineFirstChar === 'p' ) {
  446. const lineData = line.slice( 1 ).trim();
  447. const pointData = lineData.split( ' ' );
  448. state.addPointGeometry( pointData );
  449. } else if ( ( result = _object_pattern.exec( line ) ) !== null ) {
  450. // o object_name
  451. // or
  452. // g group_name
  453. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  454. // let name = result[ 0 ].slice( 1 ).trim();
  455. const name = ( ' ' + result[ 0 ].slice( 1 ).trim() ).slice( 1 );
  456. state.startObject( name );
  457. } else if ( _material_use_pattern.test( line ) ) {
  458. // material
  459. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  460. } else if ( _material_library_pattern.test( line ) ) {
  461. // mtl file
  462. state.materialLibraries.push( line.substring( 7 ).trim() );
  463. } else if ( _map_use_pattern.test( line ) ) {
  464. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  465. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  466. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  467. } else if ( lineFirstChar === 's' ) {
  468. result = line.split( ' ' );
  469. // smooth shading
  470. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  471. // but does not define a usemtl for each face set.
  472. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  473. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  474. // where explicit usemtl defines geometry groups.
  475. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  476. /*
  477. * http://paulbourke.net/dataformats/obj/
  478. *
  479. * From chapter "Grouping" Syntax explanation "s group_number":
  480. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  481. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  482. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  483. * than 0."
  484. */
  485. if ( result.length > 1 ) {
  486. const value = result[ 1 ].trim().toLowerCase();
  487. state.object.smooth = ( value !== '0' && value !== 'off' );
  488. } else {
  489. // ZBrush can produce "s" lines #11707
  490. state.object.smooth = true;
  491. }
  492. const material = state.object.currentMaterial();
  493. if ( material ) material.smooth = state.object.smooth;
  494. } else {
  495. // Handle null terminated files without exception
  496. if ( line === '\0' ) continue;
  497. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  498. }
  499. }
  500. state.finalize();
  501. const container = new Group();
  502. container.materialLibraries = [].concat( state.materialLibraries );
  503. const hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  504. if ( hasPrimitives === true ) {
  505. for ( let i = 0, l = state.objects.length; i < l; i ++ ) {
  506. const object = state.objects[ i ];
  507. const geometry = object.geometry;
  508. const materials = object.materials;
  509. const isLine = ( geometry.type === 'Line' );
  510. const isPoints = ( geometry.type === 'Points' );
  511. let hasVertexColors = false;
  512. // Skip o/g line declarations that did not follow with any faces
  513. if ( geometry.vertices.length === 0 ) continue;
  514. const buffergeometry = new BufferGeometry();
  515. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  516. if ( geometry.normals.length > 0 ) {
  517. buffergeometry.setAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  518. }
  519. if ( geometry.colors.length > 0 ) {
  520. hasVertexColors = true;
  521. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  522. }
  523. if ( geometry.hasUVIndices === true ) {
  524. buffergeometry.setAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  525. }
  526. // Create materials
  527. const createdMaterials = [];
  528. for ( let mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  529. const sourceMaterial = materials[ mi ];
  530. const materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  531. let material = state.materials[ materialHash ];
  532. if ( this.materials !== null ) {
  533. material = this.materials.create( sourceMaterial.name );
  534. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  535. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  536. const materialLine = new LineBasicMaterial();
  537. Material.prototype.copy.call( materialLine, material );
  538. materialLine.color.copy( material.color );
  539. material = materialLine;
  540. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  541. const materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  542. Material.prototype.copy.call( materialPoints, material );
  543. materialPoints.color.copy( material.color );
  544. materialPoints.map = material.map;
  545. material = materialPoints;
  546. }
  547. }
  548. if ( material === undefined ) {
  549. if ( isLine ) {
  550. material = new LineBasicMaterial();
  551. } else if ( isPoints ) {
  552. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  553. } else {
  554. material = new MeshPhongMaterial();
  555. }
  556. material.name = sourceMaterial.name;
  557. material.flatShading = sourceMaterial.smooth ? false : true;
  558. material.vertexColors = hasVertexColors;
  559. state.materials[ materialHash ] = material;
  560. }
  561. createdMaterials.push( material );
  562. }
  563. // Create mesh
  564. let mesh;
  565. if ( createdMaterials.length > 1 ) {
  566. for ( let mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  567. const sourceMaterial = materials[ mi ];
  568. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  569. }
  570. if ( isLine ) {
  571. mesh = new LineSegments( buffergeometry, createdMaterials );
  572. } else if ( isPoints ) {
  573. mesh = new Points( buffergeometry, createdMaterials );
  574. } else {
  575. mesh = new Mesh( buffergeometry, createdMaterials );
  576. }
  577. } else {
  578. if ( isLine ) {
  579. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  580. } else if ( isPoints ) {
  581. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  582. } else {
  583. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  584. }
  585. }
  586. mesh.name = object.name;
  587. container.add( mesh );
  588. }
  589. } else {
  590. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  591. if ( state.vertices.length > 0 ) {
  592. const material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  593. const buffergeometry = new BufferGeometry();
  594. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( state.vertices, 3 ) );
  595. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  596. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( state.colors, 3 ) );
  597. material.vertexColors = true;
  598. }
  599. const points = new Points( buffergeometry, material );
  600. container.add( points );
  601. }
  602. }
  603. return container;
  604. }
  605. }
  606. export { OBJLoader };
粤ICP备19079148号