LWOLoader.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. ( function () {
  2. /**
  3. * @version 1.1.1
  4. *
  5. * @desc Load files in LWO3 and LWO2 format on Three.js
  6. *
  7. * LWO3 format specification:
  8. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo3.html
  9. *
  10. * LWO2 format specification:
  11. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo2.html
  12. *
  13. **/
  14. var lwoTree;
  15. var LWOLoader = function ( manager, parameters ) {
  16. THREE.Loader.call( this, manager );
  17. parameters = parameters || {};
  18. this.resourcePath = parameters.resourcePath !== undefined ? parameters.resourcePath : '';
  19. };
  20. LWOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  21. constructor: LWOLoader,
  22. load: function ( url, onLoad, onProgress, onError ) {
  23. var scope = this;
  24. var path = scope.path === '' ? extractParentUrl( url, 'Objects' ) : scope.path; // give the mesh a default name based on the filename
  25. var modelName = url.split( path ).pop().split( '.' )[ 0 ];
  26. var loader = new THREE.FileLoader( this.manager );
  27. loader.setPath( scope.path );
  28. loader.setResponseType( 'arraybuffer' );
  29. loader.load( url, function ( buffer ) {
  30. // console.time( 'Total parsing: ' );
  31. try {
  32. onLoad( scope.parse( buffer, path, modelName ) );
  33. } catch ( e ) {
  34. if ( onError ) {
  35. onError( e );
  36. } else {
  37. console.error( e );
  38. }
  39. scope.manager.itemError( url );
  40. } // console.timeEnd( 'Total parsing: ' );
  41. }, onProgress, onError );
  42. },
  43. parse: function ( iffBuffer, path, modelName ) {
  44. lwoTree = new THREE.IFFParser().parse( iffBuffer ); // console.log( 'lwoTree', lwoTree );
  45. var textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  46. return new LWOTreeParser( textureLoader ).parse( modelName );
  47. }
  48. } ); // Parse the lwoTree object
  49. function LWOTreeParser( textureLoader ) {
  50. this.textureLoader = textureLoader;
  51. }
  52. LWOTreeParser.prototype = {
  53. constructor: LWOTreeParser,
  54. parse: function ( modelName ) {
  55. this.materials = new MaterialParser( this.textureLoader ).parse();
  56. this.defaultLayerName = modelName;
  57. this.meshes = this.parseLayers();
  58. return {
  59. materials: this.materials,
  60. meshes: this.meshes
  61. };
  62. },
  63. parseLayers() {
  64. // array of all meshes for building hierarchy
  65. var meshes = []; // final array containing meshes with scene graph hierarchy set up
  66. var finalMeshes = [];
  67. var geometryParser = new GeometryParser();
  68. var scope = this;
  69. lwoTree.layers.forEach( function ( layer ) {
  70. var geometry = geometryParser.parse( layer.geometry, layer );
  71. var mesh = scope.parseMesh( geometry, layer );
  72. meshes[ layer.number ] = mesh;
  73. if ( layer.parent === - 1 ) finalMeshes.push( mesh ); else meshes[ layer.parent ].add( mesh );
  74. } );
  75. this.applyPivots( finalMeshes );
  76. return finalMeshes;
  77. },
  78. parseMesh( geometry, layer ) {
  79. var mesh;
  80. var materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );
  81. this.duplicateUVs( geometry, materials );
  82. if ( layer.geometry.type === 'points' ) mesh = new THREE.Points( geometry, materials ); else if ( layer.geometry.type === 'lines' ) mesh = new THREE.LineSegments( geometry, materials ); else mesh = new THREE.Mesh( geometry, materials );
  83. if ( layer.name ) mesh.name = layer.name; else mesh.name = this.defaultLayerName + '_layer_' + layer.number;
  84. mesh.userData.pivot = layer.pivot;
  85. return mesh;
  86. },
  87. // TODO: may need to be reversed in z to convert LWO to three.js coordinates
  88. applyPivots( meshes ) {
  89. meshes.forEach( function ( mesh ) {
  90. mesh.traverse( function ( child ) {
  91. var pivot = child.userData.pivot;
  92. child.position.x += pivot[ 0 ];
  93. child.position.y += pivot[ 1 ];
  94. child.position.z += pivot[ 2 ];
  95. if ( child.parent ) {
  96. var parentPivot = child.parent.userData.pivot;
  97. child.position.x -= parentPivot[ 0 ];
  98. child.position.y -= parentPivot[ 1 ];
  99. child.position.z -= parentPivot[ 2 ];
  100. }
  101. } );
  102. } );
  103. },
  104. getMaterials( namesArray, type ) {
  105. var materials = [];
  106. var scope = this;
  107. namesArray.forEach( function ( name, i ) {
  108. materials[ i ] = scope.getMaterialByName( name );
  109. } ); // convert materials to line or point mats if required
  110. if ( type === 'points' || type === 'lines' ) {
  111. materials.forEach( function ( mat, i ) {
  112. var spec = {
  113. color: mat.color
  114. };
  115. if ( type === 'points' ) {
  116. spec.size = 0.1;
  117. spec.map = mat.map;
  118. spec.morphTargets = mat.morphTargets;
  119. materials[ i ] = new THREE.PointsMaterial( spec );
  120. } else if ( type === 'lines' ) {
  121. materials[ i ] = new THREE.LineBasicMaterial( spec );
  122. }
  123. } );
  124. } // if there is only one material, return that directly instead of array
  125. var filtered = materials.filter( Boolean );
  126. if ( filtered.length === 1 ) return filtered[ 0 ];
  127. return materials;
  128. },
  129. getMaterialByName( name ) {
  130. return this.materials.filter( function ( m ) {
  131. return m.name === name;
  132. } )[ 0 ];
  133. },
  134. // If the material has an aoMap, duplicate UVs
  135. duplicateUVs( geometry, materials ) {
  136. var duplicateUVs = false;
  137. if ( ! Array.isArray( materials ) ) {
  138. if ( materials.aoMap ) duplicateUVs = true;
  139. } else {
  140. materials.forEach( function ( material ) {
  141. if ( material.aoMap ) duplicateUVs = true;
  142. } );
  143. }
  144. if ( ! duplicateUVs ) return;
  145. geometry.setAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  146. }
  147. };
  148. function MaterialParser( textureLoader ) {
  149. this.textureLoader = textureLoader;
  150. }
  151. MaterialParser.prototype = {
  152. constructor: MaterialParser,
  153. parse: function () {
  154. var materials = [];
  155. this.textures = {};
  156. for ( var name in lwoTree.materials ) {
  157. if ( lwoTree.format === 'LWO3' ) {
  158. materials.push( this.parseMaterial( lwoTree.materials[ name ], name, lwoTree.textures ) );
  159. } else if ( lwoTree.format === 'LWO2' ) {
  160. materials.push( this.parseMaterialLwo2( lwoTree.materials[ name ], name, lwoTree.textures ) );
  161. }
  162. }
  163. return materials;
  164. },
  165. parseMaterial( materialData, name, textures ) {
  166. var params = {
  167. name: name,
  168. side: this.getSide( materialData.attributes ),
  169. flatShading: this.getSmooth( materialData.attributes )
  170. };
  171. var connections = this.parseConnections( materialData.connections, materialData.nodes );
  172. var maps = this.parseTextureNodes( connections.maps );
  173. this.parseAttributeImageMaps( connections.attributes, textures, maps, materialData.maps );
  174. var attributes = this.parseAttributes( connections.attributes, maps );
  175. this.parseEnvMap( connections, maps, attributes );
  176. params = Object.assign( maps, params );
  177. params = Object.assign( params, attributes );
  178. var materialType = this.getMaterialType( connections.attributes );
  179. return new materialType( params );
  180. },
  181. parseMaterialLwo2( materialData, name
  182. /*, textures*/
  183. ) {
  184. var params = {
  185. name: name,
  186. side: this.getSide( materialData.attributes ),
  187. flatShading: this.getSmooth( materialData.attributes )
  188. };
  189. var attributes = this.parseAttributes( materialData.attributes, {} );
  190. params = Object.assign( params, attributes );
  191. return new THREE.MeshPhongMaterial( params );
  192. },
  193. // Note: converting from left to right handed coords by switching x -> -x in vertices, and
  194. // then switching mat THREE.FrontSide -> THREE.BackSide
  195. // NB: this means that THREE.FrontSide and THREE.BackSide have been switched!
  196. getSide( attributes ) {
  197. if ( ! attributes.side ) return THREE.BackSide;
  198. switch ( attributes.side ) {
  199. case 0:
  200. case 1:
  201. return THREE.BackSide;
  202. case 2:
  203. return THREE.FrontSide;
  204. case 3:
  205. return THREE.DoubleSide;
  206. }
  207. },
  208. getSmooth( attributes ) {
  209. if ( ! attributes.smooth ) return true;
  210. return ! attributes.smooth;
  211. },
  212. parseConnections( connections, nodes ) {
  213. var materialConnections = {
  214. maps: {}
  215. };
  216. var inputName = connections.inputName;
  217. var inputNodeName = connections.inputNodeName;
  218. var nodeName = connections.nodeName;
  219. var scope = this;
  220. inputName.forEach( function ( name, index ) {
  221. if ( name === 'Material' ) {
  222. var matNode = scope.getNodeByRefName( inputNodeName[ index ], nodes );
  223. materialConnections.attributes = matNode.attributes;
  224. materialConnections.envMap = matNode.fileName;
  225. materialConnections.name = inputNodeName[ index ];
  226. }
  227. } );
  228. nodeName.forEach( function ( name, index ) {
  229. if ( name === materialConnections.name ) {
  230. materialConnections.maps[ inputName[ index ] ] = scope.getNodeByRefName( inputNodeName[ index ], nodes );
  231. }
  232. } );
  233. return materialConnections;
  234. },
  235. getNodeByRefName( refName, nodes ) {
  236. for ( var name in nodes ) {
  237. if ( nodes[ name ].refName === refName ) return nodes[ name ];
  238. }
  239. },
  240. parseTextureNodes( textureNodes ) {
  241. var maps = {};
  242. for ( var name in textureNodes ) {
  243. var node = textureNodes[ name ];
  244. var path = node.fileName;
  245. if ( ! path ) return;
  246. var texture = this.loadTexture( path );
  247. if ( node.widthWrappingMode !== undefined ) texture.wrapS = this.getWrappingType( node.widthWrappingMode );
  248. if ( node.heightWrappingMode !== undefined ) texture.wrapT = this.getWrappingType( node.heightWrappingMode );
  249. switch ( name ) {
  250. case 'Color':
  251. maps.map = texture;
  252. break;
  253. case 'Roughness':
  254. maps.roughnessMap = texture;
  255. maps.roughness = 0.5;
  256. break;
  257. case 'Specular':
  258. maps.specularMap = texture;
  259. maps.specular = 0xffffff;
  260. break;
  261. case 'Luminous':
  262. maps.emissiveMap = texture;
  263. maps.emissive = 0x808080;
  264. break;
  265. case 'Luminous THREE.Color':
  266. maps.emissive = 0x808080;
  267. break;
  268. case 'Metallic':
  269. maps.metalnessMap = texture;
  270. maps.metalness = 0.5;
  271. break;
  272. case 'Transparency':
  273. case 'Alpha':
  274. maps.alphaMap = texture;
  275. maps.transparent = true;
  276. break;
  277. case 'Normal':
  278. maps.normalMap = texture;
  279. if ( node.amplitude !== undefined ) maps.normalScale = new THREE.Vector2( node.amplitude, node.amplitude );
  280. break;
  281. case 'Bump':
  282. maps.bumpMap = texture;
  283. break;
  284. }
  285. } // LWO BSDF materials can have both spec and rough, but this is not valid in three
  286. if ( maps.roughnessMap && maps.specularMap ) delete maps.specularMap;
  287. return maps;
  288. },
  289. // maps can also be defined on individual material attributes, parse those here
  290. // This occurs on Standard (Phong) surfaces
  291. parseAttributeImageMaps( attributes, textures, maps ) {
  292. for ( var name in attributes ) {
  293. var attribute = attributes[ name ];
  294. if ( attribute.maps ) {
  295. var mapData = attribute.maps[ 0 ];
  296. var path = this.getTexturePathByIndex( mapData.imageIndex, textures );
  297. if ( ! path ) return;
  298. var texture = this.loadTexture( path );
  299. if ( mapData.wrap !== undefined ) texture.wrapS = this.getWrappingType( mapData.wrap.w );
  300. if ( mapData.wrap !== undefined ) texture.wrapT = this.getWrappingType( mapData.wrap.h );
  301. switch ( name ) {
  302. case 'Color':
  303. maps.map = texture;
  304. break;
  305. case 'Diffuse':
  306. maps.aoMap = texture;
  307. break;
  308. case 'Roughness':
  309. maps.roughnessMap = texture;
  310. maps.roughness = 1;
  311. break;
  312. case 'Specular':
  313. maps.specularMap = texture;
  314. maps.specular = 0xffffff;
  315. break;
  316. case 'Luminosity':
  317. maps.emissiveMap = texture;
  318. maps.emissive = 0x808080;
  319. break;
  320. case 'Metallic':
  321. maps.metalnessMap = texture;
  322. maps.metalness = 1;
  323. break;
  324. case 'Transparency':
  325. case 'Alpha':
  326. maps.alphaMap = texture;
  327. maps.transparent = true;
  328. break;
  329. case 'Normal':
  330. maps.normalMap = texture;
  331. break;
  332. case 'Bump':
  333. maps.bumpMap = texture;
  334. break;
  335. }
  336. }
  337. }
  338. },
  339. parseAttributes( attributes, maps ) {
  340. var params = {}; // don't use color data if color map is present
  341. if ( attributes.Color && ! maps.map ) {
  342. params.color = new THREE.Color().fromArray( attributes.Color.value );
  343. } else params.color = new THREE.Color();
  344. if ( attributes.Transparency && attributes.Transparency.value !== 0 ) {
  345. params.opacity = 1 - attributes.Transparency.value;
  346. params.transparent = true;
  347. }
  348. if ( attributes[ 'Bump Height' ] ) params.bumpScale = attributes[ 'Bump Height' ].value * 0.1;
  349. if ( attributes[ 'Refraction Index' ] ) params.refractionRatio = 1 / attributes[ 'Refraction Index' ].value;
  350. this.parsePhysicalAttributes( params, attributes, maps );
  351. this.parseStandardAttributes( params, attributes, maps );
  352. this.parsePhongAttributes( params, attributes, maps );
  353. return params;
  354. },
  355. parsePhysicalAttributes( params, attributes
  356. /*, maps*/
  357. ) {
  358. if ( attributes.Clearcoat && attributes.Clearcoat.value > 0 ) {
  359. params.clearcoat = attributes.Clearcoat.value;
  360. if ( attributes[ 'Clearcoat Gloss' ] ) {
  361. params.clearcoatRoughness = 0.5 * ( 1 - attributes[ 'Clearcoat Gloss' ].value );
  362. }
  363. }
  364. },
  365. parseStandardAttributes( params, attributes, maps ) {
  366. if ( attributes.Luminous ) {
  367. params.emissiveIntensity = attributes.Luminous.value;
  368. if ( attributes[ 'Luminous THREE.Color' ] && ! maps.emissive ) {
  369. params.emissive = new THREE.Color().fromArray( attributes[ 'Luminous THREE.Color' ].value );
  370. } else {
  371. params.emissive = new THREE.Color( 0x808080 );
  372. }
  373. }
  374. if ( attributes.Roughness && ! maps.roughnessMap ) params.roughness = attributes.Roughness.value;
  375. if ( attributes.Metallic && ! maps.metalnessMap ) params.metalness = attributes.Metallic.value;
  376. },
  377. parsePhongAttributes( params, attributes, maps ) {
  378. if ( attributes.Diffuse ) params.color.multiplyScalar( attributes.Diffuse.value );
  379. if ( attributes.Reflection ) {
  380. params.reflectivity = attributes.Reflection.value;
  381. params.combine = THREE.AddOperation;
  382. }
  383. if ( attributes.Luminosity ) {
  384. params.emissiveIntensity = attributes.Luminosity.value;
  385. if ( ! maps.emissiveMap && ! maps.map ) {
  386. params.emissive = params.color;
  387. } else {
  388. params.emissive = new THREE.Color( 0x808080 );
  389. }
  390. } // parse specular if there is no roughness - we will interpret the material as 'Phong' in this case
  391. if ( ! attributes.Roughness && attributes.Specular && ! maps.specularMap ) {
  392. if ( attributes[ 'Color Highlight' ] ) {
  393. params.specular = new THREE.Color().setScalar( attributes.Specular.value ).lerp( params.color.clone().multiplyScalar( attributes.Specular.value ), attributes[ 'Color Highlight' ].value );
  394. } else {
  395. params.specular = new THREE.Color().setScalar( attributes.Specular.value );
  396. }
  397. }
  398. if ( params.specular && attributes.Glossiness ) params.shininess = 7 + Math.pow( 2, attributes.Glossiness.value * 12 + 2 );
  399. },
  400. parseEnvMap( connections, maps, attributes ) {
  401. if ( connections.envMap ) {
  402. var envMap = this.loadTexture( connections.envMap );
  403. if ( attributes.transparent && attributes.opacity < 0.999 ) {
  404. envMap.mapping = THREE.EquirectangularRefractionMapping; // Reflectivity and refraction mapping don't work well together in Phong materials
  405. if ( attributes.reflectivity !== undefined ) {
  406. delete attributes.reflectivity;
  407. delete attributes.combine;
  408. }
  409. if ( attributes.metalness !== undefined ) {
  410. delete attributes.metalness;
  411. }
  412. } else envMap.mapping = THREE.EquirectangularReflectionMapping;
  413. maps.envMap = envMap;
  414. }
  415. },
  416. // get texture defined at top level by its index
  417. getTexturePathByIndex( index ) {
  418. var fileName = '';
  419. if ( ! lwoTree.textures ) return fileName;
  420. lwoTree.textures.forEach( function ( texture ) {
  421. if ( texture.index === index ) fileName = texture.fileName;
  422. } );
  423. return fileName;
  424. },
  425. loadTexture( path ) {
  426. if ( ! path ) return null;
  427. var texture;
  428. texture = this.textureLoader.load( path, undefined, undefined, function () {
  429. console.warn( 'LWOLoader: non-standard resource hierarchy. Use \`resourcePath\` parameter to specify root content directory.' );
  430. } );
  431. return texture;
  432. },
  433. // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  434. getWrappingType( num ) {
  435. switch ( num ) {
  436. case 0:
  437. console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
  438. return THREE.ClampToEdgeWrapping;
  439. case 1:
  440. return THREE.RepeatWrapping;
  441. case 2:
  442. return THREE.MirroredRepeatWrapping;
  443. case 3:
  444. return THREE.ClampToEdgeWrapping;
  445. }
  446. },
  447. getMaterialType( nodeData ) {
  448. if ( nodeData.Clearcoat && nodeData.Clearcoat.value > 0 ) return THREE.MeshPhysicalMaterial;
  449. if ( nodeData.Roughness ) return THREE.MeshStandardMaterial;
  450. return THREE.MeshPhongMaterial;
  451. }
  452. };
  453. function GeometryParser() {}
  454. GeometryParser.prototype = {
  455. constructor: GeometryParser,
  456. parse( geoData, layer ) {
  457. var geometry = new THREE.BufferGeometry();
  458. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geoData.points, 3 ) );
  459. var indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
  460. geometry.setIndex( indices );
  461. this.parseGroups( geometry, geoData );
  462. geometry.computeVertexNormals();
  463. this.parseUVs( geometry, layer, indices );
  464. this.parseMorphTargets( geometry, layer, indices ); // TODO: z may need to be reversed to account for coordinate system change
  465. geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] ); // var userData = geometry.userData;
  466. // geometry = geometry.toNonIndexed()
  467. // geometry.userData = userData;
  468. return geometry;
  469. },
  470. // split quads into tris
  471. splitIndices( indices, polygonDimensions ) {
  472. var remappedIndices = [];
  473. var i = 0;
  474. polygonDimensions.forEach( function ( dim ) {
  475. if ( dim < 4 ) {
  476. for ( var k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  477. } else if ( dim === 4 ) {
  478. remappedIndices.push( indices[ i ], indices[ i + 1 ], indices[ i + 2 ], indices[ i ], indices[ i + 2 ], indices[ i + 3 ] );
  479. } else if ( dim > 4 ) {
  480. for ( var k = 1; k < dim - 1; k ++ ) {
  481. remappedIndices.push( indices[ i ], indices[ i + k ], indices[ i + k + 1 ] );
  482. }
  483. console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  484. }
  485. i += dim;
  486. } );
  487. return remappedIndices;
  488. },
  489. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  490. parseGroups( geometry, geoData ) {
  491. var tags = lwoTree.tags;
  492. var matNames = [];
  493. var elemSize = 3;
  494. if ( geoData.type === 'lines' ) elemSize = 2;
  495. if ( geoData.type === 'points' ) elemSize = 1;
  496. var remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  497. var indexNum = 0; // create new indices in numerical order
  498. var indexPairs = {}; // original indices mapped to numerical indices
  499. var prevMaterialIndex;
  500. var prevStart = 0;
  501. var currentCount = 0;
  502. for ( var i = 0; i < remappedIndices.length; i += 2 ) {
  503. var materialIndex = remappedIndices[ i + 1 ];
  504. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  505. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  506. if ( materialIndex !== prevMaterialIndex ) {
  507. var currentIndex;
  508. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  509. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  510. } else {
  511. currentIndex = indexNum;
  512. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  513. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  514. indexNum ++;
  515. }
  516. geometry.addGroup( prevStart, currentCount, currentIndex );
  517. prevStart += currentCount;
  518. prevMaterialIndex = materialIndex;
  519. currentCount = 0;
  520. }
  521. currentCount += elemSize;
  522. } // the loop above doesn't add the last group, do that here.
  523. if ( geometry.groups.length > 0 ) {
  524. var currentIndex;
  525. if ( indexPairs[ tags[ materialIndex ] ] ) {
  526. currentIndex = indexPairs[ tags[ materialIndex ] ];
  527. } else {
  528. currentIndex = indexNum;
  529. indexPairs[ tags[ materialIndex ] ] = indexNum;
  530. matNames[ indexNum ] = tags[ materialIndex ];
  531. }
  532. geometry.addGroup( prevStart, currentCount, currentIndex );
  533. } // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  534. geometry.userData.matNames = matNames;
  535. },
  536. splitMaterialIndices( polygonDimensions, indices ) {
  537. var remappedIndices = [];
  538. polygonDimensions.forEach( function ( dim, i ) {
  539. if ( dim <= 3 ) {
  540. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  541. } else if ( dim === 4 ) {
  542. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  543. } else {
  544. // ignore > 4 for now
  545. for ( var k = 0; k < dim - 2; k ++ ) {
  546. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  547. }
  548. }
  549. } );
  550. return remappedIndices;
  551. },
  552. // UV maps:
  553. // 1: are defined via index into an array of points, not into a geometry
  554. // - the geometry is also defined by an index into this array, but the indexes may not match
  555. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  556. // with preference given to the first map encountered
  557. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  558. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  559. // UV maps are defined as partially VMAP and partially VMAD
  560. // VMADs are currently not supported
  561. parseUVs( geometry, layer ) {
  562. // start by creating a UV map set to zero for the whole geometry
  563. var remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  564. return 0;
  565. } );
  566. for ( var name in layer.uvs ) {
  567. var uvs = layer.uvs[ name ].uvs;
  568. var uvIndices = layer.uvs[ name ].uvIndices;
  569. uvIndices.forEach( function ( i, j ) {
  570. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  571. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  572. } );
  573. }
  574. geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( remappedUVs, 2 ) );
  575. },
  576. parseMorphTargets( geometry, layer ) {
  577. var num = 0;
  578. for ( var name in layer.morphTargets ) {
  579. var remappedPoints = geometry.attributes.position.array.slice();
  580. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  581. var morphPoints = layer.morphTargets[ name ].points;
  582. var morphIndices = layer.morphTargets[ name ].indices;
  583. var type = layer.morphTargets[ name ].type;
  584. morphIndices.forEach( function ( i, j ) {
  585. if ( type === 'relative' ) {
  586. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  587. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  588. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  589. } else {
  590. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  591. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  592. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  593. }
  594. } );
  595. geometry.morphAttributes.position[ num ] = new THREE.Float32BufferAttribute( remappedPoints, 3 );
  596. geometry.morphAttributes.position[ num ].name = name;
  597. num ++;
  598. }
  599. geometry.morphTargetsRelative = false;
  600. }
  601. }; // ************** UTILITY FUNCTIONS **************
  602. function extractParentUrl( url, dir ) {
  603. var index = url.indexOf( dir );
  604. if ( index === - 1 ) return './';
  605. return url.substr( 0, index );
  606. }
  607. THREE.LWOLoader = LWOLoader;
  608. } )();