LWOLoader.js 56 KB

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