FBXLoader.js 128 KB

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