IFFParser.js 26 KB

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