LWOLoader.js 56 KB

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