LWOLoader.js 23 KB

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