LWOLoader.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055
  1. /**
  2. * @version 1.1.1
  3. *
  4. * @author Lewy Blue https://github.com/looeee
  5. * @author Guilherme Avila https://github/sciecode
  6. *
  7. * @desc Load files in LWO3 and LWO2 format on Three.js
  8. *
  9. * LWO3 format specification:
  10. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo3.html
  11. *
  12. * LWO2 format specification:
  13. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo2.html
  14. *
  15. * Development and test repository:
  16. * https://github.com/threejs/lwoloader
  17. *
  18. **/
  19. function LWO2Parser( IFFParser ) {
  20. this.IFF = IFFParser;
  21. }
  22. LWO2Parser.prototype = {
  23. constructor: LWO2Parser,
  24. parseBlock: function () {
  25. this.IFF.debugger.offset = this.IFF.reader.offset;
  26. this.IFF.debugger.closeForms();
  27. var blockID = this.IFF.reader.getIDTag();
  28. var length = this.IFF.reader.getUint32(); // size of data in bytes
  29. if ( length > this.IFF.reader.dv.byteLength - this.IFF.reader.offset ) {
  30. this.IFF.reader.offset -= 4;
  31. length = this.IFF.reader.getUint16();
  32. }
  33. this.IFF.debugger.dataOffset = this.IFF.reader.offset;
  34. this.IFF.debugger.length = length;
  35. // Data types may be found in either LWO2 OR LWO3 spec
  36. switch ( blockID ) {
  37. case 'FORM': // form blocks may consist of sub -chunks or sub-forms
  38. this.IFF.parseForm( length );
  39. break;
  40. // SKIPPED CHUNKS
  41. // if break; is called directly, the position in the lwoTree is not created
  42. // any sub chunks and forms are added to the parent form instead
  43. // MISC skipped
  44. case 'ICON': // Thumbnail Icon Image
  45. case 'VMPA': // Vertex Map Parameter
  46. case 'BBOX': // bounding box
  47. // case 'VMMD':
  48. // case 'VTYP':
  49. // normal maps can be specified, normally on models imported from other applications. Currently ignored
  50. case 'NORM':
  51. // ENVL FORM skipped
  52. case 'PRE ':
  53. case 'POST':
  54. case 'KEY ':
  55. case 'SPAN':
  56. // CLIP FORM skipped
  57. case 'TIME':
  58. case 'CLRS':
  59. case 'CLRA':
  60. case 'FILT':
  61. case 'DITH':
  62. case 'CONT':
  63. case 'BRIT':
  64. case 'SATR':
  65. case 'HUE ':
  66. case 'GAMM':
  67. case 'NEGA':
  68. case 'IFLT':
  69. case 'PFLT':
  70. // Image Map Layer skipped
  71. case 'PROJ':
  72. case 'AXIS':
  73. case 'AAST':
  74. case 'PIXB':
  75. case 'AUVO':
  76. case 'STCK':
  77. // Procedural Textures skipped
  78. case 'PROC':
  79. case 'VALU':
  80. case 'FUNC':
  81. // Gradient Textures skipped
  82. case 'PNAM':
  83. case 'INAM':
  84. case 'GRST':
  85. case 'GREN':
  86. case 'GRPT':
  87. case 'FKEY':
  88. case 'IKEY':
  89. // Texture Mapping Form skipped
  90. case 'CSYS':
  91. // Surface CHUNKs skipped
  92. case 'OPAQ': // top level 'opacity' checkbox
  93. case 'CMAP': // clip map
  94. // Surface node CHUNKS skipped
  95. // These mainly specify the node editor setup in LW
  96. case 'NLOC':
  97. case 'NZOM':
  98. case 'NVER':
  99. case 'NSRV':
  100. case 'NVSK': // unknown
  101. case 'NCRD':
  102. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  103. case 'WRPH': // image wrap h
  104. case 'NMOD':
  105. case 'NPRW':
  106. case 'NPLA':
  107. case 'NODS':
  108. case 'VERS':
  109. case 'ENUM':
  110. case 'TAG ':
  111. case 'OPAC':
  112. // Car Material CHUNKS
  113. case 'CGMD':
  114. case 'CGTY':
  115. case 'CGST':
  116. case 'CGEN':
  117. case 'CGTS':
  118. case 'CGTE':
  119. case 'OSMP':
  120. case 'OMDE':
  121. case 'OUTR':
  122. case 'FLAG':
  123. case 'TRNL':
  124. case 'GLOW':
  125. case 'GVAL': // glow intensity
  126. case 'SHRP':
  127. case 'RFOP':
  128. case 'RSAN':
  129. case 'TROP':
  130. case 'RBLR':
  131. case 'TBLR':
  132. case 'CLRH':
  133. case 'CLRF':
  134. case 'ADTR':
  135. case 'LINE':
  136. case 'ALPH':
  137. case 'VCOL':
  138. case 'ENAB':
  139. this.IFF.debugger.skipped = true;
  140. this.IFF.reader.skip( length );
  141. break;
  142. case 'SURF':
  143. this.IFF.parseSurfaceLwo2( length );
  144. break;
  145. case 'CLIP':
  146. this.IFF.parseClipLwo2( length );
  147. break;
  148. // Texture node chunks (not in spec)
  149. case 'IPIX': // usePixelBlending
  150. case 'IMIP': // useMipMaps
  151. case 'IMOD': // imageBlendingMode
  152. case 'AMOD': // unknown
  153. case 'IINV': // imageInvertAlpha
  154. case 'INCR': // imageInvertColor
  155. case 'IAXS': // imageAxis ( for non-UV maps)
  156. case 'IFOT': // imageFallofType
  157. case 'ITIM': // timing for animated textures
  158. case 'IWRL':
  159. case 'IUTI':
  160. case 'IINX':
  161. case 'IINY':
  162. case 'IINZ':
  163. case 'IREF': // possibly a VX for reused texture nodes
  164. if ( length === 4 ) this.IFF.currentNode[ blockID ] = this.IFF.reader.getInt32();
  165. else this.IFF.reader.skip( length );
  166. break;
  167. case 'OTAG':
  168. this.IFF.parseObjectTag();
  169. break;
  170. case 'LAYR':
  171. this.IFF.parseLayer( length );
  172. break;
  173. case 'PNTS':
  174. this.IFF.parsePoints( length );
  175. break;
  176. case 'VMAP':
  177. this.IFF.parseVertexMapping( length );
  178. break;
  179. case 'AUVU':
  180. case 'AUVN':
  181. this.IFF.reader.skip( length - 1 );
  182. this.IFF.reader.getVariableLengthIndex(); // VX
  183. break;
  184. case 'POLS':
  185. this.IFF.parsePolygonList( length );
  186. break;
  187. case 'TAGS':
  188. this.IFF.parseTagStrings( length );
  189. break;
  190. case 'PTAG':
  191. this.IFF.parsePolygonTagMapping( length );
  192. break;
  193. case 'VMAD':
  194. this.IFF.parseVertexMapping( length, true );
  195. break;
  196. // Misc CHUNKS
  197. case 'DESC': // Description Line
  198. this.IFF.currentForm.description = this.IFF.reader.getString();
  199. break;
  200. case 'TEXT':
  201. case 'CMNT':
  202. case 'NCOM':
  203. this.IFF.currentForm.comment = this.IFF.reader.getString();
  204. break;
  205. // Envelope Form
  206. case 'NAME':
  207. this.IFF.currentForm.channelName = this.IFF.reader.getString();
  208. break;
  209. // Image Map Layer
  210. case 'WRAP':
  211. this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() };
  212. break;
  213. case 'IMAG':
  214. var index = this.IFF.reader.getVariableLengthIndex();
  215. this.IFF.currentForm.imageIndex = index;
  216. break;
  217. // Texture Mapping Form
  218. case 'OREF':
  219. this.IFF.currentForm.referenceObject = this.IFF.reader.getString();
  220. break;
  221. case 'ROID':
  222. this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32();
  223. break;
  224. // Surface Blocks
  225. case 'SSHN':
  226. this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString();
  227. break;
  228. case 'AOVN':
  229. this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString();
  230. break;
  231. // Nodal Blocks
  232. case 'NSTA':
  233. this.IFF.currentForm.disabled = this.IFF.reader.getUint16();
  234. break;
  235. case 'NRNM':
  236. this.IFF.currentForm.realName = this.IFF.reader.getString();
  237. break;
  238. case 'NNME':
  239. this.IFF.currentForm.refName = this.IFF.reader.getString();
  240. this.IFF.currentSurface.nodes[ this.IFF.currentForm.refName ] = this.IFF.currentForm;
  241. break;
  242. // Nodal Blocks : connections
  243. case 'INME':
  244. if ( ! this.IFF.currentForm.nodeName ) this.IFF.currentForm.nodeName = [];
  245. this.IFF.currentForm.nodeName.push( this.IFF.reader.getString() );
  246. break;
  247. case 'IINN':
  248. if ( ! this.IFF.currentForm.inputNodeName ) this.IFF.currentForm.inputNodeName = [];
  249. this.IFF.currentForm.inputNodeName.push( this.IFF.reader.getString() );
  250. break;
  251. case 'IINM':
  252. if ( ! this.IFF.currentForm.inputName ) this.IFF.currentForm.inputName = [];
  253. this.IFF.currentForm.inputName.push( this.IFF.reader.getString() );
  254. break;
  255. case 'IONM':
  256. if ( ! this.IFF.currentForm.inputOutputName ) this.IFF.currentForm.inputOutputName = [];
  257. this.IFF.currentForm.inputOutputName.push( this.IFF.reader.getString() );
  258. break;
  259. case 'FNAM':
  260. this.IFF.currentForm.fileName = this.IFF.reader.getString();
  261. break;
  262. case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
  263. if ( length === 4 ) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();
  264. else this.IFF.reader.skip( length );
  265. break;
  266. // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
  267. case 'SMAN':
  268. var maxSmoothingAngle = this.IFF.reader.getFloat32();
  269. this.IFF.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
  270. break;
  271. // LWO2: Basic Surface Parameters
  272. case 'COLR':
  273. this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array( 3 ) };
  274. this.IFF.reader.skip( 2 ); // VX: envelope
  275. break;
  276. case 'LUMI':
  277. this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() };
  278. this.IFF.reader.skip( 2 );
  279. break;
  280. case 'SPEC':
  281. this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() };
  282. this.IFF.reader.skip( 2 );
  283. break;
  284. case 'DIFF':
  285. this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() };
  286. this.IFF.reader.skip( 2 );
  287. break;
  288. case 'REFL':
  289. this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() };
  290. this.IFF.reader.skip( 2 );
  291. break;
  292. case 'GLOS':
  293. this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() };
  294. this.IFF.reader.skip( 2 );
  295. break;
  296. case 'TRAN':
  297. this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32();
  298. this.IFF.reader.skip( 2 );
  299. break;
  300. case 'BUMP':
  301. this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32();
  302. this.IFF.reader.skip( 2 );
  303. break;
  304. case 'SIDE':
  305. this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16();
  306. break;
  307. case 'RIMG':
  308. this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex();
  309. break;
  310. case 'RIND':
  311. this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32();
  312. this.IFF.reader.skip( 2 );
  313. break;
  314. case 'TIMG':
  315. this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex();
  316. break;
  317. case 'IMAP':
  318. this.IFF.reader.skip( 2 );
  319. break;
  320. case 'TMAP':
  321. this.IFF.debugger.skipped = true;
  322. this.IFF.reader.skip( length ); // needs implementing
  323. break;
  324. case 'IUVI': // uv channel name
  325. this.IFF.currentNode.UVChannel = this.IFF.reader.getString( length );
  326. break;
  327. case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  328. this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32();
  329. break;
  330. case 'IVTL': // heightWrappingMode
  331. this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32();
  332. break;
  333. // LWO2 USE
  334. case 'BLOK':
  335. // skip
  336. break;
  337. default:
  338. this.IFF.parseUnknownCHUNK( blockID, length );
  339. }
  340. if ( blockID != 'FORM' ) {
  341. this.IFF.debugger.node = 1;
  342. this.IFF.debugger.nodeID = blockID;
  343. this.IFF.debugger.log();
  344. }
  345. if ( this.IFF.reader.offset >= this.IFF.currentFormEnd ) {
  346. this.IFF.currentForm = this.IFF.parentForm;
  347. }
  348. }
  349. };
  350. function LWO3Parser( IFFParser ) {
  351. this.IFF = IFFParser;
  352. }
  353. LWO3Parser.prototype = {
  354. constructor: LWO3Parser,
  355. parseBlock: function () {
  356. this.IFF.debugger.offset = this.IFF.reader.offset;
  357. this.IFF.debugger.closeForms();
  358. var blockID = this.IFF.reader.getIDTag();
  359. var length = this.IFF.reader.getUint32(); // size of data in bytes
  360. this.IFF.debugger.dataOffset = this.IFF.reader.offset;
  361. this.IFF.debugger.length = length;
  362. // Data types may be found in either LWO2 OR LWO3 spec
  363. switch ( blockID ) {
  364. case 'FORM': // form blocks may consist of sub -chunks or sub-forms
  365. this.IFF.parseForm( length );
  366. break;
  367. // SKIPPED CHUNKS
  368. // MISC skipped
  369. case 'ICON': // Thumbnail Icon Image
  370. case 'VMPA': // Vertex Map Parameter
  371. case 'BBOX': // bounding box
  372. // case 'VMMD':
  373. // case 'VTYP':
  374. // normal maps can be specified, normally on models imported from other applications. Currently ignored
  375. case 'NORM':
  376. // ENVL FORM skipped
  377. case 'PRE ':
  378. case 'POST':
  379. case 'KEY ':
  380. case 'SPAN':
  381. // CLIP FORM skipped
  382. case 'TIME':
  383. case 'CLRS':
  384. case 'CLRA':
  385. case 'FILT':
  386. case 'DITH':
  387. case 'CONT':
  388. case 'BRIT':
  389. case 'SATR':
  390. case 'HUE ':
  391. case 'GAMM':
  392. case 'NEGA':
  393. case 'IFLT':
  394. case 'PFLT':
  395. // Image Map Layer skipped
  396. case 'PROJ':
  397. case 'AXIS':
  398. case 'AAST':
  399. case 'PIXB':
  400. case 'STCK':
  401. // Procedural Textures skipped
  402. case 'VALU':
  403. // Gradient Textures skipped
  404. case 'PNAM':
  405. case 'INAM':
  406. case 'GRST':
  407. case 'GREN':
  408. case 'GRPT':
  409. case 'FKEY':
  410. case 'IKEY':
  411. // Texture Mapping Form skipped
  412. case 'CSYS':
  413. // Surface CHUNKs skipped
  414. case 'OPAQ': // top level 'opacity' checkbox
  415. case 'CMAP': // clip map
  416. // Surface node CHUNKS skipped
  417. // These mainly specify the node editor setup in LW
  418. case 'NLOC':
  419. case 'NZOM':
  420. case 'NVER':
  421. case 'NSRV':
  422. case 'NCRD':
  423. case 'NMOD':
  424. case 'NSEL':
  425. case 'NPRW':
  426. case 'NPLA':
  427. case 'VERS':
  428. case 'ENUM':
  429. case 'TAG ':
  430. // Car Material CHUNKS
  431. case 'CGMD':
  432. case 'CGTY':
  433. case 'CGST':
  434. case 'CGEN':
  435. case 'CGTS':
  436. case 'CGTE':
  437. case 'OSMP':
  438. case 'OMDE':
  439. case 'OUTR':
  440. case 'FLAG':
  441. case 'TRNL':
  442. case 'GLOS':
  443. case 'SHRP':
  444. case 'RFOP':
  445. case 'RSAN':
  446. case 'TROP':
  447. case 'RBLR':
  448. case 'TBLR':
  449. case 'CLRH':
  450. case 'CLRF':
  451. case 'ADTR':
  452. case 'GLOW':
  453. case 'LINE':
  454. case 'ALPH':
  455. case 'VCOL':
  456. case 'ENAB':
  457. this.IFF.debugger.skipped = true;
  458. this.IFF.reader.skip( length );
  459. break;
  460. // Texture node chunks (not in spec)
  461. case 'IPIX': // usePixelBlending
  462. case 'IMIP': // useMipMaps
  463. case 'IMOD': // imageBlendingMode
  464. case 'AMOD': // unknown
  465. case 'IINV': // imageInvertAlpha
  466. case 'INCR': // imageInvertColor
  467. case 'IAXS': // imageAxis ( for non-UV maps)
  468. case 'IFOT': // imageFallofType
  469. case 'ITIM': // timing for animated textures
  470. case 'IWRL':
  471. case 'IUTI':
  472. case 'IINX':
  473. case 'IINY':
  474. case 'IINZ':
  475. case 'IREF': // possibly a VX for reused texture nodes
  476. if ( length === 4 ) this.IFF.currentNode[ blockID ] = this.IFF.reader.getInt32();
  477. else this.IFF.reader.skip( length );
  478. break;
  479. case 'OTAG':
  480. this.IFF.parseObjectTag();
  481. break;
  482. case 'LAYR':
  483. this.IFF.parseLayer( length );
  484. break;
  485. case 'PNTS':
  486. this.IFF.parsePoints( length );
  487. break;
  488. case 'VMAP':
  489. this.IFF.parseVertexMapping( length );
  490. break;
  491. case 'POLS':
  492. this.IFF.parsePolygonList( length );
  493. break;
  494. case 'TAGS':
  495. this.IFF.parseTagStrings( length );
  496. break;
  497. case 'PTAG':
  498. this.IFF.parsePolygonTagMapping( length );
  499. break;
  500. case 'VMAD':
  501. this.IFF.parseVertexMapping( length, true );
  502. break;
  503. // Misc CHUNKS
  504. case 'DESC': // Description Line
  505. this.IFF.currentForm.description = this.IFF.reader.getString();
  506. break;
  507. case 'TEXT':
  508. case 'CMNT':
  509. case 'NCOM':
  510. this.IFF.currentForm.comment = this.IFF.reader.getString();
  511. break;
  512. // Envelope Form
  513. case 'NAME':
  514. this.IFF.currentForm.channelName = this.IFF.reader.getString();
  515. break;
  516. // Image Map Layer
  517. case 'WRAP':
  518. this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() };
  519. break;
  520. case 'IMAG':
  521. var index = this.IFF.reader.getVariableLengthIndex();
  522. this.IFF.currentForm.imageIndex = index;
  523. break;
  524. // Texture Mapping Form
  525. case 'OREF':
  526. this.IFF.currentForm.referenceObject = this.IFF.reader.getString();
  527. break;
  528. case 'ROID':
  529. this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32();
  530. break;
  531. // Surface Blocks
  532. case 'SSHN':
  533. this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString();
  534. break;
  535. case 'AOVN':
  536. this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString();
  537. break;
  538. // Nodal Blocks
  539. case 'NSTA':
  540. this.IFF.currentForm.disabled = this.IFF.reader.getUint16();
  541. break;
  542. case 'NRNM':
  543. this.IFF.currentForm.realName = this.IFF.reader.getString();
  544. break;
  545. case 'NNME':
  546. this.IFF.currentForm.refName = this.IFF.reader.getString();
  547. this.IFF.currentSurface.nodes[ this.IFF.currentForm.refName ] = this.IFF.currentForm;
  548. break;
  549. // Nodal Blocks : connections
  550. case 'INME':
  551. if ( ! this.IFF.currentForm.nodeName ) this.IFF.currentForm.nodeName = [];
  552. this.IFF.currentForm.nodeName.push( this.IFF.reader.getString() );
  553. break;
  554. case 'IINN':
  555. if ( ! this.IFF.currentForm.inputNodeName ) this.IFF.currentForm.inputNodeName = [];
  556. this.IFF.currentForm.inputNodeName.push( this.IFF.reader.getString() );
  557. break;
  558. case 'IINM':
  559. if ( ! this.IFF.currentForm.inputName ) this.IFF.currentForm.inputName = [];
  560. this.IFF.currentForm.inputName.push( this.IFF.reader.getString() );
  561. break;
  562. case 'IONM':
  563. if ( ! this.IFF.currentForm.inputOutputName ) this.IFF.currentForm.inputOutputName = [];
  564. this.IFF.currentForm.inputOutputName.push( this.IFF.reader.getString() );
  565. break;
  566. case 'FNAM':
  567. this.IFF.currentForm.fileName = this.IFF.reader.getString();
  568. break;
  569. case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
  570. if ( length === 4 ) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();
  571. else this.IFF.reader.skip( length );
  572. break;
  573. // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
  574. case 'SMAN':
  575. var maxSmoothingAngle = this.IFF.reader.getFloat32();
  576. this.IFF.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
  577. break;
  578. // LWO2: Basic Surface Parameters
  579. case 'COLR':
  580. this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array( 3 ) };
  581. this.IFF.reader.skip( 2 ); // VX: envelope
  582. break;
  583. case 'LUMI':
  584. this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() };
  585. this.IFF.reader.skip( 2 );
  586. break;
  587. case 'SPEC':
  588. this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() };
  589. this.IFF.reader.skip( 2 );
  590. break;
  591. case 'DIFF':
  592. this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() };
  593. this.IFF.reader.skip( 2 );
  594. break;
  595. case 'REFL':
  596. this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() };
  597. this.IFF.reader.skip( 2 );
  598. break;
  599. case 'GLOS':
  600. this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() };
  601. this.IFF.reader.skip( 2 );
  602. break;
  603. case 'TRAN':
  604. this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32();
  605. this.IFF.reader.skip( 2 );
  606. break;
  607. case 'BUMP':
  608. this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32();
  609. this.IFF.reader.skip( 2 );
  610. break;
  611. case 'SIDE':
  612. this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16();
  613. break;
  614. case 'RIMG':
  615. this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex();
  616. break;
  617. case 'RIND':
  618. this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32();
  619. this.IFF.reader.skip( 2 );
  620. break;
  621. case 'TIMG':
  622. this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex();
  623. break;
  624. case 'IMAP':
  625. this.IFF.currentSurface.attributes.imageMapIndex = this.IFF.reader.getUint32();
  626. break;
  627. case 'IUVI': // uv channel name
  628. this.IFF.currentNode.UVChannel = this.IFF.reader.getString( length );
  629. break;
  630. case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  631. this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32();
  632. break;
  633. case 'IVTL': // heightWrappingMode
  634. this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32();
  635. break;
  636. default:
  637. this.IFF.parseUnknownCHUNK( blockID, length );
  638. }
  639. if ( blockID != 'FORM' ) {
  640. this.IFF.debugger.node = 1;
  641. this.IFF.debugger.nodeID = blockID;
  642. this.IFF.debugger.log();
  643. }
  644. if ( this.IFF.reader.offset >= this.IFF.currentFormEnd ) {
  645. this.IFF.currentForm = this.IFF.parentForm;
  646. }
  647. }
  648. };
  649. /**
  650. * === IFFParser ===
  651. * - Parses data from the IFF buffer.
  652. * - LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes
  653. *
  654. * ATOMIC DATA TYPES
  655. * ID Tag - 4x 7 bit uppercase ASCII chars: ID4
  656. * signed integer, 1, 2, or 4 byte length: I1, I2, I4
  657. * unsigned integer, 1, 2, or 4 byte length: U1, U2, U4
  658. * float, 4 byte length: F4
  659. * 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
  660. *
  661. * COMPOUND DATA TYPES
  662. * Variable-length Index (index into an array or collection): U2 or U4 : VX
  663. * Color (RGB): F4 + F4 + F4: COL12
  664. * Coordinate (x, y, z): F4 + F4 + F4: VEC12
  665. * Percentage F4 data type from 0->1 with 1 = 100%: FP4
  666. * Angle in radian F4: ANG4
  667. * Filename (string) S0: FNAM0
  668. * XValue F4 + index (VX) + optional envelope( ENVL ): XVAL
  669. * XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3
  670. *
  671. * The IFF file is arranged in chunks:
  672. * CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte
  673. * optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size
  674. *
  675. * COMPOUND DATA TYPES
  676. * - Chunks are combined in Forms (collections of chunks)
  677. * - FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM )
  678. * - CHUNKS and FORMS are collectively referred to as blocks
  679. * - The entire file is contained in one top level FORM
  680. *
  681. **/
  682. function IFFParser( ) {
  683. this.debugger = new Debugger();
  684. // this.debugger.enable(); // un-comment to log IFF hierarchy.
  685. }
  686. IFFParser.prototype = {
  687. constructor: IFFParser,
  688. parse: function ( buffer ) {
  689. this.reader = new DataViewReader( buffer );
  690. this.tree = {
  691. materials: {},
  692. layers: [],
  693. tags: [],
  694. textures: [],
  695. };
  696. // start out at the top level to add any data before first layer is encountered
  697. this.currentLayer = this.tree;
  698. this.currentForm = this.tree;
  699. this.parseTopForm();
  700. if ( this.tree.format === undefined ) return;
  701. if ( this.tree.format === 'LWO2' ) {
  702. this.parser = new LWO2Parser( this );
  703. while ( ! this.reader.endOfFile() ) this.parser.parseBlock();
  704. } else if ( this.tree.format === 'LWO3' ) {
  705. this.parser = new LWO3Parser( this );
  706. while ( ! this.reader.endOfFile() ) this.parser.parseBlock();
  707. }
  708. this.debugger.offset = this.reader.offset;
  709. this.debugger.closeForms();
  710. return this.tree;
  711. },
  712. parseTopForm() {
  713. this.debugger.offset = this.reader.offset;
  714. var topForm = this.reader.getIDTag();
  715. if ( topForm !== 'FORM' ) {
  716. console.warn( "LWOLoader: Top-level FORM missing." );
  717. return;
  718. }
  719. var length = this.reader.getUint32();
  720. this.debugger.dataOffset = this.reader.offset;
  721. this.debugger.length = length;
  722. var type = this.reader.getIDTag();
  723. if ( type === 'LWO2' ) {
  724. this.tree.format = type;
  725. } else if ( type === 'LWO3' ) {
  726. this.tree.format = type;
  727. }
  728. this.debugger.node = 0;
  729. this.debugger.nodeID = type;
  730. this.debugger.log();
  731. return;
  732. },
  733. ///
  734. // FORM PARSING METHODS
  735. ///
  736. // Forms are organisational and can contain any number of sub chunks and sub forms
  737. // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  738. parseForm( length ) {
  739. var type = this.reader.getIDTag();
  740. switch ( type ) {
  741. // SKIPPED FORMS
  742. // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
  743. case 'ISEQ': // Image sequence
  744. case 'ANIM': // plug in animation
  745. case 'STCC': // Color-cycling Still
  746. case 'VPVL':
  747. case 'VPRM':
  748. case 'NROT':
  749. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  750. case 'WRPH': // image wrap h
  751. case 'FUNC':
  752. case 'FALL':
  753. case 'OPAC':
  754. case 'GRAD': // gradient texture
  755. case 'ENVS':
  756. case 'VMOP':
  757. case 'VMBG':
  758. // Car Material FORMS
  759. case 'OMAX':
  760. case 'STEX':
  761. case 'CKBG':
  762. case 'CKEY':
  763. case 'VMLA':
  764. case 'VMLB':
  765. this.debugger.skipped = true;
  766. this.skipForm( length ); // not currently supported
  767. break;
  768. // if break; is called directly, the position in the lwoTree is not created
  769. // any sub chunks and forms are added to the parent form instead
  770. case 'META':
  771. case 'NNDS':
  772. case 'NODS':
  773. case 'NDTA':
  774. case 'ADAT':
  775. case 'AOVS':
  776. case 'BLOK':
  777. // used by texture nodes
  778. case 'IBGC': // imageBackgroundColor
  779. case 'IOPC': // imageOpacity
  780. case 'IIMG': // hold reference to image path
  781. case 'TXTR':
  782. // this.setupForm( type, length );
  783. this.debugger.length = 4;
  784. this.debugger.skipped = true;
  785. break;
  786. case 'IFAL': // imageFallof
  787. case 'ISCL': // imageScale
  788. case 'IPOS': // imagePosition
  789. case 'IROT': // imageRotation
  790. case 'IBMP':
  791. case 'IUTD':
  792. case 'IVTD':
  793. this.parseTextureNodeAttribute( type );
  794. break;
  795. case 'ENVL':
  796. this.parseEnvelope( length );
  797. break;
  798. // CLIP FORM AND SUB FORMS
  799. case 'CLIP':
  800. if ( this.tree.format === 'LWO2' ) {
  801. this.parseForm( length );
  802. } else {
  803. this.parseClip( length );
  804. }
  805. break;
  806. case 'STIL':
  807. this.parseImage();
  808. break;
  809. case 'XREF': // clone of another STIL
  810. this.reader.skip( 8 ); // unknown
  811. this.currentForm.referenceTexture = {
  812. index: this.reader.getUint32(),
  813. refName: this.reader.getString() // internal unique ref
  814. };
  815. break;
  816. // Not in spec, used by texture nodes
  817. case 'IMST':
  818. this.parseImageStateForm( length );
  819. break;
  820. // SURF FORM AND SUB FORMS
  821. case 'SURF':
  822. this.parseSurfaceForm( length );
  823. break;
  824. case 'VALU': // Not in spec
  825. this.parseValueForm( length );
  826. break;
  827. case 'NTAG':
  828. this.parseSubNode( length );
  829. break;
  830. case 'ATTR': // BSDF Node Attributes
  831. case 'SATR': // Standard Node Attributes
  832. this.setupForm( 'attributes', length );
  833. break;
  834. case 'NCON':
  835. this.parseConnections( length );
  836. break;
  837. case 'SSHA':
  838. this.parentForm = this.currentForm;
  839. this.currentForm = this.currentSurface;
  840. this.setupForm( 'surfaceShader', length );
  841. break;
  842. case 'SSHD':
  843. this.setupForm( 'surfaceShaderData', length );
  844. break;
  845. case 'ENTR': // Not in spec
  846. this.parseEntryForm( length );
  847. break;
  848. // Image Map Layer
  849. case 'IMAP':
  850. this.parseImageMap( length );
  851. break;
  852. case 'TAMP':
  853. this.parseXVAL( 'amplitude', length );
  854. break;
  855. //Texture Mapping Form
  856. case 'TMAP':
  857. this.setupForm( 'textureMap', length );
  858. break;
  859. case 'CNTR':
  860. this.parseXVAL3( 'center', length );
  861. break;
  862. case 'SIZE':
  863. this.parseXVAL3( 'scale', length );
  864. break;
  865. case 'ROTA':
  866. this.parseXVAL3( 'rotation', length );
  867. break;
  868. default:
  869. this.parseUnknownForm( type, length );
  870. }
  871. this.debugger.node = 0;
  872. this.debugger.nodeID = type;
  873. this.debugger.log();
  874. },
  875. setupForm( type, length ) {
  876. if ( ! this.currentForm ) this.currentForm = this.currentNode;
  877. this.currentFormEnd = this.reader.offset + length;
  878. this.parentForm = this.currentForm;
  879. if ( ! this.currentForm[ type ] ) {
  880. this.currentForm[ type ] = {};
  881. this.currentForm = this.currentForm[ type ];
  882. } else {
  883. // should never see this unless there's a bug in the reader
  884. console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );
  885. this.currentForm = this.currentForm[ type ];
  886. }
  887. },
  888. skipForm( length ) {
  889. this.reader.skip( length - 4 );
  890. },
  891. parseUnknownForm( type, length ) {
  892. console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );
  893. printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
  894. this.reader.skip( length - 4 );
  895. },
  896. parseSurfaceForm( length ) {
  897. this.reader.skip( 8 ); // unknown Uint32 x2
  898. var name = this.reader.getString();
  899. var surface = {
  900. attributes: {}, // LWO2 style non-node attributes will go here
  901. connections: {},
  902. name: name,
  903. inputName: name,
  904. nodes: {},
  905. source: this.reader.getString(),
  906. };
  907. this.tree.materials[ name ] = surface;
  908. this.currentSurface = surface;
  909. this.parentForm = this.tree.materials;
  910. this.currentForm = surface;
  911. this.currentFormEnd = this.reader.offset + length;
  912. },
  913. parseSurfaceLwo2( length ) {
  914. var name = this.reader.getString();
  915. var surface = {
  916. attributes: {}, // LWO2 style non-node attributes will go here
  917. connections: {},
  918. name: name,
  919. nodes: {},
  920. source: this.reader.getString(),
  921. };
  922. this.tree.materials[ name ] = surface;
  923. this.currentSurface = surface;
  924. this.parentForm = this.tree.materials;
  925. this.currentForm = surface;
  926. this.currentFormEnd = this.reader.offset + length;
  927. },
  928. parseSubNode( length ) {
  929. // parse the NRNM CHUNK of the subnode FORM to get
  930. // a meaningful name for the subNode
  931. // some subnodes can be renamed, but Input and Surface cannot
  932. this.reader.skip( 8 ); // NRNM + length
  933. var name = this.reader.getString();
  934. var node = {
  935. name: name
  936. };
  937. this.currentForm = node;
  938. this.currentNode = node;
  939. this.currentFormEnd = this.reader.offset + length;
  940. },
  941. // collect attributes from all nodes at the top level of a surface
  942. parseConnections( length ) {
  943. this.currentFormEnd = this.reader.offset + length;
  944. this.parentForm = this.currentForm;
  945. this.currentForm = this.currentSurface.connections;
  946. },
  947. // surface node attribute data, e.g. specular, roughness etc
  948. parseEntryForm( length ) {
  949. this.reader.skip( 8 ); // NAME + length
  950. var name = this.reader.getString();
  951. this.currentForm = this.currentNode.attributes;
  952. this.setupForm( name, length );
  953. },
  954. // parse values from material - doesn't match up to other LWO3 data types
  955. // sub form of entry form
  956. parseValueForm() {
  957. this.reader.skip( 8 ); // unknown + length
  958. var valueType = this.reader.getString();
  959. if ( valueType === 'double' ) {
  960. this.currentForm.value = this.reader.getUint64();
  961. } else if ( valueType === 'int' ) {
  962. this.currentForm.value = this.reader.getUint32();
  963. } else if ( valueType === 'vparam' ) {
  964. this.reader.skip( 24 );
  965. this.currentForm.value = this.reader.getFloat64();
  966. } else if ( valueType === 'vparam3' ) {
  967. this.reader.skip( 24 );
  968. this.currentForm.value = this.reader.getFloat64Array( 3 );
  969. }
  970. },
  971. // holds various data about texture node image state
  972. // Data other thanmipMapLevel unknown
  973. parseImageStateForm() {
  974. this.reader.skip( 8 ); // unknown
  975. this.currentForm.mipMapLevel = this.reader.getFloat32();
  976. },
  977. // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  978. parseImageMap( length ) {
  979. this.currentFormEnd = this.reader.offset + length;
  980. this.parentForm = this.currentForm;
  981. if ( ! this.currentForm.maps ) this.currentForm.maps = [];
  982. var map = {};
  983. this.currentForm.maps.push( map );
  984. this.currentForm = map;
  985. this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX
  986. },
  987. parseTextureNodeAttribute( type ) {
  988. this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32
  989. this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32
  990. switch ( type ) {
  991. case 'ISCL':
  992. this.currentNode.scale = this.reader.getFloat32Array( 3 );
  993. break;
  994. case 'IPOS':
  995. this.currentNode.position = this.reader.getFloat32Array( 3 );
  996. break;
  997. case 'IROT':
  998. this.currentNode.rotation = this.reader.getFloat32Array( 3 );
  999. break;
  1000. case 'IFAL':
  1001. this.currentNode.falloff = this.reader.getFloat32Array( 3 );
  1002. break;
  1003. case 'IBMP':
  1004. this.currentNode.amplitude = this.reader.getFloat32();
  1005. break;
  1006. case 'IUTD':
  1007. this.currentNode.uTiles = this.reader.getFloat32();
  1008. break;
  1009. case 'IVTD':
  1010. this.currentNode.vTiles = this.reader.getFloat32();
  1011. break;
  1012. }
  1013. this.reader.skip( 2 ); // unknown
  1014. },
  1015. // ENVL forms are currently ignored
  1016. parseEnvelope( length ) {
  1017. this.reader.skip( length - 4 ); // skipping entirely for now
  1018. },
  1019. ///
  1020. // CHUNK PARSING METHODS
  1021. ///
  1022. // clips can either be defined inside a surface node, or at the top
  1023. // level and they have a different format in each case
  1024. parseClip( length ) {
  1025. var tag = this.reader.getIDTag();
  1026. // inside surface node
  1027. if ( tag === 'FORM' ) {
  1028. this.reader.skip( 16 );
  1029. this.currentNode.fileName = this.reader.getString();
  1030. return;
  1031. }
  1032. // otherwise top level
  1033. this.reader.setOffset( this.reader.offset - 4 );
  1034. this.currentFormEnd = this.reader.offset + length;
  1035. this.parentForm = this.currentForm;
  1036. this.reader.skip( 8 ); // unknown
  1037. var texture = {
  1038. index: this.reader.getUint32()
  1039. };
  1040. this.tree.textures.push( texture );
  1041. this.currentForm = texture;
  1042. },
  1043. parseClipLwo2( length ) {
  1044. var texture = {
  1045. index: this.reader.getUint32(),
  1046. fileName: ""
  1047. };
  1048. // seach STIL block
  1049. while ( true ) {
  1050. var tag = this.reader.getIDTag();
  1051. var n_length = this.reader.getUint16();
  1052. if ( tag === 'STIL' ) {
  1053. texture.fileName = this.reader.getString();
  1054. break;
  1055. }
  1056. if ( n_length >= length ) {
  1057. break;
  1058. }
  1059. }
  1060. this.tree.textures.push( texture );
  1061. this.currentForm = texture;
  1062. },
  1063. parseImage() {
  1064. this.reader.skip( 8 ); // unknown
  1065. this.currentForm.fileName = this.reader.getString();
  1066. },
  1067. parseXVAL( type, length ) {
  1068. var endOffset = this.reader.offset + length - 4;
  1069. this.reader.skip( 8 );
  1070. this.currentForm[ type ] = this.reader.getFloat32();
  1071. this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope
  1072. },
  1073. parseXVAL3( type, length ) {
  1074. var endOffset = this.reader.offset + length - 4;
  1075. this.reader.skip( 8 );
  1076. this.currentForm[ type ] = {
  1077. x: this.reader.getFloat32(),
  1078. y: this.reader.getFloat32(),
  1079. z: this.reader.getFloat32(),
  1080. };
  1081. this.reader.setOffset( endOffset );
  1082. },
  1083. // Tags associated with an object
  1084. // OTAG { type[ID4], tag-string[S0] }
  1085. parseObjectTag() {
  1086. if ( ! this.tree.objectTags ) this.tree.objectTags = {};
  1087. this.tree.objectTags[ this.reader.getIDTag() ] = {
  1088. tagString: this.reader.getString()
  1089. };
  1090. },
  1091. // 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.
  1092. // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  1093. parseLayer( length ) {
  1094. var layer = {
  1095. number: this.reader.getUint16(),
  1096. flags: this.reader.getUint16(), // If the least significant bit of flags is set, the layer is hidden.
  1097. pivot: this.reader.getFloat32Array( 3 ), // Note: this seems to be superflous, as the geometry is translated when pivot is present
  1098. name: this.reader.getString(),
  1099. };
  1100. this.tree.layers.push( layer );
  1101. this.currentLayer = layer;
  1102. var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength
  1103. // if we have not reached then end of the layer block, there must be a parent defined
  1104. this.currentLayer.parent = ( parsedLength < length ) ? this.reader.getUint16() : - 1; // omitted or -1 for no parent
  1105. },
  1106. // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  1107. // Converting from left to right handed coordinate system:
  1108. // x -> -x and switch material FrontSide -> BackSide
  1109. parsePoints( length ) {
  1110. this.currentPoints = [];
  1111. for ( var i = 0; i < length / 4; i += 3 ) {
  1112. // z -> -z to match three.js right handed coords
  1113. this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1114. }
  1115. },
  1116. // parse VMAP or VMAD
  1117. // Associates a set of floating-point vectors with a set of points.
  1118. // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  1119. // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  1120. // Similar to VMAP UVs, but associates with polygon vertices rather than points
  1121. // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name,
  1122. // if they exist. The vector values in the VMAD will then replace those in the
  1123. // corresponding VMAP, but only for calculations involving the specified polygons.
  1124. // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  1125. parseVertexMapping( length, discontinuous ) {
  1126. var finalOffset = this.reader.offset + length;
  1127. var channelName = this.reader.getString();
  1128. if ( this.reader.offset === finalOffset ) {
  1129. // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
  1130. this.currentForm.UVChannel = channelName;
  1131. return;
  1132. }
  1133. // otherwise reset to initial length and parse normal VMAP CHUNK
  1134. this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );
  1135. var type = this.reader.getIDTag();
  1136. this.reader.getUint16(); // dimension
  1137. var name = this.reader.getString();
  1138. var remainingLength = length - 6 - stringOffset( name );
  1139. switch ( type ) {
  1140. case 'TXUV':
  1141. this.parseUVMapping( name, finalOffset, discontinuous );
  1142. break;
  1143. case 'MORF':
  1144. case 'SPOT':
  1145. this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
  1146. break;
  1147. // unsupported VMAPs
  1148. case 'APSL':
  1149. case 'NORM':
  1150. case 'WGHT':
  1151. case 'MNVW':
  1152. case 'PICK':
  1153. case 'RGB ':
  1154. case 'RGBA':
  1155. this.reader.skip( remainingLength );
  1156. break;
  1157. default:
  1158. console.warn( 'LWOLoader: unknown vertex map type: ' + type );
  1159. this.reader.skip( remainingLength );
  1160. }
  1161. },
  1162. parseUVMapping( name, finalOffset, discontinuous ) {
  1163. var uvIndices = [];
  1164. var polyIndices = [];
  1165. var uvs = [];
  1166. while ( this.reader.offset < finalOffset ) {
  1167. uvIndices.push( this.reader.getVariableLengthIndex() );
  1168. if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );
  1169. uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );
  1170. }
  1171. if ( discontinuous ) {
  1172. if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};
  1173. this.currentLayer.discontinuousUVs[ name ] = {
  1174. uvIndices: uvIndices,
  1175. polyIndices: polyIndices,
  1176. uvs: uvs,
  1177. };
  1178. } else {
  1179. if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};
  1180. this.currentLayer.uvs[ name ] = {
  1181. uvIndices: uvIndices,
  1182. uvs: uvs,
  1183. };
  1184. }
  1185. },
  1186. parseMorphTargets( name, finalOffset, type ) {
  1187. var indices = [];
  1188. var points = [];
  1189. type = ( type === 'MORF' ) ? 'relative' : 'absolute';
  1190. while ( this.reader.offset < finalOffset ) {
  1191. indices.push( this.reader.getVariableLengthIndex() );
  1192. // z -> -z to match three.js right handed coords
  1193. points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1194. }
  1195. if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};
  1196. this.currentLayer.morphTargets[ name ] = {
  1197. indices: indices,
  1198. points: points,
  1199. type: type,
  1200. };
  1201. },
  1202. // A list of polygons for the current layer.
  1203. // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  1204. parsePolygonList( length ) {
  1205. var finalOffset = this.reader.offset + length;
  1206. var type = this.reader.getIDTag();
  1207. var indices = [];
  1208. // hold a list of polygon sizes, to be split up later
  1209. var polygonDimensions = [];
  1210. while ( this.reader.offset < finalOffset ) {
  1211. var numverts = this.reader.getUint16();
  1212. //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
  1213. numverts = numverts & 1023; // remaining ten low order bits are vertex num
  1214. polygonDimensions.push( numverts );
  1215. for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );
  1216. }
  1217. var geometryData = {
  1218. type: type,
  1219. vertexIndices: indices,
  1220. polygonDimensions: polygonDimensions,
  1221. points: this.currentPoints
  1222. };
  1223. // Note: assuming that all polys will be lines or points if the first is
  1224. if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points';
  1225. else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';
  1226. this.currentLayer.geometry = geometryData;
  1227. },
  1228. // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  1229. // TAGS { tag-string[S0] * }
  1230. parseTagStrings( length ) {
  1231. this.tree.tags = this.reader.getStringArray( length );
  1232. },
  1233. // Associates tags of a given type with polygons in the most recent POLS chunk.
  1234. // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  1235. parsePolygonTagMapping( length ) {
  1236. var finalOffset = this.reader.offset + length;
  1237. var type = this.reader.getIDTag();
  1238. if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset );
  1239. else { //PART, SMGP, COLR not supported
  1240. this.reader.skip( length - 4 );
  1241. }
  1242. },
  1243. parseMaterialIndices( finalOffset ) {
  1244. // array holds polygon index followed by material index
  1245. this.currentLayer.geometry.materialIndices = [];
  1246. while ( this.reader.offset < finalOffset ) {
  1247. var polygonIndex = this.reader.getVariableLengthIndex();
  1248. var materialIndex = this.reader.getUint16();
  1249. this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );
  1250. }
  1251. },
  1252. parseUnknownCHUNK( blockID, length ) {
  1253. console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length );
  1254. // print the chunk plus some bytes padding either side
  1255. // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );
  1256. var data = this.reader.getString( length );
  1257. this.currentForm[ blockID ] = data;
  1258. }
  1259. };
  1260. function DataViewReader( buffer ) {
  1261. this.dv = new DataView( buffer );
  1262. this.offset = 0;
  1263. }
  1264. DataViewReader.prototype = {
  1265. constructor: DataViewReader,
  1266. size: function () {
  1267. return this.dv.buffer.byteLength;
  1268. },
  1269. setOffset( offset ) {
  1270. if ( offset > 0 && offset < this.dv.buffer.byteLength ) {
  1271. this.offset = offset;
  1272. } else {
  1273. console.error( 'LWOLoader: invalid buffer offset' );
  1274. }
  1275. },
  1276. endOfFile: function () {
  1277. if ( this.offset >= this.size() ) return true;
  1278. return false;
  1279. },
  1280. skip: function ( length ) {
  1281. this.offset += length;
  1282. },
  1283. getUint8: function () {
  1284. var value = this.dv.getUint8( this.offset );
  1285. this.offset += 1;
  1286. return value;
  1287. },
  1288. getUint16: function () {
  1289. var value = this.dv.getUint16( this.offset );
  1290. this.offset += 2;
  1291. return value;
  1292. },
  1293. getInt32: function () {
  1294. var value = this.dv.getInt32( this.offset, false );
  1295. this.offset += 4;
  1296. return value;
  1297. },
  1298. getUint32: function () {
  1299. var value = this.dv.getUint32( this.offset, false );
  1300. this.offset += 4;
  1301. return value;
  1302. },
  1303. getUint64: function () {
  1304. var low, high;
  1305. high = this.getUint32();
  1306. low = this.getUint32();
  1307. return high * 0x100000000 + low;
  1308. },
  1309. getFloat32: function () {
  1310. var value = this.dv.getFloat32( this.offset, false );
  1311. this.offset += 4;
  1312. return value;
  1313. },
  1314. getFloat32Array: function ( size ) {
  1315. var a = [];
  1316. for ( var i = 0; i < size; i ++ ) {
  1317. a.push( this.getFloat32() );
  1318. }
  1319. return a;
  1320. },
  1321. getFloat64: function () {
  1322. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  1323. this.offset += 8;
  1324. return value;
  1325. },
  1326. getFloat64Array: function ( size ) {
  1327. var a = [];
  1328. for ( var i = 0; i < size; i ++ ) {
  1329. a.push( this.getFloat64() );
  1330. }
  1331. return a;
  1332. },
  1333. // get variable-length index data type
  1334. // VX ::= index[U2] | (index + 0xFF000000)[U4]
  1335. // If the index value is less than 65,280 (0xFF00),then VX === U2
  1336. // otherwise VX === U4 with bits 24-31 set
  1337. // When reading an index, if the first byte encountered is 255 (0xFF), then
  1338. // the four-byte form is being used and the first byte should be discarded or masked out.
  1339. getVariableLengthIndex() {
  1340. var firstByte = this.getUint8();
  1341. if ( firstByte === 255 ) {
  1342. return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
  1343. }
  1344. return firstByte * 256 + this.getUint8();
  1345. },
  1346. // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  1347. getIDTag() {
  1348. return this.getString( 4 );
  1349. },
  1350. getString: function ( size ) {
  1351. if ( size === 0 ) return;
  1352. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  1353. var a = [];
  1354. if ( size ) {
  1355. for ( var i = 0; i < size; i ++ ) {
  1356. a[ i ] = this.getUint8();
  1357. }
  1358. } else {
  1359. var currentChar;
  1360. var len = 0;
  1361. while ( currentChar !== 0 ) {
  1362. currentChar = this.getUint8();
  1363. if ( currentChar !== 0 ) a.push( currentChar );
  1364. len ++;
  1365. }
  1366. if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added
  1367. }
  1368. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  1369. },
  1370. getStringArray: function ( size ) {
  1371. var a = this.getString( size );
  1372. a = a.split( '\0' );
  1373. return a.filter( Boolean ); // return array with any empty strings removed
  1374. }
  1375. };
  1376. // ************** DEBUGGER **************
  1377. function Debugger( ) {
  1378. this.active = false;
  1379. this.depth = 0;
  1380. this.formList = [];
  1381. }
  1382. Debugger.prototype = {
  1383. constructor: Debugger,
  1384. enable: function () {
  1385. this.active = true;
  1386. },
  1387. log: function () {
  1388. if ( ! this.active ) return;
  1389. var nodeType;
  1390. switch ( this.node ) {
  1391. case 0:
  1392. nodeType = "FORM";
  1393. break;
  1394. case 1:
  1395. nodeType = "CHK";
  1396. break;
  1397. case 2:
  1398. nodeType = "S-CHK";
  1399. break;
  1400. }
  1401. console.log(
  1402. "| ".repeat( this.depth ) +
  1403. nodeType,
  1404. this.nodeID,
  1405. `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`,
  1406. ( ( this.node == 0 ) ? " {" : "" ),
  1407. ( ( this.skipped ) ? "SKIPPED" : "" ),
  1408. ( ( this.node == 0 && this.skipped ) ? "}" : "" )
  1409. );
  1410. if ( this.node == 0 && ! this.skipped ) {
  1411. this.depth += 1;
  1412. this.formList.push( this.dataOffset + this.length );
  1413. }
  1414. this.skipped = false;
  1415. },
  1416. closeForms: function () {
  1417. if ( ! this.active ) return;
  1418. for ( var i = this.formList.length - 1; i >= 0; i -- ) {
  1419. if ( this.offset >= this.formList[ i ] ) {
  1420. this.depth -= 1;
  1421. console.log( "| ".repeat( this.depth ) + "}" );
  1422. this.formList.splice( - 1, 1 );
  1423. }
  1424. }
  1425. }
  1426. };
  1427. // ************** UTILITY FUNCTIONS **************
  1428. function isEven( num ) {
  1429. return num % 2;
  1430. }
  1431. // calculate the length of the string in the buffer
  1432. // this will be string.length + nullbyte + optional padbyte to make the length even
  1433. function stringOffset( string ) {
  1434. return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );
  1435. }
  1436. // for testing purposes, dump buffer to console
  1437. // printBuffer( this.reader.dv.buffer, this.reader.offset, length );
  1438. function printBuffer( buffer, from, to ) {
  1439. console.log( THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );
  1440. }
  1441. var lwoTree;
  1442. THREE.LWOLoader = function ( manager, parameters ) {
  1443. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  1444. parameters = parameters || {};
  1445. this.resourcePath = ( parameters.resourcePath !== undefined ) ? parameters.resourcePath : undefined;
  1446. };
  1447. THREE.LWOLoader.prototype = {
  1448. constructor: THREE.LWOLoader,
  1449. crossOrigin: 'anonymous',
  1450. load: function ( url, onLoad, onProgress, onError ) {
  1451. var self = this;
  1452. var path = ( self.path === undefined ) ? extractParentUrl( url, 'Objects' ) : self.path;
  1453. // give the mesh a default name based on the filename
  1454. var modelName = url.split( path ).pop().split( '.' )[ 0 ];
  1455. var loader = new THREE.FileLoader( this.manager );
  1456. loader.setPath( self.path );
  1457. loader.setResponseType( 'arraybuffer' );
  1458. loader.load( url, function ( buffer ) {
  1459. // console.time( 'Total parsing: ' );
  1460. onLoad( self.parse( buffer, path, modelName ) );
  1461. // console.timeEnd( 'Total parsing: ' );
  1462. }, onProgress, onError );
  1463. },
  1464. setCrossOrigin: function ( value ) {
  1465. this.crossOrigin = value;
  1466. return this;
  1467. },
  1468. setPath: function ( value ) {
  1469. this.path = value;
  1470. return this;
  1471. },
  1472. setResourcePath: function ( value ) {
  1473. this.resourcePath = value;
  1474. return this;
  1475. },
  1476. parse: function ( iffBuffer, path, modelName ) {
  1477. lwoTree = new IFFParser().parse( iffBuffer );
  1478. // console.log( 'lwoTree', lwoTree );
  1479. var textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  1480. return new LWOTreeParser( textureLoader ).parse( modelName );
  1481. }
  1482. };
  1483. // Parse the lwoTree object
  1484. function LWOTreeParser( textureLoader ) {
  1485. this.textureLoader = textureLoader;
  1486. }
  1487. LWOTreeParser.prototype = {
  1488. constructor: LWOTreeParser,
  1489. parse: function ( modelName ) {
  1490. this.materials = new MaterialParser( this.textureLoader ).parse();
  1491. this.defaultLayerName = modelName;
  1492. this.meshes = this.parseLayers();
  1493. return {
  1494. materials: this.materials,
  1495. meshes: this.meshes,
  1496. };
  1497. },
  1498. parseLayers() {
  1499. // array of all meshes for building hierarchy
  1500. var meshes = [];
  1501. // final array containing meshes with scene graph hierarchy set up
  1502. var finalMeshes = [];
  1503. var geometryParser = new GeometryParser();
  1504. var self = this;
  1505. lwoTree.layers.forEach( function ( layer ) {
  1506. var geometry = geometryParser.parse( layer.geometry, layer );
  1507. var mesh = self.parseMesh( geometry, layer );
  1508. meshes[ layer.number ] = mesh;
  1509. if ( layer.parent === - 1 ) finalMeshes.push( mesh );
  1510. else meshes[ layer.parent ].add( mesh );
  1511. } );
  1512. this.applyPivots( finalMeshes );
  1513. return finalMeshes;
  1514. },
  1515. parseMesh( geometry, layer ) {
  1516. var mesh;
  1517. var materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );
  1518. this.duplicateUVs( geometry, materials );
  1519. if ( layer.geometry.type === 'points' ) mesh = new THREE.Points( geometry, materials );
  1520. else if ( layer.geometry.type === 'lines' ) mesh = new THREE.LineSegments( geometry, materials );
  1521. else mesh = new THREE.Mesh( geometry, materials );
  1522. if ( layer.name ) mesh.name = layer.name;
  1523. else mesh.name = this.defaultLayerName + '_layer_' + layer.number;
  1524. mesh.userData.pivot = layer.pivot;
  1525. return mesh;
  1526. },
  1527. // TODO: may need to be reversed in z to convert LWO to three.js coordinates
  1528. applyPivots( meshes ) {
  1529. meshes.forEach( function ( mesh ) {
  1530. mesh.traverse( function ( child ) {
  1531. var pivot = child.userData.pivot;
  1532. child.position.x += pivot[ 0 ];
  1533. child.position.y += pivot[ 1 ];
  1534. child.position.z += pivot[ 2 ];
  1535. if ( child.parent ) {
  1536. var parentPivot = child.parent.userData.pivot;
  1537. child.position.x -= parentPivot[ 0 ];
  1538. child.position.y -= parentPivot[ 1 ];
  1539. child.position.z -= parentPivot[ 2 ];
  1540. }
  1541. } );
  1542. } );
  1543. },
  1544. getMaterials( namesArray, type ) {
  1545. var materials = [];
  1546. var self = this;
  1547. namesArray.forEach( function ( name, i ) {
  1548. materials[ i ] = self.getMaterialByName( name );
  1549. } );
  1550. // convert materials to line or point mats if required
  1551. if ( type === 'points' || type === 'lines' ) {
  1552. materials.forEach( function ( mat, i ) {
  1553. var spec = {
  1554. color: mat.color,
  1555. };
  1556. if ( type === 'points' ) {
  1557. spec.size = 0.1;
  1558. spec.map = mat.map;
  1559. spec.morphTargets = mat.morphTargets;
  1560. materials[ i ] = new THREE.PointsMaterial( spec );
  1561. } else if ( type === 'lines' ) {
  1562. materials[ i ] = new THREE.LineBasicMaterial( spec );
  1563. }
  1564. } );
  1565. }
  1566. // if there is only one material, return that directly instead of array
  1567. var filtered = materials.filter( Boolean );
  1568. if ( filtered.length === 1 ) return filtered[ 0 ];
  1569. return materials;
  1570. },
  1571. getMaterialByName( name ) {
  1572. return this.materials.filter( function ( m ) {
  1573. return m.name === name;
  1574. } )[ 0 ];
  1575. },
  1576. // If the material has an aoMap, duplicate UVs
  1577. duplicateUVs( geometry, materials ) {
  1578. var duplicateUVs = false;
  1579. if ( ! Array.isArray( materials ) ) {
  1580. if ( materials.aoMap ) duplicateUVs = true;
  1581. } else {
  1582. materials.forEach( function ( material ) {
  1583. if ( material.aoMap ) duplicateUVs = true;
  1584. } );
  1585. }
  1586. if ( ! duplicateUVs ) return;
  1587. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1588. },
  1589. };
  1590. function MaterialParser( textureLoader ) {
  1591. this.textureLoader = textureLoader;
  1592. }
  1593. MaterialParser.prototype = {
  1594. constructor: MaterialParser,
  1595. parse: function () {
  1596. var materials = [];
  1597. this.textures = {};
  1598. for ( var name in lwoTree.materials ) {
  1599. if ( lwoTree.format === 'LWO3' ) {
  1600. materials.push( this.parseMaterial( lwoTree.materials[ name ], name, lwoTree.textures ) );
  1601. } else if ( lwoTree.format === 'LWO2' ) {
  1602. materials.push( this.parseMaterialLwo2( lwoTree.materials[ name ], name, lwoTree.textures ) );
  1603. }
  1604. }
  1605. return materials;
  1606. },
  1607. parseMaterial( materialData, name, textures ) {
  1608. var params = {
  1609. name: name,
  1610. side: this.getSide( materialData.attributes ),
  1611. flatShading: this.getSmooth( materialData.attributes ),
  1612. };
  1613. var connections = this.parseConnections( materialData.connections, materialData.nodes );
  1614. var maps = this.parseTextureNodes( connections.maps );
  1615. this.parseAttributeImageMaps( connections.attributes, textures, maps, materialData.maps );
  1616. var attributes = this.parseAttributes( connections.attributes, maps );
  1617. this.parseEnvMap( connections, maps, attributes );
  1618. params = Object.assign( maps, params );
  1619. params = Object.assign( params, attributes );
  1620. var materialType = this.getMaterialType( connections.attributes );
  1621. return new materialType( params );
  1622. },
  1623. parseMaterialLwo2( materialData, name/*, textures*/ ) {
  1624. var params = {
  1625. name: name,
  1626. side: this.getSide( materialData.attributes ),
  1627. flatShading: this.getSmooth( materialData.attributes ),
  1628. };
  1629. var attributes = this.parseAttributes( materialData.attributes, {} );
  1630. params = Object.assign( params, attributes );
  1631. return new THREE.MeshPhongMaterial( params );
  1632. },
  1633. // Note: converting from left to right handed coords by switching x -> -x in vertices, and
  1634. // then switching mat FrontSide -> BackSide
  1635. // NB: this means that THREE.FrontSide and THREE.BackSide have been switched!
  1636. getSide( attributes ) {
  1637. if ( ! attributes.side ) return THREE.BackSide;
  1638. switch ( attributes.side ) {
  1639. case 0:
  1640. case 1:
  1641. return THREE.BackSide;
  1642. case 2: return THREE.FrontSide;
  1643. case 3: return THREE.DoubleSide;
  1644. }
  1645. },
  1646. getSmooth( attributes ) {
  1647. if ( ! attributes.smooth ) return true;
  1648. return ! attributes.smooth;
  1649. },
  1650. parseConnections( connections, nodes ) {
  1651. var materialConnections = {
  1652. maps: {}
  1653. };
  1654. var inputName = connections.inputName;
  1655. var inputNodeName = connections.inputNodeName;
  1656. var nodeName = connections.nodeName;
  1657. var self = this;
  1658. inputName.forEach( function ( name, index ) {
  1659. if ( name === 'Material' ) {
  1660. var matNode = self.getNodeByRefName( inputNodeName[ index ], nodes );
  1661. materialConnections.attributes = matNode.attributes;
  1662. materialConnections.envMap = matNode.fileName;
  1663. materialConnections.name = inputNodeName[ index ];
  1664. }
  1665. } );
  1666. nodeName.forEach( function ( name, index ) {
  1667. if ( name === materialConnections.name ) {
  1668. materialConnections.maps[ inputName[ index ] ] = self.getNodeByRefName( inputNodeName[ index ], nodes );
  1669. }
  1670. } );
  1671. return materialConnections;
  1672. },
  1673. getNodeByRefName( refName, nodes ) {
  1674. for ( var name in nodes ) {
  1675. if ( nodes[ name ].refName === refName ) return nodes[ name ];
  1676. }
  1677. },
  1678. parseTextureNodes( textureNodes ) {
  1679. var maps = {};
  1680. for ( var name in textureNodes ) {
  1681. var node = textureNodes[ name ];
  1682. var path = node.fileName;
  1683. if ( ! path ) return;
  1684. var texture = this.loadTexture( path );
  1685. if ( node.widthWrappingMode !== undefined ) texture.wrapS = this.getWrappingType( node.widthWrappingMode );
  1686. if ( node.heightWrappingMode !== undefined ) texture.wrapT = this.getWrappingType( node.heightWrappingMode );
  1687. switch ( name ) {
  1688. case 'Color':
  1689. maps.map = texture;
  1690. break;
  1691. case 'Roughness':
  1692. maps.roughnessMap = texture;
  1693. maps.roughness = 0.5;
  1694. break;
  1695. case 'Specular':
  1696. maps.specularMap = texture;
  1697. maps.specular = 0xffffff;
  1698. break;
  1699. case 'Luminous':
  1700. maps.emissiveMap = texture;
  1701. maps.emissive = 0x808080;
  1702. break;
  1703. case 'Luminous Color':
  1704. maps.emissive = 0x808080;
  1705. break;
  1706. case 'Metallic':
  1707. maps.metalnessMap = texture;
  1708. maps.metalness = 0.5;
  1709. break;
  1710. case 'Transparency':
  1711. case 'Alpha':
  1712. maps.alphaMap = texture;
  1713. maps.transparent = true;
  1714. break;
  1715. case 'Normal':
  1716. maps.normalMap = texture;
  1717. if ( node.amplitude !== undefined ) maps.normalScale = new THREE.Vector2( node.amplitude, node.amplitude );
  1718. break;
  1719. case 'Bump':
  1720. maps.bumpMap = texture;
  1721. break;
  1722. }
  1723. }
  1724. // LWO BSDF materials can have both spec and rough, but this is not valid in three
  1725. if ( maps.roughnessMap && maps.specularMap ) delete maps.specularMap;
  1726. return maps;
  1727. },
  1728. // maps can also be defined on individual material attributes, parse those here
  1729. // This occurs on Standard (Phong) surfaces
  1730. parseAttributeImageMaps( attributes, textures, maps ) {
  1731. for ( var name in attributes ) {
  1732. var attribute = attributes[ name ];
  1733. if ( attribute.maps ) {
  1734. var mapData = attribute.maps[ 0 ];
  1735. var path = this.getTexturePathByIndex( mapData.imageIndex, textures );
  1736. if ( ! path ) return;
  1737. var texture = this.loadTexture( path );
  1738. if ( mapData.wrap !== undefined ) texture.wrapS = this.getWrappingType( mapData.wrap.w );
  1739. if ( mapData.wrap !== undefined ) texture.wrapT = this.getWrappingType( mapData.wrap.h );
  1740. switch ( name ) {
  1741. case 'Color':
  1742. maps.map = texture;
  1743. break;
  1744. case 'Diffuse':
  1745. maps.aoMap = texture;
  1746. break;
  1747. case 'Roughness':
  1748. maps.roughnessMap = texture;
  1749. maps.roughness = 1;
  1750. break;
  1751. case 'Specular':
  1752. maps.specularMap = texture;
  1753. maps.specular = 0xffffff;
  1754. break;
  1755. case 'Luminosity':
  1756. maps.emissiveMap = texture;
  1757. maps.emissive = 0x808080;
  1758. break;
  1759. case 'Metallic':
  1760. maps.metalnessMap = texture;
  1761. maps.metalness = 1;
  1762. break;
  1763. case 'Transparency':
  1764. case 'Alpha':
  1765. maps.alphaMap = texture;
  1766. maps.transparent = true;
  1767. break;
  1768. case 'Normal':
  1769. maps.normalMap = texture;
  1770. break;
  1771. case 'Bump':
  1772. maps.bumpMap = texture;
  1773. break;
  1774. }
  1775. }
  1776. }
  1777. },
  1778. parseAttributes( attributes, maps ) {
  1779. var params = {};
  1780. // don't use color data if color map is present
  1781. if ( attributes.Color && ! maps.map ) {
  1782. params.color = new THREE.Color().fromArray( attributes.Color.value );
  1783. } else params.color = new THREE.Color();
  1784. if ( attributes.Transparency && attributes.Transparency.value !== 0 ) {
  1785. params.opacity = 1 - attributes.Transparency.value;
  1786. params.transparent = true;
  1787. }
  1788. if ( attributes[ 'Bump Height' ] ) params.bumpScale = attributes[ 'Bump Height' ].value * 0.1;
  1789. if ( attributes[ 'Refraction Index' ] ) params.refractionRatio = 1 / attributes[ 'Refraction Index' ].value;
  1790. this.parsePhysicalAttributes( params, attributes, maps );
  1791. this.parseStandardAttributes( params, attributes, maps );
  1792. this.parsePhongAttributes( params, attributes, maps );
  1793. return params;
  1794. },
  1795. parsePhysicalAttributes( params, attributes/*, maps*/ ) {
  1796. if ( attributes.Clearcoat && attributes.Clearcoat.value > 0 ) {
  1797. params.clearCoat = attributes.Clearcoat.value;
  1798. if ( attributes[ 'Clearcoat Gloss' ] ) {
  1799. params.clearCoatRoughness = 0.5 * ( 1 - attributes[ 'Clearcoat Gloss' ].value );
  1800. }
  1801. }
  1802. },
  1803. parseStandardAttributes( params, attributes, maps ) {
  1804. if ( attributes.Luminous ) {
  1805. params.emissiveIntensity = attributes.Luminous.value;
  1806. if ( attributes[ 'Luminous Color' ] && ! maps.emissive ) {
  1807. params.emissive = new THREE.Color().fromArray( attributes[ 'Luminous Color' ].value );
  1808. } else {
  1809. params.emissive = new THREE.Color( 0x808080 );
  1810. }
  1811. }
  1812. if ( attributes.Roughness && ! maps.roughnessMap ) params.roughness = attributes.Roughness.value;
  1813. if ( attributes.Metallic && ! maps.metalnessMap ) params.metalness = attributes.Metallic.value;
  1814. },
  1815. parsePhongAttributes( params, attributes, maps ) {
  1816. if ( attributes.Diffuse ) params.color.multiplyScalar( attributes.Diffuse.value );
  1817. if ( attributes.Reflection ) {
  1818. params.reflectivity = attributes.Reflection.value;
  1819. params.combine = THREE.AddOperation;
  1820. }
  1821. if ( attributes.Luminosity ) {
  1822. params.emissiveIntensity = attributes.Luminosity.value;
  1823. if ( ! maps.emissiveMap && ! maps.map ) {
  1824. params.emissive = params.color;
  1825. } else {
  1826. params.emissive = new THREE.Color( 0x808080 );
  1827. }
  1828. }
  1829. // parse specular if there is no roughness - we will interpret the material as 'Phong' in this case
  1830. if ( ! attributes.Roughness && attributes.Specular && ! maps.specularMap ) {
  1831. if ( attributes[ 'Color Highlight' ] ) {
  1832. params.specular = new THREE.Color().setScalar( attributes.Specular.value ).lerp( params.color.clone().multiplyScalar( attributes.Specular.value ), attributes[ 'Color Highlight' ].value );
  1833. } else {
  1834. params.specular = new THREE.Color().setScalar( attributes.Specular.value );
  1835. }
  1836. }
  1837. if ( params.specular && attributes.Glossiness ) params.shininess = 7 + Math.pow( 2, attributes.Glossiness.value * 12 + 2 );
  1838. },
  1839. parseEnvMap( connections, maps, attributes ) {
  1840. if ( connections.envMap ) {
  1841. var envMap = this.loadTexture( connections.envMap );
  1842. if ( attributes.transparent && attributes.opacity < 0.999 ) {
  1843. envMap.mapping = THREE.EquirectangularRefractionMapping;
  1844. // Reflectivity and refraction mapping don't work well together in Phong materials
  1845. if ( attributes.reflectivity !== undefined ) {
  1846. delete attributes.reflectivity;
  1847. delete attributes.combine;
  1848. }
  1849. if ( attributes.metalness !== undefined ) {
  1850. delete attributes.metalness;
  1851. }
  1852. } else envMap.mapping = THREE.EquirectangularReflectionMapping;
  1853. maps.envMap = envMap;
  1854. }
  1855. },
  1856. // get texture defined at top level by its index
  1857. getTexturePathByIndex( index ) {
  1858. var fileName = '';
  1859. if ( ! lwoTree.textures ) return fileName;
  1860. lwoTree.textures.forEach( function ( texture ) {
  1861. if ( texture.index === index ) fileName = texture.fileName;
  1862. } );
  1863. return fileName;
  1864. },
  1865. loadTexture( path ) {
  1866. if ( ! path ) return null;
  1867. var texture;
  1868. texture = this.textureLoader.load(
  1869. path,
  1870. undefined,
  1871. undefined,
  1872. function () {
  1873. console.warn( 'LWOLoader: non-standard resource hierarchy. Use \`resourcePath\` parameter to specify root content directory.' );
  1874. }
  1875. );
  1876. return texture;
  1877. },
  1878. // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  1879. getWrappingType( num ) {
  1880. switch ( num ) {
  1881. case 0:
  1882. console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
  1883. return THREE.ClampToEdgeWrapping;
  1884. case 1: return THREE.RepeatWrapping;
  1885. case 2: return THREE.MirroredRepeatWrapping;
  1886. case 3: return THREE.ClampToEdgeWrapping;
  1887. }
  1888. },
  1889. getMaterialType( nodeData ) {
  1890. if ( nodeData.Clearcoat && nodeData.Clearcoat.value > 0 ) return THREE.MeshPhysicalMaterial;
  1891. if ( nodeData.Roughness ) return THREE.MeshStandardMaterial;
  1892. return THREE.MeshPhongMaterial;
  1893. }
  1894. };
  1895. function GeometryParser() {}
  1896. GeometryParser.prototype = {
  1897. constructor: GeometryParser,
  1898. parse( geoData, layer ) {
  1899. var geometry = new THREE.BufferGeometry();
  1900. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geoData.points, 3 ) );
  1901. var indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
  1902. geometry.setIndex( indices );
  1903. this.parseGroups( geometry, geoData );
  1904. geometry.computeVertexNormals();
  1905. this.parseUVs( geometry, layer, indices );
  1906. this.parseMorphTargets( geometry, layer, indices );
  1907. // TODO: z may need to be reversed to account for coordinate system change
  1908. geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] );
  1909. // var userData = geometry.userData;
  1910. // geometry = geometry.toNonIndexed()
  1911. // geometry.userData = userData;
  1912. return geometry;
  1913. },
  1914. // split quads into tris
  1915. splitIndices( indices, polygonDimensions ) {
  1916. var remappedIndices = [];
  1917. var i = 0;
  1918. polygonDimensions.forEach( function ( dim ) {
  1919. if ( dim < 4 ) {
  1920. for ( var k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  1921. } else if ( dim === 4 ) {
  1922. remappedIndices.push(
  1923. indices[ i ],
  1924. indices[ i + 1 ],
  1925. indices[ i + 2 ],
  1926. indices[ i ],
  1927. indices[ i + 2 ],
  1928. indices[ i + 3 ]
  1929. );
  1930. } else if ( dim > 4 ) {
  1931. for ( var k = 1; k < dim - 1; k ++ ) {
  1932. remappedIndices.push( indices[ i ], indices[ i + k ], indices[ i + k + 1 ] );
  1933. }
  1934. console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  1935. }
  1936. i += dim;
  1937. } );
  1938. return remappedIndices;
  1939. },
  1940. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  1941. parseGroups( geometry, geoData ) {
  1942. var tags = lwoTree.tags;
  1943. var matNames = [];
  1944. var elemSize = 3;
  1945. if ( geoData.type === 'lines' ) elemSize = 2;
  1946. if ( geoData.type === 'points' ) elemSize = 1;
  1947. var remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  1948. var indexNum = 0; // create new indices in numerical order
  1949. var indexPairs = {}; // original indices mapped to numerical indices
  1950. var prevMaterialIndex;
  1951. var prevStart = 0;
  1952. var currentCount = 0;
  1953. for ( var i = 0; i < remappedIndices.length; i += 2 ) {
  1954. var materialIndex = remappedIndices[ i + 1 ];
  1955. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  1956. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  1957. if ( materialIndex !== prevMaterialIndex ) {
  1958. var currentIndex;
  1959. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  1960. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  1961. } else {
  1962. currentIndex = indexNum;
  1963. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  1964. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  1965. indexNum ++;
  1966. }
  1967. geometry.addGroup( prevStart, currentCount, currentIndex );
  1968. prevStart += currentCount;
  1969. prevMaterialIndex = materialIndex;
  1970. currentCount = 0;
  1971. }
  1972. currentCount += elemSize;
  1973. }
  1974. // the loop above doesn't add the last group, do that here.
  1975. if ( geometry.groups.length > 0 ) {
  1976. var currentIndex;
  1977. if ( indexPairs[ tags[ materialIndex ] ] ) {
  1978. currentIndex = indexPairs[ tags[ materialIndex ] ];
  1979. } else {
  1980. currentIndex = indexNum;
  1981. indexPairs[ tags[ materialIndex ] ] = indexNum;
  1982. matNames[ indexNum ] = tags[ materialIndex ];
  1983. }
  1984. geometry.addGroup( prevStart, currentCount, currentIndex );
  1985. }
  1986. // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  1987. geometry.userData.matNames = matNames;
  1988. },
  1989. splitMaterialIndices( polygonDimensions, indices ) {
  1990. var remappedIndices = [];
  1991. polygonDimensions.forEach( function ( dim, i ) {
  1992. if ( dim <= 3 ) {
  1993. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  1994. } else if ( dim === 4 ) {
  1995. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  1996. } else {
  1997. // ignore > 4 for now
  1998. for ( var k = 0; k < dim - 2; k ++ ) {
  1999. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  2000. }
  2001. }
  2002. } );
  2003. return remappedIndices;
  2004. },
  2005. // UV maps:
  2006. // 1: are defined via index into an array of points, not into a geometry
  2007. // - the geometry is also defined by an index into this array, but the indexes may not match
  2008. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  2009. // with preference given to the first map encountered
  2010. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  2011. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  2012. // UV maps are defined as partially VMAP and partially VMAD
  2013. // VMADs are currently not supported
  2014. parseUVs( geometry, layer ) {
  2015. // start by creating a UV map set to zero for the whole geometry
  2016. var remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  2017. return 0;
  2018. } );
  2019. for ( var name in layer.uvs ) {
  2020. var uvs = layer.uvs[ name ].uvs;
  2021. var uvIndices = layer.uvs[ name ].uvIndices;
  2022. uvIndices.forEach( function ( i, j ) {
  2023. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  2024. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  2025. } );
  2026. }
  2027. geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( remappedUVs, 2 ) );
  2028. },
  2029. parseMorphTargets( geometry, layer ) {
  2030. var num = 0;
  2031. for ( var name in layer.morphTargets ) {
  2032. var remappedPoints = geometry.attributes.position.array.slice();
  2033. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  2034. var morphPoints = layer.morphTargets[ name ].points;
  2035. var morphIndices = layer.morphTargets[ name ].indices;
  2036. var type = layer.morphTargets[ name ].type;
  2037. morphIndices.forEach( function ( i, j ) {
  2038. if ( type === 'relative' ) {
  2039. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  2040. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  2041. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  2042. } else {
  2043. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  2044. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  2045. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  2046. }
  2047. } );
  2048. geometry.morphAttributes.position[ num ] = new THREE.Float32BufferAttribute( remappedPoints, 3 );
  2049. geometry.morphAttributes.position[ num ].name = name;
  2050. num ++;
  2051. }
  2052. },
  2053. };
  2054. // ************** UTILITY FUNCTIONS **************
  2055. function extractParentUrl( url, dir ) {
  2056. var index = url.indexOf( dir );
  2057. if ( index === - 1 ) return './';
  2058. return url.substr( 0, index );
  2059. }