FBXLoader.js 127 KB

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