OBJLoader.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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. * @three_import import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';
  294. */
  295. class OBJLoader extends Loader {
  296. /**
  297. * Constructs a new OBJ loader.
  298. *
  299. * @param {LoadingManager} [manager] - The loading manager.
  300. */
  301. constructor( manager ) {
  302. super( manager );
  303. /**
  304. * A reference to a material creator.
  305. *
  306. * @type {?MaterialCreator}
  307. * @default null
  308. */
  309. this.materials = null;
  310. }
  311. /**
  312. * Starts loading from the given URL and passes the loaded OBJ asset
  313. * to the `onLoad()` callback.
  314. *
  315. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  316. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  317. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  318. * @param {onErrorCallback} onError - Executed when errors occur.
  319. */
  320. load( url, onLoad, onProgress, onError ) {
  321. const scope = this;
  322. const loader = new FileLoader( this.manager );
  323. loader.setPath( this.path );
  324. loader.setRequestHeader( this.requestHeader );
  325. loader.setWithCredentials( this.withCredentials );
  326. loader.load( url, function ( text ) {
  327. try {
  328. onLoad( scope.parse( text ) );
  329. } catch ( e ) {
  330. if ( onError ) {
  331. onError( e );
  332. } else {
  333. console.error( e );
  334. }
  335. scope.manager.itemError( url );
  336. }
  337. }, onProgress, onError );
  338. }
  339. /**
  340. * Sets the material creator for this OBJ. This object is loaded via {@link MTLLoader}.
  341. *
  342. * @param {MaterialCreator} materials - An object that creates the materials for this OBJ.
  343. * @return {OBJLoader} A reference to this loader.
  344. */
  345. setMaterials( materials ) {
  346. this.materials = materials;
  347. return this;
  348. }
  349. /**
  350. * Parses the given OBJ data and returns the resulting group.
  351. *
  352. * @param {string} text - The raw OBJ data as a string.
  353. * @return {Group} The parsed OBJ.
  354. */
  355. parse( text ) {
  356. const state = new ParserState();
  357. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  358. // This is faster than String.split with regex that splits on both
  359. text = text.replace( /\r\n/g, '\n' );
  360. }
  361. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  362. // join lines separated by a line continuation character (\)
  363. text = text.replace( /\\\n/g, '' );
  364. }
  365. const lines = text.split( '\n' );
  366. let result = [];
  367. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  368. const line = lines[ i ].trimStart();
  369. if ( line.length === 0 ) continue;
  370. const lineFirstChar = line.charAt( 0 );
  371. // @todo invoke passed in handler if any
  372. if ( lineFirstChar === '#' ) continue; // skip comments
  373. if ( lineFirstChar === 'v' ) {
  374. const data = line.split( _face_vertex_data_separator_pattern );
  375. switch ( data[ 0 ] ) {
  376. case 'v':
  377. state.vertices.push(
  378. parseFloat( data[ 1 ] ),
  379. parseFloat( data[ 2 ] ),
  380. parseFloat( data[ 3 ] )
  381. );
  382. if ( data.length >= 7 ) {
  383. _color.setRGB(
  384. parseFloat( data[ 4 ] ),
  385. parseFloat( data[ 5 ] ),
  386. parseFloat( data[ 6 ] ),
  387. SRGBColorSpace
  388. );
  389. state.colors.push( _color.r, _color.g, _color.b );
  390. } else {
  391. // if no colors are defined, add placeholders so color and vertex indices match
  392. state.colors.push( undefined, undefined, undefined );
  393. }
  394. break;
  395. case 'vn':
  396. state.normals.push(
  397. parseFloat( data[ 1 ] ),
  398. parseFloat( data[ 2 ] ),
  399. parseFloat( data[ 3 ] )
  400. );
  401. break;
  402. case 'vt':
  403. state.uvs.push(
  404. parseFloat( data[ 1 ] ),
  405. parseFloat( data[ 2 ] )
  406. );
  407. break;
  408. }
  409. } else if ( lineFirstChar === 'f' ) {
  410. const lineData = line.slice( 1 ).trim();
  411. const vertexData = lineData.split( _face_vertex_data_separator_pattern );
  412. const faceVertices = [];
  413. // Parse the face vertex data into an easy to work with format
  414. for ( let j = 0, jl = vertexData.length; j < jl; j ++ ) {
  415. const vertex = vertexData[ j ];
  416. if ( vertex.length > 0 ) {
  417. const vertexParts = vertex.split( '/' );
  418. faceVertices.push( vertexParts );
  419. }
  420. }
  421. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  422. const v1 = faceVertices[ 0 ];
  423. for ( let j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  424. const v2 = faceVertices[ j ];
  425. const v3 = faceVertices[ j + 1 ];
  426. state.addFace(
  427. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  428. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  429. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  430. );
  431. }
  432. } else if ( lineFirstChar === 'l' ) {
  433. const lineParts = line.substring( 1 ).trim().split( ' ' );
  434. let lineVertices = [];
  435. const lineUVs = [];
  436. if ( line.indexOf( '/' ) === - 1 ) {
  437. lineVertices = lineParts;
  438. } else {
  439. for ( let li = 0, llen = lineParts.length; li < llen; li ++ ) {
  440. const parts = lineParts[ li ].split( '/' );
  441. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  442. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  443. }
  444. }
  445. state.addLineGeometry( lineVertices, lineUVs );
  446. } else if ( lineFirstChar === 'p' ) {
  447. const lineData = line.slice( 1 ).trim();
  448. const pointData = lineData.split( ' ' );
  449. state.addPointGeometry( pointData );
  450. } else if ( ( result = _object_pattern.exec( line ) ) !== null ) {
  451. // o object_name
  452. // or
  453. // g group_name
  454. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  455. // let name = result[ 0 ].slice( 1 ).trim();
  456. const name = ( ' ' + result[ 0 ].slice( 1 ).trim() ).slice( 1 );
  457. state.startObject( name );
  458. } else if ( _material_use_pattern.test( line ) ) {
  459. // material
  460. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  461. } else if ( _material_library_pattern.test( line ) ) {
  462. // mtl file
  463. state.materialLibraries.push( line.substring( 7 ).trim() );
  464. } else if ( _map_use_pattern.test( line ) ) {
  465. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  466. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  467. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  468. } else if ( lineFirstChar === 's' ) {
  469. result = line.split( ' ' );
  470. // smooth shading
  471. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  472. // but does not define a usemtl for each face set.
  473. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  474. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  475. // where explicit usemtl defines geometry groups.
  476. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  477. /*
  478. * http://paulbourke.net/dataformats/obj/
  479. *
  480. * From chapter "Grouping" Syntax explanation "s group_number":
  481. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  482. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  483. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  484. * than 0."
  485. */
  486. if ( result.length > 1 ) {
  487. const value = result[ 1 ].trim().toLowerCase();
  488. state.object.smooth = ( value !== '0' && value !== 'off' );
  489. } else {
  490. // ZBrush can produce "s" lines #11707
  491. state.object.smooth = true;
  492. }
  493. const material = state.object.currentMaterial();
  494. if ( material ) material.smooth = state.object.smooth;
  495. } else {
  496. // Handle null terminated files without exception
  497. if ( line === '\0' ) continue;
  498. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  499. }
  500. }
  501. state.finalize();
  502. const container = new Group();
  503. container.materialLibraries = [].concat( state.materialLibraries );
  504. const hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  505. if ( hasPrimitives === true ) {
  506. for ( let i = 0, l = state.objects.length; i < l; i ++ ) {
  507. const object = state.objects[ i ];
  508. const geometry = object.geometry;
  509. const materials = object.materials;
  510. const isLine = ( geometry.type === 'Line' );
  511. const isPoints = ( geometry.type === 'Points' );
  512. let hasVertexColors = false;
  513. // Skip o/g line declarations that did not follow with any faces
  514. if ( geometry.vertices.length === 0 ) continue;
  515. const buffergeometry = new BufferGeometry();
  516. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  517. if ( geometry.normals.length > 0 ) {
  518. buffergeometry.setAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  519. }
  520. if ( geometry.colors.length > 0 ) {
  521. hasVertexColors = true;
  522. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  523. }
  524. if ( geometry.hasUVIndices === true ) {
  525. buffergeometry.setAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  526. }
  527. // Create materials
  528. const createdMaterials = [];
  529. for ( let mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  530. const sourceMaterial = materials[ mi ];
  531. const materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  532. let material = state.materials[ materialHash ];
  533. if ( this.materials !== null ) {
  534. material = this.materials.create( sourceMaterial.name );
  535. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  536. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  537. const materialLine = new LineBasicMaterial();
  538. Material.prototype.copy.call( materialLine, material );
  539. materialLine.color.copy( material.color );
  540. material = materialLine;
  541. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  542. const materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  543. Material.prototype.copy.call( materialPoints, material );
  544. materialPoints.color.copy( material.color );
  545. materialPoints.map = material.map;
  546. material = materialPoints;
  547. }
  548. }
  549. if ( material === undefined ) {
  550. if ( isLine ) {
  551. material = new LineBasicMaterial();
  552. } else if ( isPoints ) {
  553. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  554. } else {
  555. material = new MeshPhongMaterial();
  556. }
  557. material.name = sourceMaterial.name;
  558. material.flatShading = sourceMaterial.smooth ? false : true;
  559. material.vertexColors = hasVertexColors;
  560. state.materials[ materialHash ] = material;
  561. }
  562. createdMaterials.push( material );
  563. }
  564. // Create mesh
  565. let mesh;
  566. if ( createdMaterials.length > 1 ) {
  567. for ( let mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  568. const sourceMaterial = materials[ mi ];
  569. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  570. }
  571. if ( isLine ) {
  572. mesh = new LineSegments( buffergeometry, createdMaterials );
  573. } else if ( isPoints ) {
  574. mesh = new Points( buffergeometry, createdMaterials );
  575. } else {
  576. mesh = new Mesh( buffergeometry, createdMaterials );
  577. }
  578. } else {
  579. if ( isLine ) {
  580. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  581. } else if ( isPoints ) {
  582. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  583. } else {
  584. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  585. }
  586. }
  587. mesh.name = object.name;
  588. container.add( mesh );
  589. }
  590. } else {
  591. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  592. if ( state.vertices.length > 0 ) {
  593. const material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  594. const buffergeometry = new BufferGeometry();
  595. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( state.vertices, 3 ) );
  596. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  597. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( state.colors, 3 ) );
  598. material.vertexColors = true;
  599. }
  600. const points = new Points( buffergeometry, material );
  601. container.add( points );
  602. }
  603. }
  604. return container;
  605. }
  606. }
  607. export { OBJLoader };