LWOLoader.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  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 ( var 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 || 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. this.currentSurface.diffusePower = this.reader.getFloat32();
  739. this.reader.skip( 2 );
  740. break;
  741. case 'TRNL':
  742. case 'REFL':
  743. case 'GLOS':
  744. case 'SHRP':
  745. case 'RFOP':
  746. case 'RSAN':
  747. case 'TROP':
  748. case 'RBLR':
  749. case 'TBLR':
  750. case 'CLRH':
  751. case 'CLRF':
  752. case 'ADTR':
  753. case 'GLOW':
  754. case 'LINE':
  755. case 'ALPH':
  756. case 'VCOL':
  757. case 'ENAB':
  758. this.reader.skip( length );
  759. break;
  760. case 'SURF':
  761. if ( this.tree.format === 'LWO2' ) {
  762. this.parseSurfaceLwo2( length );
  763. }
  764. break;
  765. case 'CLIP':
  766. if ( this.tree.format === 'LWO2' ) {
  767. this.parseClipLwo2( length );
  768. }
  769. break;
  770. // Texture node chunks (not in spec)
  771. case 'IPIX': // usePixelBlending
  772. case 'IMIP': // useMipMaps
  773. case 'IMOD': // imageBlendingMode
  774. case 'AMOD': // unknown
  775. case 'IINV': // imageInvertAlpha
  776. case 'INCR': // imageInvertColor
  777. case 'IAXS': // imageAxis ( for non-UV maps)
  778. case 'IFOT': // imageFallofType
  779. case 'ITIM': // timing for animated textures
  780. case 'IWRL':
  781. case 'IUTI':
  782. case 'IINX':
  783. case 'IINY':
  784. case 'IINZ':
  785. case 'IREF': // possibly a VX for reused texture nodes
  786. if ( length === 4 ) this.currentNode[ blockID ] = this.reader.getInt32();
  787. else this.reader.skip( length );
  788. break;
  789. case 'OTAG':
  790. this.parseObjectTag();
  791. break;
  792. case 'LAYR':
  793. this.parseLayer( length );
  794. break;
  795. case 'PNTS':
  796. this.parsePoints( length );
  797. break;
  798. case 'VMAP':
  799. this.parseVertexMapping( length );
  800. break;
  801. case 'POLS':
  802. this.parsePolygonList( length );
  803. break;
  804. case 'TAGS':
  805. this.parseTagStrings( length );
  806. break;
  807. case 'PTAG':
  808. this.parsePolygonTagMapping( length );
  809. break;
  810. case 'VMAD':
  811. this.parseVertexMapping( length, true );
  812. break;
  813. // Misc CHUNKS
  814. case 'DESC': // Description Line
  815. this.currentForm.description = this.reader.getString();
  816. break;
  817. case 'TEXT':
  818. case 'CMNT':
  819. case 'NCOM':
  820. this.currentForm.comment = this.reader.getString();
  821. break;
  822. // Envelope Form
  823. case 'NAME':
  824. this.currentForm.channelName = this.reader.getString();
  825. break;
  826. // Image Map Layer
  827. case 'WRAP':
  828. this.currentForm.wrap = { w: this.reader.getUint16(), h: this.reader.getUint16() };
  829. break;
  830. case 'IMAG':
  831. var index = this.reader.getVariableLengthIndex();
  832. this.currentForm.imageIndex = index;
  833. break;
  834. // Texture Mapping Form
  835. case 'OREF':
  836. this.currentForm.referenceObject = this.reader.getString();
  837. break;
  838. case 'ROID':
  839. this.currentForm.referenceObjectID = this.reader.getUint32();
  840. break;
  841. // Surface Blocks
  842. case 'SSHN':
  843. this.currentSurface.surfaceShaderName = this.reader.getString();
  844. break;
  845. case 'AOVN':
  846. this.currentSurface.surfaceCustomAOVName = this.reader.getString();
  847. break;
  848. // Nodal Blocks
  849. case 'NSTA':
  850. this.currentForm.disabled = this.reader.getUint16();
  851. break;
  852. case 'NRNM':
  853. this.currentForm.realName = this.reader.getString();
  854. break;
  855. case 'NNME':
  856. this.currentForm.refName = this.reader.getString();
  857. this.currentSurface.nodes[ this.currentForm.refName ] = this.currentForm;
  858. break;
  859. // Nodal Blocks : connections
  860. case 'INME':
  861. if ( ! this.currentForm.nodeName ) this.currentForm.nodeName = [];
  862. this.currentForm.nodeName.push( this.reader.getString() );
  863. break;
  864. case 'IINN':
  865. if ( ! this.currentForm.inputNodeName ) this.currentForm.inputNodeName = [];
  866. this.currentForm.inputNodeName.push( this.reader.getString() );
  867. break;
  868. case 'IINM':
  869. if ( ! this.currentForm.inputName ) this.currentForm.inputName = [];
  870. this.currentForm.inputName.push( this.reader.getString() );
  871. break;
  872. case 'IONM':
  873. if ( ! this.currentForm.inputOutputName ) this.currentForm.inputOutputName = [];
  874. this.currentForm.inputOutputName.push( this.reader.getString() );
  875. break;
  876. case 'FNAM':
  877. this.currentForm.fileName = this.reader.getString();
  878. break;
  879. case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
  880. if ( length === 4 ) this.currentForm.textureChannel = this.reader.getIDTag();
  881. else this.reader.skip( length );
  882. break;
  883. // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
  884. case 'SMAN':
  885. var maxSmoothingAngle = this.reader.getFloat32();
  886. this.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
  887. break;
  888. // LWO2: Basic Surface Parameters
  889. case 'COLR':
  890. this.currentSurface.attributes.Color = {};
  891. this.currentSurface.attributes.Color.value = this.reader.getFloat32Array( 3 );
  892. this.reader.skip( 2 ); // VX: envelope
  893. break;
  894. case 'LUMI':
  895. this.currentSurface.attributes.luminosityLevel = this.reader.getFloat32();
  896. this.reader.skip( 2 );
  897. break;
  898. case 'SPEC':
  899. this.currentSurface.attributes.specularLevel = this.reader.getFloat32();
  900. this.reader.skip( 2 );
  901. break;
  902. case 'TRAN':
  903. this.currentSurface.attributes.opacity = this.reader.getFloat32();
  904. this.reader.skip( 2 );
  905. break;
  906. case 'BUMP':
  907. this.currentSurface.attributes.bumpStrength = this.reader.getFloat32();
  908. this.reader.skip( 2 );
  909. break;
  910. case 'SIDE':
  911. this.currentSurface.attributes.side = this.reader.getUint16();
  912. break;
  913. case 'RIMG':
  914. this.currentSurface.attributes.reflectionMap = this.reader.getVariableLengthIndex();
  915. break;
  916. case 'RIND':
  917. this.currentSurface.attributes.refractiveIndex = this.reader.getFloat32();
  918. this.reader.skip( 2 );
  919. break;
  920. case 'TIMG':
  921. this.currentSurface.attributes.refractionMap = this.reader.getVariableLengthIndex();
  922. break;
  923. case 'IMAP':
  924. if ( this.tree.format === 'LWO2' ) {
  925. this.reader.skip( 2 );
  926. } else {
  927. this.currentSurface.attributes.imageMapIndex = this.reader.getUint32();
  928. }
  929. break;
  930. case 'IUVI': // uv channel name
  931. this.currentNode.UVChannel = this.reader.getString( length );
  932. break;
  933. case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  934. this.currentNode.widthWrappingMode = this.reader.getUint32();
  935. break;
  936. case 'IVTL': // heightWrappingMode
  937. this.currentNode.heightWrappingMode = this.reader.getUint32();
  938. break;
  939. // LWO2 USE
  940. case 'BLOK':
  941. // skip
  942. break;
  943. default:
  944. this.parseUnknownCHUNK( blockID, length );
  945. }
  946. if ( this.reader.offset >= this.currentFormEnd ) {
  947. this.currentForm = this.parentForm;
  948. }
  949. },
  950. ///
  951. // FORM PARSING METHODS
  952. ///
  953. // Forms are organisational and can contain any number of sub chunks and sub forms
  954. // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  955. parseForm( length ) {
  956. var type = this.reader.getIDTag();
  957. switch ( type ) {
  958. // SKIPPED FORMS
  959. // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
  960. case 'ISEQ': // Image sequence
  961. case 'ANIM': // plug in animation
  962. case 'STCC': // Color-cycling Still
  963. case 'VPVL':
  964. case 'VPRM':
  965. case 'NROT':
  966. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  967. case 'WRPH': // image wrap h
  968. case 'FUNC':
  969. case 'FALL':
  970. case 'OPAC':
  971. case 'GRAD': // gradient texture
  972. case 'ENVS':
  973. case 'VMOP':
  974. case 'VMBG':
  975. // Car Material FORMS
  976. case 'OMAX':
  977. case 'STEX':
  978. case 'CKBG':
  979. case 'CKEY':
  980. case 'VMLA':
  981. case 'VMLB':
  982. this.skipForm( length ); // not currently supported
  983. break;
  984. // if break; is called directly, the position in the lwoTree is not created
  985. // any sub chunks and forms are added to the parent form instead
  986. case 'META':
  987. case 'NNDS':
  988. case 'NODS':
  989. case 'NDTA':
  990. case 'ADAT':
  991. case 'AOVS':
  992. case 'BLOK':
  993. // used by texture nodes
  994. case 'IBGC': // imageBackgroundColor
  995. case 'IOPC': // imageOpacity
  996. case 'IIMG': // hold reference to image path
  997. case 'TXTR':
  998. // this.setupForm( type, length );
  999. break;
  1000. case 'IFAL': // imageFallof
  1001. case 'ISCL': // imageScale
  1002. case 'IPOS': // imagePosition
  1003. case 'IROT': // imageRotation
  1004. case 'IBMP':
  1005. case 'IUTD':
  1006. case 'IVTD':
  1007. this.parseTextureNodeAttribute( type );
  1008. break;
  1009. case 'LWO2':
  1010. this.tree.format = type;
  1011. break;
  1012. case 'LWO3':
  1013. this.tree.format = type;
  1014. break;
  1015. case 'ENVL':
  1016. this.parseEnvelope( length );
  1017. break;
  1018. // CLIP FORM AND SUB FORMS
  1019. case 'CLIP':
  1020. if ( this.tree.format === 'LWO2' ) {
  1021. this.parseForm( length );
  1022. } else {
  1023. this.parseClip( length );
  1024. }
  1025. break;
  1026. case 'STIL':
  1027. this.parseImage();
  1028. break;
  1029. case 'XREF': // clone of another STIL
  1030. this.reader.skip( 8 ); // unknown
  1031. this.currentForm.referenceTexture = {
  1032. index: this.reader.getUint32(),
  1033. refName: this.reader.getString() // internal unique ref
  1034. };
  1035. break;
  1036. // Not in spec, used by texture nodes
  1037. case 'IMST':
  1038. this.parseImageStateForm( length );
  1039. break;
  1040. // SURF FORM AND SUB FORMS
  1041. case 'SURF':
  1042. this.parseSurfaceForm( length );
  1043. break;
  1044. case 'VALU': // Not in spec
  1045. this.parseValueForm( length );
  1046. break;
  1047. case 'NTAG':
  1048. this.parseSubNode( length );
  1049. break;
  1050. case 'ATTR': // BSDF Node Attributes
  1051. case 'SATR': // Standard Node Attributes
  1052. this.setupForm( 'attributes', length );
  1053. break;
  1054. case 'NCON':
  1055. this.parseConnections( length );
  1056. break;
  1057. case 'SSHA':
  1058. this.parentForm = this.currentForm;
  1059. this.currentForm = this.currentSurface;
  1060. this.setupForm( 'surfaceShader', length );
  1061. break;
  1062. case 'SSHD':
  1063. this.setupForm( 'surfaceShaderData', length );
  1064. break;
  1065. case 'ENTR': // Not in spec
  1066. this.parseEntryForm( length );
  1067. break;
  1068. // Image Map Layer
  1069. case 'IMAP':
  1070. this.parseImageMap( length );
  1071. break;
  1072. case 'TAMP':
  1073. this.parseXVAL( 'amplitude', length );
  1074. break;
  1075. //Texture Mapping Form
  1076. case 'TMAP':
  1077. this.setupForm( 'textureMap', length );
  1078. break;
  1079. case 'CNTR':
  1080. this.parseXVAL3( 'center', length );
  1081. break;
  1082. case 'SIZE':
  1083. this.parseXVAL3( 'scale', length );
  1084. break;
  1085. case 'ROTA':
  1086. this.parseXVAL3( 'rotation', length );
  1087. break;
  1088. default:
  1089. this.parseUnknownForm( type, length );
  1090. }
  1091. },
  1092. setupForm( type, length ) {
  1093. if ( ! this.currentForm ) this.currentForm = this.currentNode;
  1094. this.currentFormEnd = this.reader.offset + length;
  1095. this.parentForm = this.currentForm;
  1096. if ( ! this.currentForm[ type ] ) {
  1097. this.currentForm[ type ] = {};
  1098. this.currentForm = this.currentForm[ type ];
  1099. } else {
  1100. // should never see this unless there's a bug in the reader
  1101. console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );
  1102. this.currentForm = this.currentForm[ type ];
  1103. }
  1104. },
  1105. skipForm( length ) {
  1106. this.reader.skip( length - 4 );
  1107. },
  1108. parseUnknownForm( type, length ) {
  1109. console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );
  1110. printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
  1111. this.reader.skip( length - 4 );
  1112. },
  1113. parseSurfaceForm( length ) {
  1114. this.reader.skip( 8 ); // unknown Uint32 x2
  1115. var name = this.reader.getString();
  1116. var surface = {
  1117. attributes: {}, // LWO2 style non-node attributes will go here
  1118. connections: {},
  1119. name: name,
  1120. inputName: name,
  1121. nodes: {},
  1122. source: this.reader.getString(),
  1123. };
  1124. this.tree.materials[ name ] = surface;
  1125. this.currentSurface = surface;
  1126. this.parentForm = this.tree.materials;
  1127. this.currentForm = surface;
  1128. this.currentFormEnd = this.reader.offset + length;
  1129. },
  1130. parseSurfaceLwo2( length ) {
  1131. var firstOffset = this.reader.offset;
  1132. var name = this.reader.getString();
  1133. var surface = {
  1134. attributes: {}, // LWO2 style non-node attributes will go here
  1135. connections: {},
  1136. name: name,
  1137. nodes: {},
  1138. source: this.reader.getString(),
  1139. };
  1140. this.tree.materials[ name ] = surface;
  1141. this.currentSurface = surface;
  1142. this.parentForm = this.tree.materials;
  1143. this.currentForm = surface;
  1144. this.currentFormEnd = this.reader.offset + length;
  1145. },
  1146. parseSubNode( length ) {
  1147. // parse the NRNM CHUNK of the subnode FORM to get
  1148. // a meaningful name for the subNode
  1149. // some subnodes can be renamed, but Input and Surface cannot
  1150. this.reader.skip( 8 ); // NRNM + length
  1151. var name = this.reader.getString();
  1152. var node = {
  1153. name: name
  1154. };
  1155. this.currentForm = node;
  1156. this.currentNode = node;
  1157. this.currentFormEnd = this.reader.offset + length;
  1158. },
  1159. // collect attributes from all nodes at the top level of a surface
  1160. parseConnections( length ) {
  1161. this.currentFormEnd = this.reader.offset + length;
  1162. this.parentForm = this.currentForm;
  1163. this.currentForm = this.currentSurface.connections;
  1164. },
  1165. // surface node attribute data, e.g. specular, roughness etc
  1166. parseEntryForm( length ) {
  1167. this.reader.skip( 8 ); // NAME + length
  1168. var name = this.reader.getString();
  1169. this.currentForm = this.currentNode.attributes;
  1170. this.setupForm( name, length );
  1171. },
  1172. // parse values from material - doesn't match up to other LWO3 data types
  1173. // sub form of entry form
  1174. parseValueForm() {
  1175. this.reader.skip( 8 ); // unknown + length
  1176. var valueType = this.reader.getString();
  1177. if ( valueType === 'double' ) {
  1178. this.currentForm.value = this.reader.getUint64();
  1179. } else if ( valueType === 'int' ) {
  1180. this.currentForm.value = this.reader.getUint32();
  1181. } else if ( valueType === 'vparam' ) {
  1182. this.reader.skip( 24 );
  1183. this.currentForm.value = this.reader.getFloat64();
  1184. } else if ( valueType === 'vparam3' ) {
  1185. this.reader.skip( 24 );
  1186. this.currentForm.value = this.reader.getFloat64Array( 3 );
  1187. }
  1188. },
  1189. // holds various data about texture node image state
  1190. // Data other thanmipMapLevel unknown
  1191. parseImageStateForm() {
  1192. this.reader.skip( 8 ); // unknown
  1193. this.currentForm.mipMapLevel = this.reader.getFloat32();
  1194. },
  1195. // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  1196. parseImageMap( length ) {
  1197. this.currentFormEnd = this.reader.offset + length;
  1198. this.parentForm = this.currentForm;
  1199. if ( ! this.currentForm.maps ) this.currentForm.maps = [];
  1200. var map = {};
  1201. this.currentForm.maps.push( map );
  1202. this.currentForm = map;
  1203. this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX
  1204. },
  1205. parseTextureNodeAttribute( type ) {
  1206. this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32
  1207. this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32
  1208. switch ( type ) {
  1209. case 'ISCL':
  1210. this.currentNode.scale = this.reader.getFloat32Array( 3 );
  1211. break;
  1212. case 'IPOS':
  1213. this.currentNode.position = this.reader.getFloat32Array( 3 );
  1214. break;
  1215. case 'IROT':
  1216. this.currentNode.rotation = this.reader.getFloat32Array( 3 );
  1217. break;
  1218. case 'IFAL':
  1219. this.currentNode.falloff = this.reader.getFloat32Array( 3 );
  1220. break;
  1221. case 'IBMP':
  1222. this.currentNode.amplitude = this.reader.getFloat32();
  1223. break;
  1224. case 'IUTD':
  1225. this.currentNode.uTiles = this.reader.getFloat32();
  1226. break;
  1227. case 'IVTD':
  1228. this.currentNode.vTiles = this.reader.getFloat32();
  1229. break;
  1230. }
  1231. this.reader.skip( 2 ); // unknown
  1232. },
  1233. // ENVL forms are currently ignored
  1234. parseEnvelope( length ) {
  1235. this.reader.skip( length - 4 ); // skipping entirely for now
  1236. },
  1237. ///
  1238. // CHUNK PARSING METHODS
  1239. ///
  1240. // clips can either be defined inside a surface node, or at the top
  1241. // level and they have a different format in each case
  1242. parseClip( length ) {
  1243. var tag = this.reader.getIDTag();
  1244. // inside surface node
  1245. if ( tag === 'FORM' ) {
  1246. this.reader.skip( 16 );
  1247. this.currentNode.fileName = this.reader.getString();
  1248. return;
  1249. }
  1250. // otherwise top level
  1251. this.reader.setOffset( this.reader.offset - 4 );
  1252. this.currentFormEnd = this.reader.offset + length;
  1253. this.parentForm = this.currentForm;
  1254. this.reader.skip( 8 ); // unknown
  1255. var texture = {
  1256. index: this.reader.getUint32()
  1257. };
  1258. this.tree.textures.push( texture );
  1259. this.currentForm = texture;
  1260. },
  1261. parseClipLwo2( length ) {
  1262. var texture = {
  1263. index: this.reader.getUint32(),
  1264. fileName: ""
  1265. };
  1266. var readed = 4;
  1267. // seach STIL block
  1268. while ( true ) {
  1269. var tag = this.reader.getIDTag();
  1270. var n_length = this.reader.getUint16();
  1271. if ( tag === 'STIL' ) {
  1272. texture.fileName = this.reader.getString();
  1273. break;
  1274. }
  1275. readed += 4 + n_length;
  1276. if ( n_length >= length ) {
  1277. break;
  1278. }
  1279. }
  1280. this.tree.textures.push( texture );
  1281. this.currentForm = texture;
  1282. },
  1283. parseImage() {
  1284. this.reader.skip( 8 ); // unknown
  1285. this.currentForm.fileName = this.reader.getString();
  1286. },
  1287. parseXVAL( type, length ) {
  1288. var endOffset = this.reader.offset + length - 4;
  1289. this.reader.skip( 8 );
  1290. this.currentForm[ type ] = this.reader.getFloat32();
  1291. this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope
  1292. },
  1293. parseXVAL3( type, length ) {
  1294. var endOffset = this.reader.offset + length - 4;
  1295. this.reader.skip( 8 );
  1296. this.currentForm[ type ] = {
  1297. x: this.reader.getFloat32(),
  1298. y: this.reader.getFloat32(),
  1299. z: this.reader.getFloat32(),
  1300. };
  1301. this.reader.setOffset( endOffset );
  1302. },
  1303. // Tags associated with an object
  1304. // OTAG { type[ID4], tag-string[S0] }
  1305. parseObjectTag() {
  1306. if ( ! this.tree.objectTags ) this.tree.objectTags = {};
  1307. this.tree.objectTags[ this.reader.getIDTag() ] = {
  1308. tagString: this.reader.getString()
  1309. };
  1310. },
  1311. // 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.
  1312. // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  1313. parseLayer( length ) {
  1314. var layer = {
  1315. number: this.reader.getUint16(),
  1316. flags: this.reader.getUint16(), // If the least significant bit of flags is set, the layer is hidden.
  1317. pivot: this.reader.getFloat32Array( 3 ), // Note: this seems to be superflous, as the geometry is translated when pivot is present
  1318. name: this.reader.getString(),
  1319. };
  1320. this.tree.layers.push( layer );
  1321. this.currentLayer = layer;
  1322. var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength
  1323. // if we have not reached then end of the layer block, there must be a parent defined
  1324. this.currentLayer.parent = ( parsedLength < length ) ? this.reader.getUint16() : - 1; // omitted or -1 for no parent
  1325. },
  1326. // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  1327. // Converting from left to right handed coordinate system:
  1328. // x -> -x and switch material FrontSide -> BackSide
  1329. parsePoints( length ) {
  1330. this.currentPoints = [];
  1331. for ( var i = 0; i < length / 4; i += 3 ) {
  1332. // z -> -z to match three.js right handed coords
  1333. this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1334. }
  1335. },
  1336. // parse VMAP or VMAD
  1337. // Associates a set of floating-point vectors with a set of points.
  1338. // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  1339. // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  1340. // Similar to VMAP UVs, but associates with polygon vertices rather than points
  1341. // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name,
  1342. // if they exist. The vector values in the VMAD will then replace those in the
  1343. // corresponding VMAP, but only for calculations involving the specified polygons.
  1344. // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  1345. parseVertexMapping( length, discontinuous ) {
  1346. var finalOffset = this.reader.offset + length;
  1347. var channelName = this.reader.getString();
  1348. if ( this.reader.offset === finalOffset ) {
  1349. // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
  1350. this.currentForm.UVChannel = channelName;
  1351. return;
  1352. }
  1353. // otherwise reset to initial length and parse normal VMAP CHUNK
  1354. this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );
  1355. var type = this.reader.getIDTag();
  1356. this.reader.getUint16(); // dimension
  1357. var name = this.reader.getString();
  1358. var remainingLength = length - 6 - stringOffset( name );
  1359. switch ( type ) {
  1360. case 'TXUV':
  1361. this.parseUVMapping( name, finalOffset, discontinuous );
  1362. break;
  1363. case 'MORF':
  1364. case 'SPOT':
  1365. this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
  1366. break;
  1367. // unsupported VMAPs
  1368. case 'APSL':
  1369. case 'NORM':
  1370. case 'WGHT':
  1371. case 'MNVW':
  1372. case 'PICK':
  1373. case 'RGB ':
  1374. case 'RGBA':
  1375. this.reader.skip( remainingLength );
  1376. break;
  1377. default:
  1378. console.warn( 'LWOLoader: unknown vertex map type: ' + type );
  1379. this.reader.skip( remainingLength );
  1380. }
  1381. },
  1382. parseUVMapping( name, finalOffset, discontinuous ) {
  1383. var uvIndices = [];
  1384. var polyIndices = [];
  1385. var uvs = [];
  1386. while ( this.reader.offset < finalOffset ) {
  1387. uvIndices.push( this.reader.getVariableLengthIndex() );
  1388. if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );
  1389. uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );
  1390. }
  1391. if ( discontinuous ) {
  1392. if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};
  1393. this.currentLayer.discontinuousUVs[ name ] = {
  1394. uvIndices: uvIndices,
  1395. polyIndices: polyIndices,
  1396. uvs: uvs,
  1397. };
  1398. } else {
  1399. if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};
  1400. this.currentLayer.uvs[ name ] = {
  1401. uvIndices: uvIndices,
  1402. uvs: uvs,
  1403. };
  1404. }
  1405. },
  1406. parseMorphTargets( name, finalOffset, type ) {
  1407. var indices = [];
  1408. var points = [];
  1409. type = ( type === 'MORF' ) ? 'relative' : 'absolute';
  1410. while ( this.reader.offset < finalOffset ) {
  1411. indices.push( this.reader.getVariableLengthIndex() );
  1412. // z -> -z to match three.js right handed coords
  1413. points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1414. }
  1415. if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};
  1416. this.currentLayer.morphTargets[ name ] = {
  1417. indices: indices,
  1418. points: points,
  1419. type: type,
  1420. };
  1421. },
  1422. // A list of polygons for the current layer.
  1423. // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  1424. parsePolygonList( length ) {
  1425. var finalOffset = this.reader.offset + length;
  1426. var type = this.reader.getIDTag();
  1427. var indices = [];
  1428. // hold a list of polygon sizes, to be split up later
  1429. var polygonDimensions = [];
  1430. while ( this.reader.offset < finalOffset ) {
  1431. var numverts = this.reader.getUint16();
  1432. //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
  1433. numverts = numverts & 1023; // remaining ten low order bits are vertex num
  1434. polygonDimensions.push( numverts );
  1435. for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );
  1436. }
  1437. var geometryData = {
  1438. type: type,
  1439. vertexIndices: indices,
  1440. polygonDimensions: polygonDimensions,
  1441. points: this.currentPoints
  1442. };
  1443. // Note: assuming that all polys will be lines or points if the first is
  1444. if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points';
  1445. else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';
  1446. this.currentLayer.geometry = geometryData;
  1447. },
  1448. // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  1449. // TAGS { tag-string[S0] * }
  1450. parseTagStrings( length ) {
  1451. this.tree.tags = this.reader.getStringArray( length );
  1452. },
  1453. // Associates tags of a given type with polygons in the most recent POLS chunk.
  1454. // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  1455. parsePolygonTagMapping( length ) {
  1456. var finalOffset = this.reader.offset + length;
  1457. var type = this.reader.getIDTag();
  1458. if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset );
  1459. else { //PART, SMGP, COLR not supported
  1460. this.reader.skip( length - 4 );
  1461. }
  1462. },
  1463. parseMaterialIndices( finalOffset ) {
  1464. // array holds polygon index followed by material index
  1465. this.currentLayer.geometry.materialIndices = [];
  1466. var initialMatIndex;
  1467. while ( this.reader.offset < finalOffset ) {
  1468. var polygonIndex = this.reader.getVariableLengthIndex();
  1469. var materialIndex = this.reader.getUint16();
  1470. if ( ! initialMatIndex ) initialMatIndex = materialIndex; // set up first mat index
  1471. this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );
  1472. }
  1473. },
  1474. parseUnknownCHUNK( blockID, length ) {
  1475. console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length );
  1476. // print the chunk plus some bytes padding either side
  1477. // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );
  1478. var data = this.reader.getString( length );
  1479. this.currentForm[ blockID ] = data;
  1480. }
  1481. };
  1482. function DataViewReader( buffer ) {
  1483. // For testing: dump whole buffer to console as a string
  1484. // printBuffer( buffer, 0, buffer.byteLength );
  1485. this.dv = new DataView( buffer );
  1486. this.offset = 0;
  1487. }
  1488. DataViewReader.prototype = {
  1489. constructor: DataViewReader,
  1490. size: function () {
  1491. return this.dv.buffer.byteLength;
  1492. },
  1493. setOffset( offset ) {
  1494. if ( offset > 0 && offset < this.dv.buffer.byteLength ) {
  1495. this.offset = offset;
  1496. } else {
  1497. console.error( 'LWOLoader: invalid buffer offset' );
  1498. }
  1499. },
  1500. endOfFile: function () {
  1501. if ( this.offset >= this.size() ) return true;
  1502. return false;
  1503. },
  1504. skip: function ( length ) {
  1505. this.offset += length;
  1506. },
  1507. getUint8: function () {
  1508. var value = this.dv.getUint8( this.offset );
  1509. this.offset += 1;
  1510. return value;
  1511. },
  1512. getUint16: function () {
  1513. var value = this.dv.getUint16( this.offset );
  1514. this.offset += 2;
  1515. return value;
  1516. },
  1517. getInt32: function () {
  1518. var value = this.dv.getInt32( this.offset, false );
  1519. this.offset += 4;
  1520. return value;
  1521. },
  1522. getUint32: function () {
  1523. var value = this.dv.getUint32( this.offset, false );
  1524. this.offset += 4;
  1525. return value;
  1526. },
  1527. getUint64: function () {
  1528. var low, high;
  1529. high = this.getUint32();
  1530. low = this.getUint32();
  1531. return high * 0x100000000 + low;
  1532. },
  1533. getFloat32: function () {
  1534. var value = this.dv.getFloat32( this.offset, false );
  1535. this.offset += 4;
  1536. return value;
  1537. },
  1538. getFloat32Array: function ( size ) {
  1539. var a = [];
  1540. for ( var i = 0; i < size; i ++ ) {
  1541. a.push( this.getFloat32() );
  1542. }
  1543. return a;
  1544. },
  1545. getFloat64: function () {
  1546. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  1547. this.offset += 8;
  1548. return value;
  1549. },
  1550. getFloat64Array: function ( size ) {
  1551. var a = [];
  1552. for ( var i = 0; i < size; i ++ ) {
  1553. a.push( this.getFloat64() );
  1554. }
  1555. return a;
  1556. },
  1557. // get variable-length index data type
  1558. // VX ::= index[U2] | (index + 0xFF000000)[U4]
  1559. // If the index value is less than 65,280 (0xFF00),then VX === U2
  1560. // otherwise VX === U4 with bits 24-31 set
  1561. // When reading an index, if the first byte encountered is 255 (0xFF), then
  1562. // the four-byte form is being used and the first byte should be discarded or masked out.
  1563. getVariableLengthIndex() {
  1564. var firstByte = this.getUint8();
  1565. if ( firstByte === 255 ) {
  1566. return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
  1567. }
  1568. return firstByte * 256 + this.getUint8();
  1569. },
  1570. // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  1571. getIDTag() {
  1572. return this.getString( 4 );
  1573. },
  1574. getString: function ( size ) {
  1575. if ( size === 0 ) return;
  1576. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  1577. var a = [];
  1578. if ( size ) {
  1579. for ( var i = 0; i < size; i ++ ) {
  1580. a[ i ] = this.getUint8();
  1581. }
  1582. } else {
  1583. var currentChar;
  1584. var len = 0;
  1585. while ( currentChar !== 0 ) {
  1586. currentChar = this.getUint8();
  1587. if ( currentChar !== 0 ) a.push( currentChar );
  1588. len ++;
  1589. }
  1590. if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added
  1591. }
  1592. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  1593. },
  1594. getStringArray: function ( size ) {
  1595. var a = this.getString( size );
  1596. a = a.split( '\0' );
  1597. return a.filter( Boolean ); // return array with any empty strings removed
  1598. }
  1599. };
  1600. // ************** UTILITY FUNCTIONS **************
  1601. function isEven( num ) {
  1602. return num % 2;
  1603. }
  1604. // calculate the length of the string in the buffer
  1605. // this will be string.length + nullbyte + optional padbyte to make the length even
  1606. function stringOffset( string ) {
  1607. return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );
  1608. }
  1609. // for testing purposes, dump buffer to console
  1610. // printBuffer( this.reader.dv.buffer, this.reader.offset, length );
  1611. function printBuffer( buffer, from, to ) {
  1612. console.log( THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );
  1613. }
  1614. return LWOLoader;
  1615. } )();