LWOLoader.js 23 KB

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