IFFParser.js 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. ( function () {
  2. /**
  3. * === IFFParser ===
  4. * - Parses data from the IFF buffer.
  5. * - LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes
  6. *
  7. * ATOMIC DATA TYPES
  8. * ID Tag - 4x 7 bit uppercase ASCII chars: ID4
  9. * signed integer, 1, 2, or 4 byte length: I1, I2, I4
  10. * unsigned integer, 1, 2, or 4 byte length: U1, U2, U4
  11. * float, 4 byte length: F4
  12. * 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
  13. *
  14. * COMPOUND DATA TYPES
  15. * Variable-length Index (index into an array or collection): U2 or U4 : VX
  16. * Color (RGB): F4 + F4 + F4: COL12
  17. * Coordinate (x, y, z): F4 + F4 + F4: VEC12
  18. * Percentage F4 data type from 0->1 with 1 = 100%: FP4
  19. * Angle in radian F4: ANG4
  20. * Filename (string) S0: FNAM0
  21. * XValue F4 + index (VX) + optional envelope( ENVL ): XVAL
  22. * XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3
  23. *
  24. * The IFF file is arranged in chunks:
  25. * CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte
  26. * optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size
  27. *
  28. * COMPOUND DATA TYPES
  29. * - Chunks are combined in Forms (collections of chunks)
  30. * - FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM )
  31. * - CHUNKS and FORMS are collectively referred to as blocks
  32. * - The entire file is contained in one top level FORM
  33. *
  34. **/
  35. function IFFParser() {
  36. this.debugger = new Debugger(); // this.debugger.enable(); // un-comment to log IFF hierarchy.
  37. }
  38. IFFParser.prototype = {
  39. constructor: IFFParser,
  40. parse: function ( buffer ) {
  41. this.reader = new DataViewReader( buffer );
  42. this.tree = {
  43. materials: {},
  44. layers: [],
  45. tags: [],
  46. textures: []
  47. }; // start out at the top level to add any data before first layer is encountered
  48. this.currentLayer = this.tree;
  49. this.currentForm = this.tree;
  50. this.parseTopForm();
  51. if ( this.tree.format === undefined ) return;
  52. if ( this.tree.format === 'LWO2' ) {
  53. this.parser = new THREE.LWO2Parser( this );
  54. while ( ! this.reader.endOfFile() ) this.parser.parseBlock();
  55. } else if ( this.tree.format === 'LWO3' ) {
  56. this.parser = new THREE.LWO3Parser( this );
  57. while ( ! this.reader.endOfFile() ) this.parser.parseBlock();
  58. }
  59. this.debugger.offset = this.reader.offset;
  60. this.debugger.closeForms();
  61. return this.tree;
  62. },
  63. parseTopForm() {
  64. this.debugger.offset = this.reader.offset;
  65. var topForm = this.reader.getIDTag();
  66. if ( topForm !== 'FORM' ) {
  67. console.warn( 'LWOLoader: Top-level FORM missing.' );
  68. return;
  69. }
  70. var length = this.reader.getUint32();
  71. this.debugger.dataOffset = this.reader.offset;
  72. this.debugger.length = length;
  73. var type = this.reader.getIDTag();
  74. if ( type === 'LWO2' ) {
  75. this.tree.format = type;
  76. } else if ( type === 'LWO3' ) {
  77. this.tree.format = type;
  78. }
  79. this.debugger.node = 0;
  80. this.debugger.nodeID = type;
  81. this.debugger.log();
  82. return;
  83. },
  84. ///
  85. // FORM PARSING METHODS
  86. ///
  87. // Forms are organisational and can contain any number of sub chunks and sub forms
  88. // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  89. parseForm( length ) {
  90. var type = this.reader.getIDTag();
  91. switch ( type ) {
  92. // SKIPPED FORMS
  93. // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
  94. case 'ISEQ': // Image sequence
  95. case 'ANIM': // plug in animation
  96. case 'STCC': // Color-cycling Still
  97. case 'VPVL':
  98. case 'VPRM':
  99. case 'NROT':
  100. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  101. case 'WRPH': // image wrap h
  102. case 'FUNC':
  103. case 'FALL':
  104. case 'OPAC':
  105. case 'GRAD': // gradient texture
  106. case 'ENVS':
  107. case 'VMOP':
  108. case 'VMBG': // Car Material FORMS
  109. case 'OMAX':
  110. case 'STEX':
  111. case 'CKBG':
  112. case 'CKEY':
  113. case 'VMLA':
  114. case 'VMLB':
  115. this.debugger.skipped = true;
  116. this.skipForm( length ); // not currently supported
  117. break;
  118. // if break; is called directly, the position in the lwoTree is not created
  119. // any sub chunks and forms are added to the parent form instead
  120. case 'META':
  121. case 'NNDS':
  122. case 'NODS':
  123. case 'NDTA':
  124. case 'ADAT':
  125. case 'AOVS':
  126. case 'BLOK': // used by texture nodes
  127. case 'IBGC': // imageBackgroundColor
  128. case 'IOPC': // imageOpacity
  129. case 'IIMG': // hold reference to image path
  130. case 'TXTR':
  131. // this.setupForm( type, length );
  132. this.debugger.length = 4;
  133. this.debugger.skipped = true;
  134. break;
  135. case 'IFAL': // imageFallof
  136. case 'ISCL': // imageScale
  137. case 'IPOS': // imagePosition
  138. case 'IROT': // imageRotation
  139. case 'IBMP':
  140. case 'IUTD':
  141. case 'IVTD':
  142. this.parseTextureNodeAttribute( type );
  143. break;
  144. case 'ENVL':
  145. this.parseEnvelope( length );
  146. break;
  147. // CLIP FORM AND SUB FORMS
  148. case 'CLIP':
  149. if ( this.tree.format === 'LWO2' ) {
  150. this.parseForm( length );
  151. } else {
  152. this.parseClip( length );
  153. }
  154. break;
  155. case 'STIL':
  156. this.parseImage();
  157. break;
  158. case 'XREF':
  159. // clone of another STIL
  160. this.reader.skip( 8 ); // unknown
  161. this.currentForm.referenceTexture = {
  162. index: this.reader.getUint32(),
  163. refName: this.reader.getString() // internal unique ref
  164. };
  165. break;
  166. // Not in spec, used by texture nodes
  167. case 'IMST':
  168. this.parseImageStateForm( length );
  169. break;
  170. // SURF FORM AND SUB FORMS
  171. case 'SURF':
  172. this.parseSurfaceForm( length );
  173. break;
  174. case 'VALU':
  175. // Not in spec
  176. this.parseValueForm( length );
  177. break;
  178. case 'NTAG':
  179. this.parseSubNode( length );
  180. break;
  181. case 'ATTR': // BSDF Node Attributes
  182. case 'SATR':
  183. // Standard Node Attributes
  184. this.setupForm( 'attributes', length );
  185. break;
  186. case 'NCON':
  187. this.parseConnections( length );
  188. break;
  189. case 'SSHA':
  190. this.parentForm = this.currentForm;
  191. this.currentForm = this.currentSurface;
  192. this.setupForm( 'surfaceShader', length );
  193. break;
  194. case 'SSHD':
  195. this.setupForm( 'surfaceShaderData', length );
  196. break;
  197. case 'ENTR':
  198. // Not in spec
  199. this.parseEntryForm( length );
  200. break;
  201. // Image Map Layer
  202. case 'IMAP':
  203. this.parseImageMap( length );
  204. break;
  205. case 'TAMP':
  206. this.parseXVAL( 'amplitude', length );
  207. break;
  208. //Texture Mapping Form
  209. case 'TMAP':
  210. this.setupForm( 'textureMap', length );
  211. break;
  212. case 'CNTR':
  213. this.parseXVAL3( 'center', length );
  214. break;
  215. case 'SIZE':
  216. this.parseXVAL3( 'scale', length );
  217. break;
  218. case 'ROTA':
  219. this.parseXVAL3( 'rotation', length );
  220. break;
  221. default:
  222. this.parseUnknownForm( type, length );
  223. }
  224. this.debugger.node = 0;
  225. this.debugger.nodeID = type;
  226. this.debugger.log();
  227. },
  228. setupForm( type, length ) {
  229. if ( ! this.currentForm ) this.currentForm = this.currentNode;
  230. this.currentFormEnd = this.reader.offset + length;
  231. this.parentForm = this.currentForm;
  232. if ( ! this.currentForm[ type ] ) {
  233. this.currentForm[ type ] = {};
  234. this.currentForm = this.currentForm[ type ];
  235. } else {
  236. // should never see this unless there's a bug in the reader
  237. console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );
  238. this.currentForm = this.currentForm[ type ];
  239. }
  240. },
  241. skipForm( length ) {
  242. this.reader.skip( length - 4 );
  243. },
  244. parseUnknownForm( type, length ) {
  245. console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );
  246. printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
  247. this.reader.skip( length - 4 );
  248. },
  249. parseSurfaceForm( length ) {
  250. this.reader.skip( 8 ); // unknown Uint32 x2
  251. var name = this.reader.getString();
  252. var surface = {
  253. attributes: {},
  254. // LWO2 style non-node attributes will go here
  255. connections: {},
  256. name: name,
  257. inputName: name,
  258. nodes: {},
  259. source: this.reader.getString()
  260. };
  261. this.tree.materials[ name ] = surface;
  262. this.currentSurface = surface;
  263. this.parentForm = this.tree.materials;
  264. this.currentForm = surface;
  265. this.currentFormEnd = this.reader.offset + length;
  266. },
  267. parseSurfaceLwo2( length ) {
  268. var name = this.reader.getString();
  269. var surface = {
  270. attributes: {},
  271. // LWO2 style non-node attributes will go here
  272. connections: {},
  273. name: name,
  274. nodes: {},
  275. source: this.reader.getString()
  276. };
  277. this.tree.materials[ name ] = surface;
  278. this.currentSurface = surface;
  279. this.parentForm = this.tree.materials;
  280. this.currentForm = surface;
  281. this.currentFormEnd = this.reader.offset + length;
  282. },
  283. parseSubNode( length ) {
  284. // parse the NRNM CHUNK of the subnode FORM to get
  285. // a meaningful name for the subNode
  286. // some subnodes can be renamed, but Input and Surface cannot
  287. this.reader.skip( 8 ); // NRNM + length
  288. var name = this.reader.getString();
  289. var node = {
  290. name: name
  291. };
  292. this.currentForm = node;
  293. this.currentNode = node;
  294. this.currentFormEnd = this.reader.offset + length;
  295. },
  296. // collect attributes from all nodes at the top level of a surface
  297. parseConnections( length ) {
  298. this.currentFormEnd = this.reader.offset + length;
  299. this.parentForm = this.currentForm;
  300. this.currentForm = this.currentSurface.connections;
  301. },
  302. // surface node attribute data, e.g. specular, roughness etc
  303. parseEntryForm( length ) {
  304. this.reader.skip( 8 ); // NAME + length
  305. var name = this.reader.getString();
  306. this.currentForm = this.currentNode.attributes;
  307. this.setupForm( name, length );
  308. },
  309. // parse values from material - doesn't match up to other LWO3 data types
  310. // sub form of entry form
  311. parseValueForm() {
  312. this.reader.skip( 8 ); // unknown + length
  313. var valueType = this.reader.getString();
  314. if ( valueType === 'double' ) {
  315. this.currentForm.value = this.reader.getUint64();
  316. } else if ( valueType === 'int' ) {
  317. this.currentForm.value = this.reader.getUint32();
  318. } else if ( valueType === 'vparam' ) {
  319. this.reader.skip( 24 );
  320. this.currentForm.value = this.reader.getFloat64();
  321. } else if ( valueType === 'vparam3' ) {
  322. this.reader.skip( 24 );
  323. this.currentForm.value = this.reader.getFloat64Array( 3 );
  324. }
  325. },
  326. // holds various data about texture node image state
  327. // Data other thanmipMapLevel unknown
  328. parseImageStateForm() {
  329. this.reader.skip( 8 ); // unknown
  330. this.currentForm.mipMapLevel = this.reader.getFloat32();
  331. },
  332. // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  333. parseImageMap( length ) {
  334. this.currentFormEnd = this.reader.offset + length;
  335. this.parentForm = this.currentForm;
  336. if ( ! this.currentForm.maps ) this.currentForm.maps = [];
  337. var map = {};
  338. this.currentForm.maps.push( map );
  339. this.currentForm = map;
  340. this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX
  341. },
  342. parseTextureNodeAttribute( type ) {
  343. this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32
  344. this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32
  345. switch ( type ) {
  346. case 'ISCL':
  347. this.currentNode.scale = this.reader.getFloat32Array( 3 );
  348. break;
  349. case 'IPOS':
  350. this.currentNode.position = this.reader.getFloat32Array( 3 );
  351. break;
  352. case 'IROT':
  353. this.currentNode.rotation = this.reader.getFloat32Array( 3 );
  354. break;
  355. case 'IFAL':
  356. this.currentNode.falloff = this.reader.getFloat32Array( 3 );
  357. break;
  358. case 'IBMP':
  359. this.currentNode.amplitude = this.reader.getFloat32();
  360. break;
  361. case 'IUTD':
  362. this.currentNode.uTiles = this.reader.getFloat32();
  363. break;
  364. case 'IVTD':
  365. this.currentNode.vTiles = this.reader.getFloat32();
  366. break;
  367. }
  368. this.reader.skip( 2 ); // unknown
  369. },
  370. // ENVL forms are currently ignored
  371. parseEnvelope( length ) {
  372. this.reader.skip( length - 4 ); // skipping entirely for now
  373. },
  374. ///
  375. // CHUNK PARSING METHODS
  376. ///
  377. // clips can either be defined inside a surface node, or at the top
  378. // level and they have a different format in each case
  379. parseClip( length ) {
  380. var tag = this.reader.getIDTag(); // inside surface node
  381. if ( tag === 'FORM' ) {
  382. this.reader.skip( 16 );
  383. this.currentNode.fileName = this.reader.getString();
  384. return;
  385. } // otherwise top level
  386. this.reader.setOffset( this.reader.offset - 4 );
  387. this.currentFormEnd = this.reader.offset + length;
  388. this.parentForm = this.currentForm;
  389. this.reader.skip( 8 ); // unknown
  390. var texture = {
  391. index: this.reader.getUint32()
  392. };
  393. this.tree.textures.push( texture );
  394. this.currentForm = texture;
  395. },
  396. parseClipLwo2( length ) {
  397. var texture = {
  398. index: this.reader.getUint32(),
  399. fileName: ''
  400. }; // seach STIL block
  401. while ( true ) {
  402. var tag = this.reader.getIDTag();
  403. var n_length = this.reader.getUint16();
  404. if ( tag === 'STIL' ) {
  405. texture.fileName = this.reader.getString();
  406. break;
  407. }
  408. if ( n_length >= length ) {
  409. break;
  410. }
  411. }
  412. this.tree.textures.push( texture );
  413. this.currentForm = texture;
  414. },
  415. parseImage() {
  416. this.reader.skip( 8 ); // unknown
  417. this.currentForm.fileName = this.reader.getString();
  418. },
  419. parseXVAL( type, length ) {
  420. var endOffset = this.reader.offset + length - 4;
  421. this.reader.skip( 8 );
  422. this.currentForm[ type ] = this.reader.getFloat32();
  423. this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope
  424. },
  425. parseXVAL3( type, length ) {
  426. var endOffset = this.reader.offset + length - 4;
  427. this.reader.skip( 8 );
  428. this.currentForm[ type ] = {
  429. x: this.reader.getFloat32(),
  430. y: this.reader.getFloat32(),
  431. z: this.reader.getFloat32()
  432. };
  433. this.reader.setOffset( endOffset );
  434. },
  435. // Tags associated with an object
  436. // OTAG { type[ID4], tag-string[S0] }
  437. parseObjectTag() {
  438. if ( ! this.tree.objectTags ) this.tree.objectTags = {};
  439. this.tree.objectTags[ this.reader.getIDTag() ] = {
  440. tagString: this.reader.getString()
  441. };
  442. },
  443. // 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.
  444. // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  445. parseLayer( length ) {
  446. var layer = {
  447. number: this.reader.getUint16(),
  448. flags: this.reader.getUint16(),
  449. // If the least significant bit of flags is set, the layer is hidden.
  450. pivot: this.reader.getFloat32Array( 3 ),
  451. // Note: this seems to be superflous, as the geometry is translated when pivot is present
  452. name: this.reader.getString()
  453. };
  454. this.tree.layers.push( layer );
  455. this.currentLayer = layer;
  456. var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength
  457. // if we have not reached then end of the layer block, there must be a parent defined
  458. this.currentLayer.parent = parsedLength < length ? this.reader.getUint16() : - 1; // omitted or -1 for no parent
  459. },
  460. // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  461. // Converting from left to right handed coordinate system:
  462. // x -> -x and switch material FrontSide -> BackSide
  463. parsePoints( length ) {
  464. this.currentPoints = [];
  465. for ( var i = 0; i < length / 4; i += 3 ) {
  466. // z -> -z to match three.js right handed coords
  467. this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  468. }
  469. },
  470. // parse VMAP or VMAD
  471. // Associates a set of floating-point vectors with a set of points.
  472. // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  473. // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  474. // Similar to VMAP UVs, but associates with polygon vertices rather than points
  475. // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name,
  476. // if they exist. The vector values in the VMAD will then replace those in the
  477. // corresponding VMAP, but only for calculations involving the specified polygons.
  478. // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  479. parseVertexMapping( length, discontinuous ) {
  480. var finalOffset = this.reader.offset + length;
  481. var channelName = this.reader.getString();
  482. if ( this.reader.offset === finalOffset ) {
  483. // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
  484. this.currentForm.UVChannel = channelName;
  485. return;
  486. } // otherwise reset to initial length and parse normal VMAP CHUNK
  487. this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );
  488. var type = this.reader.getIDTag();
  489. this.reader.getUint16(); // dimension
  490. var name = this.reader.getString();
  491. var remainingLength = length - 6 - stringOffset( name );
  492. switch ( type ) {
  493. case 'TXUV':
  494. this.parseUVMapping( name, finalOffset, discontinuous );
  495. break;
  496. case 'MORF':
  497. case 'SPOT':
  498. this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
  499. break;
  500. // unsupported VMAPs
  501. case 'APSL':
  502. case 'NORM':
  503. case 'WGHT':
  504. case 'MNVW':
  505. case 'PICK':
  506. case 'RGB ':
  507. case 'RGBA':
  508. this.reader.skip( remainingLength );
  509. break;
  510. default:
  511. console.warn( 'LWOLoader: unknown vertex map type: ' + type );
  512. this.reader.skip( remainingLength );
  513. }
  514. },
  515. parseUVMapping( name, finalOffset, discontinuous ) {
  516. var uvIndices = [];
  517. var polyIndices = [];
  518. var uvs = [];
  519. while ( this.reader.offset < finalOffset ) {
  520. uvIndices.push( this.reader.getVariableLengthIndex() );
  521. if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );
  522. uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );
  523. }
  524. if ( discontinuous ) {
  525. if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};
  526. this.currentLayer.discontinuousUVs[ name ] = {
  527. uvIndices: uvIndices,
  528. polyIndices: polyIndices,
  529. uvs: uvs
  530. };
  531. } else {
  532. if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};
  533. this.currentLayer.uvs[ name ] = {
  534. uvIndices: uvIndices,
  535. uvs: uvs
  536. };
  537. }
  538. },
  539. parseMorphTargets( name, finalOffset, type ) {
  540. var indices = [];
  541. var points = [];
  542. type = type === 'MORF' ? 'relative' : 'absolute';
  543. while ( this.reader.offset < finalOffset ) {
  544. indices.push( this.reader.getVariableLengthIndex() ); // z -> -z to match three.js right handed coords
  545. points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  546. }
  547. if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};
  548. this.currentLayer.morphTargets[ name ] = {
  549. indices: indices,
  550. points: points,
  551. type: type
  552. };
  553. },
  554. // A list of polygons for the current layer.
  555. // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  556. parsePolygonList( length ) {
  557. var finalOffset = this.reader.offset + length;
  558. var type = this.reader.getIDTag();
  559. var indices = []; // hold a list of polygon sizes, to be split up later
  560. var polygonDimensions = [];
  561. while ( this.reader.offset < finalOffset ) {
  562. var numverts = this.reader.getUint16(); //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
  563. numverts = numverts & 1023; // remaining ten low order bits are vertex num
  564. polygonDimensions.push( numverts );
  565. for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );
  566. }
  567. var geometryData = {
  568. type: type,
  569. vertexIndices: indices,
  570. polygonDimensions: polygonDimensions,
  571. points: this.currentPoints
  572. }; // Note: assuming that all polys will be lines or points if the first is
  573. if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points'; else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';
  574. this.currentLayer.geometry = geometryData;
  575. },
  576. // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  577. // TAGS { tag-string[S0] * }
  578. parseTagStrings( length ) {
  579. this.tree.tags = this.reader.getStringArray( length );
  580. },
  581. // Associates tags of a given type with polygons in the most recent POLS chunk.
  582. // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  583. parsePolygonTagMapping( length ) {
  584. var finalOffset = this.reader.offset + length;
  585. var type = this.reader.getIDTag();
  586. if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset ); else {
  587. //PART, SMGP, COLR not supported
  588. this.reader.skip( length - 4 );
  589. }
  590. },
  591. parseMaterialIndices( finalOffset ) {
  592. // array holds polygon index followed by material index
  593. this.currentLayer.geometry.materialIndices = [];
  594. while ( this.reader.offset < finalOffset ) {
  595. var polygonIndex = this.reader.getVariableLengthIndex();
  596. var materialIndex = this.reader.getUint16();
  597. this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );
  598. }
  599. },
  600. parseUnknownCHUNK( blockID, length ) {
  601. console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length ); // print the chunk plus some bytes padding either side
  602. // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );
  603. var data = this.reader.getString( length );
  604. this.currentForm[ blockID ] = data;
  605. }
  606. };
  607. function DataViewReader( buffer ) {
  608. this.dv = new DataView( buffer );
  609. this.offset = 0;
  610. }
  611. DataViewReader.prototype = {
  612. constructor: DataViewReader,
  613. size: function () {
  614. return this.dv.buffer.byteLength;
  615. },
  616. setOffset( offset ) {
  617. if ( offset > 0 && offset < this.dv.buffer.byteLength ) {
  618. this.offset = offset;
  619. } else {
  620. console.error( 'LWOLoader: invalid buffer offset' );
  621. }
  622. },
  623. endOfFile: function () {
  624. if ( this.offset >= this.size() ) return true;
  625. return false;
  626. },
  627. skip: function ( length ) {
  628. this.offset += length;
  629. },
  630. getUint8: function () {
  631. var value = this.dv.getUint8( this.offset );
  632. this.offset += 1;
  633. return value;
  634. },
  635. getUint16: function () {
  636. var value = this.dv.getUint16( this.offset );
  637. this.offset += 2;
  638. return value;
  639. },
  640. getInt32: function () {
  641. var value = this.dv.getInt32( this.offset, false );
  642. this.offset += 4;
  643. return value;
  644. },
  645. getUint32: function () {
  646. var value = this.dv.getUint32( this.offset, false );
  647. this.offset += 4;
  648. return value;
  649. },
  650. getUint64: function () {
  651. var low, high;
  652. high = this.getUint32();
  653. low = this.getUint32();
  654. return high * 0x100000000 + low;
  655. },
  656. getFloat32: function () {
  657. var value = this.dv.getFloat32( this.offset, false );
  658. this.offset += 4;
  659. return value;
  660. },
  661. getFloat32Array: function ( size ) {
  662. var a = [];
  663. for ( var i = 0; i < size; i ++ ) {
  664. a.push( this.getFloat32() );
  665. }
  666. return a;
  667. },
  668. getFloat64: function () {
  669. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  670. this.offset += 8;
  671. return value;
  672. },
  673. getFloat64Array: function ( size ) {
  674. var a = [];
  675. for ( var i = 0; i < size; i ++ ) {
  676. a.push( this.getFloat64() );
  677. }
  678. return a;
  679. },
  680. // get variable-length index data type
  681. // VX ::= index[U2] | (index + 0xFF000000)[U4]
  682. // If the index value is less than 65,280 (0xFF00),then VX === U2
  683. // otherwise VX === U4 with bits 24-31 set
  684. // When reading an index, if the first byte encountered is 255 (0xFF), then
  685. // the four-byte form is being used and the first byte should be discarded or masked out.
  686. getVariableLengthIndex() {
  687. var firstByte = this.getUint8();
  688. if ( firstByte === 255 ) {
  689. return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
  690. }
  691. return firstByte * 256 + this.getUint8();
  692. },
  693. // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  694. getIDTag() {
  695. return this.getString( 4 );
  696. },
  697. getString: function ( size ) {
  698. if ( size === 0 ) return; // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  699. var a = [];
  700. if ( size ) {
  701. for ( var i = 0; i < size; i ++ ) {
  702. a[ i ] = this.getUint8();
  703. }
  704. } else {
  705. var currentChar;
  706. var len = 0;
  707. while ( currentChar !== 0 ) {
  708. currentChar = this.getUint8();
  709. if ( currentChar !== 0 ) a.push( currentChar );
  710. len ++;
  711. }
  712. if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added
  713. }
  714. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  715. },
  716. getStringArray: function ( size ) {
  717. var a = this.getString( size );
  718. a = a.split( '\0' );
  719. return a.filter( Boolean ); // return array with any empty strings removed
  720. }
  721. }; // ************** DEBUGGER **************
  722. function Debugger() {
  723. this.active = false;
  724. this.depth = 0;
  725. this.formList = [];
  726. }
  727. Debugger.prototype = {
  728. constructor: Debugger,
  729. enable: function () {
  730. this.active = true;
  731. },
  732. log: function () {
  733. if ( ! this.active ) return;
  734. var nodeType;
  735. switch ( this.node ) {
  736. case 0:
  737. nodeType = 'FORM';
  738. break;
  739. case 1:
  740. nodeType = 'CHK';
  741. break;
  742. case 2:
  743. nodeType = 'S-CHK';
  744. break;
  745. }
  746. console.log( '| '.repeat( this.depth ) + nodeType, this.nodeID, `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`, this.node == 0 ? ' {' : '', this.skipped ? 'SKIPPED' : '', this.node == 0 && this.skipped ? '}' : '' );
  747. if ( this.node == 0 && ! this.skipped ) {
  748. this.depth += 1;
  749. this.formList.push( this.dataOffset + this.length );
  750. }
  751. this.skipped = false;
  752. },
  753. closeForms: function () {
  754. if ( ! this.active ) return;
  755. for ( var i = this.formList.length - 1; i >= 0; i -- ) {
  756. if ( this.offset >= this.formList[ i ] ) {
  757. this.depth -= 1;
  758. console.log( '| '.repeat( this.depth ) + '}' );
  759. this.formList.splice( - 1, 1 );
  760. }
  761. }
  762. }
  763. }; // ************** UTILITY FUNCTIONS **************
  764. function isEven( num ) {
  765. return num % 2;
  766. } // calculate the length of the string in the buffer
  767. // this will be string.length + nullbyte + optional padbyte to make the length even
  768. function stringOffset( string ) {
  769. return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );
  770. } // for testing purposes, dump buffer to console
  771. // printBuffer( this.reader.dv.buffer, this.reader.offset, length );
  772. function printBuffer( buffer, from, to ) {
  773. console.log( THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );
  774. }
  775. THREE.IFFParser = IFFParser;
  776. } )();