IFFParser.js 26 KB

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