LWOLoader.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  1. /**
  2. * @author Lewy Blue https://github.com/looeee
  3. *
  4. * Load files in LWO3 format
  5. *
  6. * LWO3 format specification:
  7. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo3.html
  8. *
  9. * LWO2 format specification (not tested, however the loader should be largely backwards compatible)
  10. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo2.html
  11. *
  12. */
  13. THREE.LWOLoader = ( function () {
  14. var lwoTree;
  15. function LWOLoader( manager ) {
  16. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  17. }
  18. LWOLoader.prototype = {
  19. constructor: LWOLoader,
  20. crossOrigin: 'anonymous',
  21. load: function ( url, onLoad, onProgress, onError ) {
  22. var self = this;
  23. var path = ( self.path === undefined ) ? THREE.LoaderUtils.extractUrlBase( url ) : self.path;
  24. // give the mesh a default name based on the filename
  25. var modelName = url.split( path ).pop().split( '.' )[ 0 ];
  26. var loader = new THREE.FileLoader( this.manager );
  27. loader.setPath( self.path );
  28. loader.setResponseType( 'arraybuffer' );
  29. loader.load( url, function ( buffer ) {
  30. // console.time( 'Total parsing: ' );
  31. onLoad( self.parse( buffer, path, modelName ) );
  32. // console.timeEnd( 'Total parsing: ' );
  33. }, onProgress, onError );
  34. },
  35. setCrossOrigin: function ( value ) {
  36. this.crossOrigin = value;
  37. return this;
  38. },
  39. setPath: function ( value ) {
  40. this.path = value;
  41. return this;
  42. },
  43. setResourcePath: function ( value ) {
  44. this.resourcePath = value;
  45. return this;
  46. },
  47. parse: function ( iffBuffer, path, modelName ) {
  48. lwoTree = new IFFParser().parse( iffBuffer );
  49. // console.log( 'lwoTree', lwoTree );
  50. var textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  51. return new LWOTreeParser( textureLoader ).parse( modelName );
  52. }
  53. };
  54. // Parse the lwoTree object
  55. function LWOTreeParser( textureLoader ) {
  56. this.textureLoader = textureLoader;
  57. }
  58. LWOTreeParser.prototype = {
  59. constructor: LWOTreeParser,
  60. parse: function ( modelName ) {
  61. this.materials = new MaterialParser( this.textureLoader ).parse();
  62. this.defaultLayerName = modelName;
  63. this.meshes = this.parseLayers();
  64. return {
  65. materials: this.materials,
  66. meshes: this.meshes,
  67. };
  68. },
  69. parseLayers() {
  70. // array of all meshes for building hierarchy
  71. var meshes = [];
  72. // final array containing meshes with scene graph hierarchy set up
  73. var finalMeshes = [];
  74. var geometryParser = new GeometryParser();
  75. var self = this;
  76. lwoTree.layers.forEach( function ( layer ) {
  77. var geometry = geometryParser.parse( layer.geometry, layer );
  78. var mesh = self.parseMesh( geometry, layer );
  79. meshes[ layer.number ] = mesh;
  80. if ( layer.parent === - 1 ) finalMeshes.push( mesh );
  81. else meshes[ layer.parent ].add( mesh );
  82. } );
  83. this.applyPivots( finalMeshes );
  84. return finalMeshes;
  85. },
  86. parseMesh( geometry, layer ) {
  87. var mesh;
  88. var materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );
  89. this.duplicateUVs( geometry, materials );
  90. if ( layer.geometry.type === 'points' ) mesh = new THREE.Points( geometry, materials );
  91. else if ( layer.geometry.type === 'lines' ) mesh = new THREE.LineSegments( geometry, materials );
  92. else mesh = new THREE.Mesh( geometry, materials );
  93. if ( layer.name ) mesh.name = layer.name;
  94. else mesh.name = this.defaultLayerName + '_layer_' + layer.number;
  95. mesh.userData.pivot = layer.pivot;
  96. return mesh;
  97. },
  98. // TODO: may need to be reversed in z to convert LWO to three.js coordinates
  99. applyPivots( meshes ) {
  100. meshes.forEach( function ( mesh ) {
  101. mesh.traverse( function ( child ) {
  102. var pivot = child.userData.pivot;
  103. child.position.x += pivot[ 0 ];
  104. child.position.y += pivot[ 1 ];
  105. child.position.z += pivot[ 2 ];
  106. if ( child.parent ) {
  107. var parentPivot = child.parent.userData.pivot;
  108. child.position.x -= parentPivot[ 0 ];
  109. child.position.y -= parentPivot[ 1 ];
  110. child.position.z -= parentPivot[ 2 ];
  111. }
  112. } );
  113. } );
  114. },
  115. getMaterials( namesArray, type ) {
  116. var materials = [];
  117. var self = this;
  118. namesArray.forEach( function ( name, i ) {
  119. materials[ i ] = self.getMaterialByName( name );
  120. } );
  121. // convert materials to line or point mats if required
  122. if ( type === 'points' || type === 'lines' ) {
  123. materials.forEach( function ( mat, i ) {
  124. var spec = {
  125. color: mat.color,
  126. };
  127. if ( type === 'points' ) {
  128. spec.size = 0.1;
  129. spec.map = mat.map;
  130. spec.morphTargets = mat.morphTargets;
  131. materials[ i ] = new THREE.PointsMaterial( spec );
  132. } else if ( type === 'lines' ) {
  133. materials[ i ] = new THREE.LineBasicMaterial( spec );
  134. }
  135. } );
  136. }
  137. // if there is only one material, return that directly instead of array
  138. var filtered = materials.filter( Boolean );
  139. if ( filtered.length === 1 ) return filtered[ 0 ];
  140. return materials;
  141. },
  142. getMaterialByName( name ) {
  143. return this.materials.filter( function ( m ) {
  144. return m.name === name;
  145. } )[ 0 ];
  146. },
  147. // If the material has an aoMap, duplicate UVs
  148. duplicateUVs( geometry, materials ) {
  149. var duplicateUVs = false;
  150. if ( ! Array.isArray( materials ) ) {
  151. if ( materials.aoMap ) duplicateUVs = true;
  152. } else {
  153. materials.forEach( function ( material ) {
  154. if ( material.aoMap ) duplicateUVs = true;
  155. } );
  156. }
  157. if ( ! duplicateUVs ) return;
  158. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  159. },
  160. };
  161. function MaterialParser( textureLoader ) {
  162. this.textureLoader = textureLoader;
  163. }
  164. MaterialParser.prototype = {
  165. constructor: MaterialParser,
  166. parse: function () {
  167. var materials = [];
  168. this.textures = {};
  169. for ( var name in lwoTree.materials ) {
  170. materials.push( this.parseMaterial( lwoTree.materials[ name ], name, lwoTree.textures ) );
  171. }
  172. return materials;
  173. },
  174. parseMaterial( materialData, name, textures ) {
  175. var params = {
  176. name: name,
  177. side: this.getSide( materialData.attributes ),
  178. flatShading: this.getSmooth( materialData.attributes ),
  179. };
  180. var connections = this.parseConnections( materialData.connections, materialData.nodes );
  181. var maps = this.parseTextureNodes( connections.maps );
  182. this.parseAttributeImageMaps( connections.attributes, textures, maps, materialData.maps );
  183. var attributes = this.parseAttributes( connections.attributes, maps );
  184. this.parseEnvMap( connections, maps, attributes );
  185. params = Object.assign( maps, params );
  186. params = Object.assign( params, attributes );
  187. var type = connections.attributes.Roughness ? 'Standard' : 'Phong';
  188. return new THREE[ 'Mesh' + type + 'Material' ]( params );
  189. },
  190. // Note: converting from left to right handed coords by switching x -> -x in vertices, and
  191. // then switching mat FrontSide -> BackSide
  192. // NB: this means that THREE.FrontSide and THREE.BackSide have been switched!
  193. getSide( attributes ) {
  194. if ( ! attributes.side ) return THREE.BackSide;
  195. switch ( attributes.side ) {
  196. case 0:
  197. case 1:
  198. return THREE.BackSide;
  199. case 2: return THREE.FrontSide;
  200. case 3: return THREE.DoubleSide;
  201. }
  202. },
  203. getSmooth( attributes ) {
  204. if ( ! attributes.smooth ) return true;
  205. return ! attributes.smooth;
  206. },
  207. parseConnections( connections, nodes ) {
  208. var materialConnections = {
  209. maps: {}
  210. };
  211. var inputName = connections.inputName;
  212. var inputNodeName = connections.inputNodeName;
  213. var nodeName = connections.nodeName;
  214. var self = this;
  215. inputName.forEach( function ( name, index ) {
  216. if ( name === 'Material' ) {
  217. var matNode = self.getNodeByRefName( inputNodeName[ index ], nodes );
  218. materialConnections.attributes = matNode.attributes;
  219. materialConnections.envMap = matNode.fileName;
  220. materialConnections.name = inputNodeName[ index ];
  221. }
  222. } );
  223. nodeName.forEach( function ( name, index ) {
  224. if ( name === materialConnections.name ) {
  225. materialConnections.maps[ inputName[ index ] ] = self.getNodeByRefName( inputNodeName[ index ], nodes );
  226. }
  227. } );
  228. return materialConnections;
  229. },
  230. getNodeByRefName( refName, nodes ) {
  231. for ( var name in nodes ) {
  232. if ( nodes[ name ].refName === refName ) return nodes[ name ];
  233. }
  234. },
  235. parseTextureNodes( textureNodes ) {
  236. var maps = {};
  237. for ( name in textureNodes ) {
  238. var node = textureNodes[ name ];
  239. var path = node.fileName;
  240. if ( ! path ) return;
  241. var texture = this.loadTexture( path );
  242. if ( node.widthWrappingMode !== undefined ) texture.wrapS = this.getWrappingType( node.widthWrappingMode );
  243. if ( node.heightWrappingMode !== undefined ) texture.wrapT = this.getWrappingType( node.heightWrappingMode );
  244. switch ( name ) {
  245. case 'Color':
  246. maps.map = texture;
  247. break;
  248. case 'Roughness':
  249. maps.roughnessMap = texture;
  250. maps.roughness = 0.5;
  251. break;
  252. case 'Specular':
  253. maps.specularMap = texture;
  254. maps.specular = 0xffffff;
  255. break;
  256. case 'Luminous':
  257. maps.emissiveMap = texture;
  258. maps.emissive = 0x808080;
  259. break;
  260. case 'Metallic':
  261. maps.metalnessMap = texture;
  262. maps.metalness = 0.5;
  263. break;
  264. case 'Transparency':
  265. case 'Alpha':
  266. maps.alphaMap = texture;
  267. maps.transparent = true;
  268. break;
  269. case 'Normal':
  270. maps.normalMap = texture;
  271. if ( node.amplitude !== undefined ) maps.normalScale = new THREE.Vector2( node.amplitude, node.amplitude );
  272. break;
  273. case 'Bump':
  274. maps.bumpMap = texture;
  275. break;
  276. }
  277. }
  278. // LWO BSDF materials can have both spec and rough, but this is not valid in three
  279. if ( maps.roughnessMap && maps.specularMap ) delete maps.specularMap;
  280. return maps;
  281. },
  282. // maps can also be defined on individual material attributes, parse those here
  283. // This occurs on Standard (Phong) surfaces
  284. parseAttributeImageMaps( attributes, textures, maps ) {
  285. for ( var name in attributes ) {
  286. var attribute = attributes[ name ];
  287. if ( attribute.maps ) {
  288. var mapData = attribute.maps[ 0 ];
  289. var path = this.getTexturePathByIndex( mapData.imageIndex, textures );
  290. if ( ! path ) return;
  291. var texture = this.loadTexture( path );
  292. if ( mapData.wrap !== undefined ) texture.wrapS = this.getWrappingType( mapData.wrap.w );
  293. if ( mapData.wrap !== undefined ) texture.wrapT = this.getWrappingType( mapData.wrap.h );
  294. switch ( name ) {
  295. case 'Color':
  296. maps.map = texture;
  297. break;
  298. case 'Diffuse':
  299. maps.aoMap = texture;
  300. break;
  301. case 'Roughness':
  302. maps.roughnessMap = texture;
  303. maps.roughness = 1;
  304. break;
  305. case 'Specular':
  306. maps.specularMap = texture;
  307. maps.specular = 0xffffff;
  308. break;
  309. case 'Luminosity':
  310. maps.emissiveMap = texture;
  311. maps.emissive = 0x808080;
  312. break;
  313. case 'Metallic':
  314. maps.metalnessMap = texture;
  315. maps.metalness = 1;
  316. break;
  317. case 'Transparency':
  318. case 'Alpha':
  319. maps.alphaMap = texture;
  320. maps.transparent = true;
  321. break;
  322. case 'Normal':
  323. maps.normalMap = texture;
  324. break;
  325. case 'Bump':
  326. maps.bumpMap = texture;
  327. break;
  328. }
  329. }
  330. }
  331. },
  332. parseAttributes( attributes, maps ) {
  333. var params = {};
  334. // don't use color data if color map is present
  335. if ( attributes.Color && ! maps.map ) {
  336. params.color = new THREE.Color().fromArray( attributes.Color.value );
  337. } else params.color = new THREE.Color();
  338. if ( attributes.Transparency && attributes.Transparency.value !== 0 ) {
  339. params.opacity = 1 - attributes.Transparency.value;
  340. params.transparent = true;
  341. }
  342. if ( attributes[ 'Bump Height' ] ) params.bumpScale = attributes[ 'Bump Height' ].value * 0.1;
  343. if ( attributes[ 'Refraction Index' ] ) params.refractionRatio = 1 / attributes[ 'Refraction Index' ].value;
  344. this.parseStandardAttributes( params, attributes, maps );
  345. this.parsePhongAttributes( params, attributes, maps );
  346. return params;
  347. },
  348. parseStandardAttributes( params, attributes, maps ) {
  349. if ( attributes.Luminous && attributes.Luminous.value !== 0 && attributes[ 'Luminous Color' ] ) {
  350. var emissiveColor = attributes[ 'Luminous Color' ].value.map( function ( val ) {
  351. return val * attributes.Luminous.value;
  352. } );
  353. params.emissive = new THREE.Color().fromArray( emissiveColor );
  354. }
  355. if ( attributes.Roughness && ! maps.roughnessMap ) params.roughness = attributes.Roughness.value;
  356. if ( attributes.Metallic && ! maps.metalnessMap ) params.metalness = attributes.Metallic.value;
  357. },
  358. parsePhongAttributes( params, attributes, maps ) {
  359. if ( attributes.Diffuse ) params.color.multiplyScalar( attributes.Diffuse.value );
  360. if ( attributes.Reflection ) {
  361. params.reflectivity = attributes.Reflection.value;
  362. params.combine = THREE.AddOperation;
  363. }
  364. if ( attributes.Luminosity && ! maps.emissiveMap ) params.emissive = new THREE.Color().setScalar( attributes.Luminosity.value );
  365. if ( attributes.Glossiness !== undefined ) params.shininess = 5 + Math.pow( attributes.Glossiness.value * 7, 6 );
  366. // parse specular if there is no roughness - we will interpret the material as 'Phong' in this case
  367. if ( ! attributes.Roughness && attributes.Specular && ! maps.specularMap ) params.specular = new THREE.Color().setScalar( attributes.Specular.value * 1.5 );
  368. },
  369. parseEnvMap( connections, maps, attributes ) {
  370. if ( connections.envMap ) {
  371. var envMap = this.loadTexture( connections.envMap );
  372. if ( attributes.transparent && attributes.opacity < 0.999 ) {
  373. envMap.mapping = THREE.EquirectangularRefractionMapping;
  374. // Reflectivity and refraction mapping don't work well together in Phong materials
  375. if ( attributes.reflectivity !== undefined ) {
  376. delete attributes.reflectivity;
  377. delete attributes.combine;
  378. }
  379. if ( attributes.metalness !== undefined ) {
  380. delete attributes.metalness;
  381. }
  382. } else envMap.mapping = THREE.EquirectangularReflectionMapping;
  383. maps.envMap = envMap;
  384. }
  385. },
  386. // get texture defined at top level by its index
  387. getTexturePathByIndex( index ) {
  388. var fileName = '';
  389. if ( ! lwoTree.textures ) return fileName;
  390. lwoTree.textures.forEach( function ( texture ) {
  391. if ( texture.index === index ) fileName = texture.fileName;
  392. } );
  393. return fileName;
  394. },
  395. loadTexture( path ) {
  396. if ( ! path ) return null;
  397. return this.textureLoader.load( this.cleanPath( path ) );
  398. },
  399. // if texture files are contained in the standard "../Images"
  400. // directory, then LW stores the path as relative.
  401. // Otherwise it stores the full drive path, on windows "C:/dir/subdir/texture.jpg"
  402. cleanPath( path ) {
  403. if ( path.indexOf( 'Images' ) === 0 ) return '../' + path;
  404. return path.split( '/' ).pop().split( '\\' ).pop();
  405. },
  406. // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  407. getWrappingType( num ) {
  408. switch ( num ) {
  409. case 0:
  410. console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
  411. return THREE.ClampToEdgeWrapping;
  412. case 1: return THREE.RepeatWrapping;
  413. case 2: return THREE.MirroredRepeatWrapping;
  414. case 3: return THREE.ClampToEdgeWrapping;
  415. }
  416. },
  417. getType( nodeData ) {
  418. if ( nodeData.roughness ) return 'Standard';
  419. return 'Phong';
  420. },
  421. };
  422. function GeometryParser() {}
  423. GeometryParser.prototype = {
  424. constructor: GeometryParser,
  425. parse( geoData, layer ) {
  426. var geometry = new THREE.BufferGeometry();
  427. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geoData.points, 3 ) );
  428. var indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
  429. geometry.setIndex( indices );
  430. this.parseGroups( geometry, geoData );
  431. geometry.computeVertexNormals();
  432. this.parseUVs( geometry, layer, indices );
  433. this.parseMorphTargets( geometry, layer, indices );
  434. // TODO: z may need to be reversed to account for coordinate system change
  435. geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] );
  436. // var userData = geometry.userData;
  437. // geometry = geometry.toNonIndexed()
  438. // geometry.userData = userData;
  439. return geometry;
  440. },
  441. // split quads into tris
  442. splitIndices( indices, polygonDimensions ) {
  443. var remappedIndices = [];
  444. var i = 0;
  445. polygonDimensions.forEach( function ( dim ) {
  446. if ( dim < 4 ) {
  447. for ( var k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  448. } else if ( dim === 4 ) {
  449. remappedIndices.push(
  450. indices[ i ],
  451. indices[ i + 1 ],
  452. indices[ i + 2 ],
  453. indices[ i ],
  454. indices[ i + 2 ],
  455. indices[ i + 3 ]
  456. );
  457. } else if ( dim > 4 ) console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  458. i += dim;
  459. } );
  460. return remappedIndices;
  461. },
  462. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  463. parseGroups( geometry, geoData ) {
  464. var tags = lwoTree.tags;
  465. var matNames = [];
  466. var elemSize = 3;
  467. if ( geoData.type === 'lines' ) elemSize = 2;
  468. if ( geoData.type === 'points' ) elemSize = 1;
  469. var remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  470. var indexNum = 0; // create new indices in numerical order
  471. var indexPairs = {}; // original indices mapped to numerical indices
  472. var prevMaterialIndex;
  473. var prevStart = 0;
  474. var currentCount = 0;
  475. for ( var i = 0; i < remappedIndices.length; i += 2 ) {
  476. var materialIndex = remappedIndices[ i + 1 ];
  477. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  478. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  479. if ( materialIndex !== prevMaterialIndex ) {
  480. var currentIndex;
  481. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  482. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  483. } else {
  484. currentIndex = indexNum;
  485. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  486. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  487. indexNum ++;
  488. }
  489. geometry.addGroup( prevStart, currentCount, currentIndex );
  490. prevStart += currentCount;
  491. prevMaterialIndex = materialIndex;
  492. currentCount = 0;
  493. }
  494. currentCount += elemSize;
  495. }
  496. // the loop above doesn't add the last group, do that here.
  497. if ( geometry.groups.length > 0 ) {
  498. var currentIndex;
  499. if ( indexPairs[ tags[ materialIndex ] ] ) {
  500. currentIndex = indexPairs[ tags[ materialIndex ] ];
  501. } else {
  502. currentIndex = indexNum;
  503. indexPairs[ tags[ materialIndex ] ] = indexNum;
  504. matNames[ indexNum ] = tags[ materialIndex ];
  505. }
  506. geometry.addGroup( prevStart, currentCount, currentIndex );
  507. }
  508. // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  509. geometry.userData.matNames = matNames;
  510. },
  511. splitMaterialIndices( polygonDimensions, indices ) {
  512. var remappedIndices = [];
  513. polygonDimensions.forEach( function ( dim, i ) {
  514. if ( dim <= 3 ) {
  515. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  516. } else if ( dim === 4 ) {
  517. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  518. } // ignore > 4 for now
  519. } );
  520. return remappedIndices;
  521. },
  522. // UV maps:
  523. // 1: are defined via index into an array of points, not into a geometry
  524. // - the geometry is also defined by an index into this array, but the indexes may not match
  525. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  526. // with preference given to the first map encountered
  527. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  528. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  529. // UV maps are defined as partially VMAP and partially VMAD
  530. // VMADs are currently not supported
  531. parseUVs( geometry, layer ) {
  532. // start by creating a UV map set to zero for the whole geometry
  533. var remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  534. return 0;
  535. } );
  536. for ( var name in layer.uvs ) {
  537. var uvs = layer.uvs[ name ].uvs;
  538. var uvIndices = layer.uvs[ name ].uvIndices;
  539. uvIndices.forEach( function ( i, j ) {
  540. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  541. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  542. } );
  543. }
  544. geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( remappedUVs, 2 ) );
  545. },
  546. parseMorphTargets( geometry, layer ) {
  547. var num = 0;
  548. for ( var name in layer.morphTargets ) {
  549. var remappedPoints = geometry.attributes.position.array.slice();
  550. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  551. var morphPoints = layer.morphTargets[ name ].points;
  552. var morphIndices = layer.morphTargets[ name ].indices;
  553. var type = layer.morphTargets[ name ].type;
  554. morphIndices.forEach( function ( i, j ) {
  555. if ( type === 'relative' ) {
  556. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  557. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  558. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  559. } else {
  560. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  561. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  562. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  563. }
  564. } );
  565. geometry.morphAttributes.position[ num ] = new THREE.Float32BufferAttribute( remappedPoints, 3 );
  566. geometry.morphAttributes.position[ num ].name = name;
  567. num ++;
  568. }
  569. },
  570. };
  571. // parse data from the IFF buffer.
  572. // LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes
  573. //
  574. // ATOMIC DATA TYPES
  575. // ID Tag - 4x 7 bit uppercase ASCII chars: ID4
  576. // signed integer, 1, 2, or 4 byte length: I1, I2, I4
  577. // unsigned integer, 1, 2, or 4 byte length: U1, U2, U4
  578. // float, 4 byte length: F4
  579. // string, series of ASCII chars followed by null byte (If the length of the string including the null terminating byte is odd, an extra null is added so that the data that follows will begin on an even byte boundary): S0
  580. //
  581. // COMPOUND DATA TYPES
  582. // Variable-length Index (index into an array or collection): U2 or U4 : VX
  583. // Color (RGB): F4 + F4 + F4: COL12
  584. // Coordinate (x, y, z): F4 + F4 + F4: VEC12
  585. // Percentage F4 data type from 0->1 with 1 = 100%: FP4
  586. // Angle in radian F4: ANG4
  587. // Filename (string) S0: FNAM0
  588. // XValue F4 + index (VX) + optional envelope( ENVL ): XVAL
  589. // XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3
  590. //
  591. // The IFF file is arranged in chunks:
  592. // CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte
  593. // optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size
  594. // Chunks are combined in Forms (collections of chunks)
  595. // FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM )
  596. // CHUNKS and FORMS are collectively referred to as blocks
  597. // The entire file is contained in one top level FORM
  598. function IFFParser() {}
  599. IFFParser.prototype = {
  600. constructor: IFFParser,
  601. parse: function ( buffer ) {
  602. // dump the whole buffer as a string for testing
  603. // printBuffer( buffer );
  604. this.reader = new DataViewReader( buffer );
  605. this.tree = {
  606. materials: {},
  607. layers: [],
  608. tags: [],
  609. textures: [],
  610. };
  611. // start out at the top level to add any data before first layer is encountered
  612. this.currentLayer = this.tree;
  613. this.currentForm = this.tree;
  614. // parse blocks until end of file is reached
  615. while ( ! this.reader.endOfFile() ) this.parseBlock();
  616. return this.tree;
  617. },
  618. parseBlock() {
  619. var blockID = this.reader.getIDTag();
  620. var length = this.reader.getUint32(); // size of data in bytes
  621. // Data types may be found in either LWO2 OR LWO3 spec
  622. switch ( blockID ) {
  623. case 'FORM': // form blocks may consist of sub -chunks or sub-forms
  624. this.parseForm( length );
  625. break;
  626. // SKIPPED CHUNKS
  627. // MISC skipped
  628. case 'ICON': // Thumbnail Icon Image
  629. case 'VMPA': // Vertex Map Parameter
  630. case 'BBOX': // bounding box
  631. // case 'VMMD':
  632. // case 'VTYP':
  633. // normal maps can be specified, normally on models imported from other applications. Currently ignored
  634. case 'NORM':
  635. // ENVL FORM skipped
  636. case 'PRE ':
  637. case 'POST':
  638. case 'KEY ':
  639. case 'SPAN':
  640. // CLIP FORM skipped
  641. case 'TIME':
  642. case 'CLRS':
  643. case 'CLRA':
  644. case 'FILT':
  645. case 'DITH':
  646. case 'CONT':
  647. case 'BRIT':
  648. case 'SATR':
  649. case 'HUE ':
  650. case 'GAMM':
  651. case 'NEGA':
  652. case 'IFLT':
  653. case 'PFLT':
  654. // Image Map Layer skipped
  655. case 'PROJ':
  656. case 'AXIS':
  657. case 'AAST':
  658. case 'PIXB':
  659. case 'STCK':
  660. // Procedural Textures skipped
  661. case 'VALU':
  662. // Gradient Textures skipped
  663. case 'PNAM':
  664. case 'INAM':
  665. case 'GRST':
  666. case 'GREN':
  667. case 'GRPT':
  668. case 'FKEY':
  669. case 'IKEY':
  670. // Texture Mapping Form skipped
  671. case 'CSYS':
  672. // Surface CHUNKs skipped
  673. case 'OPAQ': // top level 'opacity' checkbox
  674. case 'CMAP': // clip map
  675. // Surface node CHUNKS skipped
  676. // These mainly specify the node editor setup in LW
  677. case 'NLOC':
  678. case 'NZOM':
  679. case 'NVER':
  680. case 'NSRV':
  681. case 'NCRD':
  682. case 'NMOD':
  683. case 'NPRW':
  684. case 'NPLA':
  685. case 'VERS':
  686. case 'ENUM':
  687. case 'FLAG':
  688. case 'TAG ':
  689. // Car Material CHUNKS
  690. case 'CGMD':
  691. case 'CGTY':
  692. case 'CGST':
  693. case 'CGEN':
  694. case 'CGTS':
  695. case 'CGTE':
  696. case 'OSMP':
  697. case 'OMDE':
  698. case 'OUTR':
  699. this.reader.skip( length );
  700. break;
  701. // Skipped LWO2 chunks
  702. case 'DIFF': // diffuse level, may be necessary to modulate COLR with this
  703. case 'TRNL':
  704. case 'REFL':
  705. case 'GLOS':
  706. case 'SHRP':
  707. case 'RFOP':
  708. case 'RSAN':
  709. case 'TROP':
  710. case 'RBLR':
  711. case 'TBLR':
  712. case 'CLRH':
  713. case 'CLRF':
  714. case 'ADTR':
  715. case 'GLOW':
  716. case 'LINE':
  717. case 'ALPH':
  718. case 'LINE':
  719. case 'VCOL':
  720. case 'ENAB':
  721. this.reader.skip( length );
  722. break;
  723. // Texture node chunks (not in spec)
  724. case 'IPIX': // usePixelBlending
  725. case 'IMIP': // useMipMaps
  726. case 'IMOD': // imageBlendingMode
  727. case 'AMOD': // unknown
  728. case 'IINV': // imageInvertAlpha
  729. case 'INCR': // imageInvertColor
  730. case 'IAXS': // imageAxis ( for non-UV maps)
  731. case 'IFOT': // imageFallofType
  732. case 'ITIM': // timing for animated textures
  733. case 'IWRL':
  734. case 'IUTI':
  735. case 'IINX':
  736. case 'IINY':
  737. case 'IINZ':
  738. case 'IREF': // possibly a VX for reused texture nodes
  739. if ( length === 4 ) this.currentNode[ blockID ] = this.reader.getInt32();
  740. else this.reader.skip( length );
  741. break;
  742. case 'OTAG':
  743. this.parseObjectTag();
  744. break;
  745. case 'LAYR':
  746. this.parseLayer( length );
  747. break;
  748. case 'PNTS':
  749. this.parsePoints( length );
  750. break;
  751. case 'VMAP':
  752. this.parseVertexMapping( length );
  753. break;
  754. case 'POLS':
  755. this.parsePolygonList( length );
  756. break;
  757. case 'TAGS':
  758. this.parseTagStrings( length );
  759. break;
  760. case 'PTAG':
  761. this.parsePolygonTagMapping( length );
  762. break;
  763. case 'VMAD':
  764. this.parseVertexMapping( length, true );
  765. break;
  766. // Misc CHUNKS
  767. case 'DESC': // Description Line
  768. this.currentForm.description = this.reader.getString();
  769. break;
  770. case 'TEXT':
  771. case 'CMNT':
  772. case 'NCOM':
  773. this.currentForm.comment = this.reader.getString();
  774. break;
  775. // Envelope Form
  776. case 'NAME':
  777. this.currentForm.channelName = this.reader.getString();
  778. break;
  779. // Image Map Layer
  780. case 'WRAP':
  781. this.currentForm.wrap = { w: this.reader.getUint16(), h: this.reader.getUint16() };
  782. break;
  783. case 'IMAG':
  784. var index = this.reader.getVariableLengthIndex();
  785. this.currentForm.imageIndex = index;
  786. break;
  787. // Texture Mapping Form
  788. case 'OREF':
  789. this.currentForm.referenceObject = this.reader.getString();
  790. break;
  791. case 'ROID':
  792. this.currentForm.referenceObjectID = this.reader.getUint32();
  793. break;
  794. // Surface Blocks
  795. case 'SSHN':
  796. this.currentSurface.surfaceShaderName = this.reader.getString();
  797. break;
  798. case 'AOVN':
  799. this.currentSurface.surfaceCustomAOVName = this.reader.getString();
  800. break;
  801. // Nodal Blocks
  802. case 'NSTA':
  803. this.currentForm.disabled = this.reader.getUint16();
  804. break;
  805. case 'NRNM':
  806. this.currentForm.realName = this.reader.getString();
  807. break;
  808. case 'NNME':
  809. this.currentForm.refName = this.reader.getString();
  810. this.currentSurface.nodes[ this.currentForm.refName ] = this.currentForm;
  811. break;
  812. // Nodal Blocks : connections
  813. case 'INME':
  814. if ( ! this.currentForm.nodeName ) this.currentForm.nodeName = [];
  815. this.currentForm.nodeName.push( this.reader.getString() );
  816. break;
  817. case 'IINN':
  818. if ( ! this.currentForm.inputNodeName ) this.currentForm.inputNodeName = [];
  819. this.currentForm.inputNodeName.push( this.reader.getString() );
  820. break;
  821. case 'IINM':
  822. if ( ! this.currentForm.inputName ) this.currentForm.inputName = [];
  823. this.currentForm.inputName.push( this.reader.getString() );
  824. break;
  825. case 'IONM':
  826. if ( ! this.currentForm.inputOutputName ) this.currentForm.inputOutputName = [];
  827. this.currentForm.inputOutputName.push( this.reader.getString() );
  828. break;
  829. case 'FNAM':
  830. this.currentForm.fileName = this.reader.getString();
  831. break;
  832. case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
  833. if ( length === 4 ) this.currentForm.textureChannel = this.reader.getIDTag();
  834. else this.reader.skip( length );
  835. break;
  836. // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
  837. case 'SMAN':
  838. var maxSmoothingAngle = this.reader.getFloat32();
  839. this.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
  840. break;
  841. case 'ENAB':
  842. this.currentForm.enabled = this.reader.getUint16();
  843. break;
  844. // LWO2: Basic Surface Parameters
  845. case 'COLR':
  846. this.currentSurface.attributes.color = this.reader.getFloat32Array( 3 );
  847. this.reader.skip( 2 ); // VX: envelope
  848. break;
  849. case 'LUMI':
  850. this.currentSurface.attributes.luminosityLevel = this.reader.getFloat32();
  851. this.reader.skip( 2 );
  852. break;
  853. case 'SPEC':
  854. this.currentSurface.attributes.specularLevel = this.reader.getFloat32();
  855. this.reader.skip( 2 );
  856. break;
  857. case 'REFL':
  858. this.currentSurface.attributes.reflectivity = this.reader.getFloat32();
  859. this.reader.skip( 2 );
  860. break;
  861. case 'TRAN':
  862. this.currentSurface.attributes.opacity = this.reader.getFloat32();
  863. this.reader.skip( 2 );
  864. break;
  865. case 'BUMP':
  866. this.currentSurface.attributes.bumpStrength = this.reader.getFloat32();
  867. this.reader.skip( 2 );
  868. break;
  869. case 'SIDE':
  870. this.currentSurface.attributes.side = this.reader.getUint16();
  871. break;
  872. case 'RIMG':
  873. this.currentSurface.attributes.reflectionMap = this.reader.getVariableLengthIndex();
  874. break;
  875. case 'RIND':
  876. this.currentSurface.attributes.refractiveIndex = this.reader.getFloat32();
  877. this.reader.skip( 2 );
  878. break;
  879. case 'TIMG':
  880. this.currentSurface.attributes.refractionMap = this.reader.getVariableLengthIndex();
  881. break;
  882. case 'IMAP':
  883. this.currentSurface.attributes.imageMapIndex = this.reader.getUint32();
  884. break;
  885. case 'IUVI': // uv channel name
  886. this.currentNode.UVChannel = this.reader.getString( length );
  887. break;
  888. case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  889. this.currentNode.widthWrappingMode = this.reader.getUint32();
  890. break;
  891. case 'IVTL': // heightWrappingMode
  892. this.currentNode.heightWrappingMode = this.reader.getUint32();
  893. break;
  894. default:
  895. this.parseUnknownCHUNK( blockID, length );
  896. }
  897. if ( this.reader.offset >= this.currentFormEnd ) {
  898. this.currentForm = this.parentForm;
  899. }
  900. },
  901. ///
  902. // FORM PARSING METHODS
  903. ///
  904. // Forms are organisational and can contain any number of sub chunks and sub forms
  905. // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  906. parseForm( length ) {
  907. var type = this.reader.getIDTag();
  908. switch ( type ) {
  909. // SKIPPED FORMS
  910. // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
  911. case 'ISEQ': // Image sequence
  912. case 'ANIM': // plug in animation
  913. case 'STCC': // Color-cycling Still
  914. case 'VPVL':
  915. case 'VPRM':
  916. case 'NROT':
  917. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  918. case 'WRPH': // image wrap h
  919. case 'FUNC':
  920. case 'FALL':
  921. case 'OPAC':
  922. case 'GRAD': // gradient texture
  923. case 'ENVS':
  924. case 'VMOP':
  925. case 'VMBG':
  926. // Car Material FORMS
  927. case 'OMAX':
  928. case 'STEX':
  929. case 'CKBG':
  930. case 'CKEY':
  931. case 'VMLA':
  932. case 'VMLB':
  933. this.skipForm( length ); // not currently supported
  934. break;
  935. // if break; is called directly, the position in the lwoTree is not created
  936. // any sub chunks and forms are added to the parent form instead
  937. case 'META':
  938. case 'NNDS':
  939. case 'NODS':
  940. case 'NDTA':
  941. case 'ADAT':
  942. case 'AOVS':
  943. case 'BLOK':
  944. // used by texture nodes
  945. case 'IBGC': // imageBackgroundColor
  946. case 'IOPC': // imageOpacity
  947. case 'IIMG': // hold reference to image path
  948. case 'TXTR':
  949. // this.setupForm( type, length );
  950. break;
  951. case 'IFAL': // imageFallof
  952. case 'ISCL': // imageScale
  953. case 'IPOS': // imagePosition
  954. case 'IROT': // imageRotation
  955. case 'IBMP':
  956. case 'IUTD':
  957. case 'IVTD':
  958. this.parseTextureNodeAttribute( type );
  959. break;
  960. case 'LWO3':
  961. this.tree.format = type;
  962. break;
  963. case 'ENVL':
  964. this.parseEnvelope( length );
  965. break;
  966. // CLIP FORM AND SUB FORMS
  967. case 'CLIP':
  968. this.parseClip( length );
  969. break;
  970. case 'STIL':
  971. this.parseImage();
  972. break;
  973. case 'XREF': // clone of another STIL
  974. this.reader.skip( 8 ); // unknown
  975. this.currentForm.referenceTexture = {
  976. index: this.reader.getUint32(),
  977. refName: this.reader.getString() // internal unique ref
  978. };
  979. break;
  980. // Not in spec, used by texture nodes
  981. case 'IMST':
  982. this.parseImageStateForm( length );
  983. break;
  984. // SURF FORM AND SUB FORMS
  985. case 'SURF':
  986. this.parseSurfaceForm( length );
  987. break;
  988. case 'VALU': // Not in spec
  989. this.parseValueForm( length );
  990. break;
  991. case 'NTAG':
  992. this.parseSubNode( length );
  993. break;
  994. case 'NNDS':
  995. this.setupForm( 'nodes', length );
  996. break;
  997. case 'ATTR': // BSDF Node Attributes
  998. case 'SATR': // Standard Node Attributes
  999. this.setupForm( 'attributes', length );
  1000. break;
  1001. case 'NCON':
  1002. this.parseConnections( length );
  1003. break;
  1004. case 'SSHA':
  1005. this.parentForm = this.currentForm;
  1006. this.currentForm = this.currentSurface;
  1007. this.setupForm( 'surfaceShader', length );
  1008. break;
  1009. case 'SSHD':
  1010. this.setupForm( 'surfaceShaderData', length );
  1011. break;
  1012. case 'ENTR': // Not in spec
  1013. this.parseEntryForm( length );
  1014. break;
  1015. // Image Map Layer
  1016. case 'IMAP':
  1017. this.parseImageMap( length );
  1018. break;
  1019. case 'TAMP':
  1020. this.parseXVAL( 'amplitude', length );
  1021. break;
  1022. //Texture Mapping Form
  1023. case 'TMAP':
  1024. this.setupForm( 'textureMap', length );
  1025. break;
  1026. case 'CNTR':
  1027. this.parseXVAL3( 'center', length );
  1028. break;
  1029. case 'SIZE':
  1030. this.parseXVAL3( 'scale', length );
  1031. break;
  1032. case 'ROTA':
  1033. this.parseXVAL3( 'rotation', length );
  1034. break;
  1035. default:
  1036. this.parseUnknownForm( type, length );
  1037. }
  1038. },
  1039. setupForm( type, length ) {
  1040. if ( ! this.currentForm ) this.currentForm = this.currentNode;
  1041. this.currentFormEnd = this.reader.offset + length;
  1042. this.parentForm = this.currentForm;
  1043. if ( ! this.currentForm[ type ] ) {
  1044. this.currentForm[ type ] = {};
  1045. this.currentForm = this.currentForm[ type ];
  1046. } else {
  1047. // should never see this unless there's a bug in the reader
  1048. console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );
  1049. this.currentForm = this.currentForm[ type ];
  1050. }
  1051. },
  1052. skipForm( length ) {
  1053. this.reader.skip( length - 4 );
  1054. },
  1055. parseUnknownForm( type, length ) {
  1056. console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );
  1057. printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
  1058. this.reader.skip( length - 4 );
  1059. },
  1060. parseSurfaceForm( length ) {
  1061. this.reader.skip( 8 ); // unknown Uint32 x2
  1062. var name = this.reader.getString();
  1063. var surface = {
  1064. attributes: {}, // LWO2 style non-node attributes will go here
  1065. connections: {},
  1066. name: name,
  1067. nodes: {},
  1068. source: this.reader.getString(),
  1069. };
  1070. this.tree.materials[ name ] = surface;
  1071. this.currentSurface = surface;
  1072. this.parentForm = this.tree.materials;
  1073. this.currentForm = surface;
  1074. this.currentFormEnd = this.reader.offset + length;
  1075. },
  1076. parseSubNode( length ) {
  1077. // parse the NRNM CHUNK of the subnode FORM to get
  1078. // a meaningful name for the subNode
  1079. // some subnodes can be renamed, but Input and Surface cannot
  1080. this.reader.skip( 8 ); // NRNM + length
  1081. var name = this.reader.getString();
  1082. var node = {
  1083. name: name
  1084. };
  1085. this.currentForm = node;
  1086. this.currentNode = node;
  1087. this.currentFormEnd = this.reader.offset + length;
  1088. },
  1089. // collect attributes from all nodes at the top level of a surface
  1090. parseConnections( length ) {
  1091. this.currentFormEnd = this.reader.offset + length;
  1092. this.parentForm = this.currentForm;
  1093. this.currentForm = this.currentSurface.connections;
  1094. },
  1095. // surface node attribute data, e.g. specular, roughness etc
  1096. parseEntryForm( length ) {
  1097. this.reader.skip( 8 ); // NAME + length
  1098. var name = this.reader.getString();
  1099. this.currentForm = this.currentNode.attributes;
  1100. this.setupForm( name, length );
  1101. },
  1102. // parse values from material - doesn't match up to other LWO3 data types
  1103. // sub form of entry form
  1104. parseValueForm() {
  1105. this.reader.skip( 8 ); // unknown + length
  1106. var valueType = this.reader.getString();
  1107. if ( valueType === 'double' ) {
  1108. this.currentForm.value = this.reader.getUint64();
  1109. } else if ( valueType === 'int' ) {
  1110. this.currentForm.value = this.reader.getUint32();
  1111. } else if ( valueType === 'vparam' ) {
  1112. this.reader.skip( 24 );
  1113. this.currentForm.value = this.reader.getFloat64();
  1114. } else if ( valueType === 'vparam3' ) {
  1115. this.reader.skip( 24 );
  1116. this.currentForm.value = this.reader.getFloat64Array( 3 );
  1117. }
  1118. },
  1119. // holds various data about texture node image state
  1120. // Data other thanmipMapLevel unknown
  1121. parseImageStateForm() {
  1122. this.reader.skip( 8 ); // unknown
  1123. this.currentForm.mipMapLevel = this.reader.getFloat32();
  1124. },
  1125. // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  1126. parseImageMap( length ) {
  1127. this.currentFormEnd = this.reader.offset + length;
  1128. this.parentForm = this.currentForm;
  1129. if ( ! this.currentForm.maps ) this.currentForm.maps = [];
  1130. var map = {};
  1131. this.currentForm.maps.push( map );
  1132. this.currentForm = map;
  1133. this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX
  1134. },
  1135. parseTextureNodeAttribute( type ) {
  1136. this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32
  1137. this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32
  1138. switch ( type ) {
  1139. case 'ISCL':
  1140. this.currentNode.scale = this.reader.getFloat32Array( 3 );
  1141. break;
  1142. case 'IPOS':
  1143. this.currentNode.position = this.reader.getFloat32Array( 3 );
  1144. break;
  1145. case 'IROT':
  1146. this.currentNode.rotation = this.reader.getFloat32Array( 3 );
  1147. break;
  1148. case 'IFAL':
  1149. this.currentNode.falloff = this.reader.getFloat32Array( 3 );
  1150. break;
  1151. case 'IBMP':
  1152. this.currentNode.amplitude = this.reader.getFloat32();
  1153. break;
  1154. case 'IUTD':
  1155. this.currentNode.uTiles = this.reader.getFloat32();
  1156. break;
  1157. case 'IVTD':
  1158. this.currentNode.vTiles = this.reader.getFloat32();
  1159. break;
  1160. }
  1161. this.reader.skip( 2 ); // unknown
  1162. },
  1163. // ENVL forms are currently ignored
  1164. parseEnvelope( length ) {
  1165. this.reader.skip( length - 4 ); // skipping entirely for now
  1166. },
  1167. ///
  1168. // CHUNK PARSING METHODS
  1169. ///
  1170. // clips can either be defined inside a surface node, or at the top
  1171. // level and they have a different format in each case
  1172. parseClip( length ) {
  1173. var tag = this.reader.getIDTag();
  1174. // inside surface node
  1175. if ( tag === 'FORM' ) {
  1176. this.reader.skip( 16 );
  1177. this.currentNode.fileName = this.reader.getString();
  1178. return;
  1179. }
  1180. // otherwise top level
  1181. this.reader.setOffset( this.reader.offset - 4 );
  1182. this.currentFormEnd = this.reader.offset + length;
  1183. this.parentForm = this.currentForm;
  1184. this.reader.skip( 8 ); // unknown
  1185. var texture = {
  1186. index: this.reader.getUint32()
  1187. };
  1188. this.tree.textures.push( texture );
  1189. this.currentForm = texture;
  1190. },
  1191. parseImage() {
  1192. this.reader.skip( 8 ); // unknown
  1193. this.currentForm.fileName = this.reader.getString();
  1194. },
  1195. parseXVAL( type, length ) {
  1196. var endOffset = this.reader.offset + length - 4;
  1197. this.reader.skip( 8 );
  1198. this.currentForm[ type ] = this.reader.getFloat32();
  1199. this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope
  1200. },
  1201. parseXVAL3( type, length ) {
  1202. var endOffset = this.reader.offset + length - 4;
  1203. this.reader.skip( 8 );
  1204. this.currentForm[ type ] = {
  1205. x: this.reader.getFloat32(),
  1206. y: this.reader.getFloat32(),
  1207. z: this.reader.getFloat32(),
  1208. };
  1209. this.reader.setOffset( endOffset );
  1210. },
  1211. // Tags associated with an object
  1212. // OTAG { type[ID4], tag-string[S0] }
  1213. parseObjectTag() {
  1214. if ( ! this.tree.objectTags ) this.tree.objectTags = {};
  1215. this.tree.objectTags[ this.reader.getIDTag() ] = {
  1216. tagString: this.reader.getString()
  1217. };
  1218. },
  1219. // Signals the start of a new layer. All the data chunks which follow will be included in this layer until another layer chunk is encountered.
  1220. // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  1221. parseLayer( length ) {
  1222. var layer = {
  1223. number: this.reader.getUint16(),
  1224. flags: this.reader.getUint16(), // If the least significant bit of flags is set, the layer is hidden.
  1225. pivot: this.reader.getFloat32Array( 3 ), // Note: this seems to be superflous, as the geometry is translated when pivot is present
  1226. name: this.reader.getString(),
  1227. };
  1228. this.tree.layers.push( layer );
  1229. this.currentLayer = layer;
  1230. var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength
  1231. // if we have not reached then end of the layer block, there must be a parent defined
  1232. this.currentLayer.parent = ( parsedLength < length ) ? this.reader.getUint16() : - 1; // omitted or -1 for no parent
  1233. },
  1234. // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  1235. // Converting from left to right handed coordinate system:
  1236. // x -> -x and switch material FrontSide -> BackSide
  1237. parsePoints( length ) {
  1238. this.currentPoints = [];
  1239. for ( var i = 0; i < length / 4; i += 3 ) {
  1240. // z -> -z to match three.js right handed coords
  1241. this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1242. }
  1243. },
  1244. // parse VMAP or VMAD
  1245. // Associates a set of floating-point vectors with a set of points.
  1246. // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  1247. // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  1248. // Similar to VMAP UVs, but associates with polygon vertices rather than points
  1249. // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name,
  1250. // if they exist. The vector values in the VMAD will then replace those in the
  1251. // corresponding VMAP, but only for calculations involving the specified polygons.
  1252. // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  1253. parseVertexMapping( length, discontinuous ) {
  1254. var finalOffset = this.reader.offset + length;
  1255. var channelName = this.reader.getString();
  1256. if ( this.reader.offset === finalOffset ) {
  1257. // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
  1258. this.currentForm.UVChannel = channelName;
  1259. return;
  1260. }
  1261. // otherwise reset to initial length and parse normal VMAP CHUNK
  1262. this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );
  1263. var type = this.reader.getIDTag();
  1264. this.reader.getUint16(); // dimension
  1265. var name = this.reader.getString();
  1266. var remainingLength = length - 6 - stringOffset( name );
  1267. switch ( type ) {
  1268. case 'TXUV':
  1269. this.parseUVMapping( name, finalOffset, discontinuous );
  1270. break;
  1271. case 'MORF':
  1272. case 'SPOT':
  1273. this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
  1274. break;
  1275. // unsupported VMAPs
  1276. case 'APSL':
  1277. case 'NORM':
  1278. case 'WGHT':
  1279. case 'MNVW':
  1280. case 'PICK':
  1281. case 'RGB ':
  1282. case 'RGBA':
  1283. this.reader.skip( remainingLength );
  1284. break;
  1285. default:
  1286. console.warn( 'LWOLoader: unknown vertex map type: ' + type );
  1287. this.reader.skip( remainingLength );
  1288. }
  1289. },
  1290. parseUVMapping( name, finalOffset, discontinuous ) {
  1291. var uvIndices = [];
  1292. var polyIndices = [];
  1293. var uvs = [];
  1294. while ( this.reader.offset < finalOffset ) {
  1295. uvIndices.push( this.reader.getVariableLengthIndex() );
  1296. if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );
  1297. uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );
  1298. }
  1299. if ( discontinuous ) {
  1300. if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};
  1301. this.currentLayer.discontinuousUVs[ name ] = {
  1302. uvIndices: uvIndices,
  1303. polyIndices: polyIndices,
  1304. uvs: uvs,
  1305. };
  1306. } else {
  1307. if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};
  1308. this.currentLayer.uvs[ name ] = {
  1309. uvIndices: uvIndices,
  1310. uvs: uvs,
  1311. };
  1312. }
  1313. },
  1314. parseMorphTargets( name, finalOffset, type ) {
  1315. var indices = [];
  1316. var points = [];
  1317. type = ( type === 'MORF' ) ? 'relative' : 'absolute';
  1318. while ( this.reader.offset < finalOffset ) {
  1319. indices.push( this.reader.getVariableLengthIndex() );
  1320. // z -> -z to match three.js right handed coords
  1321. points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1322. }
  1323. if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};
  1324. this.currentLayer.morphTargets[ name ] = {
  1325. indices: indices,
  1326. points: points,
  1327. type: type,
  1328. };
  1329. },
  1330. // A list of polygons for the current layer.
  1331. // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  1332. parsePolygonList( length ) {
  1333. var finalOffset = this.reader.offset + length;
  1334. var type = this.reader.getIDTag();
  1335. var indices = [];
  1336. // hold a list of polygon sizes, to be split up later
  1337. var polygonDimensions = [];
  1338. while ( this.reader.offset < finalOffset ) {
  1339. var numverts = this.reader.getUint16();
  1340. //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
  1341. numverts = numverts & 1023; // remaining ten low order bits are vertex num
  1342. polygonDimensions.push( numverts );
  1343. for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );
  1344. }
  1345. var geometryData = {
  1346. type: type,
  1347. vertexIndices: indices,
  1348. polygonDimensions: polygonDimensions,
  1349. points: this.currentPoints
  1350. };
  1351. // Note: assuming that all polys will be lines or points if the first is
  1352. if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points';
  1353. else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';
  1354. this.currentLayer.geometry = geometryData;
  1355. },
  1356. // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  1357. // TAGS { tag-string[S0] * }
  1358. parseTagStrings( length ) {
  1359. this.tree.tags = this.reader.getStringArray( length );
  1360. },
  1361. // Associates tags of a given type with polygons in the most recent POLS chunk.
  1362. // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  1363. parsePolygonTagMapping( length ) {
  1364. var finalOffset = this.reader.offset + length;
  1365. var type = this.reader.getIDTag();
  1366. if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset );
  1367. else { //PART, SMGP, COLR not supported
  1368. this.reader.skip( length - 4 );
  1369. }
  1370. },
  1371. parseMaterialIndices( finalOffset ) {
  1372. // array holds polygon index followed by material index
  1373. this.currentLayer.geometry.materialIndices = [];
  1374. var initialMatIndex;
  1375. while ( this.reader.offset < finalOffset ) {
  1376. var polygonIndex = this.reader.getVariableLengthIndex();
  1377. var materialIndex = this.reader.getUint16();
  1378. if ( ! initialMatIndex ) initialMatIndex = materialIndex; // set up first mat index
  1379. this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );
  1380. }
  1381. },
  1382. parseUnknownCHUNK( blockID, length ) {
  1383. console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length );
  1384. // print the chunk plus some bytes padding either side
  1385. // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );
  1386. var data = this.reader.getString( length );
  1387. this.currentForm[ blockID ] = data;
  1388. }
  1389. };
  1390. function DataViewReader( buffer ) {
  1391. // For testing: dump whole buffer to console as a string
  1392. // printBuffer( buffer, 0, buffer.byteLength );
  1393. this.dv = new DataView( buffer );
  1394. this.offset = 0;
  1395. }
  1396. DataViewReader.prototype = {
  1397. constructor: DataViewReader,
  1398. size: function () {
  1399. return this.dv.buffer.byteLength;
  1400. },
  1401. setOffset( offset ) {
  1402. if ( offset > 0 && offset < this.dv.buffer.byteLength ) {
  1403. this.offset = offset;
  1404. } else {
  1405. console.error( 'LWOLoader: invalid buffer offset' );
  1406. }
  1407. },
  1408. endOfFile: function () {
  1409. if ( this.offset >= this.size() ) return true;
  1410. return false;
  1411. },
  1412. skip: function ( length ) {
  1413. this.offset += length;
  1414. },
  1415. getUint8: function () {
  1416. var value = this.dv.getUint8( this.offset );
  1417. this.offset += 1;
  1418. return value;
  1419. },
  1420. getUint16: function () {
  1421. var value = this.dv.getUint16( this.offset );
  1422. this.offset += 2;
  1423. return value;
  1424. },
  1425. getInt32: function () {
  1426. var value = this.dv.getInt32( this.offset, false );
  1427. this.offset += 4;
  1428. return value;
  1429. },
  1430. getUint32: function () {
  1431. var value = this.dv.getUint32( this.offset, false );
  1432. this.offset += 4;
  1433. return value;
  1434. },
  1435. getUint64: function () {
  1436. var low, high;
  1437. high = this.getUint32();
  1438. low = this.getUint32();
  1439. return high * 0x100000000 + low;
  1440. },
  1441. getFloat32: function () {
  1442. var value = this.dv.getFloat32( this.offset, false );
  1443. this.offset += 4;
  1444. return value;
  1445. },
  1446. getFloat32Array: function ( size ) {
  1447. var a = [];
  1448. for ( var i = 0; i < size; i ++ ) {
  1449. a.push( this.getFloat32() );
  1450. }
  1451. return a;
  1452. },
  1453. getFloat64: function () {
  1454. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  1455. this.offset += 8;
  1456. return value;
  1457. },
  1458. getFloat64Array: function ( size ) {
  1459. var a = [];
  1460. for ( var i = 0; i < size; i ++ ) {
  1461. a.push( this.getFloat64() );
  1462. }
  1463. return a;
  1464. },
  1465. // get variable-length index data type
  1466. // VX ::= index[U2] | (index + 0xFF000000)[U4]
  1467. // If the index value is less than 65,280 (0xFF00),then VX === U2
  1468. // otherwise VX === U4 with bits 24-31 set
  1469. // When reading an index, if the first byte encountered is 255 (0xFF), then
  1470. // the four-byte form is being used and the first byte should be discarded or masked out.
  1471. getVariableLengthIndex() {
  1472. var firstByte = this.getUint8();
  1473. if ( firstByte === 255 ) {
  1474. return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
  1475. }
  1476. return firstByte * 256 + this.getUint8();
  1477. },
  1478. // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  1479. getIDTag() {
  1480. return this.getString( 4 );
  1481. },
  1482. getString: function ( size ) {
  1483. if ( size === 0 ) return;
  1484. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  1485. var a = [];
  1486. if ( size ) {
  1487. for ( var i = 0; i < size; i ++ ) {
  1488. a[ i ] = this.getUint8();
  1489. }
  1490. } else {
  1491. var currentChar;
  1492. var len = 0;
  1493. while ( currentChar !== 0 ) {
  1494. currentChar = this.getUint8();
  1495. if ( currentChar !== 0 ) a.push( currentChar );
  1496. len ++;
  1497. }
  1498. if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added
  1499. }
  1500. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  1501. },
  1502. getStringArray: function ( size ) {
  1503. var a = this.getString( size );
  1504. a = a.split( '\0' );
  1505. return a.filter( Boolean ); // return array with any empty strings removed
  1506. }
  1507. };
  1508. // ************** UTILITY FUNCTIONS **************
  1509. function isEven( num ) {
  1510. return num % 2;
  1511. }
  1512. // calculate the length of the string in the buffer
  1513. // this will be string.length + nullbyte + optional padbyte to make the length even
  1514. function stringOffset( string ) {
  1515. return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );
  1516. }
  1517. // for testing purposes, dump buffer to console
  1518. // printBuffer( this.reader.dv.buffer, this.reader.offset, length );
  1519. function printBuffer( buffer, from, to ) {
  1520. console.log( THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );
  1521. }
  1522. return LWOLoader;
  1523. } )();