LWOLoader.js 24 KB

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