FBXLoader.js 127 KB

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