LWOLoader.js 24 KB

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