FBXLoader.js 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. *
  5. * Loader loads FBX file and generates Group representing FBX scene.
  6. * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
  7. *
  8. * Supports:
  9. * Mesh Generation (Positional Data)
  10. * Normal Data (Per Vertex Drawing Instance)
  11. * UV Data (Per Vertex Drawing Instance)
  12. * Skinning
  13. * Animation
  14. * - Separated Animations based on stacks.
  15. * - Skeletal & Non-Skeletal Animations
  16. * NURBS (Open, Closed and Periodic forms)
  17. *
  18. * Needs Support:
  19. * Indexed Buffers
  20. * PreRotation support.
  21. */
  22. ( function () {
  23. /**
  24. * Generates a loader for loading FBX files from URL and parsing into
  25. * a THREE.Group.
  26. * @param {THREE.LoadingManager} manager - Loading Manager for loader to use.
  27. */
  28. THREE.FBXLoader = function ( manager ) {
  29. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  30. };
  31. Object.assign( THREE.FBXLoader.prototype, {
  32. /**
  33. * Loads an ASCII/Binary FBX file from URL and parses into a THREE.Group.
  34. * THREE.Group will have an animations property of AnimationClips
  35. * of the different animations exported with the FBX.
  36. * @param {string} url - URL of the FBX file.
  37. * @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed.
  38. * @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server.
  39. * @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors).
  40. */
  41. load: function ( url, onLoad, onProgress, onError ) {
  42. var self = this;
  43. var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
  44. var loader = new THREE.FileLoader( this.manager );
  45. loader.setResponseType( 'arraybuffer' );
  46. loader.load( url, function ( buffer ) {
  47. try {
  48. var scene = self.parse( buffer, resourceDirectory );
  49. onLoad( scene );
  50. } catch ( error ) {
  51. window.setTimeout( function () {
  52. if ( onError ) onError( error );
  53. self.manager.itemError( url );
  54. }, 0 );
  55. }
  56. }, onProgress, onError );
  57. },
  58. /**
  59. * Parses an ASCII/Binary FBX file and returns a THREE.Group.
  60. * THREE.Group will have an animations property of AnimationClips
  61. * of the different animations within the FBX file.
  62. * @param {ArrayBuffer} FBXBuffer - Contents of FBX file to parse.
  63. * @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from.
  64. * @returns {THREE.Group}
  65. */
  66. parse: function ( FBXBuffer, resourceDirectory ) {
  67. var FBXTree;
  68. if ( isFbxFormatBinary( FBXBuffer ) ) {
  69. FBXTree = new BinaryParser().parse( FBXBuffer );
  70. } else {
  71. var FBXText = convertArrayBufferToString( FBXBuffer );
  72. if ( ! isFbxFormatASCII( FBXText ) ) {
  73. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  74. }
  75. if ( getFbxVersion( FBXText ) < 7000 ) {
  76. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  77. }
  78. FBXTree = new TextParser().parse( FBXText );
  79. }
  80. // console.log( FBXTree );
  81. var connections = parseConnections( FBXTree );
  82. var images = parseImages( FBXTree );
  83. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  84. var materials = parseMaterials( FBXTree, textures, connections );
  85. var deformers = parseDeformers( FBXTree, connections );
  86. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  87. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  88. return sceneGraph;
  89. }
  90. } );
  91. /**
  92. * Parses map of relationships between objects.
  93. * @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree
  94. * @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  95. */
  96. function parseConnections( FBXTree ) {
  97. /**
  98. * @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  99. */
  100. var connectionMap = new Map();
  101. if ( 'Connections' in FBXTree ) {
  102. /**
  103. * @type {[number, number, string][]}
  104. */
  105. var connectionArray = FBXTree.Connections.properties.connections;
  106. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  107. var connection = connectionArray[ connectionArrayIndex ];
  108. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  109. connectionMap.set( connection[ 0 ], {
  110. parents: [],
  111. children: []
  112. } );
  113. }
  114. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  115. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  116. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  117. connectionMap.set( connection[ 1 ], {
  118. parents: [],
  119. children: []
  120. } );
  121. }
  122. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  123. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  124. }
  125. }
  126. return connectionMap;
  127. }
  128. /**
  129. * Parses map of images referenced in FBXTree.
  130. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  131. * @returns {Map<number, string(image blob/data URL)>}
  132. */
  133. function parseImages( FBXTree ) {
  134. /**
  135. * @type {Map<number, string(image blob/data URL)>}
  136. */
  137. var imageMap = new Map();
  138. if ( 'Video' in FBXTree.Objects.subNodes ) {
  139. var videoNodes = FBXTree.Objects.subNodes.Video;
  140. for ( var nodeID in videoNodes ) {
  141. var videoNode = videoNodes[ nodeID ];
  142. // raw image data is in videoNode.properties.Content
  143. if ( 'Content' in videoNode.properties ) {
  144. var image = parseImage( videoNodes[ nodeID ] );
  145. imageMap.set( parseInt( nodeID ), image );
  146. }
  147. }
  148. }
  149. return imageMap;
  150. }
  151. /**
  152. * @param {videoNode} videoNode - Node to get texture image information from.
  153. * @returns {string} - image blob/data URL
  154. */
  155. function parseImage( videoNode ) {
  156. var content = videoNode.properties.Content;
  157. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  158. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  159. var type;
  160. switch ( extension ) {
  161. case 'bmp':
  162. type = 'image/bmp';
  163. break;
  164. case 'jpg':
  165. type = 'image/jpeg';
  166. break;
  167. case 'png':
  168. type = 'image/png';
  169. break;
  170. case 'tif':
  171. type = 'image/tiff';
  172. break;
  173. default:
  174. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  175. return;
  176. }
  177. if ( typeof content === 'string' ) {
  178. // ASCII format sometimes an extra ',' gets added to the end of the content string
  179. // TODO: Investigate why the parser is adding this character
  180. if ( content.slice( - 1 ) === ',' ) {
  181. content = content.slice( 0, - 1 );
  182. }
  183. return 'data:' + type + ';base64,' + content;
  184. } else {
  185. var array = new Uint8Array( content );
  186. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  187. }
  188. }
  189. /**
  190. * Parses map of textures referenced in FBXTree.
  191. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  192. * @param {THREE.TextureLoader} loader
  193. * @param {Map<number, string(image blob/data URL)>} imageMap
  194. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  195. * @returns {Map<number, THREE.Texture>}
  196. */
  197. function parseTextures( FBXTree, loader, imageMap, connections ) {
  198. /**
  199. * @type {Map<number, THREE.Texture>}
  200. */
  201. var textureMap = new Map();
  202. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  203. var textureNodes = FBXTree.Objects.subNodes.Texture;
  204. for ( var nodeID in textureNodes ) {
  205. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  206. textureMap.set( parseInt( nodeID ), texture );
  207. }
  208. }
  209. return textureMap;
  210. }
  211. /**
  212. * @param {textureNode} textureNode - Node to get texture information from.
  213. * @param {THREE.TextureLoader} loader
  214. * @param {Map<number, string(image blob/data URL)>} imageMap
  215. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  216. * @returns {THREE.Texture}
  217. */
  218. function parseTexture( textureNode, loader, imageMap, connections ) {
  219. var FBX_ID = textureNode.id;
  220. var name = textureNode.attrName;
  221. var fileName;
  222. var filePath = textureNode.properties.FileName;
  223. var relativeFilePath = textureNode.properties.RelativeFilename;
  224. var children = connections.get( FBX_ID ).children;
  225. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  226. fileName = imageMap.get( children[ 0 ].ID );
  227. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' &&
  228. relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  229. // use textureNode.properties.RelativeFilename
  230. // if it exists and it doesn't seem an absolute path
  231. fileName = relativeFilePath;
  232. } else {
  233. var split = filePath.split( /[\\\/]/ );
  234. if ( split.length > 0 ) {
  235. fileName = split[ split.length - 1 ];
  236. } else {
  237. fileName = filePath;
  238. }
  239. }
  240. var currentPath = loader.path;
  241. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  242. loader.setPath( undefined );
  243. }
  244. /**
  245. * @type {THREE.Texture}
  246. */
  247. var texture = loader.load( fileName );
  248. texture.name = name;
  249. texture.FBX_ID = FBX_ID;
  250. var wrapModeU = textureNode.properties.WrapModeU;
  251. var wrapModeV = textureNode.properties.WrapModeV;
  252. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  253. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  254. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  255. // 0: repeat(default), 1: clamp
  256. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  257. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  258. loader.setPath( currentPath );
  259. return texture;
  260. }
  261. /**
  262. * Parses map of Material information.
  263. * @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree
  264. * @param {Map<number, THREE.Texture>} textureMap
  265. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  266. * @returns {Map<number, THREE.Material>}
  267. */
  268. function parseMaterials( FBXTree, textureMap, connections ) {
  269. var materialMap = new Map();
  270. if ( 'Material' in FBXTree.Objects.subNodes ) {
  271. var materialNodes = FBXTree.Objects.subNodes.Material;
  272. for ( var nodeID in materialNodes ) {
  273. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  274. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  275. }
  276. }
  277. return materialMap;
  278. }
  279. /**
  280. * Takes information from Material node and returns a generated THREE.Material
  281. * @param {FBXMaterialNode} materialNode
  282. * @param {Map<number, THREE.Texture>} textureMap
  283. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  284. * @returns {THREE.Material}
  285. */
  286. function parseMaterial( materialNode, textureMap, connections ) {
  287. var FBX_ID = materialNode.id;
  288. var name = materialNode.attrName;
  289. var type = materialNode.properties.ShadingModel;
  290. //Case where FBX wraps shading model in property object.
  291. if ( typeof type === 'object' ) {
  292. type = type.value;
  293. }
  294. // Seems like FBX can include unused materials which don't have any connections.
  295. // Ignores them so far.
  296. if ( ! connections.has( FBX_ID ) ) return null;
  297. var children = connections.get( FBX_ID ).children;
  298. var parameters = parseParameters( materialNode.properties, textureMap, children );
  299. var material;
  300. switch ( type.toLowerCase() ) {
  301. case 'phong':
  302. material = new THREE.MeshPhongMaterial();
  303. break;
  304. case 'lambert':
  305. material = new THREE.MeshLambertMaterial();
  306. break;
  307. default:
  308. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  309. material = new THREE.MeshPhongMaterial( { color: 0x3300ff } );
  310. break;
  311. }
  312. material.setValues( parameters );
  313. material.name = name;
  314. return material;
  315. }
  316. /**
  317. * @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties
  318. */
  319. /**
  320. * @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack
  321. */
  322. /**
  323. * @param {FBXMaterialProperties} properties
  324. * @param {Map<number, THREE.Texture>} textureMap
  325. * @param {{ID: number, relationship: string}[]} childrenRelationships
  326. * @returns {THREEMaterialParameterPack}
  327. */
  328. function parseParameters( properties, textureMap, childrenRelationships ) {
  329. var parameters = {};
  330. if ( properties.BumpFactor ) {
  331. parameters.bumpScale = parseFloat( properties.BumpFactor.value );
  332. }
  333. if ( properties.Diffuse ) {
  334. parameters.color = parseColor( properties.Diffuse );
  335. }
  336. if ( properties.DisplacementFactor ) {
  337. parameters.displacementScale = parseFloat( properties.DisplacementFactor.value );
  338. }
  339. if ( properties.ReflectionFactor ) {
  340. parameters.reflectivity = parseFloat( properties.ReflectionFactor.value );
  341. }
  342. if ( properties.Specular ) {
  343. parameters.specular = parseColor( properties.Specular );
  344. }
  345. if ( properties.Shininess ) {
  346. parameters.shininess = parseFloat( properties.Shininess.value );
  347. }
  348. if ( properties.Emissive ) {
  349. parameters.emissive = parseColor( properties.Emissive );
  350. }
  351. if ( properties.EmissiveFactor ) {
  352. parameters.emissiveIntensity = parseFloat( properties.EmissiveFactor.value );
  353. }
  354. if ( properties.Opacity ) {
  355. parameters.opacity = parseFloat( properties.Opacity.value );
  356. }
  357. if ( parameters.opacity < 1.0 ) {
  358. parameters.transparent = true;
  359. }
  360. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  361. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  362. var type = relationship.relationship;
  363. switch ( type ) {
  364. case 'Bump':
  365. case ' "Bump':
  366. parameters.bumpMap = textureMap.get( relationship.ID );
  367. break;
  368. case 'DiffuseColor':
  369. case ' "DiffuseColor':
  370. parameters.map = textureMap.get( relationship.ID );
  371. break;
  372. case 'DisplacementColor':
  373. case ' "DisplacementColor':
  374. parameters.displacementMap = textureMap.get( relationship.ID );
  375. break;
  376. case 'EmissiveColor':
  377. case ' "EmissiveColor':
  378. parameters.emissiveMap = textureMap.get( relationship.ID );
  379. break;
  380. case 'NormalMap':
  381. case ' "NormalMap':
  382. parameters.normalMap = textureMap.get( relationship.ID );
  383. break;
  384. case 'ReflectionColor':
  385. case ' "ReflectionColor':
  386. parameters.envMap = textureMap.get( relationship.ID );
  387. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  388. break;
  389. case 'SpecularColor':
  390. case ' "SpecularColor':
  391. parameters.specularMap = textureMap.get( relationship.ID );
  392. break;
  393. case 'TransparentColor':
  394. case ' "TransparentColor':
  395. parameters.alphaMap = textureMap.get( relationship.ID );
  396. parameters.transparent = true;
  397. break;
  398. case 'AmbientColor':
  399. case ' "AmbientColor':
  400. case 'ShininessExponent': // AKA glossiness map
  401. case ' "ShininessExponent':
  402. case 'SpecularFactor': // AKA specularLevel
  403. case ' "SpecularFactor':
  404. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  405. case ' "VectorDisplacementColor':
  406. default:
  407. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  408. break;
  409. }
  410. }
  411. return parameters;
  412. }
  413. /**
  414. * Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  415. * @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree
  416. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  417. * @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>}
  418. */
  419. function parseDeformers( FBXTree, connections ) {
  420. var deformers = {};
  421. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  422. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  423. for ( var nodeID in DeformerNodes ) {
  424. var deformerNode = DeformerNodes[ nodeID ];
  425. if ( deformerNode.attrType === 'Skin' ) {
  426. var conns = connections.get( parseInt( nodeID ) );
  427. var skeleton = parseSkeleton( conns, DeformerNodes );
  428. skeleton.FBX_ID = parseInt( nodeID );
  429. deformers[ nodeID ] = skeleton;
  430. }
  431. }
  432. }
  433. return deformers;
  434. }
  435. /**
  436. * Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes.
  437. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
  438. * @param {Object.<number, FBXSubDeformerNode>} DeformerNodes
  439. * @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}}
  440. */
  441. function parseSkeleton( connections, DeformerNodes ) {
  442. var subDeformers = {};
  443. var children = connections.children;
  444. for ( var i = 0, l = children.length; i < l; ++ i ) {
  445. var child = children[ i ];
  446. var subDeformerNode = DeformerNodes[ child.ID ];
  447. var subDeformer = {
  448. FBX_ID: child.ID,
  449. index: i,
  450. indices: [],
  451. weights: [],
  452. transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
  453. transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  454. linkMode: subDeformerNode.properties.Mode
  455. };
  456. if ( 'Indexes' in subDeformerNode.subNodes ) {
  457. subDeformer.indices = parseIntArray( subDeformerNode.subNodes.Indexes.properties.a );
  458. subDeformer.weights = parseFloatArray( subDeformerNode.subNodes.Weights.properties.a );
  459. }
  460. subDeformers[ child.ID ] = subDeformer;
  461. }
  462. return {
  463. map: subDeformers,
  464. bones: []
  465. };
  466. }
  467. /**
  468. * Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries
  469. * @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree
  470. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  471. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  472. * @returns {Map<number, THREE.BufferGeometry>}
  473. */
  474. function parseGeometries( FBXTree, connections, deformers ) {
  475. var geometryMap = new Map();
  476. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  477. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  478. for ( var nodeID in geometryNodes ) {
  479. var relationships = connections.get( parseInt( nodeID ) );
  480. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  481. geometryMap.set( parseInt( nodeID ), geo );
  482. }
  483. }
  484. return geometryMap;
  485. }
  486. /**
  487. * Generates BufferGeometry from FBXGeometryNode.
  488. * @param {FBXGeometryNode} geometryNode
  489. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  490. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers
  491. * @returns {THREE.BufferGeometry}
  492. */
  493. function parseGeometry( geometryNode, relationships, deformers ) {
  494. switch ( geometryNode.attrType ) {
  495. case 'Mesh':
  496. return parseMeshGeometry( geometryNode, relationships, deformers );
  497. break;
  498. case 'NurbsCurve':
  499. return parseNurbsGeometry( geometryNode );
  500. break;
  501. }
  502. }
  503. /**
  504. * Specialty function for parsing Mesh based Geometry Nodes.
  505. * @param {FBXGeometryNode} geometryNode
  506. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes.
  507. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers - Map object of deformers and subDeformers by ID.
  508. * @returns {THREE.BufferGeometry}
  509. */
  510. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  511. for ( var i = 0; i < relationships.children.length; ++ i ) {
  512. var deformer = deformers[ relationships.children[ i ].ID ];
  513. if ( deformer !== undefined ) break;
  514. }
  515. return genGeometry( geometryNode, deformer );
  516. }
  517. /**
  518. * @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer - Skeleton representation for geometry instance.
  519. * @returns {THREE.BufferGeometry}
  520. */
  521. function genGeometry( geometryNode, deformer ) {
  522. var geometry = new Geometry();
  523. var subNodes = geometryNode.subNodes;
  524. // First, each index is going to be its own vertex.
  525. var vertexBuffer = parseFloatArray( subNodes.Vertices.properties.a );
  526. var indexBuffer = parseIntArray( subNodes.PolygonVertexIndex.properties.a );
  527. if ( subNodes.LayerElementNormal ) {
  528. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  529. }
  530. if ( subNodes.LayerElementUV ) {
  531. var uvInfo = [];
  532. var i = 0;
  533. while ( subNodes.LayerElementUV[ i ] ) {
  534. uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
  535. i ++;
  536. }
  537. }
  538. if ( subNodes.LayerElementColor ) {
  539. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  540. }
  541. if ( subNodes.LayerElementMaterial ) {
  542. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  543. }
  544. var weightTable = {};
  545. if ( deformer ) {
  546. var subDeformers = deformer.map;
  547. for ( var key in subDeformers ) {
  548. var subDeformer = subDeformers[ key ];
  549. var indices = subDeformer.indices;
  550. for ( var j = 0; j < indices.length; j ++ ) {
  551. var index = indices[ j ];
  552. var weight = subDeformer.weights[ j ];
  553. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  554. weightTable[ index ].push( {
  555. id: subDeformer.index,
  556. weight: weight
  557. } );
  558. }
  559. }
  560. }
  561. var faceVertexBuffer = [];
  562. var polygonIndex = 0;
  563. var displayedWeightsWarning = false;
  564. for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; polygonVertexIndex ++ ) {
  565. var vertexIndex = indexBuffer[ polygonVertexIndex ];
  566. var endOfFace = false;
  567. if ( vertexIndex < 0 ) {
  568. vertexIndex = vertexIndex ^ - 1;
  569. indexBuffer[ polygonVertexIndex ] = vertexIndex;
  570. endOfFace = true;
  571. }
  572. var vertex = new Vertex();
  573. var weightIndices = [];
  574. var weights = [];
  575. vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
  576. if ( deformer ) {
  577. if ( weightTable[ vertexIndex ] !== undefined ) {
  578. var array = weightTable[ vertexIndex ];
  579. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  580. weights.push( array[ j ].weight );
  581. weightIndices.push( array[ j ].id );
  582. }
  583. }
  584. if ( weights.length > 4 ) {
  585. if ( ! displayedWeightsWarning ) {
  586. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  587. displayedWeightsWarning = true;
  588. }
  589. var WIndex = [ 0, 0, 0, 0 ];
  590. var Weight = [ 0, 0, 0, 0 ];
  591. weights.forEach( function ( weight, weightIndex ) {
  592. var currentWeight = weight;
  593. var currentIndex = weightIndices[ weightIndex ];
  594. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  595. if ( currentWeight > comparedWeight ) {
  596. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  597. currentWeight = comparedWeight;
  598. var tmp = WIndex[ comparedWeightIndex ];
  599. WIndex[ comparedWeightIndex ] = currentIndex;
  600. currentIndex = tmp;
  601. }
  602. } );
  603. } );
  604. weightIndices = WIndex;
  605. weights = Weight;
  606. }
  607. for ( var i = weights.length; i < 4; ++ i ) {
  608. weights[ i ] = 0;
  609. weightIndices[ i ] = 0;
  610. }
  611. vertex.skinWeights.fromArray( weights );
  612. vertex.skinIndices.fromArray( weightIndices );
  613. }
  614. if ( normalInfo ) {
  615. vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
  616. }
  617. if ( uvInfo ) {
  618. var uvTemp = new THREE.Vector2();
  619. for ( var i = 0; i < uvInfo.length; i ++ ) {
  620. vertex.uv.push( uvTemp.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo[ i ] ) ) );
  621. }
  622. }
  623. if ( colorInfo ) {
  624. vertex.color.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo ) );
  625. }
  626. faceVertexBuffer.push( vertex );
  627. if ( endOfFace ) {
  628. var face = new Face();
  629. face.genTrianglesFromVertices( faceVertexBuffer );
  630. if ( materialInfo !== undefined ) {
  631. var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
  632. face.materialIndex = materials[ 0 ];
  633. } else {
  634. // Seems like some models don't have materialInfo(subNodes.LayerElementMaterial).
  635. // Set 0 in such a case.
  636. face.materialIndex = 0;
  637. }
  638. geometry.faces.push( face );
  639. faceVertexBuffer = [];
  640. polygonIndex ++;
  641. endOfFace = false;
  642. }
  643. }
  644. /**
  645. * @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  646. */
  647. var bufferInfo = geometry.flattenToBuffers();
  648. var geo = new THREE.BufferGeometry();
  649. geo.name = geometryNode.name;
  650. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( bufferInfo.vertexBuffer, 3 ) );
  651. if ( bufferInfo.normalBuffer.length > 0 ) {
  652. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( bufferInfo.normalBuffer, 3 ) );
  653. }
  654. if ( bufferInfo.uvBuffers.length > 0 ) {
  655. for ( var i = 0; i < bufferInfo.uvBuffers.length; i ++ ) {
  656. var name = 'uv' + ( i + 1 ).toString();
  657. if ( i == 0 ) {
  658. name = 'uv';
  659. }
  660. geo.addAttribute( name, new THREE.Float32BufferAttribute( bufferInfo.uvBuffers[ i ], 2 ) );
  661. }
  662. }
  663. if ( subNodes.LayerElementColor ) {
  664. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( bufferInfo.colorBuffer, 3 ) );
  665. }
  666. if ( deformer ) {
  667. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( bufferInfo.skinIndexBuffer, 4 ) );
  668. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( bufferInfo.skinWeightBuffer, 4 ) );
  669. geo.FBX_Deformer = deformer;
  670. }
  671. // Convert the material indices of each vertex into rendering groups on the geometry.
  672. var materialIndexBuffer = bufferInfo.materialIndexBuffer;
  673. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  674. var startIndex = 0;
  675. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  676. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  677. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  678. prevMaterialIndex = materialIndexBuffer[ i ];
  679. startIndex = i;
  680. }
  681. }
  682. return geo;
  683. }
  684. /**
  685. * Parses normal information for geometry.
  686. * @param {FBXGeometryNode} geometryNode
  687. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  688. */
  689. function getNormals( NormalNode ) {
  690. var mappingType = NormalNode.properties.MappingInformationType;
  691. var referenceType = NormalNode.properties.ReferenceInformationType;
  692. var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
  693. var indexBuffer = [];
  694. if ( referenceType === 'IndexToDirect' ) {
  695. if ( 'NormalIndex' in NormalNode.subNodes ) {
  696. indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
  697. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  698. indexBuffer = parseIntArray( NormalNode.subNodes.NormalsIndex.properties.a );
  699. }
  700. }
  701. return {
  702. dataSize: 3,
  703. buffer: buffer,
  704. indices: indexBuffer,
  705. mappingType: mappingType,
  706. referenceType: referenceType
  707. };
  708. }
  709. /**
  710. * Parses UV information for geometry.
  711. * @param {FBXGeometryNode} geometryNode
  712. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  713. */
  714. function getUVs( UVNode ) {
  715. var mappingType = UVNode.properties.MappingInformationType;
  716. var referenceType = UVNode.properties.ReferenceInformationType;
  717. var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
  718. var indexBuffer = [];
  719. if ( referenceType === 'IndexToDirect' ) {
  720. indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
  721. }
  722. return {
  723. dataSize: 2,
  724. buffer: buffer,
  725. indices: indexBuffer,
  726. mappingType: mappingType,
  727. referenceType: referenceType
  728. };
  729. }
  730. /**
  731. * Parses Vertex Color information for geometry.
  732. * @param {FBXGeometryNode} geometryNode
  733. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  734. */
  735. function getColors( ColorNode ) {
  736. var mappingType = ColorNode.properties.MappingInformationType;
  737. var referenceType = ColorNode.properties.ReferenceInformationType;
  738. var buffer = parseFloatArray( ColorNode.subNodes.Colors.properties.a );
  739. var indexBuffer = [];
  740. if ( referenceType === 'IndexToDirect' ) {
  741. indexBuffer = parseFloatArray( ColorNode.subNodes.ColorIndex.properties.a );
  742. }
  743. return {
  744. dataSize: 4,
  745. buffer: buffer,
  746. indices: indexBuffer,
  747. mappingType: mappingType,
  748. referenceType: referenceType
  749. };
  750. }
  751. /**
  752. * Parses material application information for geometry.
  753. * @param {FBXGeometryNode}
  754. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  755. */
  756. function getMaterials( MaterialNode ) {
  757. var mappingType = MaterialNode.properties.MappingInformationType;
  758. var referenceType = MaterialNode.properties.ReferenceInformationType;
  759. if ( mappingType === 'NoMappingInformation' ) {
  760. return {
  761. dataSize: 1,
  762. buffer: [ 0 ],
  763. indices: [ 0 ],
  764. mappingType: 'AllSame',
  765. referenceType: referenceType
  766. };
  767. }
  768. var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
  769. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  770. // we expect. So we create an intermediate buffer that points to the index in the buffer,
  771. // for conforming with the other functions we've written for other data.
  772. var materialIndices = [];
  773. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  774. materialIndices.push( materialIndexBufferIndex );
  775. }
  776. return {
  777. dataSize: 1,
  778. buffer: materialIndexBuffer,
  779. indices: materialIndices,
  780. mappingType: mappingType,
  781. referenceType: referenceType
  782. };
  783. }
  784. /**
  785. * Function uses the infoObject and given indices to return value array of object.
  786. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  787. * @param {number} polygonIndex - Index of polygon in geometry.
  788. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  789. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  790. * @returns {number[]}
  791. */
  792. var dataArray = [];
  793. var GetData = {
  794. ByPolygonVertex: {
  795. /**
  796. * Function uses the infoObject and given indices to return value array of object.
  797. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  798. * @param {number} polygonIndex - Index of polygon in geometry.
  799. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  800. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  801. * @returns {number[]}
  802. */
  803. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  804. var from = ( polygonVertexIndex * infoObject.dataSize );
  805. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  806. // return infoObject.buffer.slice( from, to );
  807. return slice( dataArray, infoObject.buffer, from, to );
  808. },
  809. /**
  810. * Function uses the infoObject and given indices to return value array of object.
  811. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  812. * @param {number} polygonIndex - Index of polygon in geometry.
  813. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  814. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  815. * @returns {number[]}
  816. */
  817. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  818. var index = infoObject.indices[ polygonVertexIndex ];
  819. var from = ( index * infoObject.dataSize );
  820. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  821. // return infoObject.buffer.slice( from, to );
  822. return slice( dataArray, infoObject.buffer, from, to );
  823. }
  824. },
  825. ByPolygon: {
  826. /**
  827. * Function uses the infoObject and given indices to return value array of object.
  828. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  829. * @param {number} polygonIndex - Index of polygon in geometry.
  830. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  831. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  832. * @returns {number[]}
  833. */
  834. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  835. var from = polygonIndex * infoObject.dataSize;
  836. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  837. // return infoObject.buffer.slice( from, to );
  838. return slice( dataArray, infoObject.buffer, from, to );
  839. },
  840. /**
  841. * Function uses the infoObject and given indices to return value array of object.
  842. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  843. * @param {number} polygonIndex - Index of polygon in geometry.
  844. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  845. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  846. * @returns {number[]}
  847. */
  848. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  849. var index = infoObject.indices[ polygonIndex ];
  850. var from = index * infoObject.dataSize;
  851. var to = index * infoObject.dataSize + infoObject.dataSize;
  852. // return infoObject.buffer.slice( from, to );
  853. return slice( dataArray, infoObject.buffer, from, to );
  854. }
  855. },
  856. ByVertice: {
  857. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  858. var from = ( vertexIndex * infoObject.dataSize );
  859. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  860. // return infoObject.buffer.slice( from, to );
  861. return slice( dataArray, infoObject.buffer, from, to );
  862. }
  863. },
  864. AllSame: {
  865. /**
  866. * Function uses the infoObject and given indices to return value array of object.
  867. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  868. * @param {number} polygonIndex - Index of polygon in geometry.
  869. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  870. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  871. * @returns {number[]}
  872. */
  873. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  874. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  875. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  876. // return infoObject.buffer.slice( from, to );
  877. return slice( dataArray, infoObject.buffer, from, to );
  878. }
  879. }
  880. };
  881. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  882. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  883. }
  884. /**
  885. * Specialty function for parsing NurbsCurve based Geometry Nodes.
  886. * @param {FBXGeometryNode} geometryNode
  887. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  888. * @returns {THREE.BufferGeometry}
  889. */
  890. function parseNurbsGeometry( geometryNode ) {
  891. if ( THREE.NURBSCurve === undefined ) {
  892. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  893. return new THREE.BufferGeometry();
  894. }
  895. var order = parseInt( geometryNode.properties.Order );
  896. if ( isNaN( order ) ) {
  897. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  898. return new THREE.BufferGeometry();
  899. }
  900. var degree = order - 1;
  901. var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a );
  902. var controlPoints = [];
  903. var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a );
  904. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  905. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  906. }
  907. var startKnot, endKnot;
  908. if ( geometryNode.properties.Form === 'Closed' ) {
  909. controlPoints.push( controlPoints[ 0 ] );
  910. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  911. startKnot = degree;
  912. endKnot = knots.length - 1 - startKnot;
  913. for ( var i = 0; i < degree; ++ i ) {
  914. controlPoints.push( controlPoints[ i ] );
  915. }
  916. }
  917. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  918. var vertices = curve.getPoints( controlPoints.length * 7 );
  919. var positions = new Float32Array( vertices.length * 3 );
  920. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  921. vertices[ i ].toArray( positions, i * 3 );
  922. }
  923. var geometry = new THREE.BufferGeometry();
  924. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  925. return geometry;
  926. }
  927. /**
  928. * Finally generates Scene graph and Scene graph Objects.
  929. * @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree
  930. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  931. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  932. * @param {Map<number, THREE.BufferGeometry>} geometryMap
  933. * @param {Map<number, THREE.Material>} materialMap
  934. * @returns {THREE.Group}
  935. */
  936. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  937. var sceneGraph = new THREE.Group();
  938. var ModelNode = FBXTree.Objects.subNodes.Model;
  939. /**
  940. * @type {Array.<THREE.Object3D>}
  941. */
  942. var modelArray = [];
  943. /**
  944. * @type {Map.<number, THREE.Object3D>}
  945. */
  946. var modelMap = new Map();
  947. for ( var nodeID in ModelNode ) {
  948. var id = parseInt( nodeID );
  949. var node = ModelNode[ nodeID ];
  950. var conns = connections.get( id );
  951. var model = null;
  952. for ( var i = 0; i < conns.parents.length; ++ i ) {
  953. for ( var FBX_ID in deformers ) {
  954. var deformer = deformers[ FBX_ID ];
  955. var subDeformers = deformer.map;
  956. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  957. if ( subDeformer ) {
  958. var model2 = model;
  959. model = new THREE.Bone();
  960. deformer.bones[ subDeformer.index ] = model;
  961. // seems like we need this not to make non-connected bone, maybe?
  962. // TODO: confirm
  963. if ( model2 !== null ) model.add( model2 );
  964. }
  965. }
  966. }
  967. if ( ! model ) {
  968. switch ( node.attrType ) {
  969. case 'Camera':
  970. /* ***********
  971. * Supported camera types:
  972. * PerspectiveCamera
  973. * OrthographicCamera
  974. ************** */
  975. var cameraAttribute;
  976. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  977. var childID = conns.children[ childrenIndex ].ID;
  978. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  979. if ( attr !== undefined && attr.properties !== undefined ) {
  980. cameraAttribute = attr.properties;
  981. }
  982. }
  983. if ( cameraAttribute === undefined ) {
  984. model = new THREE.Object3D();
  985. } else {
  986. var type = 0;
  987. if ( cameraAttribute.CameraProjectionType !== undefined && ( cameraAttribute.CameraProjectionType.value === '1' || cameraAttribute.CameraProjectionType.value === 1 ) ) {
  988. type = 1;
  989. }
  990. var nearClippingPlane = 1;
  991. if ( cameraAttribute.NearPlane !== undefined ) {
  992. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  993. }
  994. var farClippingPlane = 1000;
  995. if ( cameraAttribute.FarPlane !== undefined ) {
  996. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  997. }
  998. var width = window.innerWidth;
  999. var height = window.innerHeight;
  1000. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  1001. width = parseFloat( cameraAttribute.AspectWidth.value );
  1002. height = parseFloat( cameraAttribute.AspectHeight.value );
  1003. }
  1004. var aspect = width / height;
  1005. var fov = 45;
  1006. if ( cameraAttribute.FieldOfView !== undefined ) {
  1007. fov = parseFloat( cameraAttribute.FieldOfView.value );
  1008. }
  1009. switch ( type ) {
  1010. case '0': // Perspective
  1011. case 0:
  1012. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  1013. break;
  1014. case '1': // Orthographic
  1015. case 1:
  1016. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  1017. break;
  1018. default:
  1019. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  1020. model = new THREE.Object3D();
  1021. break;
  1022. }
  1023. }
  1024. break;
  1025. case 'Light':
  1026. /* ***********
  1027. * Supported light types:
  1028. * DirectionalLight
  1029. * PointLight
  1030. * SpotLight
  1031. ************** */
  1032. var lightAttribute;
  1033. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1034. var childID = conns.children[ childrenIndex ].ID;
  1035. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  1036. if ( attr !== undefined && attr.properties !== undefined ) {
  1037. lightAttribute = attr.properties;
  1038. }
  1039. }
  1040. if ( lightAttribute === undefined ) {
  1041. model = new THREE.Object3D();
  1042. } else {
  1043. var type;
  1044. // LightType can be undefined for Point lights
  1045. if ( lightAttribute.LightType === undefined ) {
  1046. type = 0;
  1047. } else {
  1048. type = lightAttribute.LightType.value;
  1049. }
  1050. var color = 0xffffff;
  1051. if ( lightAttribute.Color !== undefined ) {
  1052. var temp = lightAttribute.Color.value.split( ',' );
  1053. var r = parseFloat( temp[ 0 ] );
  1054. var g = parseFloat( temp[ 1 ] );
  1055. var b = parseFloat( temp[ 1 ] );
  1056. color = new THREE.Color( r, g, b );
  1057. }
  1058. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  1059. // light disabled
  1060. if ( lightAttribute.CastLightOnObject !== undefined && ( lightAttribute.CastLightOnObject.value === '0' || lightAttribute.CastLightOnObject.value === 0 ) ) {
  1061. intensity = 0;
  1062. }
  1063. var distance = 0;
  1064. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  1065. if ( lightAttribute.EnableFarAttenuation !== undefined && ( lightAttribute.EnableFarAttenuation.value === '0' || lightAttribute.EnableFarAttenuation.value === 0 ) ) {
  1066. distance = 0;
  1067. } else {
  1068. distance = lightAttribute.FarAttenuationEnd.value / 1000;
  1069. }
  1070. }
  1071. // TODO
  1072. // could be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  1073. var decay = 1;
  1074. switch ( type ) {
  1075. case '0': // Point
  1076. case 0:
  1077. model = new THREE.PointLight( color, intensity, distance, decay );
  1078. break;
  1079. case '1': // Directional
  1080. case 1:
  1081. model = new THREE.DirectionalLight( color, intensity );
  1082. break;
  1083. case '2': // Spot
  1084. case 2:
  1085. var angle = Math.PI / 3;
  1086. if ( lightAttribute.InnerAngle !== undefined ) {
  1087. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1088. }
  1089. var penumbra = 0;
  1090. if ( lightAttribute.OuterAngle !== undefined ) {
  1091. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1092. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1093. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1094. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1095. penumbra = Math.max( penumbra, 1 );
  1096. }
  1097. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1098. break;
  1099. default:
  1100. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1101. model = new THREE.PointLight( color, intensity );
  1102. break;
  1103. }
  1104. if ( lightAttribute.CastShadows !== undefined && ( lightAttribute.CastShadows.value === '1' || lightAttribute.CastShadows.value === 1 ) ) {
  1105. model.castShadow = true;
  1106. }
  1107. }
  1108. break;
  1109. case 'Mesh':
  1110. /**
  1111. * @type {?THREE.BufferGeometry}
  1112. */
  1113. var geometry = null;
  1114. /**
  1115. * @type {THREE.MultiMaterial|THREE.Material}
  1116. */
  1117. var material = null;
  1118. /**
  1119. * @type {Array.<THREE.Material>}
  1120. */
  1121. var materials = [];
  1122. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1123. var child = conns.children[ childrenIndex ];
  1124. if ( geometryMap.has( child.ID ) ) {
  1125. geometry = geometryMap.get( child.ID );
  1126. }
  1127. if ( materialMap.has( child.ID ) ) {
  1128. materials.push( materialMap.get( child.ID ) );
  1129. }
  1130. }
  1131. if ( materials.length > 1 ) {
  1132. material = materials;
  1133. } else if ( materials.length > 0 ) {
  1134. material = materials[ 0 ];
  1135. } else {
  1136. material = new THREE.MeshStandardMaterial( { color: 0x3300ff } );
  1137. materials.push( material );
  1138. }
  1139. if ( 'color' in geometry.attributes ) {
  1140. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++ materialIndex ) {
  1141. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  1142. }
  1143. }
  1144. if ( geometry.FBX_Deformer ) {
  1145. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  1146. materials[ materialsIndex ].skinning = true;
  1147. }
  1148. model = new THREE.SkinnedMesh( geometry, material );
  1149. } else {
  1150. model = new THREE.Mesh( geometry, material );
  1151. }
  1152. break;
  1153. case 'NurbsCurve':
  1154. var geometry = null;
  1155. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1156. var child = conns.children[ childrenIndex ];
  1157. if ( geometryMap.has( child.ID ) ) {
  1158. geometry = geometryMap.get( child.ID );
  1159. }
  1160. }
  1161. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1162. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1163. model = new THREE.Line( geometry, material );
  1164. break;
  1165. default:
  1166. model = new THREE.Group();
  1167. break;
  1168. }
  1169. }
  1170. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  1171. model.FBX_ID = id;
  1172. modelArray.push( model );
  1173. modelMap.set( id, model );
  1174. }
  1175. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1176. var model = modelArray[ modelArrayIndex ];
  1177. var node = ModelNode[ model.FBX_ID ];
  1178. if ( 'Lcl_Translation' in node.properties ) {
  1179. model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
  1180. }
  1181. if ( 'Lcl_Rotation' in node.properties ) {
  1182. var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( degreeToRadian );
  1183. rotation.push( 'ZYX' );
  1184. model.rotation.fromArray( rotation );
  1185. }
  1186. if ( 'Lcl_Scaling' in node.properties ) {
  1187. model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
  1188. }
  1189. if ( 'PreRotation' in node.properties ) {
  1190. var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( DEG2RAD ), 'ZYX' );
  1191. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1192. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1193. preRotations.multiply( currentRotation );
  1194. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1195. }
  1196. // allow transformed pivots - see https://github.com/mrdoob/three.js/issues/11895
  1197. if ( 'GeometricTranslation' in node.properties ) {
  1198. var array = node.properties.GeometricTranslation.value;
  1199. model.traverse( function ( child ) {
  1200. if ( child.geometry ) {
  1201. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1202. }
  1203. } );
  1204. }
  1205. if ( 'LookAtProperty' in node.properties ) {
  1206. var conns = connections.get( model.FBX_ID );
  1207. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1208. var child = conns.children[ childrenIndex ];
  1209. if ( child.relationship === 'LookAtProperty' || child.relationship === ' "LookAtProperty' ) {
  1210. var lookAtTarget = FBXTree.Objects.subNodes.Model[ child.ID ];
  1211. if ( 'Lcl_Translation' in lookAtTarget.properties ) {
  1212. var pos = lookAtTarget.properties.Lcl_Translation.value.split( ',' ).map( function ( val ) {
  1213. return parseFloat( val );
  1214. } );
  1215. // DirectionalLight, SpotLight
  1216. if ( model.target !== undefined ) {
  1217. model.target.position.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1218. sceneGraph.add( model.target );
  1219. } else { // Cameras and other Object3Ds
  1220. model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
  1221. }
  1222. }
  1223. }
  1224. }
  1225. }
  1226. var conns = connections.get( model.FBX_ID );
  1227. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1228. var pIndex = findIndex( modelArray, function ( mod ) {
  1229. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1230. } );
  1231. if ( pIndex > - 1 ) {
  1232. modelArray[ pIndex ].add( model );
  1233. break;
  1234. }
  1235. }
  1236. if ( model.parent === null ) {
  1237. sceneGraph.add( model );
  1238. }
  1239. }
  1240. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1241. sceneGraph.updateMatrixWorld( true );
  1242. // Put skeleton into bind pose.
  1243. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1244. for ( var nodeID in BindPoseNode ) {
  1245. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1246. BindPoseNode = BindPoseNode[ nodeID ];
  1247. break;
  1248. }
  1249. }
  1250. if ( BindPoseNode ) {
  1251. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1252. var worldMatrices = new Map();
  1253. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1254. var node = PoseNode[ PoseNodeIndex ];
  1255. var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
  1256. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1257. }
  1258. }
  1259. for ( var FBX_ID in deformers ) {
  1260. var deformer = deformers[ FBX_ID ];
  1261. var subDeformers = deformer.map;
  1262. for ( var key in subDeformers ) {
  1263. var subDeformer = subDeformers[ key ];
  1264. var subDeformerIndex = subDeformer.index;
  1265. /**
  1266. * @type {THREE.Bone}
  1267. */
  1268. var bone = deformer.bones[ subDeformerIndex ];
  1269. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1270. break;
  1271. }
  1272. var mat = worldMatrices.get( bone.FBX_ID );
  1273. bone.matrixWorld.copy( mat );
  1274. }
  1275. // Now that skeleton is in bind pose, bind to model.
  1276. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1277. var conns = connections.get( deformer.FBX_ID );
  1278. var parents = conns.parents;
  1279. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1280. var parent = parents[ parentsIndex ];
  1281. if ( geometryMap.has( parent.ID ) ) {
  1282. var geoID = parent.ID;
  1283. var geoConns = connections.get( geoID );
  1284. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1285. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1286. var model = modelMap.get( geoConns.parents[ i ].ID );
  1287. //ASSERT model typeof SkinnedMesh
  1288. model.bind( deformer.skeleton, model.matrixWorld );
  1289. break;
  1290. }
  1291. }
  1292. }
  1293. }
  1294. }
  1295. //Skeleton is now bound, return objects to starting
  1296. //world positions.
  1297. sceneGraph.updateMatrixWorld( true );
  1298. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1299. // to attach animations to, since FBX treats animations as animations for the entire scene,
  1300. // not just for individual objects.
  1301. sceneGraph.skeleton = {
  1302. bones: modelArray
  1303. };
  1304. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1305. addAnimations( sceneGraph, animations );
  1306. // Parse ambient color - if it's not set to black (default), create an ambient light
  1307. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings.properties ) {
  1308. var ambientColor = FBXTree.GlobalSettings.properties.AmbientColor.value;
  1309. var r = ambientColor[ 0 ];
  1310. var g = ambientColor[ 1 ];
  1311. var b = ambientColor[ 2 ];
  1312. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1313. var color = new THREE.Color( r, g, b );
  1314. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1315. }
  1316. }
  1317. return sceneGraph;
  1318. }
  1319. /**
  1320. * Parses animation information from FBXTree and generates an AnimationInfoObject.
  1321. * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
  1322. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1323. */
  1324. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1325. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1326. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1327. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1328. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1329. var fps = 30; // default framerate
  1330. if ( 'GlobalSettings' in FBXTree && 'TimeMode' in FBXTree.GlobalSettings.properties ) {
  1331. /* Autodesk time mode documentation can be found here:
  1332. * http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/class_fbx_time.html,topicNumber=cpp_ref_class_fbx_time_html
  1333. */
  1334. var timeModeEnum = [
  1335. 30, // 0: eDefaultMode
  1336. 120, // 1: eFrames120
  1337. 100, // 2: eFrames100
  1338. 60, // 3: eFrames60
  1339. 50, // 4: eFrames50
  1340. 48, // 5: eFrames48
  1341. 30, // 6: eFrames30 (black and white NTSC )
  1342. 30, // 7: eFrames30Drop
  1343. 29.97, // 8: eNTSCDropFrame
  1344. 29.97, // 90: eNTSCFullFrame
  1345. 25, // 10: ePal ( PAL/SECAM )
  1346. 24, // 11: eFrames24 (Film/Cinema)
  1347. 1, // 12: eFrames1000 (use for date time))
  1348. 23.976, // 13: eFilmFullFrame
  1349. 30, // 14: eCustom: use GlobalSettings.properties.CustomFrameRate.value
  1350. 96, // 15: eFrames96
  1351. 72, // 16: eFrames72
  1352. 59.94, // 17: eFrames59dot94
  1353. ];
  1354. var eMode = FBXTree.GlobalSettings.properties.TimeMode.value;
  1355. if ( eMode === 14 ) {
  1356. if ( 'CustomFrameRate' in FBXTree.GlobalSettings.properties ) {
  1357. fps = parseFloat( FBXTree.GlobalSettings.properties.CustomFrameRate.value );
  1358. fps = ( fps === - 1 ) ? 30 : fps;
  1359. }
  1360. } else if ( eMode <= 17 ) { // for future proofing - if more eModes get added, they will default to 30fps
  1361. fps = timeModeEnum[ eMode ];
  1362. }
  1363. }
  1364. /**
  1365. * @type {{
  1366. curves: Map<number, {
  1367. T: {
  1368. id: number;
  1369. attr: string;
  1370. internalID: number;
  1371. attrX: boolean;
  1372. attrY: boolean;
  1373. attrZ: boolean;
  1374. containerBoneID: number;
  1375. containerID: number;
  1376. curves: {
  1377. x: {
  1378. version: any;
  1379. id: number;
  1380. internalID: number;
  1381. times: number[];
  1382. values: number[];
  1383. attrFlag: number[];
  1384. attrData: number[];
  1385. };
  1386. y: {
  1387. version: any;
  1388. id: number;
  1389. internalID: number;
  1390. times: number[];
  1391. values: number[];
  1392. attrFlag: number[];
  1393. attrData: number[];
  1394. };
  1395. z: {
  1396. version: any;
  1397. id: number;
  1398. internalID: number;
  1399. times: number[];
  1400. values: number[];
  1401. attrFlag: number[];
  1402. attrData: number[];
  1403. };
  1404. };
  1405. },
  1406. R: {
  1407. id: number;
  1408. attr: string;
  1409. internalID: number;
  1410. attrX: boolean;
  1411. attrY: boolean;
  1412. attrZ: boolean;
  1413. containerBoneID: number;
  1414. containerID: number;
  1415. curves: {
  1416. x: {
  1417. version: any;
  1418. id: number;
  1419. internalID: number;
  1420. times: number[];
  1421. values: number[];
  1422. attrFlag: number[];
  1423. attrData: number[];
  1424. };
  1425. y: {
  1426. version: any;
  1427. id: number;
  1428. internalID: number;
  1429. times: number[];
  1430. values: number[];
  1431. attrFlag: number[];
  1432. attrData: number[];
  1433. };
  1434. z: {
  1435. version: any;
  1436. id: number;
  1437. internalID: number;
  1438. times: number[];
  1439. values: number[];
  1440. attrFlag: number[];
  1441. attrData: number[];
  1442. };
  1443. };
  1444. },
  1445. S: {
  1446. id: number;
  1447. attr: string;
  1448. internalID: number;
  1449. attrX: boolean;
  1450. attrY: boolean;
  1451. attrZ: boolean;
  1452. containerBoneID: number;
  1453. containerID: number;
  1454. curves: {
  1455. x: {
  1456. version: any;
  1457. id: number;
  1458. internalID: number;
  1459. times: number[];
  1460. values: number[];
  1461. attrFlag: number[];
  1462. attrData: number[];
  1463. };
  1464. y: {
  1465. version: any;
  1466. id: number;
  1467. internalID: number;
  1468. times: number[];
  1469. values: number[];
  1470. attrFlag: number[];
  1471. attrData: number[];
  1472. };
  1473. z: {
  1474. version: any;
  1475. id: number;
  1476. internalID: number;
  1477. times: number[];
  1478. values: number[];
  1479. attrFlag: number[];
  1480. attrData: number[];
  1481. };
  1482. };
  1483. }
  1484. }>,
  1485. layers: Map<number, {
  1486. T: {
  1487. id: number;
  1488. attr: string;
  1489. internalID: number;
  1490. attrX: boolean;
  1491. attrY: boolean;
  1492. attrZ: boolean;
  1493. containerBoneID: number;
  1494. containerID: number;
  1495. curves: {
  1496. x: {
  1497. version: any;
  1498. id: number;
  1499. internalID: number;
  1500. times: number[];
  1501. values: number[];
  1502. attrFlag: number[];
  1503. attrData: number[];
  1504. };
  1505. y: {
  1506. version: any;
  1507. id: number;
  1508. internalID: number;
  1509. times: number[];
  1510. values: number[];
  1511. attrFlag: number[];
  1512. attrData: number[];
  1513. };
  1514. z: {
  1515. version: any;
  1516. id: number;
  1517. internalID: number;
  1518. times: number[];
  1519. values: number[];
  1520. attrFlag: number[];
  1521. attrData: number[];
  1522. };
  1523. },
  1524. },
  1525. R: {
  1526. id: number;
  1527. attr: string;
  1528. internalID: number;
  1529. attrX: boolean;
  1530. attrY: boolean;
  1531. attrZ: boolean;
  1532. containerBoneID: number;
  1533. containerID: number;
  1534. curves: {
  1535. x: {
  1536. version: any;
  1537. id: number;
  1538. internalID: number;
  1539. times: number[];
  1540. values: number[];
  1541. attrFlag: number[];
  1542. attrData: number[];
  1543. };
  1544. y: {
  1545. version: any;
  1546. id: number;
  1547. internalID: number;
  1548. times: number[];
  1549. values: number[];
  1550. attrFlag: number[];
  1551. attrData: number[];
  1552. };
  1553. z: {
  1554. version: any;
  1555. id: number;
  1556. internalID: number;
  1557. times: number[];
  1558. values: number[];
  1559. attrFlag: number[];
  1560. attrData: number[];
  1561. };
  1562. },
  1563. },
  1564. S: {
  1565. id: number;
  1566. attr: string;
  1567. internalID: number;
  1568. attrX: boolean;
  1569. attrY: boolean;
  1570. attrZ: boolean;
  1571. containerBoneID: number;
  1572. containerID: number;
  1573. curves: {
  1574. x: {
  1575. version: any;
  1576. id: number;
  1577. internalID: number;
  1578. times: number[];
  1579. values: number[];
  1580. attrFlag: number[];
  1581. attrData: number[];
  1582. };
  1583. y: {
  1584. version: any;
  1585. id: number;
  1586. internalID: number;
  1587. times: number[];
  1588. values: number[];
  1589. attrFlag: number[];
  1590. attrData: number[];
  1591. };
  1592. z: {
  1593. version: any;
  1594. id: number;
  1595. internalID: number;
  1596. times: number[];
  1597. values: number[];
  1598. attrFlag: number[];
  1599. attrData: number[];
  1600. };
  1601. },
  1602. }
  1603. }[]>,
  1604. stacks: Map<number, {
  1605. name: string,
  1606. layers: {
  1607. T: {
  1608. id: number;
  1609. attr: string;
  1610. internalID: number;
  1611. attrX: boolean;
  1612. attrY: boolean;
  1613. attrZ: boolean;
  1614. containerBoneID: number;
  1615. containerID: number;
  1616. curves: {
  1617. x: {
  1618. version: any;
  1619. id: number;
  1620. internalID: number;
  1621. times: number[];
  1622. values: number[];
  1623. attrFlag: number[];
  1624. attrData: number[];
  1625. };
  1626. y: {
  1627. version: any;
  1628. id: number;
  1629. internalID: number;
  1630. times: number[];
  1631. values: number[];
  1632. attrFlag: number[];
  1633. attrData: number[];
  1634. };
  1635. z: {
  1636. version: any;
  1637. id: number;
  1638. internalID: number;
  1639. times: number[];
  1640. values: number[];
  1641. attrFlag: number[];
  1642. attrData: number[];
  1643. };
  1644. };
  1645. };
  1646. R: {
  1647. id: number;
  1648. attr: string;
  1649. internalID: number;
  1650. attrX: boolean;
  1651. attrY: boolean;
  1652. attrZ: boolean;
  1653. containerBoneID: number;
  1654. containerID: number;
  1655. curves: {
  1656. x: {
  1657. version: any;
  1658. id: number;
  1659. internalID: number;
  1660. times: number[];
  1661. values: number[];
  1662. attrFlag: number[];
  1663. attrData: number[];
  1664. };
  1665. y: {
  1666. version: any;
  1667. id: number;
  1668. internalID: number;
  1669. times: number[];
  1670. values: number[];
  1671. attrFlag: number[];
  1672. attrData: number[];
  1673. };
  1674. z: {
  1675. version: any;
  1676. id: number;
  1677. internalID: number;
  1678. times: number[];
  1679. values: number[];
  1680. attrFlag: number[];
  1681. attrData: number[];
  1682. };
  1683. };
  1684. };
  1685. S: {
  1686. id: number;
  1687. attr: string;
  1688. internalID: number;
  1689. attrX: boolean;
  1690. attrY: boolean;
  1691. attrZ: boolean;
  1692. containerBoneID: number;
  1693. containerID: number;
  1694. curves: {
  1695. x: {
  1696. version: any;
  1697. id: number;
  1698. internalID: number;
  1699. times: number[];
  1700. values: number[];
  1701. attrFlag: number[];
  1702. attrData: number[];
  1703. };
  1704. y: {
  1705. version: any;
  1706. id: number;
  1707. internalID: number;
  1708. times: number[];
  1709. values: number[];
  1710. attrFlag: number[];
  1711. attrData: number[];
  1712. };
  1713. z: {
  1714. version: any;
  1715. id: number;
  1716. internalID: number;
  1717. times: number[];
  1718. values: number[];
  1719. attrFlag: number[];
  1720. attrData: number[];
  1721. };
  1722. };
  1723. };
  1724. }[][],
  1725. length: number,
  1726. frames: number }>,
  1727. length: number,
  1728. fps: number,
  1729. frames: number
  1730. }}
  1731. */
  1732. var returnObject = {
  1733. curves: new Map(),
  1734. layers: {},
  1735. stacks: {},
  1736. length: 0,
  1737. fps: fps,
  1738. frames: 0
  1739. };
  1740. /**
  1741. * @type {Array.<{
  1742. id: number;
  1743. attr: string;
  1744. internalID: number;
  1745. attrX: boolean;
  1746. attrY: boolean;
  1747. attrZ: boolean;
  1748. containerBoneID: number;
  1749. containerID: number;
  1750. }>}
  1751. */
  1752. var animationCurveNodes = [];
  1753. for ( var nodeID in rawNodes ) {
  1754. if ( nodeID.match( /\d+/ ) ) {
  1755. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1756. animationCurveNodes.push( animationNode );
  1757. }
  1758. }
  1759. /**
  1760. * @type {Map.<number, {
  1761. id: number,
  1762. attr: string,
  1763. internalID: number,
  1764. attrX: boolean,
  1765. attrY: boolean,
  1766. attrZ: boolean,
  1767. containerBoneID: number,
  1768. containerID: number,
  1769. curves: {
  1770. x: {
  1771. version: any,
  1772. id: number,
  1773. internalID: number,
  1774. times: number[],
  1775. values: number[],
  1776. attrFlag: number[],
  1777. attrData: number[],
  1778. },
  1779. y: {
  1780. version: any,
  1781. id: number,
  1782. internalID: number,
  1783. times: number[],
  1784. values: number[],
  1785. attrFlag: number[],
  1786. attrData: number[],
  1787. },
  1788. z: {
  1789. version: any,
  1790. id: number,
  1791. internalID: number,
  1792. times: number[],
  1793. values: number[],
  1794. attrFlag: number[],
  1795. attrData: number[],
  1796. }
  1797. }
  1798. }>}
  1799. */
  1800. var tmpMap = new Map();
  1801. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1802. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1803. continue;
  1804. }
  1805. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1806. }
  1807. /**
  1808. * @type {{
  1809. version: any,
  1810. id: number,
  1811. internalID: number,
  1812. times: number[],
  1813. values: number[],
  1814. attrFlag: number[],
  1815. attrData: number[],
  1816. }[]}
  1817. */
  1818. var animationCurves = [];
  1819. for ( nodeID in rawCurves ) {
  1820. if ( nodeID.match( /\d+/ ) ) {
  1821. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1822. // seems like this check would be necessary?
  1823. if ( ! connections.has( animationCurve.id ) ) continue;
  1824. animationCurves.push( animationCurve );
  1825. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1826. var firstParentID = firstParentConn.ID;
  1827. var firstParentRelationship = firstParentConn.relationship;
  1828. var axis = '';
  1829. if ( firstParentRelationship.match( /X/ ) ) {
  1830. axis = 'x';
  1831. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1832. axis = 'y';
  1833. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1834. axis = 'z';
  1835. } else {
  1836. continue;
  1837. }
  1838. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1839. }
  1840. }
  1841. tmpMap.forEach( function ( curveNode ) {
  1842. var id = curveNode.containerBoneID;
  1843. if ( ! returnObject.curves.has( id ) ) {
  1844. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1845. }
  1846. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1847. if ( curveNode.attr === 'R' ) {
  1848. var curves = curveNode.curves;
  1849. // Seems like some FBX files have AnimationCurveNode
  1850. // which doesn't have any connected AnimationCurve.
  1851. // Setting animation parameter for them here.
  1852. if ( curves.x === null ) {
  1853. curves.x = {
  1854. version: null,
  1855. times: [ 0.0 ],
  1856. values: [ 0.0 ]
  1857. };
  1858. }
  1859. if ( curves.y === null ) {
  1860. curves.y = {
  1861. version: null,
  1862. times: [ 0.0 ],
  1863. values: [ 0.0 ]
  1864. };
  1865. }
  1866. if ( curves.z === null ) {
  1867. curves.z = {
  1868. version: null,
  1869. times: [ 0.0 ],
  1870. values: [ 0.0 ]
  1871. };
  1872. }
  1873. curves.x.values = curves.x.values.map( degreeToRadian );
  1874. curves.y.values = curves.y.values.map( degreeToRadian );
  1875. curves.z.values = curves.z.values.map( degreeToRadian );
  1876. if ( curveNode.preRotations !== null ) {
  1877. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1878. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1879. var frameRotation = new THREE.Euler();
  1880. var frameRotationQuaternion = new THREE.Quaternion();
  1881. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1882. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1883. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1884. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1885. curves.x.values[ frame ] = frameRotation.x;
  1886. curves.y.values[ frame ] = frameRotation.y;
  1887. curves.z.values[ frame ] = frameRotation.z;
  1888. }
  1889. }
  1890. }
  1891. } );
  1892. for ( var nodeID in rawLayers ) {
  1893. /**
  1894. * @type {{
  1895. T: {
  1896. id: number;
  1897. attr: string;
  1898. internalID: number;
  1899. attrX: boolean;
  1900. attrY: boolean;
  1901. attrZ: boolean;
  1902. containerBoneID: number;
  1903. containerID: number;
  1904. curves: {
  1905. x: {
  1906. version: any;
  1907. id: number;
  1908. internalID: number;
  1909. times: number[];
  1910. values: number[];
  1911. attrFlag: number[];
  1912. attrData: number[];
  1913. };
  1914. y: {
  1915. version: any;
  1916. id: number;
  1917. internalID: number;
  1918. times: number[];
  1919. values: number[];
  1920. attrFlag: number[];
  1921. attrData: number[];
  1922. };
  1923. z: {
  1924. version: any;
  1925. id: number;
  1926. internalID: number;
  1927. times: number[];
  1928. values: number[];
  1929. attrFlag: number[];
  1930. attrData: number[];
  1931. };
  1932. },
  1933. },
  1934. R: {
  1935. id: number;
  1936. attr: string;
  1937. internalID: number;
  1938. attrX: boolean;
  1939. attrY: boolean;
  1940. attrZ: boolean;
  1941. containerBoneID: number;
  1942. containerID: number;
  1943. curves: {
  1944. x: {
  1945. version: any;
  1946. id: number;
  1947. internalID: number;
  1948. times: number[];
  1949. values: number[];
  1950. attrFlag: number[];
  1951. attrData: number[];
  1952. };
  1953. y: {
  1954. version: any;
  1955. id: number;
  1956. internalID: number;
  1957. times: number[];
  1958. values: number[];
  1959. attrFlag: number[];
  1960. attrData: number[];
  1961. };
  1962. z: {
  1963. version: any;
  1964. id: number;
  1965. internalID: number;
  1966. times: number[];
  1967. values: number[];
  1968. attrFlag: number[];
  1969. attrData: number[];
  1970. };
  1971. },
  1972. },
  1973. S: {
  1974. id: number;
  1975. attr: string;
  1976. internalID: number;
  1977. attrX: boolean;
  1978. attrY: boolean;
  1979. attrZ: boolean;
  1980. containerBoneID: number;
  1981. containerID: number;
  1982. curves: {
  1983. x: {
  1984. version: any;
  1985. id: number;
  1986. internalID: number;
  1987. times: number[];
  1988. values: number[];
  1989. attrFlag: number[];
  1990. attrData: number[];
  1991. };
  1992. y: {
  1993. version: any;
  1994. id: number;
  1995. internalID: number;
  1996. times: number[];
  1997. values: number[];
  1998. attrFlag: number[];
  1999. attrData: number[];
  2000. };
  2001. z: {
  2002. version: any;
  2003. id: number;
  2004. internalID: number;
  2005. times: number[];
  2006. values: number[];
  2007. attrFlag: number[];
  2008. attrData: number[];
  2009. };
  2010. },
  2011. }
  2012. }[]}
  2013. */
  2014. var layer = [];
  2015. var children = connections.get( parseInt( nodeID ) ).children;
  2016. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  2017. // Skip lockInfluenceWeights
  2018. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  2019. var curveNode = tmpMap.get( children[ childIndex ].ID );
  2020. var boneID = curveNode.containerBoneID;
  2021. if ( layer[ boneID ] === undefined ) {
  2022. layer[ boneID ] = {
  2023. T: null,
  2024. R: null,
  2025. S: null
  2026. };
  2027. }
  2028. layer[ boneID ][ curveNode.attr ] = curveNode;
  2029. }
  2030. }
  2031. returnObject.layers[ nodeID ] = layer;
  2032. }
  2033. for ( var nodeID in rawStacks ) {
  2034. var layers = [];
  2035. var children = connections.get( parseInt( nodeID ) ).children;
  2036. var timestamps = { max: 0, min: Number.MAX_VALUE };
  2037. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  2038. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  2039. if ( currentLayer !== undefined ) {
  2040. layers.push( currentLayer );
  2041. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  2042. var layer = currentLayer[ currentLayerIndex ];
  2043. if ( layer ) {
  2044. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  2045. }
  2046. }
  2047. }
  2048. }
  2049. // Do we have an animation clip with actual length?
  2050. if ( timestamps.max > timestamps.min ) {
  2051. returnObject.stacks[ nodeID ] = {
  2052. name: rawStacks[ nodeID ].attrName,
  2053. layers: layers,
  2054. length: timestamps.max - timestamps.min,
  2055. frames: ( timestamps.max - timestamps.min ) * returnObject.fps
  2056. };
  2057. }
  2058. }
  2059. return returnObject;
  2060. }
  2061. /**
  2062. * @param {Object} FBXTree
  2063. * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
  2064. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  2065. * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
  2066. */
  2067. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  2068. var rawModels = FBXTree.Objects.subNodes.Model;
  2069. var returnObject = {
  2070. /**
  2071. * @type {number}
  2072. */
  2073. id: animationCurveNode.id,
  2074. /**
  2075. * @type {string}
  2076. */
  2077. attr: animationCurveNode.attrName,
  2078. /**
  2079. * @type {number}
  2080. */
  2081. internalID: animationCurveNode.id,
  2082. /**
  2083. * @type {boolean}
  2084. */
  2085. attrX: false,
  2086. /**
  2087. * @type {boolean}
  2088. */
  2089. attrY: false,
  2090. /**
  2091. * @type {boolean}
  2092. */
  2093. attrZ: false,
  2094. /**
  2095. * @type {number}
  2096. */
  2097. containerBoneID: - 1,
  2098. /**
  2099. * @type {number}
  2100. */
  2101. containerID: - 1,
  2102. curves: {
  2103. x: null,
  2104. y: null,
  2105. z: null
  2106. },
  2107. /**
  2108. * @type {number[]}
  2109. */
  2110. preRotations: null
  2111. };
  2112. if ( returnObject.attr.match( /S|R|T/ ) ) {
  2113. for ( var attributeKey in animationCurveNode.properties ) {
  2114. if ( attributeKey.match( /X/ ) ) {
  2115. returnObject.attrX = true;
  2116. }
  2117. if ( attributeKey.match( /Y/ ) ) {
  2118. returnObject.attrY = true;
  2119. }
  2120. if ( attributeKey.match( /Z/ ) ) {
  2121. returnObject.attrZ = true;
  2122. }
  2123. }
  2124. } else {
  2125. return null;
  2126. }
  2127. var conns = connections.get( returnObject.id );
  2128. var containerIndices = conns.parents;
  2129. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  2130. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  2131. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  2132. } );
  2133. if ( boneID > - 1 ) {
  2134. returnObject.containerBoneID = boneID;
  2135. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  2136. var model = rawModels[ returnObject.containerID.toString() ];
  2137. if ( 'PreRotation' in model.properties ) {
  2138. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  2139. }
  2140. break;
  2141. }
  2142. }
  2143. return returnObject;
  2144. }
  2145. /**
  2146. * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
  2147. */
  2148. function parseAnimationCurve( animationCurve ) {
  2149. return {
  2150. version: null,
  2151. id: animationCurve.id,
  2152. internalID: animationCurve.id,
  2153. times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( convertFBXTimeToSeconds ),
  2154. values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
  2155. attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
  2156. attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
  2157. };
  2158. }
  2159. /**
  2160. * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  2161. * than the max or min respectively.
  2162. * @param {{
  2163. T: {
  2164. id: number,
  2165. attr: string,
  2166. internalID: number,
  2167. attrX: boolean,
  2168. attrY: boolean,
  2169. attrZ: boolean,
  2170. containerBoneID: number,
  2171. containerID: number,
  2172. curves: {
  2173. x: {
  2174. version: any,
  2175. id: number,
  2176. internalID: number,
  2177. times: number[],
  2178. values: number[],
  2179. attrFlag: number[],
  2180. attrData: number[],
  2181. },
  2182. y: {
  2183. version: any,
  2184. id: number,
  2185. internalID: number,
  2186. times: number[],
  2187. values: number[],
  2188. attrFlag: number[],
  2189. attrData: number[],
  2190. },
  2191. z: {
  2192. version: any,
  2193. id: number,
  2194. internalID: number,
  2195. times: number[],
  2196. values: number[],
  2197. attrFlag: number[],
  2198. attrData: number[],
  2199. },
  2200. },
  2201. },
  2202. R: {
  2203. id: number,
  2204. attr: string,
  2205. internalID: number,
  2206. attrX: boolean,
  2207. attrY: boolean,
  2208. attrZ: boolean,
  2209. containerBoneID: number,
  2210. containerID: number,
  2211. curves: {
  2212. x: {
  2213. version: any,
  2214. id: number,
  2215. internalID: number,
  2216. times: number[],
  2217. values: number[],
  2218. attrFlag: number[],
  2219. attrData: number[],
  2220. },
  2221. y: {
  2222. version: any,
  2223. id: number,
  2224. internalID: number,
  2225. times: number[],
  2226. values: number[],
  2227. attrFlag: number[],
  2228. attrData: number[],
  2229. },
  2230. z: {
  2231. version: any,
  2232. id: number,
  2233. internalID: number,
  2234. times: number[],
  2235. values: number[],
  2236. attrFlag: number[],
  2237. attrData: number[],
  2238. },
  2239. },
  2240. },
  2241. S: {
  2242. id: number,
  2243. attr: string,
  2244. internalID: number,
  2245. attrX: boolean,
  2246. attrY: boolean,
  2247. attrZ: boolean,
  2248. containerBoneID: number,
  2249. containerID: number,
  2250. curves: {
  2251. x: {
  2252. version: any,
  2253. id: number,
  2254. internalID: number,
  2255. times: number[],
  2256. values: number[],
  2257. attrFlag: number[],
  2258. attrData: number[],
  2259. },
  2260. y: {
  2261. version: any,
  2262. id: number,
  2263. internalID: number,
  2264. times: number[],
  2265. values: number[],
  2266. attrFlag: number[],
  2267. attrData: number[],
  2268. },
  2269. z: {
  2270. version: any,
  2271. id: number,
  2272. internalID: number,
  2273. times: number[],
  2274. values: number[],
  2275. attrFlag: number[],
  2276. attrData: number[],
  2277. },
  2278. },
  2279. },
  2280. }} layer
  2281. */
  2282. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  2283. if ( layer.R ) {
  2284. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  2285. }
  2286. if ( layer.S ) {
  2287. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  2288. }
  2289. if ( layer.T ) {
  2290. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  2291. }
  2292. }
  2293. /**
  2294. * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  2295. * exceeds the maximum or minimum.
  2296. * @param {{
  2297. x: {
  2298. version: any,
  2299. id: number,
  2300. internalID: number,
  2301. times: number[],
  2302. values: number[],
  2303. attrFlag: number[],
  2304. attrData: number[],
  2305. },
  2306. y: {
  2307. version: any,
  2308. id: number,
  2309. internalID: number,
  2310. times: number[],
  2311. values: number[],
  2312. attrFlag: number[],
  2313. attrData: number[],
  2314. },
  2315. z: {
  2316. version: any,
  2317. id: number,
  2318. internalID: number,
  2319. times: number[],
  2320. values: number[],
  2321. attrFlag: number[],
  2322. attrData: number[],
  2323. }
  2324. }} curve
  2325. */
  2326. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  2327. if ( curve.x ) {
  2328. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  2329. }
  2330. if ( curve.y ) {
  2331. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  2332. }
  2333. if ( curve.z ) {
  2334. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  2335. }
  2336. }
  2337. /**
  2338. * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  2339. * @param {{times: number[]}} axis
  2340. */
  2341. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  2342. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  2343. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  2344. }
  2345. /**
  2346. * @param {{
  2347. curves: Map<number, {
  2348. T: {
  2349. id: number;
  2350. attr: string;
  2351. internalID: number;
  2352. attrX: boolean;
  2353. attrY: boolean;
  2354. attrZ: boolean;
  2355. containerBoneID: number;
  2356. containerID: number;
  2357. curves: {
  2358. x: {
  2359. version: any;
  2360. id: number;
  2361. internalID: number;
  2362. times: number[];
  2363. values: number[];
  2364. attrFlag: number[];
  2365. attrData: number[];
  2366. };
  2367. y: {
  2368. version: any;
  2369. id: number;
  2370. internalID: number;
  2371. times: number[];
  2372. values: number[];
  2373. attrFlag: number[];
  2374. attrData: number[];
  2375. };
  2376. z: {
  2377. version: any;
  2378. id: number;
  2379. internalID: number;
  2380. times: number[];
  2381. values: number[];
  2382. attrFlag: number[];
  2383. attrData: number[];
  2384. };
  2385. };
  2386. };
  2387. R: {
  2388. id: number;
  2389. attr: string;
  2390. internalID: number;
  2391. attrX: boolean;
  2392. attrY: boolean;
  2393. attrZ: boolean;
  2394. containerBoneID: number;
  2395. containerID: number;
  2396. curves: {
  2397. x: {
  2398. version: any;
  2399. id: number;
  2400. internalID: number;
  2401. times: number[];
  2402. values: number[];
  2403. attrFlag: number[];
  2404. attrData: number[];
  2405. };
  2406. y: {
  2407. version: any;
  2408. id: number;
  2409. internalID: number;
  2410. times: number[];
  2411. values: number[];
  2412. attrFlag: number[];
  2413. attrData: number[];
  2414. };
  2415. z: {
  2416. version: any;
  2417. id: number;
  2418. internalID: number;
  2419. times: number[];
  2420. values: number[];
  2421. attrFlag: number[];
  2422. attrData: number[];
  2423. };
  2424. };
  2425. };
  2426. S: {
  2427. id: number;
  2428. attr: string;
  2429. internalID: number;
  2430. attrX: boolean;
  2431. attrY: boolean;
  2432. attrZ: boolean;
  2433. containerBoneID: number;
  2434. containerID: number;
  2435. curves: {
  2436. x: {
  2437. version: any;
  2438. id: number;
  2439. internalID: number;
  2440. times: number[];
  2441. values: number[];
  2442. attrFlag: number[];
  2443. attrData: number[];
  2444. };
  2445. y: {
  2446. version: any;
  2447. id: number;
  2448. internalID: number;
  2449. times: number[];
  2450. values: number[];
  2451. attrFlag: number[];
  2452. attrData: number[];
  2453. };
  2454. z: {
  2455. version: any;
  2456. id: number;
  2457. internalID: number;
  2458. times: number[];
  2459. values: number[];
  2460. attrFlag: number[];
  2461. attrData: number[];
  2462. };
  2463. };
  2464. };
  2465. }>;
  2466. layers: Map<number, {
  2467. T: {
  2468. id: number;
  2469. attr: string;
  2470. internalID: number;
  2471. attrX: boolean;
  2472. attrY: boolean;
  2473. attrZ: boolean;
  2474. containerBoneID: number;
  2475. containerID: number;
  2476. curves: {
  2477. x: {
  2478. version: any;
  2479. id: number;
  2480. internalID: number;
  2481. times: number[];
  2482. values: number[];
  2483. attrFlag: number[];
  2484. attrData: number[];
  2485. };
  2486. y: {
  2487. version: any;
  2488. id: number;
  2489. internalID: number;
  2490. times: number[];
  2491. values: number[];
  2492. attrFlag: number[];
  2493. attrData: number[];
  2494. };
  2495. z: {
  2496. version: any;
  2497. id: number;
  2498. internalID: number;
  2499. times: number[];
  2500. values: number[];
  2501. attrFlag: number[];
  2502. attrData: number[];
  2503. };
  2504. };
  2505. };
  2506. R: {
  2507. id: number;
  2508. attr: string;
  2509. internalID: number;
  2510. attrX: boolean;
  2511. attrY: boolean;
  2512. attrZ: boolean;
  2513. containerBoneID: number;
  2514. containerID: number;
  2515. curves: {
  2516. x: {
  2517. version: any;
  2518. id: number;
  2519. internalID: number;
  2520. times: number[];
  2521. values: number[];
  2522. attrFlag: number[];
  2523. attrData: number[];
  2524. };
  2525. y: {
  2526. version: any;
  2527. id: number;
  2528. internalID: number;
  2529. times: number[];
  2530. values: number[];
  2531. attrFlag: number[];
  2532. attrData: number[];
  2533. };
  2534. z: {
  2535. version: any;
  2536. id: number;
  2537. internalID: number;
  2538. times: number[];
  2539. values: number[];
  2540. attrFlag: number[];
  2541. attrData: number[];
  2542. };
  2543. };
  2544. };
  2545. S: {
  2546. id: number;
  2547. attr: string;
  2548. internalID: number;
  2549. attrX: boolean;
  2550. attrY: boolean;
  2551. attrZ: boolean;
  2552. containerBoneID: number;
  2553. containerID: number;
  2554. curves: {
  2555. x: {
  2556. version: any;
  2557. id: number;
  2558. internalID: number;
  2559. times: number[];
  2560. values: number[];
  2561. attrFlag: number[];
  2562. attrData: number[];
  2563. };
  2564. y: {
  2565. version: any;
  2566. id: number;
  2567. internalID: number;
  2568. times: number[];
  2569. values: number[];
  2570. attrFlag: number[];
  2571. attrData: number[];
  2572. };
  2573. z: {
  2574. version: any;
  2575. id: number;
  2576. internalID: number;
  2577. times: number[];
  2578. values: number[];
  2579. attrFlag: number[];
  2580. attrData: number[];
  2581. };
  2582. };
  2583. };
  2584. }[]>;
  2585. stacks: Map<number, {
  2586. name: string;
  2587. layers: {
  2588. T: {
  2589. id: number;
  2590. attr: string;
  2591. internalID: number;
  2592. attrX: boolean;
  2593. attrY: boolean;
  2594. attrZ: boolean;
  2595. containerBoneID: number;
  2596. containerID: number;
  2597. curves: {
  2598. x: {
  2599. version: any;
  2600. id: number;
  2601. internalID: number;
  2602. times: number[];
  2603. values: number[];
  2604. attrFlag: number[];
  2605. attrData: number[];
  2606. };
  2607. y: {
  2608. version: any;
  2609. id: number;
  2610. internalID: number;
  2611. times: number[];
  2612. values: number[];
  2613. attrFlag: number[];
  2614. attrData: number[];
  2615. };
  2616. z: {
  2617. version: any;
  2618. id: number;
  2619. internalID: number;
  2620. times: number[];
  2621. values: number[];
  2622. attrFlag: number[];
  2623. attrData: number[];
  2624. };
  2625. };
  2626. };
  2627. R: {
  2628. id: number;
  2629. attr: string;
  2630. internalID: number;
  2631. attrX: boolean;
  2632. attrY: boolean;
  2633. attrZ: boolean;
  2634. containerBoneID: number;
  2635. containerID: number;
  2636. curves: {
  2637. x: {
  2638. version: any;
  2639. id: number;
  2640. internalID: number;
  2641. times: number[];
  2642. values: number[];
  2643. attrFlag: number[];
  2644. attrData: number[];
  2645. };
  2646. y: {
  2647. version: any;
  2648. id: number;
  2649. internalID: number;
  2650. times: number[];
  2651. values: number[];
  2652. attrFlag: number[];
  2653. attrData: number[];
  2654. };
  2655. z: {
  2656. version: any;
  2657. id: number;
  2658. internalID: number;
  2659. times: number[];
  2660. values: number[];
  2661. attrFlag: number[];
  2662. attrData: number[];
  2663. };
  2664. };
  2665. };
  2666. S: {
  2667. id: number;
  2668. attr: string;
  2669. internalID: number;
  2670. attrX: boolean;
  2671. attrY: boolean;
  2672. attrZ: boolean;
  2673. containerBoneID: number;
  2674. containerID: number;
  2675. curves: {
  2676. x: {
  2677. version: any;
  2678. id: number;
  2679. internalID: number;
  2680. times: number[];
  2681. values: number[];
  2682. attrFlag: number[];
  2683. attrData: number[];
  2684. };
  2685. y: {
  2686. version: any;
  2687. id: number;
  2688. internalID: number;
  2689. times: number[];
  2690. values: number[];
  2691. attrFlag: number[];
  2692. attrData: number[];
  2693. };
  2694. z: {
  2695. version: any;
  2696. id: number;
  2697. internalID: number;
  2698. times: number[];
  2699. values: number[];
  2700. attrFlag: number[];
  2701. attrData: number[];
  2702. };
  2703. };
  2704. };
  2705. }[][];
  2706. length: number;
  2707. frames: number;
  2708. }>;
  2709. length: number;
  2710. fps: number;
  2711. frames: number;
  2712. }} animations,
  2713. * @param {{skeleton: { bones: THREE.Bone[]}}} group
  2714. */
  2715. function addAnimations( group, animations ) {
  2716. if ( group.animations === undefined ) {
  2717. group.animations = [];
  2718. }
  2719. var stacks = animations.stacks;
  2720. for ( var key in stacks ) {
  2721. var stack = stacks[ key ];
  2722. /**
  2723. * @type {{
  2724. * name: string,
  2725. * fps: number,
  2726. * length: number,
  2727. * hierarchy: Array.<{
  2728. * parent: number,
  2729. * name: string,
  2730. * keys: Array.<{
  2731. * time: number,
  2732. * pos: Array.<number>,
  2733. * rot: Array.<number>,
  2734. * scl: Array.<number>
  2735. * }>
  2736. * }>
  2737. * }}
  2738. */
  2739. var animationData = {
  2740. name: stack.name,
  2741. fps: animations.fps,
  2742. length: stack.length,
  2743. hierarchy: []
  2744. };
  2745. var bones = group.skeleton.bones;
  2746. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2747. var bone = bones[ bonesIndex ];
  2748. var name = bone.name.replace( /.*:/, '' );
  2749. var parentIndex = findIndex( bones, function ( parentBone ) {
  2750. return bone.parent === parentBone;
  2751. } );
  2752. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  2753. }
  2754. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  2755. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2756. var bone = bones[ bonesIndex ];
  2757. var boneIndex = bonesIndex;
  2758. var animationNode = stack.layers[ 0 ][ boneIndex ];
  2759. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  2760. var node = animationData.hierarchy[ hierarchyIndex ];
  2761. if ( node.name === bone.name ) {
  2762. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  2763. }
  2764. }
  2765. }
  2766. }
  2767. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  2768. }
  2769. }
  2770. var euler = new THREE.Euler();
  2771. var quaternion = new THREE.Quaternion();
  2772. /**
  2773. * @param {THREE.Bone} bone
  2774. */
  2775. function generateKey( animations, animationNode, bone, frame ) {
  2776. var key = {
  2777. time: frame / animations.fps,
  2778. pos: bone.position.toArray(),
  2779. rot: bone.quaternion.toArray(),
  2780. scl: bone.scale.toArray()
  2781. };
  2782. if ( animationNode === undefined ) return key;
  2783. try {
  2784. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  2785. key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
  2786. }
  2787. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  2788. var rotationX = animationNode.R.curves.x.values[ frame ];
  2789. var rotationY = animationNode.R.curves.y.values[ frame ];
  2790. var rotationZ = animationNode.R.curves.z.values[ frame ];
  2791. quaternion.setFromEuler( euler.set( rotationX, rotationY, rotationZ, 'ZYX' ) );
  2792. key.rot = quaternion.toArray();
  2793. }
  2794. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  2795. key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
  2796. }
  2797. } catch ( error ) {
  2798. // Curve is not fully plotted.
  2799. console.log( 'THREE.FBXLoader: ', bone );
  2800. console.log( 'THREE.FBXLoader: ', error );
  2801. }
  2802. return key;
  2803. }
  2804. var AXES = [ 'x', 'y', 'z' ];
  2805. function hasCurve( animationNode, attribute ) {
  2806. if ( animationNode === undefined ) {
  2807. return false;
  2808. }
  2809. var attributeNode = animationNode[ attribute ];
  2810. if ( ! attributeNode ) {
  2811. return false;
  2812. }
  2813. return AXES.every( function ( key ) {
  2814. return attributeNode.curves[ key ] !== null;
  2815. } );
  2816. }
  2817. function hasKeyOnFrame( attributeNode, frame ) {
  2818. return AXES.every( function ( key ) {
  2819. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  2820. } );
  2821. }
  2822. function isKeyExistOnFrame( curve, frame ) {
  2823. return curve.values[ frame ] !== undefined;
  2824. }
  2825. /**
  2826. * An instance of a Vertex with data for drawing vertices to the screen.
  2827. * @constructor
  2828. */
  2829. function Vertex() {
  2830. /**
  2831. * Position of the vertex.
  2832. * @type {THREE.Vector3}
  2833. */
  2834. this.position = new THREE.Vector3();
  2835. /**
  2836. * Normal of the vertex
  2837. * @type {THREE.Vector3}
  2838. */
  2839. this.normal = new THREE.Vector3();
  2840. /**
  2841. * Array of UV coordinates of the vertex.
  2842. * @type {Array of THREE.Vector2}
  2843. */
  2844. this.uv = [];
  2845. /**
  2846. * Color of the vertex
  2847. * @type {THREE.Vector3}
  2848. */
  2849. this.color = new THREE.Vector3();
  2850. /**
  2851. * Indices of the bones vertex is influenced by.
  2852. * @type {THREE.Vector4}
  2853. */
  2854. this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
  2855. /**
  2856. * Weights that each bone influences the vertex.
  2857. * @type {THREE.Vector4}
  2858. */
  2859. this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
  2860. }
  2861. Object.assign( Vertex.prototype, {
  2862. copy: function ( target ) {
  2863. var returnVar = target || new Vertex();
  2864. returnVar.position.copy( this.position );
  2865. returnVar.normal.copy( this.normal );
  2866. returnVar.uv.copy( this.uv );
  2867. returnVar.skinIndices.copy( this.skinIndices );
  2868. returnVar.skinWeights.copy( this.skinWeights );
  2869. return returnVar;
  2870. },
  2871. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2872. this.position.toArray( vertexBuffer, vertexBuffer.length );
  2873. this.normal.toArray( normalBuffer, normalBuffer.length );
  2874. for ( var i = 0; i < this.uv.length; i ++ ) {
  2875. this.uv[ i ].toArray( uvBuffers[ i ], uvBuffers[ i ].length );
  2876. }
  2877. this.color.toArray( colorBuffer, colorBuffer.length );
  2878. this.skinIndices.toArray( skinIndexBuffer, skinIndexBuffer.length );
  2879. this.skinWeights.toArray( skinWeightBuffer, skinWeightBuffer.length );
  2880. }
  2881. } );
  2882. /**
  2883. * @constructor
  2884. */
  2885. function Triangle() {
  2886. /**
  2887. * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
  2888. */
  2889. this.vertices = [];
  2890. }
  2891. Object.assign( Triangle.prototype, {
  2892. copy: function ( target ) {
  2893. var returnVar = target || new Triangle();
  2894. for ( var i = 0; i < this.vertices.length; ++ i ) {
  2895. this.vertices[ i ].copy( returnVar.vertices[ i ] );
  2896. }
  2897. return returnVar;
  2898. },
  2899. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2900. var vertices = this.vertices;
  2901. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  2902. vertices[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2903. }
  2904. }
  2905. } );
  2906. /**
  2907. * @constructor
  2908. */
  2909. function Face() {
  2910. /**
  2911. * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
  2912. */
  2913. this.triangles = [];
  2914. this.materialIndex = 0;
  2915. }
  2916. Object.assign( Face.prototype, {
  2917. copy: function ( target ) {
  2918. var returnVar = target || new Face();
  2919. for ( var i = 0; i < this.triangles.length; ++ i ) {
  2920. this.triangles[ i ].copy( returnVar.triangles[ i ] );
  2921. }
  2922. returnVar.materialIndex = this.materialIndex;
  2923. return returnVar;
  2924. },
  2925. genTrianglesFromVertices: function ( vertexArray ) {
  2926. for ( var i = 2; i < vertexArray.length; ++ i ) {
  2927. var triangle = new Triangle();
  2928. triangle.vertices[ 0 ] = vertexArray[ 0 ];
  2929. triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
  2930. triangle.vertices[ 2 ] = vertexArray[ i ];
  2931. this.triangles.push( triangle );
  2932. }
  2933. },
  2934. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer ) {
  2935. var triangles = this.triangles;
  2936. var materialIndex = this.materialIndex;
  2937. for ( var i = 0, l = triangles.length; i < l; ++ i ) {
  2938. triangles[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2939. append( materialIndexBuffer, [ materialIndex, materialIndex, materialIndex ] );
  2940. }
  2941. }
  2942. } );
  2943. /**
  2944. * @constructor
  2945. */
  2946. function Geometry() {
  2947. /**
  2948. * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: Array of THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
  2949. */
  2950. this.faces = [];
  2951. /**
  2952. * @type {{}|THREE.Skeleton}
  2953. */
  2954. this.skeleton = null;
  2955. }
  2956. Object.assign( Geometry.prototype, {
  2957. /**
  2958. * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffers: Array of number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  2959. */
  2960. flattenToBuffers: function () {
  2961. var vertexBuffer = [];
  2962. var normalBuffer = [];
  2963. var uvBuffers = [];
  2964. var colorBuffer = [];
  2965. var skinIndexBuffer = [];
  2966. var skinWeightBuffer = [];
  2967. var materialIndexBuffer = [];
  2968. var faces = this.faces;
  2969. for ( var i = 0; i < faces[ 0 ].triangles[ 0 ].vertices[ 0 ].uv.length; i ++ ) {
  2970. uvBuffers.push( [] );
  2971. }
  2972. for ( var i = 0, l = faces.length; i < l; ++ i ) {
  2973. faces[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer );
  2974. }
  2975. return {
  2976. vertexBuffer: vertexBuffer,
  2977. normalBuffer: normalBuffer,
  2978. uvBuffers: uvBuffers,
  2979. colorBuffer: colorBuffer,
  2980. skinIndexBuffer: skinIndexBuffer,
  2981. skinWeightBuffer: skinWeightBuffer,
  2982. materialIndexBuffer: materialIndexBuffer
  2983. };
  2984. }
  2985. } );
  2986. function TextParser() {}
  2987. Object.assign( TextParser.prototype, {
  2988. getPrevNode: function () {
  2989. return this.nodeStack[ this.currentIndent - 2 ];
  2990. },
  2991. getCurrentNode: function () {
  2992. return this.nodeStack[ this.currentIndent - 1 ];
  2993. },
  2994. getCurrentProp: function () {
  2995. return this.currentProp;
  2996. },
  2997. pushStack: function ( node ) {
  2998. this.nodeStack.push( node );
  2999. this.currentIndent += 1;
  3000. },
  3001. popStack: function () {
  3002. this.nodeStack.pop();
  3003. this.currentIndent -= 1;
  3004. },
  3005. setCurrentProp: function ( val, name ) {
  3006. this.currentProp = val;
  3007. this.currentPropName = name;
  3008. },
  3009. // ----------parse ---------------------------------------------------
  3010. parse: function ( text ) {
  3011. this.currentIndent = 0;
  3012. this.allNodes = new FBXTree();
  3013. this.nodeStack = [];
  3014. this.currentProp = [];
  3015. this.currentPropName = '';
  3016. var split = text.split( '\n' );
  3017. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  3018. var l = split[ lineNum ];
  3019. // skip comment line
  3020. if ( l.match( /^[\s\t]*;/ ) ) {
  3021. continue;
  3022. }
  3023. // skip empty line
  3024. if ( l.match( /^[\s\t]*$/ ) ) {
  3025. continue;
  3026. }
  3027. // beginning of node
  3028. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  3029. var match = l.match( beginningOfNodeExp );
  3030. if ( match ) {
  3031. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  3032. var nodeAttrs = match[ 2 ].split( ',' );
  3033. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  3034. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  3035. }
  3036. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  3037. continue;
  3038. }
  3039. // node's property
  3040. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  3041. var match = l.match( propExp );
  3042. if ( match ) {
  3043. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  3044. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  3045. // for special case: base64 image data follows "Content: ," line
  3046. // Content: ,
  3047. // "iVB..."
  3048. if ( propName === 'Content' && propValue === ',' ) {
  3049. propValue = split[ ++ lineNum ].replace( /"/g, '' ).trim();
  3050. }
  3051. this.parseNodeProperty( l, propName, propValue );
  3052. continue;
  3053. }
  3054. // end of node
  3055. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  3056. if ( l.match( endOfNodeExp ) ) {
  3057. this.nodeEnd();
  3058. continue;
  3059. }
  3060. // for special case,
  3061. //
  3062. // Vertices: *8670 {
  3063. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  3064. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  3065. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  3066. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  3067. //
  3068. // in these case the lines must continue from the previous line
  3069. if ( l.match( /^[^\s\t}]/ ) ) {
  3070. this.parseNodePropertyContinued( l );
  3071. }
  3072. }
  3073. return this.allNodes;
  3074. },
  3075. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  3076. // var nodeName = match[1];
  3077. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  3078. var attrs = this.parseNodeAttr( nodeAttrs );
  3079. var currentNode = this.getCurrentNode();
  3080. // a top node
  3081. if ( this.currentIndent === 0 ) {
  3082. this.allNodes.add( nodeName, node );
  3083. } else {
  3084. // a subnode
  3085. // already exists subnode, then append it
  3086. if ( nodeName in currentNode.subNodes ) {
  3087. var tmp = currentNode.subNodes[ nodeName ];
  3088. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  3089. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  3090. if ( attrs.id === '' ) {
  3091. currentNode.subNodes[ nodeName ] = [];
  3092. currentNode.subNodes[ nodeName ].push( tmp );
  3093. } else {
  3094. currentNode.subNodes[ nodeName ] = {};
  3095. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  3096. }
  3097. }
  3098. if ( attrs.id === '' ) {
  3099. currentNode.subNodes[ nodeName ].push( node );
  3100. } else {
  3101. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  3102. }
  3103. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  3104. currentNode.subNodes[ nodeName ] = {};
  3105. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  3106. } else {
  3107. currentNode.subNodes[ nodeName ] = node;
  3108. }
  3109. }
  3110. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  3111. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  3112. if ( nodeAttrs ) {
  3113. node.id = attrs.id;
  3114. node.attrName = attrs.name;
  3115. node.attrType = attrs.type;
  3116. }
  3117. this.pushStack( node );
  3118. },
  3119. parseNodeAttr: function ( attrs ) {
  3120. var id = attrs[ 0 ];
  3121. if ( attrs[ 0 ] !== '' ) {
  3122. id = parseInt( attrs[ 0 ] );
  3123. if ( isNaN( id ) ) {
  3124. // PolygonVertexIndex: *16380 {
  3125. id = attrs[ 0 ];
  3126. }
  3127. }
  3128. var name = '', type = '';
  3129. if ( attrs.length > 1 ) {
  3130. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  3131. type = attrs[ 2 ];
  3132. }
  3133. return { id: id, name: name, type: type };
  3134. },
  3135. parseNodeProperty: function ( line, propName, propValue ) {
  3136. var currentNode = this.getCurrentNode();
  3137. var parentName = currentNode.name;
  3138. // special case parent node's is like "Properties70"
  3139. // these children nodes must treat with careful
  3140. if ( parentName !== undefined ) {
  3141. var propMatch = parentName.match( /Properties(\d)+/ );
  3142. if ( propMatch ) {
  3143. this.parseNodeSpecialProperty( line, propName, propValue );
  3144. return;
  3145. }
  3146. }
  3147. // special case Connections
  3148. if ( propName === 'C' ) {
  3149. var connProps = propValue.split( ',' ).slice( 1 );
  3150. var from = parseInt( connProps[ 0 ] );
  3151. var to = parseInt( connProps[ 1 ] );
  3152. var rest = propValue.split( ',' ).slice( 3 );
  3153. propName = 'connections';
  3154. propValue = [ from, to ];
  3155. append( propValue, rest );
  3156. if ( currentNode.properties[ propName ] === undefined ) {
  3157. currentNode.properties[ propName ] = [];
  3158. }
  3159. }
  3160. // special case Connections
  3161. if ( propName === 'Node' ) {
  3162. var id = parseInt( propValue );
  3163. currentNode.properties.id = id;
  3164. currentNode.id = id;
  3165. }
  3166. // already exists in properties, then append this
  3167. if ( propName in currentNode.properties ) {
  3168. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  3169. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  3170. currentNode.properties[ propName ].push( propValue );
  3171. } else {
  3172. currentNode.properties[ propName ] += propValue;
  3173. }
  3174. } else {
  3175. // console.log( propName + ": " + propValue );
  3176. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  3177. currentNode.properties[ propName ].push( propValue );
  3178. } else {
  3179. currentNode.properties[ propName ] = propValue;
  3180. }
  3181. }
  3182. this.setCurrentProp( currentNode.properties, propName );
  3183. },
  3184. // TODO:
  3185. parseNodePropertyContinued: function ( line ) {
  3186. this.currentProp[ this.currentPropName ] += line;
  3187. },
  3188. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  3189. // split this
  3190. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  3191. // into array like below
  3192. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  3193. var props = propValue.split( '",' );
  3194. for ( var i = 0, l = props.length; i < l; i ++ ) {
  3195. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  3196. }
  3197. var innerPropName = props[ 0 ];
  3198. var innerPropType1 = props[ 1 ];
  3199. var innerPropType2 = props[ 2 ];
  3200. var innerPropFlag = props[ 3 ];
  3201. var innerPropValue = props[ 4 ];
  3202. /*
  3203. if ( innerPropValue === undefined ) {
  3204. innerPropValue = props[3];
  3205. }
  3206. */
  3207. // cast value in its type
  3208. switch ( innerPropType1 ) {
  3209. case 'int':
  3210. innerPropValue = parseInt( innerPropValue );
  3211. break;
  3212. case 'double':
  3213. innerPropValue = parseFloat( innerPropValue );
  3214. break;
  3215. case 'ColorRGB':
  3216. case 'Vector3D':
  3217. innerPropValue = parseFloatArray( innerPropValue );
  3218. break;
  3219. }
  3220. // CAUTION: these props must append to parent's parent
  3221. this.getPrevNode().properties[ innerPropName ] = {
  3222. 'type': innerPropType1,
  3223. 'type2': innerPropType2,
  3224. 'flag': innerPropFlag,
  3225. 'value': innerPropValue
  3226. };
  3227. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  3228. },
  3229. nodeEnd: function () {
  3230. this.popStack();
  3231. },
  3232. /* ---------------------------------------------------------------- */
  3233. /* util */
  3234. isFlattenNode: function ( node ) {
  3235. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  3236. }
  3237. } );
  3238. // Binary format specification:
  3239. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  3240. // https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  3241. function BinaryParser() {}
  3242. Object.assign( BinaryParser.prototype, {
  3243. /**
  3244. * Parses binary data and builds FBXTree as much compatible as possible with the one built by TextParser.
  3245. * @param {ArrayBuffer} buffer
  3246. * @returns {THREE.FBXTree}
  3247. */
  3248. parse: function ( buffer ) {
  3249. var reader = new BinaryReader( buffer );
  3250. reader.skip( 23 ); // skip magic 23 bytes
  3251. var version = reader.getUint32();
  3252. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  3253. var allNodes = new FBXTree();
  3254. while ( ! this.endOfContent( reader ) ) {
  3255. var node = this.parseNode( reader, version );
  3256. if ( node !== null ) allNodes.add( node.name, node );
  3257. }
  3258. return allNodes;
  3259. },
  3260. /**
  3261. * Checks if reader has reached the end of content.
  3262. * @param {BinaryReader} reader
  3263. * @returns {boolean}
  3264. */
  3265. endOfContent: function ( reader ) {
  3266. // footer size: 160bytes + 16-byte alignment padding
  3267. // - 16bytes: magic
  3268. // - padding til 16-byte alignment (at least 1byte?)
  3269. // (seems like some exporters embed fixed 15 or 16bytes?)
  3270. // - 4bytes: magic
  3271. // - 4bytes: version
  3272. // - 120bytes: zero
  3273. // - 16bytes: magic
  3274. if ( reader.size() % 16 === 0 ) {
  3275. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  3276. } else {
  3277. return reader.getOffset() + 160 + 16 >= reader.size();
  3278. }
  3279. },
  3280. /**
  3281. * Parses Node as much compatible as possible with the one parsed by TextParser
  3282. * TODO: could be optimized more?
  3283. * @param {BinaryReader} reader
  3284. * @param {number} version
  3285. * @returns {Object} - Returns an Object as node, or null if NULL-record.
  3286. */
  3287. parseNode: function ( reader, version ) {
  3288. // The first three data sizes depends on version.
  3289. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3290. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3291. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3292. var nameLen = reader.getUint8();
  3293. var name = reader.getString( nameLen );
  3294. // Regards this node as NULL-record if endOffset is zero
  3295. if ( endOffset === 0 ) return null;
  3296. var propertyList = [];
  3297. for ( var i = 0; i < numProperties; i ++ ) {
  3298. propertyList.push( this.parseProperty( reader ) );
  3299. }
  3300. // Regards the first three elements in propertyList as id, attrName, and attrType
  3301. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  3302. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  3303. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  3304. var subNodes = {};
  3305. var properties = {};
  3306. var isSingleProperty = false;
  3307. // if this node represents just a single property
  3308. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  3309. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  3310. isSingleProperty = true;
  3311. }
  3312. while ( endOffset > reader.getOffset() ) {
  3313. var node = this.parseNode( reader, version );
  3314. if ( node === null ) continue;
  3315. // special case: child node is single property
  3316. if ( node.singleProperty === true ) {
  3317. var value = node.propertyList[ 0 ];
  3318. if ( Array.isArray( value ) ) {
  3319. // node represents
  3320. // Vertices: *3 {
  3321. // a: 0.01, 0.02, 0.03
  3322. // }
  3323. // of text format here.
  3324. node.properties[ node.name ] = node.propertyList[ 0 ];
  3325. subNodes[ node.name ] = node;
  3326. // Later phase expects single property array is in node.properties.a as String.
  3327. // TODO: optimize
  3328. node.properties.a = value.toString();
  3329. } else {
  3330. // node represents
  3331. // Version: 100
  3332. // of text format here.
  3333. properties[ node.name ] = value;
  3334. }
  3335. continue;
  3336. }
  3337. // special case: connections
  3338. if ( name === 'Connections' && node.name === 'C' ) {
  3339. var array = [];
  3340. // node.propertyList would be like
  3341. // ["OO", 111264976, 144038752, "d|x"] (?, from, to, additional values)
  3342. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  3343. array[ i - 1 ] = node.propertyList[ i ];
  3344. }
  3345. if ( properties.connections === undefined ) {
  3346. properties.connections = [];
  3347. }
  3348. properties.connections.push( array );
  3349. continue;
  3350. }
  3351. // special case: child node is Properties\d+
  3352. if ( node.name.match( /^Properties\d+$/ ) ) {
  3353. // move child node's properties to this node.
  3354. var keys = Object.keys( node.properties );
  3355. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  3356. var key = keys[ i ];
  3357. properties[ key ] = node.properties[ key ];
  3358. }
  3359. continue;
  3360. }
  3361. // special case: properties
  3362. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  3363. var innerPropName = node.propertyList[ 0 ];
  3364. var innerPropType1 = node.propertyList[ 1 ];
  3365. var innerPropType2 = node.propertyList[ 2 ];
  3366. var innerPropFlag = node.propertyList[ 3 ];
  3367. var innerPropValue;
  3368. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  3369. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  3370. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' ||
  3371. innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3372. innerPropValue = [
  3373. node.propertyList[ 4 ],
  3374. node.propertyList[ 5 ],
  3375. node.propertyList[ 6 ]
  3376. ];
  3377. } else {
  3378. innerPropValue = node.propertyList[ 4 ];
  3379. }
  3380. if ( innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3381. innerPropValue = innerPropValue.toString();
  3382. }
  3383. // this will be copied to parent. see above.
  3384. properties[ innerPropName ] = {
  3385. 'type': innerPropType1,
  3386. 'type2': innerPropType2,
  3387. 'flag': innerPropFlag,
  3388. 'value': innerPropValue
  3389. };
  3390. continue;
  3391. }
  3392. // standard case
  3393. // follows TextParser's manner.
  3394. if ( subNodes[ node.name ] === undefined ) {
  3395. if ( typeof node.id === 'number' ) {
  3396. subNodes[ node.name ] = {};
  3397. subNodes[ node.name ][ node.id ] = node;
  3398. } else {
  3399. subNodes[ node.name ] = node;
  3400. }
  3401. } else {
  3402. if ( node.id === '' ) {
  3403. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  3404. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  3405. }
  3406. subNodes[ node.name ].push( node );
  3407. } else {
  3408. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  3409. subNodes[ node.name ][ node.id ] = node;
  3410. } else {
  3411. // conflict id. irregular?
  3412. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  3413. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  3414. }
  3415. subNodes[ node.name ][ node.id ].push( node );
  3416. }
  3417. }
  3418. }
  3419. }
  3420. return {
  3421. singleProperty: isSingleProperty,
  3422. id: id,
  3423. attrName: attrName,
  3424. attrType: attrType,
  3425. name: name,
  3426. properties: properties,
  3427. propertyList: propertyList, // raw property list, would be used by parent
  3428. subNodes: subNodes
  3429. };
  3430. },
  3431. parseProperty: function ( reader ) {
  3432. var type = reader.getChar();
  3433. switch ( type ) {
  3434. case 'F':
  3435. return reader.getFloat32();
  3436. case 'D':
  3437. return reader.getFloat64();
  3438. case 'L':
  3439. return reader.getInt64();
  3440. case 'I':
  3441. return reader.getInt32();
  3442. case 'Y':
  3443. return reader.getInt16();
  3444. case 'C':
  3445. return reader.getBoolean();
  3446. case 'f':
  3447. case 'd':
  3448. case 'l':
  3449. case 'i':
  3450. case 'b':
  3451. var arrayLength = reader.getUint32();
  3452. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  3453. var compressedLength = reader.getUint32();
  3454. if ( encoding === 0 ) {
  3455. switch ( type ) {
  3456. case 'f':
  3457. return reader.getFloat32Array( arrayLength );
  3458. case 'd':
  3459. return reader.getFloat64Array( arrayLength );
  3460. case 'l':
  3461. return reader.getInt64Array( arrayLength );
  3462. case 'i':
  3463. return reader.getInt32Array( arrayLength );
  3464. case 'b':
  3465. return reader.getBooleanArray( arrayLength );
  3466. }
  3467. }
  3468. if ( window.Zlib === undefined ) {
  3469. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  3470. }
  3471. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  3472. var reader2 = new BinaryReader( inflate.decompress().buffer );
  3473. switch ( type ) {
  3474. case 'f':
  3475. return reader2.getFloat32Array( arrayLength );
  3476. case 'd':
  3477. return reader2.getFloat64Array( arrayLength );
  3478. case 'l':
  3479. return reader2.getInt64Array( arrayLength );
  3480. case 'i':
  3481. return reader2.getInt32Array( arrayLength );
  3482. case 'b':
  3483. return reader2.getBooleanArray( arrayLength );
  3484. }
  3485. case 'S':
  3486. var length = reader.getUint32();
  3487. return reader.getString( length );
  3488. case 'R':
  3489. var length = reader.getUint32();
  3490. return reader.getArrayBuffer( length );
  3491. default:
  3492. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  3493. }
  3494. }
  3495. } );
  3496. function BinaryReader( buffer, littleEndian ) {
  3497. this.dv = new DataView( buffer );
  3498. this.offset = 0;
  3499. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  3500. }
  3501. Object.assign( BinaryReader.prototype, {
  3502. getOffset: function () {
  3503. return this.offset;
  3504. },
  3505. size: function () {
  3506. return this.dv.buffer.byteLength;
  3507. },
  3508. skip: function ( length ) {
  3509. this.offset += length;
  3510. },
  3511. // seems like true/false representation depends on exporter.
  3512. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  3513. // then sees LSB.
  3514. getBoolean: function () {
  3515. return ( this.getUint8() & 1 ) === 1;
  3516. },
  3517. getBooleanArray: function ( size ) {
  3518. var a = [];
  3519. for ( var i = 0; i < size; i ++ ) {
  3520. a.push( this.getBoolean() );
  3521. }
  3522. return a;
  3523. },
  3524. getInt8: function () {
  3525. var value = this.dv.getInt8( this.offset );
  3526. this.offset += 1;
  3527. return value;
  3528. },
  3529. getInt8Array: function ( size ) {
  3530. var a = [];
  3531. for ( var i = 0; i < size; i ++ ) {
  3532. a.push( this.getInt8() );
  3533. }
  3534. return a;
  3535. },
  3536. getUint8: function () {
  3537. var value = this.dv.getUint8( this.offset );
  3538. this.offset += 1;
  3539. return value;
  3540. },
  3541. getUint8Array: function ( size ) {
  3542. var a = [];
  3543. for ( var i = 0; i < size; i ++ ) {
  3544. a.push( this.getUint8() );
  3545. }
  3546. return a;
  3547. },
  3548. getInt16: function () {
  3549. var value = this.dv.getInt16( this.offset, this.littleEndian );
  3550. this.offset += 2;
  3551. return value;
  3552. },
  3553. getInt16Array: function ( size ) {
  3554. var a = [];
  3555. for ( var i = 0; i < size; i ++ ) {
  3556. a.push( this.getInt16() );
  3557. }
  3558. return a;
  3559. },
  3560. getUint16: function () {
  3561. var value = this.dv.getUint16( this.offset, this.littleEndian );
  3562. this.offset += 2;
  3563. return value;
  3564. },
  3565. getUint16Array: function ( size ) {
  3566. var a = [];
  3567. for ( var i = 0; i < size; i ++ ) {
  3568. a.push( this.getUint16() );
  3569. }
  3570. return a;
  3571. },
  3572. getInt32: function () {
  3573. var value = this.dv.getInt32( this.offset, this.littleEndian );
  3574. this.offset += 4;
  3575. return value;
  3576. },
  3577. getInt32Array: function ( size ) {
  3578. var a = [];
  3579. for ( var i = 0; i < size; i ++ ) {
  3580. a.push( this.getInt32() );
  3581. }
  3582. return a;
  3583. },
  3584. getUint32: function () {
  3585. var value = this.dv.getUint32( this.offset, this.littleEndian );
  3586. this.offset += 4;
  3587. return value;
  3588. },
  3589. getUint32Array: function ( size ) {
  3590. var a = [];
  3591. for ( var i = 0; i < size; i ++ ) {
  3592. a.push( this.getUint32() );
  3593. }
  3594. return a;
  3595. },
  3596. // JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
  3597. // 1 << 32 will return 1 so using multiply operation instead here.
  3598. // There'd be a possibility that this method returns wrong value if the value
  3599. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  3600. // TODO: safely handle 64-bit integer
  3601. getInt64: function () {
  3602. var low, high;
  3603. if ( this.littleEndian ) {
  3604. low = this.getUint32();
  3605. high = this.getUint32();
  3606. } else {
  3607. high = this.getUint32();
  3608. low = this.getUint32();
  3609. }
  3610. // calculate negative value
  3611. if ( high & 0x80000000 ) {
  3612. high = ~ high & 0xFFFFFFFF;
  3613. low = ~ low & 0xFFFFFFFF;
  3614. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  3615. low = ( low + 1 ) & 0xFFFFFFFF;
  3616. return - ( high * 0x100000000 + low );
  3617. }
  3618. return high * 0x100000000 + low;
  3619. },
  3620. getInt64Array: function ( size ) {
  3621. var a = [];
  3622. for ( var i = 0; i < size; i ++ ) {
  3623. a.push( this.getInt64() );
  3624. }
  3625. return a;
  3626. },
  3627. // Note: see getInt64() comment
  3628. getUint64: function () {
  3629. var low, high;
  3630. if ( this.littleEndian ) {
  3631. low = this.getUint32();
  3632. high = this.getUint32();
  3633. } else {
  3634. high = this.getUint32();
  3635. low = this.getUint32();
  3636. }
  3637. return high * 0x100000000 + low;
  3638. },
  3639. getUint64Array: function ( size ) {
  3640. var a = [];
  3641. for ( var i = 0; i < size; i ++ ) {
  3642. a.push( this.getUint64() );
  3643. }
  3644. return a;
  3645. },
  3646. getFloat32: function () {
  3647. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  3648. this.offset += 4;
  3649. return value;
  3650. },
  3651. getFloat32Array: function ( size ) {
  3652. var a = [];
  3653. for ( var i = 0; i < size; i ++ ) {
  3654. a.push( this.getFloat32() );
  3655. }
  3656. return a;
  3657. },
  3658. getFloat64: function () {
  3659. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  3660. this.offset += 8;
  3661. return value;
  3662. },
  3663. getFloat64Array: function ( size ) {
  3664. var a = [];
  3665. for ( var i = 0; i < size; i ++ ) {
  3666. a.push( this.getFloat64() );
  3667. }
  3668. return a;
  3669. },
  3670. getArrayBuffer: function ( size ) {
  3671. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  3672. this.offset += size;
  3673. return value;
  3674. },
  3675. getChar: function () {
  3676. return String.fromCharCode( this.getUint8() );
  3677. },
  3678. getString: function ( size ) {
  3679. var s = '';
  3680. while ( size > 0 ) {
  3681. var value = this.getUint8();
  3682. size --;
  3683. if ( value === 0 ) break;
  3684. s += String.fromCharCode( value );
  3685. }
  3686. // Manage UTF8 encoding
  3687. s = decodeURIComponent( escape( s ) );
  3688. this.skip( size );
  3689. return s;
  3690. }
  3691. } );
  3692. function FBXTree() {}
  3693. Object.assign( FBXTree.prototype, {
  3694. add: function ( key, val ) {
  3695. this[ key ] = val;
  3696. },
  3697. searchConnectionParent: function ( id ) {
  3698. if ( this.__cache_search_connection_parent === undefined ) {
  3699. this.__cache_search_connection_parent = [];
  3700. }
  3701. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  3702. return this.__cache_search_connection_parent[ id ];
  3703. } else {
  3704. this.__cache_search_connection_parent[ id ] = [];
  3705. }
  3706. var conns = this.Connections.properties.connections;
  3707. var results = [];
  3708. for ( var i = 0; i < conns.length; ++ i ) {
  3709. if ( conns[ i ][ 0 ] == id ) {
  3710. // 0 means scene root
  3711. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  3712. results.push( res );
  3713. }
  3714. }
  3715. if ( results.length > 0 ) {
  3716. append( this.__cache_search_connection_parent[ id ], results );
  3717. return results;
  3718. } else {
  3719. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  3720. return [ - 1 ];
  3721. }
  3722. },
  3723. searchConnectionChildren: function ( id ) {
  3724. if ( this.__cache_search_connection_children === undefined ) {
  3725. this.__cache_search_connection_children = [];
  3726. }
  3727. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  3728. return this.__cache_search_connection_children[ id ];
  3729. } else {
  3730. this.__cache_search_connection_children[ id ] = [];
  3731. }
  3732. var conns = this.Connections.properties.connections;
  3733. var res = [];
  3734. for ( var i = 0; i < conns.length; ++ i ) {
  3735. if ( conns[ i ][ 1 ] == id ) {
  3736. // 0 means scene root
  3737. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  3738. // there may more than one kid, then search to the end
  3739. }
  3740. }
  3741. if ( res.length > 0 ) {
  3742. append( this.__cache_search_connection_children[ id ], res );
  3743. return res;
  3744. } else {
  3745. this.__cache_search_connection_children[ id ] = [ ];
  3746. return [ ];
  3747. }
  3748. },
  3749. searchConnectionType: function ( id, to ) {
  3750. var key = id + ',' + to; // TODO: to hash
  3751. if ( this.__cache_search_connection_type === undefined ) {
  3752. this.__cache_search_connection_type = {};
  3753. }
  3754. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  3755. return this.__cache_search_connection_type[ key ];
  3756. } else {
  3757. this.__cache_search_connection_type[ key ] = '';
  3758. }
  3759. var conns = this.Connections.properties.connections;
  3760. for ( var i = 0; i < conns.length; ++ i ) {
  3761. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  3762. // 0 means scene root
  3763. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  3764. return conns[ i ][ 2 ];
  3765. }
  3766. }
  3767. this.__cache_search_connection_type[ id ] = null;
  3768. return null;
  3769. }
  3770. } );
  3771. /**
  3772. * @param {ArrayBuffer} buffer
  3773. * @returns {boolean}
  3774. */
  3775. function isFbxFormatBinary( buffer ) {
  3776. var CORRECT = 'Kaydara FBX Binary \0';
  3777. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  3778. }
  3779. /**
  3780. * @returns {boolean}
  3781. */
  3782. function isFbxFormatASCII( text ) {
  3783. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  3784. var cursor = 0;
  3785. function read( offset ) {
  3786. var result = text[ offset - 1 ];
  3787. text = text.slice( cursor + offset );
  3788. cursor ++;
  3789. return result;
  3790. }
  3791. for ( var i = 0; i < CORRECT.length; ++ i ) {
  3792. var num = read( 1 );
  3793. if ( num === CORRECT[ i ] ) {
  3794. return false;
  3795. }
  3796. }
  3797. return true;
  3798. }
  3799. /**
  3800. * @returns {number}
  3801. */
  3802. function getFbxVersion( text ) {
  3803. var versionRegExp = /FBXVersion: (\d+)/;
  3804. var match = text.match( versionRegExp );
  3805. if ( match ) {
  3806. var version = parseInt( match[ 1 ] );
  3807. return version;
  3808. }
  3809. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  3810. }
  3811. /**
  3812. * Converts FBX ticks into real time seconds.
  3813. * @param {number} time - FBX tick timestamp to convert.
  3814. * @returns {number} - FBX tick in real world time.
  3815. */
  3816. function convertFBXTimeToSeconds( time ) {
  3817. // Constant is FBX ticks per second.
  3818. return time / 46186158000;
  3819. }
  3820. /**
  3821. * Parses comma separated list of float numbers and returns them in an array.
  3822. * @example
  3823. * // Returns [ 5.6, 9.4, 2.5, 1.4 ]
  3824. * parseFloatArray( "5.6,9.4,2.5,1.4" )
  3825. * @returns {number[]}
  3826. */
  3827. function parseFloatArray( string ) {
  3828. var array = string.split( ',' );
  3829. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3830. array[ i ] = parseFloat( array[ i ] );
  3831. }
  3832. return array;
  3833. }
  3834. /**
  3835. * Parses comma separated list of int numbers and returns them in an array.
  3836. * @example
  3837. * // Returns [ 5, 8, 2, 3 ]
  3838. * parseFloatArray( "5,8,2,3" )
  3839. * @returns {number[]}
  3840. */
  3841. function parseIntArray( string ) {
  3842. var array = string.split( ',' );
  3843. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3844. array[ i ] = parseInt( array[ i ] );
  3845. }
  3846. return array;
  3847. }
  3848. /**
  3849. * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
  3850. * @param {FBXVector3} property - Property to parse as Vector3.
  3851. * @returns {THREE.Vector3}
  3852. */
  3853. function parseVector3( property ) {
  3854. return new THREE.Vector3().fromArray( property.value );
  3855. }
  3856. /**
  3857. * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
  3858. * @param {FBXVector3} property - Property to parse as Color.
  3859. * @returns {THREE.Color}
  3860. */
  3861. function parseColor( property ) {
  3862. return new THREE.Color().fromArray( property.value );
  3863. }
  3864. function parseMatrixArray( floatString ) {
  3865. return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
  3866. }
  3867. /**
  3868. * Converts ArrayBuffer to String.
  3869. * @param {ArrayBuffer} buffer
  3870. * @param {number} from
  3871. * @param {number} to
  3872. * @returns {String}
  3873. */
  3874. function convertArrayBufferToString( buffer, from, to ) {
  3875. if ( from === undefined ) from = 0;
  3876. if ( to === undefined ) to = buffer.byteLength;
  3877. var array = new Uint8Array( buffer, from, to );
  3878. if ( window.TextDecoder !== undefined ) {
  3879. return new TextDecoder().decode( array );
  3880. }
  3881. var s = '';
  3882. for ( var i = 0, il = array.length; i < il; i ++ ) {
  3883. s += String.fromCharCode( array[ i ] );
  3884. }
  3885. return s;
  3886. }
  3887. /**
  3888. * Converts number from degrees into radians.
  3889. * @param {number} value
  3890. * @returns {number}
  3891. */
  3892. function degreeToRadian( value ) {
  3893. return value * DEG2RAD;
  3894. }
  3895. var DEG2RAD = Math.PI / 180;
  3896. //
  3897. function findIndex( array, func ) {
  3898. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3899. if ( func( array[ i ] ) ) return i;
  3900. }
  3901. return - 1;
  3902. }
  3903. function append( a, b ) {
  3904. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  3905. a[ j ] = b[ i ];
  3906. }
  3907. }
  3908. function slice( a, b, from, to ) {
  3909. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  3910. a[ j ] = b[ i ];
  3911. }
  3912. return a;
  3913. }
  3914. } )();