FBXLoader.js 128 KB

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