aframe-extras.loaders.js 155 KB

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