FBXLoader.js 127 KB

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