1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148 |
- (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){
- require('./src/loaders').registerAll();
- },{"./src/loaders":8}],2:[function(require,module,exports){
- /**
- * @author Kyle-Larson https://github.com/Kyle-Larson
- * @author Takahiro https://github.com/takahirox
- *
- * Loader loads FBX file and generates Group representing FBX scene.
- * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
- *
- * Supports:
- * Mesh Generation (Positional Data)
- * Normal Data (Per Vertex Drawing Instance)
- * UV Data (Per Vertex Drawing Instance)
- * Skinning
- * Animation
- * - Separated Animations based on stacks.
- * - Skeletal & Non-Skeletal Animations
- * NURBS (Open, Closed and Periodic forms)
- *
- * Needs Support:
- * Indexed Buffers
- * PreRotation support.
- */
- ( function () {
- /**
- * Generates a loader for loading FBX files from URL and parsing into
- * a THREE.Group.
- * @param {THREE.LoadingManager} manager - Loading Manager for loader to use.
- */
- module.exports = THREE.FBXLoader = function ( manager ) {
- this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
- };
- Object.assign( THREE.FBXLoader.prototype, {
- /**
- * Loads an ASCII/Binary FBX file from URL and parses into a THREE.Group.
- * THREE.Group will have an animations property of AnimationClips
- * of the different animations exported with the FBX.
- * @param {string} url - URL of the FBX file.
- * @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed.
- * @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server.
- * @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors).
- */
- load: function ( url, onLoad, onProgress, onError ) {
- var self = this;
- var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
- var loader = new THREE.FileLoader( this.manager );
- loader.setResponseType( 'arraybuffer' );
- loader.load( url, function ( buffer ) {
- try {
- var scene = self.parse( buffer, resourceDirectory );
- onLoad( scene );
- } catch ( error ) {
- window.setTimeout( function () {
- if ( onError ) onError( error );
- self.manager.itemError( url );
- }, 0 );
- }
- }, onProgress, onError );
- },
- /**
- * Parses an ASCII/Binary FBX file and returns a THREE.Group.
- * THREE.Group will have an animations property of AnimationClips
- * of the different animations within the FBX file.
- * @param {ArrayBuffer} FBXBuffer - Contents of FBX file to parse.
- * @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from.
- * @returns {THREE.Group}
- */
- parse: function ( FBXBuffer, resourceDirectory ) {
- var FBXTree;
- if ( isFbxFormatBinary( FBXBuffer ) ) {
- FBXTree = new BinaryParser().parse( FBXBuffer );
- } else {
- var FBXText = convertArrayBufferToString( FBXBuffer );
- if ( ! isFbxFormatASCII( FBXText ) ) {
- throw new Error( 'THREE.FBXLoader: Unknown format.' );
- }
- if ( getFbxVersion( FBXText ) < 7000 ) {
- throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
- }
- FBXTree = new TextParser().parse( FBXText );
- }
- // console.log( FBXTree );
- var connections = parseConnections( FBXTree );
- var images = parseImages( FBXTree );
- var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
- var materials = parseMaterials( FBXTree, textures, connections );
- var deformers = parseDeformers( FBXTree, connections );
- var geometryMap = parseGeometries( FBXTree, connections, deformers );
- var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
- return sceneGraph;
- }
- } );
- /**
- * Parses map of relationships between objects.
- * @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree
- * @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
- */
- function parseConnections( FBXTree ) {
- /**
- * @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
- */
- var connectionMap = new Map();
- if ( 'Connections' in FBXTree ) {
- /**
- * @type {[number, number, string][]}
- */
- var connectionArray = FBXTree.Connections.properties.connections;
- for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
- var connection = connectionArray[ connectionArrayIndex ];
- if ( ! connectionMap.has( connection[ 0 ] ) ) {
- connectionMap.set( connection[ 0 ], {
- parents: [],
- children: []
- } );
- }
- var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
- connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
- if ( ! connectionMap.has( connection[ 1 ] ) ) {
- connectionMap.set( connection[ 1 ], {
- parents: [],
- children: []
- } );
- }
- var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
- connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
- }
- }
- return connectionMap;
- }
- /**
- * Parses map of images referenced in FBXTree.
- * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
- * @returns {Map<number, string(image blob/data URL)>}
- */
- function parseImages( FBXTree ) {
- /**
- * @type {Map<number, string(image blob/data URL)>}
- */
- var imageMap = new Map();
- if ( 'Video' in FBXTree.Objects.subNodes ) {
- var videoNodes = FBXTree.Objects.subNodes.Video;
- for ( var nodeID in videoNodes ) {
- var videoNode = videoNodes[ nodeID ];
- // raw image data is in videoNode.properties.Content
- if ( 'Content' in videoNode.properties ) {
- var image = parseImage( videoNodes[ nodeID ] );
- imageMap.set( parseInt( nodeID ), image );
- }
- }
- }
- return imageMap;
- }
- /**
- * @param {videoNode} videoNode - Node to get texture image information from.
- * @returns {string} - image blob/data URL
- */
- function parseImage( videoNode ) {
- var content = videoNode.properties.Content;
- var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
- var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
- var type;
- switch ( extension ) {
- case 'bmp':
- type = 'image/bmp';
- break;
- case 'jpg':
- type = 'image/jpeg';
- break;
- case 'png':
- type = 'image/png';
- break;
- case 'tif':
- type = 'image/tiff';
- break;
- default:
- console.warn( 'FBXLoader: No support image type ' + extension );
- return;
- }
- if ( typeof content === 'string' ) {
- return 'data:' + type + ';base64,' + content;
- } else {
- var array = new Uint8Array( content );
- return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
- }
- }
- /**
- * Parses map of textures referenced in FBXTree.
- * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
- * @param {THREE.TextureLoader} loader
- * @param {Map<number, string(image blob/data URL)>} imageMap
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @returns {Map<number, THREE.Texture>}
- */
- function parseTextures( FBXTree, loader, imageMap, connections ) {
- /**
- * @type {Map<number, THREE.Texture>}
- */
- var textureMap = new Map();
- if ( 'Texture' in FBXTree.Objects.subNodes ) {
- var textureNodes = FBXTree.Objects.subNodes.Texture;
- for ( var nodeID in textureNodes ) {
- var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
- textureMap.set( parseInt( nodeID ), texture );
- }
- }
- return textureMap;
- }
- /**
- * @param {textureNode} textureNode - Node to get texture information from.
- * @param {THREE.TextureLoader} loader
- * @param {Map<number, string(image blob/data URL)>} imageMap
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @returns {THREE.Texture}
- */
- function parseTexture( textureNode, loader, imageMap, connections ) {
- var FBX_ID = textureNode.id;
- var name = textureNode.name;
- var fileName;
- var filePath = textureNode.properties.FileName;
- var relativeFilePath = textureNode.properties.RelativeFilename;
- var children = connections.get( FBX_ID ).children;
- if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
- fileName = imageMap.get( children[ 0 ].ID );
- } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' &&
- relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
- // use textureNode.properties.RelativeFilename
- // if it exists and it doesn't seem an absolute path
- fileName = relativeFilePath;
- } else {
- var split = filePath.split( /[\\\/]/ );
- if ( split.length > 0 ) {
- fileName = split[ split.length - 1 ];
- } else {
- fileName = filePath;
- }
- }
- var currentPath = loader.path;
- if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
- loader.setPath( undefined );
- }
- /**
- * @type {THREE.Texture}
- */
- var texture = loader.load( fileName );
- texture.name = name;
- texture.FBX_ID = FBX_ID;
- var wrapModeU = textureNode.properties.WrapModeU;
- var wrapModeV = textureNode.properties.WrapModeV;
- var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
- var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
- // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
- // 0: repeat(default), 1: clamp
- texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
- texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
- loader.setPath( currentPath );
- return texture;
- }
- /**
- * Parses map of Material information.
- * @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree
- * @param {Map<number, THREE.Texture>} textureMap
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @returns {Map<number, THREE.Material>}
- */
- function parseMaterials( FBXTree, textureMap, connections ) {
- var materialMap = new Map();
- if ( 'Material' in FBXTree.Objects.subNodes ) {
- var materialNodes = FBXTree.Objects.subNodes.Material;
- for ( var nodeID in materialNodes ) {
- var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
- if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
- }
- }
- return materialMap;
- }
- /**
- * Takes information from Material node and returns a generated THREE.Material
- * @param {FBXMaterialNode} materialNode
- * @param {Map<number, THREE.Texture>} textureMap
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @returns {THREE.Material}
- */
- function parseMaterial( materialNode, textureMap, connections ) {
- var FBX_ID = materialNode.id;
- var name = materialNode.attrName;
- var type = materialNode.properties.ShadingModel;
- //Case where FBXs wrap shading model in property object.
- if ( typeof type === 'object' ) {
- type = type.value;
- }
- // Seems like FBX can include unused materials which don't have any connections.
- // Ignores them so far.
- if ( ! connections.has( FBX_ID ) ) return null;
- var children = connections.get( FBX_ID ).children;
- var parameters = parseParameters( materialNode.properties, textureMap, children );
- var material;
- switch ( type.toLowerCase() ) {
- case 'phong':
- material = new THREE.MeshPhongMaterial();
- break;
- case 'lambert':
- material = new THREE.MeshLambertMaterial();
- break;
- default:
- console.warn( 'THREE.FBXLoader: No implementation given for material type %s in FBXLoader.js. Defaulting to standard material.', type );
- material = new THREE.MeshStandardMaterial( { color: 0x3300ff } );
- break;
- }
- material.setValues( parameters );
- material.name = name;
- return material;
- }
- /**
- * @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties
- */
- /**
- * @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack
- */
- /**
- * @param {FBXMaterialProperties} properties
- * @param {Map<number, THREE.Texture>} textureMap
- * @param {{ID: number, relationship: string}[]} childrenRelationships
- * @returns {THREEMaterialParameterPack}
- */
- function parseParameters( properties, textureMap, childrenRelationships ) {
- var parameters = {};
- if ( properties.Diffuse ) {
- parameters.color = parseColor( properties.Diffuse );
- }
- if ( properties.Specular ) {
- parameters.specular = parseColor( properties.Specular );
- }
- if ( properties.Shininess ) {
- parameters.shininess = properties.Shininess.value;
- }
- if ( properties.Emissive ) {
- parameters.emissive = parseColor( properties.Emissive );
- }
- if ( properties.EmissiveFactor ) {
- parameters.emissiveIntensity = properties.EmissiveFactor.value;
- }
- if ( properties.Opacity ) {
- parameters.opacity = properties.Opacity.value;
- }
- if ( parameters.opacity < 1.0 ) {
- parameters.transparent = true;
- }
- for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
- var relationship = childrenRelationships[ childrenRelationshipsIndex ];
- var type = relationship.relationship;
- switch ( type ) {
- case 'DiffuseColor':
- case ' "DiffuseColor':
- parameters.map = textureMap.get( relationship.ID );
- break;
- case 'Bump':
- case ' "Bump':
- parameters.bumpMap = textureMap.get( relationship.ID );
- break;
- case 'NormalMap':
- case ' "NormalMap':
- parameters.normalMap = textureMap.get( relationship.ID );
- break;
- case 'AmbientColor':
- case 'EmissiveColor':
- case ' "AmbientColor':
- case ' "EmissiveColor':
- default:
- console.warn( 'THREE.FBXLoader: Unknown texture application of type %s, skipping texture.', type );
- break;
- }
- }
- return parameters;
- }
- /**
- * Generates map of Skeleton-like objects for use later when generating and binding skeletons.
- * @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @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}>}
- */
- function parseDeformers( FBXTree, connections ) {
- var deformers = {};
- if ( 'Deformer' in FBXTree.Objects.subNodes ) {
- var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
- for ( var nodeID in DeformerNodes ) {
- var deformerNode = DeformerNodes[ nodeID ];
- if ( deformerNode.attrType === 'Skin' ) {
- var conns = connections.get( parseInt( nodeID ) );
- var skeleton = parseSkeleton( conns, DeformerNodes );
- skeleton.FBX_ID = parseInt( nodeID );
- deformers[ nodeID ] = skeleton;
- }
- }
- }
- return deformers;
- }
- /**
- * Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes.
- * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
- * @param {Object.<number, FBXSubDeformerNode>} DeformerNodes
- * @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}}
- */
- function parseSkeleton( connections, DeformerNodes ) {
- var subDeformers = {};
- var children = connections.children;
- for ( var i = 0, l = children.length; i < l; ++ i ) {
- var child = children[ i ];
- var subDeformerNode = DeformerNodes[ child.ID ];
- var subDeformer = {
- FBX_ID: child.ID,
- index: i,
- indices: [],
- weights: [],
- transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
- transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
- linkMode: subDeformerNode.properties.Mode
- };
- if ( 'Indexes' in subDeformerNode.subNodes ) {
- subDeformer.indices = parseIntArray( subDeformerNode.subNodes.Indexes.properties.a );
- subDeformer.weights = parseFloatArray( subDeformerNode.subNodes.Weights.properties.a );
- }
- subDeformers[ child.ID ] = subDeformer;
- }
- return {
- map: subDeformers,
- bones: []
- };
- }
- /**
- * Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries
- * @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @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
- * @returns {Map<number, THREE.BufferGeometry>}
- */
- function parseGeometries( FBXTree, connections, deformers ) {
- var geometryMap = new Map();
- if ( 'Geometry' in FBXTree.Objects.subNodes ) {
- var geometryNodes = FBXTree.Objects.subNodes.Geometry;
- for ( var nodeID in geometryNodes ) {
- var relationships = connections.get( parseInt( nodeID ) );
- var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
- geometryMap.set( parseInt( nodeID ), geo );
- }
- }
- return geometryMap;
- }
- /**
- * Generates BufferGeometry from FBXGeometryNode.
- * @param {FBXGeometryNode} geometryNode
- * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
- * @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
- * @returns {THREE.BufferGeometry}
- */
- function parseGeometry( geometryNode, relationships, deformers ) {
- switch ( geometryNode.attrType ) {
- case 'Mesh':
- return parseMeshGeometry( geometryNode, relationships, deformers );
- break;
- case 'NurbsCurve':
- return parseNurbsGeometry( geometryNode );
- break;
- }
- }
- /**
- * Specialty function for parsing Mesh based Geometry Nodes.
- * @param {FBXGeometryNode} geometryNode
- * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes.
- * @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.
- * @returns {THREE.BufferGeometry}
- */
- function parseMeshGeometry( geometryNode, relationships, deformers ) {
- for ( var i = 0; i < relationships.children.length; ++ i ) {
- var deformer = deformers[ relationships.children[ i ].ID ];
- if ( deformer !== undefined ) break;
- }
- return genGeometry( geometryNode, deformer );
- }
- /**
- * @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.
- * @returns {THREE.BufferGeometry}
- */
- function genGeometry( geometryNode, deformer ) {
- var geometry = new Geometry();
- var subNodes = geometryNode.subNodes;
- // First, each index is going to be its own vertex.
- var vertexBuffer = parseFloatArray( subNodes.Vertices.properties.a );
- var indexBuffer = parseIntArray( subNodes.PolygonVertexIndex.properties.a );
- if ( subNodes.LayerElementNormal ) {
- var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
- }
- if ( subNodes.LayerElementUV ) {
- var uvInfo = getUVs( subNodes.LayerElementUV[ 0 ] );
- }
- if ( subNodes.LayerElementColor ) {
- var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
- }
- if ( subNodes.LayerElementMaterial ) {
- var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
- }
- var weightTable = {};
- if ( deformer ) {
- var subDeformers = deformer.map;
- for ( var key in subDeformers ) {
- var subDeformer = subDeformers[ key ];
- var indices = subDeformer.indices;
- for ( var j = 0; j < indices.length; j ++ ) {
- var index = indices[ j ];
- var weight = subDeformer.weights[ j ];
- if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
- weightTable[ index ].push( {
- id: subDeformer.index,
- weight: weight
- } );
- }
- }
- }
- var faceVertexBuffer = [];
- var polygonIndex = 0;
- var displayedWeightsWarning = false;
- for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; polygonVertexIndex ++ ) {
- var vertexIndex = indexBuffer[ polygonVertexIndex ];
- var endOfFace = false;
- if ( vertexIndex < 0 ) {
- vertexIndex = vertexIndex ^ - 1;
- indexBuffer[ polygonVertexIndex ] = vertexIndex;
- endOfFace = true;
- }
- var vertex = new Vertex();
- var weightIndices = [];
- var weights = [];
- vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
- if ( deformer ) {
- if ( weightTable[ vertexIndex ] !== undefined ) {
- var array = weightTable[ vertexIndex ];
- for ( var j = 0, jl = array.length; j < jl; j ++ ) {
- weights.push( array[ j ].weight );
- weightIndices.push( array[ j ].id );
- }
- }
- if ( weights.length > 4 ) {
- if ( ! displayedWeightsWarning ) {
- console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
- displayedWeightsWarning = true;
- }
- var WIndex = [ 0, 0, 0, 0 ];
- var Weight = [ 0, 0, 0, 0 ];
- weights.forEach( function ( weight, weightIndex ) {
- var currentWeight = weight;
- var currentIndex = weightIndices[ weightIndex ];
- Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
- if ( currentWeight > comparedWeight ) {
- comparedWeightArray[ comparedWeightIndex ] = currentWeight;
- currentWeight = comparedWeight;
- var tmp = WIndex[ comparedWeightIndex ];
- WIndex[ comparedWeightIndex ] = currentIndex;
- currentIndex = tmp;
- }
- } );
- } );
- weightIndices = WIndex;
- weights = Weight;
- }
- for ( var i = weights.length; i < 4; ++ i ) {
- weights[ i ] = 0;
- weightIndices[ i ] = 0;
- }
- vertex.skinWeights.fromArray( weights );
- vertex.skinIndices.fromArray( weightIndices );
- }
- if ( normalInfo ) {
- vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
- }
- if ( uvInfo ) {
- vertex.uv.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo ) );
- }
- if ( colorInfo ) {
- vertex.color.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo ) );
- }
- faceVertexBuffer.push( vertex );
- if ( endOfFace ) {
- var face = new Face();
- face.genTrianglesFromVertices( faceVertexBuffer );
- if ( materialInfo !== undefined ) {
- var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
- face.materialIndex = materials[ 0 ];
- } else {
- // Seems like some models don't have materialInfo(subNodes.LayerElementMaterial).
- // Set 0 in such a case.
- face.materialIndex = 0;
- }
- geometry.faces.push( face );
- faceVertexBuffer = [];
- polygonIndex ++;
- endOfFace = false;
- }
- }
- /**
- * @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
- */
- var bufferInfo = geometry.flattenToBuffers();
- var geo = new THREE.BufferGeometry();
- geo.name = geometryNode.name;
- geo.addAttribute( 'position', new THREE.Float32BufferAttribute( bufferInfo.vertexBuffer, 3 ) );
- if ( bufferInfo.normalBuffer.length > 0 ) {
- geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( bufferInfo.normalBuffer, 3 ) );
- }
- if ( bufferInfo.uvBuffer.length > 0 ) {
- geo.addAttribute( 'uv', new THREE.Float32BufferAttribute( bufferInfo.uvBuffer, 2 ) );
- }
- if ( subNodes.LayerElementColor ) {
- geo.addAttribute( 'color', new THREE.Float32BufferAttribute( bufferInfo.colorBuffer, 3 ) );
- }
- if ( deformer ) {
- geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( bufferInfo.skinIndexBuffer, 4 ) );
- geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( bufferInfo.skinWeightBuffer, 4 ) );
- geo.FBX_Deformer = deformer;
- }
- // Convert the material indices of each vertex into rendering groups on the geometry.
- var materialIndexBuffer = bufferInfo.materialIndexBuffer;
- var prevMaterialIndex = materialIndexBuffer[ 0 ];
- var startIndex = 0;
- for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
- if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
- geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
- prevMaterialIndex = materialIndexBuffer[ i ];
- startIndex = i;
- }
- }
- return geo;
- }
- /**
- * Parses normal information for geometry.
- * @param {FBXGeometryNode} geometryNode
- * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
- */
- function getNormals( NormalNode ) {
- var mappingType = NormalNode.properties.MappingInformationType;
- var referenceType = NormalNode.properties.ReferenceInformationType;
- var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
- var indexBuffer = [];
- if ( referenceType === 'IndexToDirect' ) {
- if ( 'NormalIndex' in NormalNode.subNodes ) {
- indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
- } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
- indexBuffer = parseIntArray( NormalNode.subNodes.NormalsIndex.properties.a );
- }
- }
- return {
- dataSize: 3,
- buffer: buffer,
- indices: indexBuffer,
- mappingType: mappingType,
- referenceType: referenceType
- };
- }
- /**
- * Parses UV information for geometry.
- * @param {FBXGeometryNode} geometryNode
- * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
- */
- function getUVs( UVNode ) {
- var mappingType = UVNode.properties.MappingInformationType;
- var referenceType = UVNode.properties.ReferenceInformationType;
- var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
- var indexBuffer = [];
- if ( referenceType === 'IndexToDirect' ) {
- indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
- }
- return {
- dataSize: 2,
- buffer: buffer,
- indices: indexBuffer,
- mappingType: mappingType,
- referenceType: referenceType
- };
- }
- /**
- * Parses Vertex Color information for geometry.
- * @param {FBXGeometryNode} geometryNode
- * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
- */
- function getColors( ColorNode ) {
- var mappingType = ColorNode.properties.MappingInformationType;
- var referenceType = ColorNode.properties.ReferenceInformationType;
- var buffer = parseFloatArray( ColorNode.subNodes.Colors.properties.a );
- var indexBuffer = [];
- if ( referenceType === 'IndexToDirect' ) {
- indexBuffer = parseFloatArray( ColorNode.subNodes.ColorIndex.properties.a );
- }
- return {
- dataSize: 4,
- buffer: buffer,
- indices: indexBuffer,
- mappingType: mappingType,
- referenceType: referenceType
- };
- }
- /**
- * Parses material application information for geometry.
- * @param {FBXGeometryNode}
- * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
- */
- function getMaterials( MaterialNode ) {
- var mappingType = MaterialNode.properties.MappingInformationType;
- var referenceType = MaterialNode.properties.ReferenceInformationType;
- if ( mappingType === 'NoMappingInformation' ) {
- return {
- dataSize: 1,
- buffer: [ 0 ],
- indices: [ 0 ],
- mappingType: 'AllSame',
- referenceType: referenceType
- };
- }
- var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
- // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
- // we expect. So we create an intermediate buffer that points to the index in the buffer,
- // for conforming with the other functions we've written for other data.
- var materialIndices = [];
- for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
- materialIndices.push( materialIndexBufferIndex );
- }
- return {
- dataSize: 1,
- buffer: materialIndexBuffer,
- indices: materialIndices,
- mappingType: mappingType,
- referenceType: referenceType
- };
- }
- /**
- * Function uses the infoObject and given indices to return value array of object.
- * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
- * @param {number} polygonIndex - Index of polygon in geometry.
- * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
- * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
- * @returns {number[]}
- */
- var dataArray = [];
- var GetData = {
- ByPolygonVertex: {
- /**
- * Function uses the infoObject and given indices to return value array of object.
- * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
- * @param {number} polygonIndex - Index of polygon in geometry.
- * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
- * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
- * @returns {number[]}
- */
- Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- var from = ( polygonVertexIndex * infoObject.dataSize );
- var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
- // return infoObject.buffer.slice( from, to );
- return slice( dataArray, infoObject.buffer, from, to );
- },
- /**
- * Function uses the infoObject and given indices to return value array of object.
- * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
- * @param {number} polygonIndex - Index of polygon in geometry.
- * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
- * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
- * @returns {number[]}
- */
- IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- var index = infoObject.indices[ polygonVertexIndex ];
- var from = ( index * infoObject.dataSize );
- var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
- // return infoObject.buffer.slice( from, to );
- return slice( dataArray, infoObject.buffer, from, to );
- }
- },
- ByPolygon: {
- /**
- * Function uses the infoObject and given indices to return value array of object.
- * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
- * @param {number} polygonIndex - Index of polygon in geometry.
- * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
- * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
- * @returns {number[]}
- */
- Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- var from = polygonIndex * infoObject.dataSize;
- var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
- // return infoObject.buffer.slice( from, to );
- return slice( dataArray, infoObject.buffer, from, to );
- },
- /**
- * Function uses the infoObject and given indices to return value array of object.
- * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
- * @param {number} polygonIndex - Index of polygon in geometry.
- * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
- * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
- * @returns {number[]}
- */
- IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- var index = infoObject.indices[ polygonIndex ];
- var from = index * infoObject.dataSize;
- var to = index * infoObject.dataSize + infoObject.dataSize;
- // return infoObject.buffer.slice( from, to );
- return slice( dataArray, infoObject.buffer, from, to );
- }
- },
- ByVertice: {
- Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- var from = ( vertexIndex * infoObject.dataSize );
- var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
- // return infoObject.buffer.slice( from, to );
- return slice( dataArray, infoObject.buffer, from, to );
- }
- },
- AllSame: {
- /**
- * Function uses the infoObject and given indices to return value array of object.
- * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
- * @param {number} polygonIndex - Index of polygon in geometry.
- * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
- * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
- * @returns {number[]}
- */
- IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- var from = infoObject.indices[ 0 ] * infoObject.dataSize;
- var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
- // return infoObject.buffer.slice( from, to );
- return slice( dataArray, infoObject.buffer, from, to );
- }
- }
- };
- function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
- return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
- }
- /**
- * Specialty function for parsing NurbsCurve based Geometry Nodes.
- * @param {FBXGeometryNode} geometryNode
- * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
- * @returns {THREE.BufferGeometry}
- */
- function parseNurbsGeometry( geometryNode ) {
- if ( THREE.NURBSCurve === undefined ) {
- console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
- return new THREE.BufferGeometry();
- }
- var order = parseInt( geometryNode.properties.Order );
- if ( isNaN( order ) ) {
- console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
- return new THREE.BufferGeometry();
- }
- var degree = order - 1;
- var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a );
- var controlPoints = [];
- var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a );
- for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
- controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
- }
- var startKnot, endKnot;
- if ( geometryNode.properties.Form === 'Closed' ) {
- controlPoints.push( controlPoints[ 0 ] );
- } else if ( geometryNode.properties.Form === 'Periodic' ) {
- startKnot = degree;
- endKnot = knots.length - 1 - startKnot;
- for ( var i = 0; i < degree; ++ i ) {
- controlPoints.push( controlPoints[ i ] );
- }
- }
- var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
- var vertices = curve.getPoints( controlPoints.length * 7 );
- var positions = new Float32Array( vertices.length * 3 );
- for ( var i = 0, l = vertices.length; i < l; ++ i ) {
- vertices[ i ].toArray( positions, i * 3 );
- }
- var geometry = new THREE.BufferGeometry();
- geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
- return geometry;
- }
- /**
- * Finally generates Scene graph and Scene graph Objects.
- * @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @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
- * @param {Map<number, THREE.BufferGeometry>} geometryMap
- * @param {Map<number, THREE.Material>} materialMap
- * @returns {THREE.Group}
- */
- function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
- var sceneGraph = new THREE.Group();
- var ModelNode = FBXTree.Objects.subNodes.Model;
- /**
- * @type {Array.<THREE.Object3D>}
- */
- var modelArray = [];
- /**
- * @type {Map.<number, THREE.Object3D>}
- */
- var modelMap = new Map();
- for ( var nodeID in ModelNode ) {
- var id = parseInt( nodeID );
- var node = ModelNode[ nodeID ];
- var conns = connections.get( id );
- var model = null;
- for ( var i = 0; i < conns.parents.length; ++ i ) {
- for ( var FBX_ID in deformers ) {
- var deformer = deformers[ FBX_ID ];
- var subDeformers = deformer.map;
- var subDeformer = subDeformers[ conns.parents[ i ].ID ];
- if ( subDeformer ) {
- var model2 = model;
- model = new THREE.Bone();
- deformer.bones[ subDeformer.index ] = model;
- // seems like we need this not to make non-connected bone, maybe?
- // TODO: confirm
- if ( model2 !== null ) model.add( model2 );
- }
- }
- }
- if ( ! model ) {
- switch ( node.attrType ) {
- case 'Mesh':
- /**
- * @type {?THREE.BufferGeometry}
- */
- var geometry = null;
- /**
- * @type {THREE.MultiMaterial|THREE.Material}
- */
- var material = null;
- /**
- * @type {Array.<THREE.Material>}
- */
- var materials = [];
- for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
- var child = conns.children[ childrenIndex ];
- if ( geometryMap.has( child.ID ) ) {
- geometry = geometryMap.get( child.ID );
- }
- if ( materialMap.has( child.ID ) ) {
- materials.push( materialMap.get( child.ID ) );
- }
- }
- if ( materials.length > 1 ) {
- material = materials;
- } else if ( materials.length > 0 ) {
- material = materials[ 0 ];
- } else {
- material = new THREE.MeshStandardMaterial( { color: 0x3300ff } );
- materials.push( material );
- }
- if ( 'color' in geometry.attributes ) {
- for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++materialIndex ) {
- materials[ materialIndex ].vertexColors = THREE.VertexColors;
- }
- }
- if ( geometry.FBX_Deformer ) {
- for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
- materials[ materialsIndex ].skinning = true;
- }
- model = new THREE.SkinnedMesh( geometry, material );
- } else {
- model = new THREE.Mesh( geometry, material );
- }
- break;
- case 'NurbsCurve':
- var geometry = null;
- for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
- var child = conns.children[ childrenIndex ];
- if ( geometryMap.has( child.ID ) ) {
- geometry = geometryMap.get( child.ID );
- }
- }
- // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
- material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
- model = new THREE.Line( geometry, material );
- break;
- default:
- model = new THREE.Object3D();
- break;
- }
- }
- model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' );
- model.FBX_ID = id;
- modelArray.push( model );
- modelMap.set( id, model );
- }
- for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
- var model = modelArray[ modelArrayIndex ];
- var node = ModelNode[ model.FBX_ID ];
- if ( 'Lcl_Translation' in node.properties ) {
- model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
- }
- if ( 'Lcl_Rotation' in node.properties ) {
- var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( degreeToRadian );
- rotation.push( 'ZYX' );
- model.rotation.fromArray( rotation );
- }
- if ( 'Lcl_Scaling' in node.properties ) {
- model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
- }
- if ( 'PreRotation' in node.properties ) {
- var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( DEG2RAD ), 'ZYX' );
- preRotations = new THREE.Quaternion().setFromEuler( preRotations );
- var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
- preRotations.multiply( currentRotation );
- model.rotation.setFromQuaternion( preRotations, 'ZYX' );
- }
- var conns = connections.get( model.FBX_ID );
- for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
- var pIndex = findIndex( modelArray, function ( mod ) {
- return mod.FBX_ID === conns.parents[ parentIndex ].ID;
- } );
- if ( pIndex > - 1 ) {
- modelArray[ pIndex ].add( model );
- break;
- }
- }
- if ( model.parent === null ) {
- sceneGraph.add( model );
- }
- }
- // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
- sceneGraph.updateMatrixWorld( true );
- // Put skeleton into bind pose.
- var BindPoseNode = FBXTree.Objects.subNodes.Pose;
- for ( var nodeID in BindPoseNode ) {
- if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
- BindPoseNode = BindPoseNode[ nodeID ];
- break;
- }
- }
- if ( BindPoseNode ) {
- var PoseNode = BindPoseNode.subNodes.PoseNode;
- var worldMatrices = new Map();
- for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
- var node = PoseNode[ PoseNodeIndex ];
- var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
- worldMatrices.set( parseInt( node.id ), rawMatWrd );
- }
- }
- for ( var FBX_ID in deformers ) {
- var deformer = deformers[ FBX_ID ];
- var subDeformers = deformer.map;
- for ( var key in subDeformers ) {
- var subDeformer = subDeformers[ key ];
- var subDeformerIndex = subDeformer.index;
- /**
- * @type {THREE.Bone}
- */
- var bone = deformer.bones[ subDeformerIndex ];
- if ( ! worldMatrices.has( bone.FBX_ID ) ) {
- break;
- }
- var mat = worldMatrices.get( bone.FBX_ID );
- bone.matrixWorld.copy( mat );
- }
- // Now that skeleton is in bind pose, bind to model.
- deformer.skeleton = new THREE.Skeleton( deformer.bones );
- var conns = connections.get( deformer.FBX_ID );
- var parents = conns.parents;
- for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
- var parent = parents[ parentsIndex ];
- if ( geometryMap.has( parent.ID ) ) {
- var geoID = parent.ID;
- var geoConns = connections.get( geoID );
- for ( var i = 0; i < geoConns.parents.length; ++ i ) {
- if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
- var model = modelMap.get( geoConns.parents[ i ].ID );
- //ASSERT model typeof SkinnedMesh
- model.bind( deformer.skeleton, model.matrixWorld );
- break;
- }
- }
- }
- }
- }
- //Skeleton is now bound, return objects to starting
- //world positions.
- sceneGraph.updateMatrixWorld( true );
- // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
- // to attach animations to, since FBXs treat animations as animations for the entire scene,
- // not just for individual objects.
- sceneGraph.skeleton = {
- bones: modelArray
- };
- var animations = parseAnimations( FBXTree, connections, sceneGraph );
- addAnimations( sceneGraph, animations );
- return sceneGraph;
- }
- /**
- * Parses animation information from FBXTree and generates an AnimationInfoObject.
- * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- */
- function parseAnimations( FBXTree, connections, sceneGraph ) {
- var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
- var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
- var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
- var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
- /**
- * @type {{
- curves: Map<number, {
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- },
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- },
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- }
- }>,
- layers: Map<number, {
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- },
- },
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- },
- },
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- },
- }
- }[]>,
- stacks: Map<number, {
- name: string,
- layers: {
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- }[][],
- length: number,
- frames: number }>,
- length: number,
- fps: number,
- frames: number
- }}
- */
- var returnObject = {
- curves: new Map(),
- layers: {},
- stacks: {},
- length: 0,
- fps: 30,
- frames: 0
- };
- /**
- * @type {Array.<{
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- }>}
- */
- var animationCurveNodes = [];
- for ( var nodeID in rawNodes ) {
- if ( nodeID.match( /\d+/ ) ) {
- var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
- animationCurveNodes.push( animationNode );
- }
- }
- /**
- * @type {Map.<number, {
- id: number,
- attr: string,
- internalID: number,
- attrX: boolean,
- attrY: boolean,
- attrZ: boolean,
- containerBoneID: number,
- containerID: number,
- curves: {
- x: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- y: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- z: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- }
- }
- }>}
- */
- var tmpMap = new Map();
- for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
- if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
- continue;
- }
- tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
- }
- /**
- * @type {{
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- }[]}
- */
- var animationCurves = [];
- for ( nodeID in rawCurves ) {
- if ( nodeID.match( /\d+/ ) ) {
- var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
- // seems like this check would be necessary?
- if ( ! connections.has( animationCurve.id ) ) continue;
- animationCurves.push( animationCurve );
- var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
- var firstParentID = firstParentConn.ID;
- var firstParentRelationship = firstParentConn.relationship;
- var axis = '';
- if ( firstParentRelationship.match( /X/ ) ) {
- axis = 'x';
- } else if ( firstParentRelationship.match( /Y/ ) ) {
- axis = 'y';
- } else if ( firstParentRelationship.match( /Z/ ) ) {
- axis = 'z';
- } else {
- continue;
- }
- tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
- }
- }
- tmpMap.forEach( function ( curveNode ) {
- var id = curveNode.containerBoneID;
- if ( ! returnObject.curves.has( id ) ) {
- returnObject.curves.set( id, { T: null, R: null, S: null } );
- }
- returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
- if ( curveNode.attr === 'R' ) {
- var curves = curveNode.curves;
- // Seems like some FBX files have AnimationCurveNode
- // which doesn't have any connected AnimationCurve.
- // Setting animation parameter for them here.
- if ( curves.x === null ) {
- curves.x = {
- version: null,
- times: [ 0.0 ],
- values: [ 0.0 ]
- };
- }
- if ( curves.y === null ) {
- curves.y = {
- version: null,
- times: [ 0.0 ],
- values: [ 0.0 ]
- };
- }
- if ( curves.z === null ) {
- curves.z = {
- version: null,
- times: [ 0.0 ],
- values: [ 0.0 ]
- };
- }
- curves.x.values = curves.x.values.map( degreeToRadian );
- curves.y.values = curves.y.values.map( degreeToRadian );
- curves.z.values = curves.z.values.map( degreeToRadian );
- if ( curveNode.preRotations !== null ) {
- var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
- preRotations = new THREE.Quaternion().setFromEuler( preRotations );
- var frameRotation = new THREE.Euler();
- var frameRotationQuaternion = new THREE.Quaternion();
- for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
- frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
- frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
- frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
- curves.x.values[ frame ] = frameRotation.x;
- curves.y.values[ frame ] = frameRotation.y;
- curves.z.values[ frame ] = frameRotation.z;
- }
- }
- }
- } );
- for ( var nodeID in rawLayers ) {
- /**
- * @type {{
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- },
- },
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- },
- },
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- },
- }
- }[]}
- */
- var layer = [];
- var children = connections.get( parseInt( nodeID ) ).children;
- for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
- // Skip lockInfluenceWeights
- if ( tmpMap.has( children[ childIndex ].ID ) ) {
- var curveNode = tmpMap.get( children[ childIndex ].ID );
- var boneID = curveNode.containerBoneID;
- if ( layer[ boneID ] === undefined ) {
- layer[ boneID ] = {
- T: null,
- R: null,
- S: null
- };
- }
- layer[ boneID ][ curveNode.attr ] = curveNode;
- }
- }
- returnObject.layers[ nodeID ] = layer;
- }
- for ( var nodeID in rawStacks ) {
- var layers = [];
- var children = connections.get( parseInt( nodeID ) ).children;
- var timestamps = { max: 0, min: Number.MAX_VALUE };
- for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
- var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
- if ( currentLayer !== undefined ) {
- layers.push( currentLayer );
- for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
- var layer = currentLayer[ currentLayerIndex ];
- if ( layer ) {
- getCurveNodeMaxMinTimeStamps( layer, timestamps );
- }
- }
- }
- }
- // Do we have an animation clip with actual length?
- if ( timestamps.max > timestamps.min ) {
- returnObject.stacks[ nodeID ] = {
- name: rawStacks[ nodeID ].attrName,
- layers: layers,
- length: timestamps.max - timestamps.min,
- frames: ( timestamps.max - timestamps.min ) * 30
- };
- }
- }
- return returnObject;
- }
- /**
- * @param {Object} FBXTree
- * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
- * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
- * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
- */
- function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
- var rawModels = FBXTree.Objects.subNodes.Model;
- var returnObject = {
- /**
- * @type {number}
- */
- id: animationCurveNode.id,
- /**
- * @type {string}
- */
- attr: animationCurveNode.attrName,
- /**
- * @type {number}
- */
- internalID: animationCurveNode.id,
- /**
- * @type {boolean}
- */
- attrX: false,
- /**
- * @type {boolean}
- */
- attrY: false,
- /**
- * @type {boolean}
- */
- attrZ: false,
- /**
- * @type {number}
- */
- containerBoneID: - 1,
- /**
- * @type {number}
- */
- containerID: - 1,
- curves: {
- x: null,
- y: null,
- z: null
- },
- /**
- * @type {number[]}
- */
- preRotations: null
- };
- if ( returnObject.attr.match( /S|R|T/ ) ) {
- for ( var attributeKey in animationCurveNode.properties ) {
- if ( attributeKey.match( /X/ ) ) {
- returnObject.attrX = true;
- }
- if ( attributeKey.match( /Y/ ) ) {
- returnObject.attrY = true;
- }
- if ( attributeKey.match( /Z/ ) ) {
- returnObject.attrZ = true;
- }
- }
- } else {
- return null;
- }
- var conns = connections.get( returnObject.id );
- var containerIndices = conns.parents;
- for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
- var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
- return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
- } );
- if ( boneID > - 1 ) {
- returnObject.containerBoneID = boneID;
- returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
- var model = rawModels[ returnObject.containerID.toString() ];
- if ( 'PreRotation' in model.properties ) {
- returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
- }
- break;
- }
- }
- return returnObject;
- }
- /**
- * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
- */
- function parseAnimationCurve( animationCurve ) {
- return {
- version: null,
- id: animationCurve.id,
- internalID: animationCurve.id,
- times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( convertFBXTimeToSeconds ),
- values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
- attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
- attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
- };
- }
- /**
- * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
- * than the max or min respectively.
- * @param {{
- T: {
- id: number,
- attr: string,
- internalID: number,
- attrX: boolean,
- attrY: boolean,
- attrZ: boolean,
- containerBoneID: number,
- containerID: number,
- curves: {
- x: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- y: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- z: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- },
- },
- R: {
- id: number,
- attr: string,
- internalID: number,
- attrX: boolean,
- attrY: boolean,
- attrZ: boolean,
- containerBoneID: number,
- containerID: number,
- curves: {
- x: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- y: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- z: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- },
- },
- S: {
- id: number,
- attr: string,
- internalID: number,
- attrX: boolean,
- attrY: boolean,
- attrZ: boolean,
- containerBoneID: number,
- containerID: number,
- curves: {
- x: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- y: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- z: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- },
- },
- }} layer
- */
- function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
- if ( layer.R ) {
- getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
- }
- if ( layer.S ) {
- getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
- }
- if ( layer.T ) {
- getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
- }
- }
- /**
- * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
- * exceeds the maximum or minimum.
- * @param {{
- x: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- y: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- },
- z: {
- version: any,
- id: number,
- internalID: number,
- times: number[],
- values: number[],
- attrFlag: number[],
- attrData: number[],
- }
- }} curve
- */
- function getCurveMaxMinTimeStamp( curve, timestamps ) {
- if ( curve.x ) {
- getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
- }
- if ( curve.y ) {
- getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
- }
- if ( curve.z ) {
- getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
- }
- }
- /**
- * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
- * @param {{times: number[]}} axis
- */
- function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
- timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
- timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
- }
- /**
- * @param {{
- curves: Map<number, {
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- }>;
- layers: Map<number, {
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- }[]>;
- stacks: Map<number, {
- name: string;
- layers: {
- T: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- R: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- S: {
- id: number;
- attr: string;
- internalID: number;
- attrX: boolean;
- attrY: boolean;
- attrZ: boolean;
- containerBoneID: number;
- containerID: number;
- curves: {
- x: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- y: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- z: {
- version: any;
- id: number;
- internalID: number;
- times: number[];
- values: number[];
- attrFlag: number[];
- attrData: number[];
- };
- };
- };
- }[][];
- length: number;
- frames: number;
- }>;
- length: number;
- fps: number;
- frames: number;
- }} animations,
- * @param {{skeleton: { bones: THREE.Bone[]}}} group
- */
- function addAnimations( group, animations ) {
- if ( group.animations === undefined ) {
- group.animations = [];
- }
- var stacks = animations.stacks;
- for ( var key in stacks ) {
- var stack = stacks[ key ];
- /**
- * @type {{
- * name: string,
- * fps: number,
- * length: number,
- * hierarchy: Array.<{
- * parent: number,
- * name: string,
- * keys: Array.<{
- * time: number,
- * pos: Array.<number>,
- * rot: Array.<number>,
- * scl: Array.<number>
- * }>
- * }>
- * }}
- */
- var animationData = {
- name: stack.name,
- fps: 30,
- length: stack.length,
- hierarchy: []
- };
- var bones = group.skeleton.bones;
- for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
- var bone = bones[ bonesIndex ];
- var name = bone.name.replace( /.*:/, '' );
- var parentIndex = findIndex( bones, function ( parentBone ) {
- return bone.parent === parentBone;
- } );
- animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
- }
- for ( var frame = 0; frame <= stack.frames; frame ++ ) {
- for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
- var bone = bones[ bonesIndex ];
- var boneIndex = bonesIndex;
- var animationNode = stack.layers[ 0 ][ boneIndex ];
- for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
- var node = animationData.hierarchy[ hierarchyIndex ];
- if ( node.name === bone.name ) {
- node.keys.push( generateKey( animations, animationNode, bone, frame ) );
- }
- }
- }
- }
- group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
- }
- }
- var euler = new THREE.Euler();
- var quaternion = new THREE.Quaternion();
- /**
- * @param {THREE.Bone} bone
- */
- function generateKey( animations, animationNode, bone, frame ) {
- var key = {
- time: frame / animations.fps,
- pos: bone.position.toArray(),
- rot: bone.quaternion.toArray(),
- scl: bone.scale.toArray()
- };
- if ( animationNode === undefined ) return key;
- try {
- if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
- key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
- }
- if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
- var rotationX = animationNode.R.curves.x.values[ frame ];
- var rotationY = animationNode.R.curves.y.values[ frame ];
- var rotationZ = animationNode.R.curves.z.values[ frame ];
- quaternion.setFromEuler( euler.set( rotationX, rotationY, rotationZ, 'ZYX' ) );
- key.rot = quaternion.toArray();
- }
- if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
- key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
- }
- } catch ( error ) {
- // Curve is not fully plotted.
- console.log( 'THREE.FBXLoader: ', bone );
- console.log( 'THREE.FBXLoader: ', error );
- }
- return key;
- }
- var AXES = [ 'x', 'y', 'z' ];
- function hasCurve( animationNode, attribute ) {
- if ( animationNode === undefined ) {
- return false;
- }
- var attributeNode = animationNode[ attribute ];
- if ( ! attributeNode ) {
- return false;
- }
- return AXES.every( function ( key ) {
- return attributeNode.curves[ key ] !== null;
- } );
- }
- function hasKeyOnFrame( attributeNode, frame ) {
- return AXES.every( function ( key ) {
- return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
- } );
- }
- function isKeyExistOnFrame( curve, frame ) {
- return curve.values[ frame ] !== undefined;
- }
- /**
- * An instance of a Vertex with data for drawing vertices to the screen.
- * @constructor
- */
- function Vertex() {
- /**
- * Position of the vertex.
- * @type {THREE.Vector3}
- */
- this.position = new THREE.Vector3();
- /**
- * Normal of the vertex
- * @type {THREE.Vector3}
- */
- this.normal = new THREE.Vector3();
- /**
- * UV coordinates of the vertex.
- * @type {THREE.Vector2}
- */
- this.uv = new THREE.Vector2();
- /**
- * Color of the vertex
- * @type {THREE.Vector3}
- */
- this.color = new THREE.Vector3();
- /**
- * Indices of the bones vertex is influenced by.
- * @type {THREE.Vector4}
- */
- this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
- /**
- * Weights that each bone influences the vertex.
- * @type {THREE.Vector4}
- */
- this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
- }
- Object.assign( Vertex.prototype, {
- copy: function ( target ) {
- var returnVar = target || new Vertex();
- returnVar.position.copy( this.position );
- returnVar.normal.copy( this.normal );
- returnVar.uv.copy( this.uv );
- returnVar.skinIndices.copy( this.skinIndices );
- returnVar.skinWeights.copy( this.skinWeights );
- return returnVar;
- },
- flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
- this.position.toArray( vertexBuffer, vertexBuffer.length );
- this.normal.toArray( normalBuffer, normalBuffer.length );
- this.uv.toArray( uvBuffer, uvBuffer.length );
- this.color.toArray( colorBuffer, colorBuffer.length );
- this.skinIndices.toArray( skinIndexBuffer, skinIndexBuffer.length );
- this.skinWeights.toArray( skinWeightBuffer, skinWeightBuffer.length );
- }
- } );
- /**
- * @constructor
- */
- function Triangle() {
- /**
- * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
- */
- this.vertices = [];
- }
- Object.assign( Triangle.prototype, {
- copy: function ( target ) {
- var returnVar = target || new Triangle();
- for ( var i = 0; i < this.vertices.length; ++ i ) {
- this.vertices[ i ].copy( returnVar.vertices[ i ] );
- }
- return returnVar;
- },
- flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
- var vertices = this.vertices;
- for ( var i = 0, l = vertices.length; i < l; ++ i ) {
- vertices[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
- }
- }
- } );
- /**
- * @constructor
- */
- function Face() {
- /**
- * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
- */
- this.triangles = [];
- this.materialIndex = 0;
- }
- Object.assign( Face.prototype, {
- copy: function ( target ) {
- var returnVar = target || new Face();
- for ( var i = 0; i < this.triangles.length; ++ i ) {
- this.triangles[ i ].copy( returnVar.triangles[ i ] );
- }
- returnVar.materialIndex = this.materialIndex;
- return returnVar;
- },
- genTrianglesFromVertices: function ( vertexArray ) {
- for ( var i = 2; i < vertexArray.length; ++ i ) {
- var triangle = new Triangle();
- triangle.vertices[ 0 ] = vertexArray[ 0 ];
- triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
- triangle.vertices[ 2 ] = vertexArray[ i ];
- this.triangles.push( triangle );
- }
- },
- flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer ) {
- var triangles = this.triangles;
- var materialIndex = this.materialIndex;
- for ( var i = 0, l = triangles.length; i < l; ++ i ) {
- triangles[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
- append( materialIndexBuffer, [ materialIndex, materialIndex, materialIndex ] );
- }
- }
- } );
- /**
- * @constructor
- */
- function Geometry() {
- /**
- * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
- */
- this.faces = [];
- /**
- * @type {{}|THREE.Skeleton}
- */
- this.skeleton = null;
- }
- Object.assign( Geometry.prototype, {
- /**
- * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
- */
- flattenToBuffers: function () {
- var vertexBuffer = [];
- var normalBuffer = [];
- var uvBuffer = [];
- var colorBuffer = [];
- var skinIndexBuffer = [];
- var skinWeightBuffer = [];
- var materialIndexBuffer = [];
- var faces = this.faces;
- for ( var i = 0, l = faces.length; i < l; ++ i ) {
- faces[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer );
- }
- return {
- vertexBuffer: vertexBuffer,
- normalBuffer: normalBuffer,
- uvBuffer: uvBuffer,
- colorBuffer: colorBuffer,
- skinIndexBuffer: skinIndexBuffer,
- skinWeightBuffer: skinWeightBuffer,
- materialIndexBuffer: materialIndexBuffer
- };
- }
- } );
- function TextParser() {}
- Object.assign( TextParser.prototype, {
- getPrevNode: function () {
- return this.nodeStack[ this.currentIndent - 2 ];
- },
- getCurrentNode: function () {
- return this.nodeStack[ this.currentIndent - 1 ];
- },
- getCurrentProp: function () {
- return this.currentProp;
- },
- pushStack: function ( node ) {
- this.nodeStack.push( node );
- this.currentIndent += 1;
- },
- popStack: function () {
- this.nodeStack.pop();
- this.currentIndent -= 1;
- },
- setCurrentProp: function ( val, name ) {
- this.currentProp = val;
- this.currentPropName = name;
- },
- // ----------parse ---------------------------------------------------
- parse: function ( text ) {
- this.currentIndent = 0;
- this.allNodes = new FBXTree();
- this.nodeStack = [];
- this.currentProp = [];
- this.currentPropName = '';
- var split = text.split( '\n' );
- for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
- var l = split[ lineNum ];
- // skip comment line
- if ( l.match( /^[\s\t]*;/ ) ) {
- continue;
- }
- // skip empty line
- if ( l.match( /^[\s\t]*$/ ) ) {
- continue;
- }
- // beginning of node
- var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
- var match = l.match( beginningOfNodeExp );
- if ( match ) {
- var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
- var nodeAttrs = match[ 2 ].split( ',' );
- for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
- nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
- }
- this.parseNodeBegin( l, nodeName, nodeAttrs || null );
- continue;
- }
- // node's property
- var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
- var match = l.match( propExp );
- if ( match ) {
- var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
- var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
- // for special case: base64 image data follows "Content: ," line
- // Content: ,
- // "iVB..."
- if ( propName === 'Content' && propValue === ',' ) {
- propValue = split[ ++ lineNum ].replace( /"/g, '' ).trim();
- }
- this.parseNodeProperty( l, propName, propValue );
- continue;
- }
- // end of node
- var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
- if ( l.match( endOfNodeExp ) ) {
- this.nodeEnd();
- continue;
- }
- // for special case,
- //
- // Vertices: *8670 {
- // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
- // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
- // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
- // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
- //
- // these case the lines must contiue with previous line
- if ( l.match( /^[^\s\t}]/ ) ) {
- this.parseNodePropertyContinued( l );
- }
- }
- return this.allNodes;
- },
- parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
- // var nodeName = match[1];
- var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
- var attrs = this.parseNodeAttr( nodeAttrs );
- var currentNode = this.getCurrentNode();
- // a top node
- if ( this.currentIndent === 0 ) {
- this.allNodes.add( nodeName, node );
- } else {
- // a subnode
- // already exists subnode, then append it
- if ( nodeName in currentNode.subNodes ) {
- var tmp = currentNode.subNodes[ nodeName ];
- // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
- if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
- if ( attrs.id === '' ) {
- currentNode.subNodes[ nodeName ] = [];
- currentNode.subNodes[ nodeName ].push( tmp );
- } else {
- currentNode.subNodes[ nodeName ] = {};
- currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
- }
- }
- if ( attrs.id === '' ) {
- currentNode.subNodes[ nodeName ].push( node );
- } else {
- currentNode.subNodes[ nodeName ][ attrs.id ] = node;
- }
- } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
- currentNode.subNodes[ nodeName ] = {};
- currentNode.subNodes[ nodeName ][ attrs.id ] = node;
- } else {
- currentNode.subNodes[ nodeName ] = node;
- }
- }
- // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
- // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
- if ( nodeAttrs ) {
- node.id = attrs.id;
- node.attrName = attrs.name;
- node.attrType = attrs.type;
- }
- this.pushStack( node );
- },
- parseNodeAttr: function ( attrs ) {
- var id = attrs[ 0 ];
- if ( attrs[ 0 ] !== '' ) {
- id = parseInt( attrs[ 0 ] );
- if ( isNaN( id ) ) {
- // PolygonVertexIndex: *16380 {
- id = attrs[ 0 ];
- }
- }
- var name = '', type = '';
- if ( attrs.length > 1 ) {
- name = attrs[ 1 ].replace( /^(\w+)::/, '' );
- type = attrs[ 2 ];
- }
- return { id: id, name: name, type: type };
- },
- parseNodeProperty: function ( line, propName, propValue ) {
- var currentNode = this.getCurrentNode();
- var parentName = currentNode.name;
- // special case parent node's is like "Properties70"
- // these children nodes must treat with careful
- if ( parentName !== undefined ) {
- var propMatch = parentName.match( /Properties(\d)+/ );
- if ( propMatch ) {
- this.parseNodeSpecialProperty( line, propName, propValue );
- return;
- }
- }
- // special case Connections
- if ( propName === 'C' ) {
- var connProps = propValue.split( ',' ).slice( 1 );
- var from = parseInt( connProps[ 0 ] );
- var to = parseInt( connProps[ 1 ] );
- var rest = propValue.split( ',' ).slice( 3 );
- propName = 'connections';
- propValue = [ from, to ];
- append( propValue, rest );
- if ( currentNode.properties[ propName ] === undefined ) {
- currentNode.properties[ propName ] = [];
- }
- }
- // special case Connections
- if ( propName === 'Node' ) {
- var id = parseInt( propValue );
- currentNode.properties.id = id;
- currentNode.id = id;
- }
- // already exists in properties, then append this
- if ( propName in currentNode.properties ) {
- // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
- if ( Array.isArray( currentNode.properties[ propName ] ) ) {
- currentNode.properties[ propName ].push( propValue );
- } else {
- currentNode.properties[ propName ] += propValue;
- }
- } else {
- // console.log( propName + ": " + propValue );
- if ( Array.isArray( currentNode.properties[ propName ] ) ) {
- currentNode.properties[ propName ].push( propValue );
- } else {
- currentNode.properties[ propName ] = propValue;
- }
- }
- this.setCurrentProp( currentNode.properties, propName );
- },
- // TODO:
- parseNodePropertyContinued: function ( line ) {
- this.currentProp[ this.currentPropName ] += line;
- },
- parseNodeSpecialProperty: function ( line, propName, propValue ) {
- // split this
- // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
- // into array like below
- // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
- var props = propValue.split( '",' );
- for ( var i = 0, l = props.length; i < l; i ++ ) {
- props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
- }
- var innerPropName = props[ 0 ];
- var innerPropType1 = props[ 1 ];
- var innerPropType2 = props[ 2 ];
- var innerPropFlag = props[ 3 ];
- var innerPropValue = props[ 4 ];
- /*
- if ( innerPropValue === undefined ) {
- innerPropValue = props[3];
- }
- */
- // cast value in its type
- switch ( innerPropType1 ) {
- case 'int':
- innerPropValue = parseInt( innerPropValue );
- break;
- case 'double':
- innerPropValue = parseFloat( innerPropValue );
- break;
- case 'ColorRGB':
- case 'Vector3D':
- innerPropValue = parseFloatArray( innerPropValue );
- break;
- }
- // CAUTION: these props must append to parent's parent
- this.getPrevNode().properties[ innerPropName ] = {
- 'type': innerPropType1,
- 'type2': innerPropType2,
- 'flag': innerPropFlag,
- 'value': innerPropValue
- };
- this.setCurrentProp( this.getPrevNode().properties, innerPropName );
- },
- nodeEnd: function () {
- this.popStack();
- },
- /* ---------------------------------------------------------------- */
- /* util */
- isFlattenNode: function ( node ) {
- return ( 'subNodes' in node && 'properties' in node ) ? true : false;
- }
- } );
- // Binary format specification:
- // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
- // https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
- function BinaryParser() {}
- Object.assign( BinaryParser.prototype, {
- /**
- * Parses binary data and builds FBXTree as much compatible as possible with the one built by TextParser.
- * @param {ArrayBuffer} buffer
- * @returns {THREE.FBXTree}
- */
- parse: function ( buffer ) {
- var reader = new BinaryReader( buffer );
- reader.skip( 23 ); // skip magic 23 bytes
- var version = reader.getUint32();
- console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
- var allNodes = new FBXTree();
- while ( ! this.endOfContent( reader ) ) {
- var node = this.parseNode( reader, version );
- if ( node !== null ) allNodes.add( node.name, node );
- }
- return allNodes;
- },
- /**
- * Checks if reader has reached the end of content.
- * @param {BinaryReader} reader
- * @returns {boolean}
- */
- endOfContent: function( reader ) {
- // footer size: 160bytes + 16-byte alignment padding
- // - 16bytes: magic
- // - padding til 16-byte alignment (at least 1byte?)
- // (seems like some exporters embed fixed 15 or 16bytes?)
- // - 4bytes: magic
- // - 4bytes: version
- // - 120bytes: zero
- // - 16bytes: magic
- if ( reader.size() % 16 === 0 ) {
- return ( ( reader.getOffset() + 160 + 16 ) & ~0xf ) >= reader.size();
- } else {
- return reader.getOffset() + 160 + 16 >= reader.size();
- }
- },
- /**
- * Parses Node as much compatible as possible with the one parsed by TextParser
- * TODO: could be optimized more?
- * @param {BinaryReader} reader
- * @param {number} version
- * @returns {Object} - Returns an Object as node, or null if NULL-record.
- */
- parseNode: function ( reader, version ) {
- // The first three data sizes depends on version.
- var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
- var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
- var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
- var nameLen = reader.getUint8();
- var name = reader.getString( nameLen );
- // Regards this node as NULL-record if endOffset is zero
- if ( endOffset === 0 ) return null;
- var propertyList = [];
- for ( var i = 0; i < numProperties; i ++ ) {
- propertyList.push( this.parseProperty( reader ) );
- }
- // Regards the first three elements in propertyList as id, attrName, and attrType
- var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
- var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
- var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
- var subNodes = {};
- var properties = {};
- var isSingleProperty = false;
- // if this node represents just a single property
- // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
- if ( numProperties === 1 && reader.getOffset() === endOffset ) {
- isSingleProperty = true;
- }
- while ( endOffset > reader.getOffset() ) {
- var node = this.parseNode( reader, version );
- if ( node === null ) continue;
- // special case: child node is single property
- if ( node.singleProperty === true ) {
- var value = node.propertyList[ 0 ];
- if ( Array.isArray( value ) ) {
- // node represents
- // Vertices: *3 {
- // a: 0.01, 0.02, 0.03
- // }
- // of text format here.
- node.properties[ node.name ] = node.propertyList[ 0 ];
- subNodes[ node.name ] = node;
- // Later phase expects single property array is in node.properties.a as String.
- // TODO: optimize
- node.properties.a = value.toString();
- } else {
- // node represents
- // Version: 100
- // of text format here.
- properties[ node.name ] = value;
- }
- continue;
- }
- // special case: connections
- if ( name === 'Connections' && node.name === 'C' ) {
- var array = [];
- // node.propertyList would be like
- // ["OO", 111264976, 144038752, "d|x"] (?, from, to, additional values)
- for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
- array[ i - 1 ] = node.propertyList[ i ];
- }
- if ( properties.connections === undefined ) {
- properties.connections = [];
- }
- properties.connections.push( array );
- continue;
- }
- // special case: child node is Properties\d+
- if ( node.name.match( /^Properties\d+$/ ) ) {
- // move child node's properties to this node.
- var keys = Object.keys( node.properties );
- for ( var i = 0, il = keys.length; i < il; i ++ ) {
- var key = keys[ i ];
- properties[ key ] = node.properties[ key ];
- }
- continue;
- }
- // special case: properties
- if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
- var innerPropName = node.propertyList[ 0 ];
- var innerPropType1 = node.propertyList[ 1 ];
- var innerPropType2 = node.propertyList[ 2 ];
- var innerPropFlag = node.propertyList[ 3 ];
- var innerPropValue;
- if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
- if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
- if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' ||
- innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
- innerPropValue = [
- node.propertyList[ 4 ],
- node.propertyList[ 5 ],
- node.propertyList[ 6 ]
- ];
- } else {
- innerPropValue = node.propertyList[ 4 ];
- }
- if ( innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
- innerPropValue = innerPropValue.toString();
- }
- // this will be copied to parent. see above.
- properties[ innerPropName ] = {
- 'type': innerPropType1,
- 'type2': innerPropType2,
- 'flag': innerPropFlag,
- 'value': innerPropValue
- };
- continue;
- }
- // standard case
- // follows TextParser's manner.
- if ( subNodes[ node.name ] === undefined ) {
- if ( typeof node.id === 'number' ) {
- subNodes[ node.name ] = {};
- subNodes[ node.name ][ node.id ] = node;
- } else {
- subNodes[ node.name ] = node;
- }
- } else {
- if ( node.id === '' ) {
- if ( ! Array.isArray( subNodes[ node.name ] ) ) {
- subNodes[ node.name ] = [ subNodes[ node.name ] ];
- }
- subNodes[ node.name ].push( node );
- } else {
- if ( subNodes[ node.name ][ node.id ] === undefined ) {
- subNodes[ node.name ][ node.id ] = node;
- } else {
- // conflict id. irregular?
- if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
- subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
- }
- subNodes[ node.name ][ node.id ].push( node );
- }
- }
- }
- }
- return {
- singleProperty: isSingleProperty,
- id: id,
- attrName: attrName,
- attrType: attrType,
- name: name,
- properties: properties,
- propertyList: propertyList, // raw property list, would be used by parent
- subNodes: subNodes
- };
- },
- parseProperty: function ( reader ) {
- var type = reader.getChar();
- switch ( type ) {
- case 'F':
- return reader.getFloat32();
- case 'D':
- return reader.getFloat64();
- case 'L':
- return reader.getInt64();
- case 'I':
- return reader.getInt32();
- case 'Y':
- return reader.getInt16();
- case 'C':
- return reader.getBoolean();
- case 'f':
- case 'd':
- case 'l':
- case 'i':
- case 'b':
- var arrayLength = reader.getUint32();
- var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
- var compressedLength = reader.getUint32();
- if ( encoding === 0 ) {
- switch ( type ) {
- case 'f':
- return reader.getFloat32Array( arrayLength );
- case 'd':
- return reader.getFloat64Array( arrayLength );
- case 'l':
- return reader.getInt64Array( arrayLength );
- case 'i':
- return reader.getInt32Array( arrayLength );
- case 'b':
- return reader.getBooleanArray( arrayLength );
- }
- }
- if ( window.Zlib === undefined ) {
- throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
- }
- var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) );
- var reader2 = new BinaryReader( inflate.decompress().buffer );
- switch ( type ) {
- case 'f':
- return reader2.getFloat32Array( arrayLength );
- case 'd':
- return reader2.getFloat64Array( arrayLength );
- case 'l':
- return reader2.getInt64Array( arrayLength );
- case 'i':
- return reader2.getInt32Array( arrayLength );
- case 'b':
- return reader2.getBooleanArray( arrayLength );
- }
- case 'S':
- var length = reader.getUint32();
- return reader.getString( length );
- case 'R':
- var length = reader.getUint32();
- return reader.getArrayBuffer( length );
- default:
- throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
- }
- }
- } );
- function BinaryReader( buffer, littleEndian ) {
- this.dv = new DataView( buffer );
- this.offset = 0;
- this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
- }
- Object.assign( BinaryReader.prototype, {
- getOffset: function () {
- return this.offset;
- },
- size: function () {
- return this.dv.buffer.byteLength;
- },
- skip: function ( length ) {
- this.offset += length;
- },
- // seems like true/false representation depends on exporter.
- // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
- // then sees LSB.
- getBoolean: function () {
- return ( this.getUint8() & 1 ) === 1;
- },
- getBooleanArray: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getBoolean() );
- }
- return a;
- },
- getInt8: function () {
- var value = this.dv.getInt8( this.offset );
- this.offset += 1;
- return value;
- },
- getInt8Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getInt8() );
- }
- return a;
- },
- getUint8: function () {
- var value = this.dv.getUint8( this.offset );
- this.offset += 1;
- return value;
- },
- getUint8Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getUint8() );
- }
- return a;
- },
- getInt16: function () {
- var value = this.dv.getInt16( this.offset, this.littleEndian );
- this.offset += 2;
- return value;
- },
- getInt16Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getInt16() );
- }
- return a;
- },
- getUint16: function () {
- var value = this.dv.getUint16( this.offset, this.littleEndian );
- this.offset += 2;
- return value;
- },
- getUint16Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getUint16() );
- }
- return a;
- },
- getInt32: function () {
- var value = this.dv.getInt32( this.offset, this.littleEndian );
- this.offset += 4;
- return value;
- },
- getInt32Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getInt32() );
- }
- return a;
- },
- getUint32: function () {
- var value = this.dv.getUint32( this.offset, this.littleEndian );
- this.offset += 4;
- return value;
- },
- getUint32Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getUint32() );
- }
- return a;
- },
- // JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
- // 1 << 32 will return 1 so using multiply operation instead here.
- // There'd be a possibility that this method returns wrong value if the value
- // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
- // TODO: safely handle 64-bit integer
- getInt64: function () {
- var low, high;
- if ( this.littleEndian ) {
- low = this.getUint32();
- high = this.getUint32();
- } else {
- high = this.getUint32();
- low = this.getUint32();
- }
- // calculate negative value
- if ( high & 0x80000000 ) {
- high = ~high & 0xFFFFFFFF;
- low = ~low & 0xFFFFFFFF;
- if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
- low = ( low + 1 ) & 0xFFFFFFFF;
- return - ( high * 0x100000000 + low );
- }
- return high * 0x100000000 + low;
- },
- getInt64Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getInt64() );
- }
- return a;
- },
- // Note: see getInt64() comment
- getUint64: function () {
- var low, high;
- if ( this.littleEndian ) {
- low = this.getUint32();
- high = this.getUint32();
- } else {
- high = this.getUint32();
- low = this.getUint32();
- }
- return high * 0x100000000 + low;
- },
- getUint64Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getUint64() );
- }
- return a;
- },
- getFloat32: function () {
- var value = this.dv.getFloat32( this.offset, this.littleEndian );
- this.offset += 4;
- return value;
- },
- getFloat32Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getFloat32() );
- }
- return a;
- },
- getFloat64: function () {
- var value = this.dv.getFloat64( this.offset, this.littleEndian );
- this.offset += 8;
- return value;
- },
- getFloat64Array: function ( size ) {
- var a = [];
- for ( var i = 0; i < size; i ++ ) {
- a.push( this.getFloat64() );
- }
- return a;
- },
- getArrayBuffer: function ( size ) {
- var value = this.dv.buffer.slice( this.offset, this.offset + size );
- this.offset += size;
- return value;
- },
- getChar: function () {
- return String.fromCharCode( this.getUint8() );
- },
- getString: function ( size ) {
- var s = '';
- while ( size > 0 ) {
- var value = this.getUint8();
- size--;
- if ( value === 0 ) break;
- s += String.fromCharCode( value );
- }
- this.skip( size );
- return s;
- }
- } );
- function FBXTree() {}
- Object.assign( FBXTree.prototype, {
- add: function ( key, val ) {
- this[ key ] = val;
- },
- searchConnectionParent: function ( id ) {
- if ( this.__cache_search_connection_parent === undefined ) {
- this.__cache_search_connection_parent = [];
- }
- if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
- return this.__cache_search_connection_parent[ id ];
- } else {
- this.__cache_search_connection_parent[ id ] = [];
- }
- var conns = this.Connections.properties.connections;
- var results = [];
- for ( var i = 0; i < conns.length; ++ i ) {
- if ( conns[ i ][ 0 ] == id ) {
- // 0 means scene root
- var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
- results.push( res );
- }
- }
- if ( results.length > 0 ) {
- append( this.__cache_search_connection_parent[ id ], results );
- return results;
- } else {
- this.__cache_search_connection_parent[ id ] = [ - 1 ];
- return [ - 1 ];
- }
- },
- searchConnectionChildren: function ( id ) {
- if ( this.__cache_search_connection_children === undefined ) {
- this.__cache_search_connection_children = [];
- }
- if ( this.__cache_search_connection_children[ id ] !== undefined ) {
- return this.__cache_search_connection_children[ id ];
- } else {
- this.__cache_search_connection_children[ id ] = [];
- }
- var conns = this.Connections.properties.connections;
- var res = [];
- for ( var i = 0; i < conns.length; ++ i ) {
- if ( conns[ i ][ 1 ] == id ) {
- // 0 means scene root
- res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
- // there may more than one kid, then search to the end
- }
- }
- if ( res.length > 0 ) {
- append( this.__cache_search_connection_children[ id ], res );
- return res;
- } else {
- this.__cache_search_connection_children[ id ] = [ ];
- return [ ];
- }
- },
- searchConnectionType: function ( id, to ) {
- var key = id + ',' + to; // TODO: to hash
- if ( this.__cache_search_connection_type === undefined ) {
- this.__cache_search_connection_type = {};
- }
- if ( this.__cache_search_connection_type[ key ] !== undefined ) {
- return this.__cache_search_connection_type[ key ];
- } else {
- this.__cache_search_connection_type[ key ] = '';
- }
- var conns = this.Connections.properties.connections;
- for ( var i = 0; i < conns.length; ++ i ) {
- if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
- // 0 means scene root
- this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
- return conns[ i ][ 2 ];
- }
- }
- this.__cache_search_connection_type[ id ] = null;
- return null;
- }
- } );
- /**
- * @param {ArrayBuffer} buffer
- * @returns {boolean}
- */
- function isFbxFormatBinary( buffer ) {
- var CORRECT = 'Kaydara FBX Binary \0';
- return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
- }
- /**
- * @returns {boolean}
- */
- function isFbxFormatASCII( text ) {
- var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
- var cursor = 0;
- function read( offset ) {
- var result = text[ offset - 1 ];
- text = text.slice( cursor + offset );
- cursor ++;
- return result;
- }
- for ( var i = 0; i < CORRECT.length; ++ i ) {
- var num = read( 1 );
- if ( num === CORRECT[ i ] ) {
- return false;
- }
- }
- return true;
- }
- /**
- * @returns {number}
- */
- function getFbxVersion( text ) {
- var versionRegExp = /FBXVersion: (\d+)/;
- var match = text.match( versionRegExp );
- if ( match ) {
- var version = parseInt( match[ 1 ] );
- return version;
- }
- throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
- }
- /**
- * Converts FBX ticks into real time seconds.
- * @param {number} time - FBX tick timestamp to convert.
- * @returns {number} - FBX tick in real world time.
- */
- function convertFBXTimeToSeconds( time ) {
- // Constant is FBX ticks per second.
- return time / 46186158000;
- }
- /**
- * Parses comma separated list of float numbers and returns them in an array.
- * @example
- * // Returns [ 5.6, 9.4, 2.5, 1.4 ]
- * parseFloatArray( "5.6,9.4,2.5,1.4" )
- * @returns {number[]}
- */
- function parseFloatArray( string ) {
- var array = string.split( ',' );
- for ( var i = 0, l = array.length; i < l; i ++ ) {
- array[ i ] = parseFloat( array[ i ] );
- }
- return array;
- }
- /**
- * Parses comma separated list of int numbers and returns them in an array.
- * @example
- * // Returns [ 5, 8, 2, 3 ]
- * parseFloatArray( "5,8,2,3" )
- * @returns {number[]}
- */
- function parseIntArray( string ) {
- var array = string.split( ',' );
- for ( var i = 0, l = array.length; i < l; i ++ ) {
- array[ i ] = parseInt( array[ i ] );
- }
- return array;
- }
- /**
- * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
- * @param {FBXVector3} property - Property to parse as Vector3.
- * @returns {THREE.Vector3}
- */
- function parseVector3( property ) {
- return new THREE.Vector3().fromArray( property.value );
- }
- /**
- * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
- * @param {FBXVector3} property - Property to parse as Color.
- * @returns {THREE.Color}
- */
- function parseColor( property ) {
- return new THREE.Color().fromArray( property.value );
- }
- function parseMatrixArray( floatString ) {
- return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
- }
- /**
- * Converts ArrayBuffer to String.
- * @param {ArrayBuffer} buffer
- * @param {number} from
- * @param {number} to
- * @returns {String}
- */
- function convertArrayBufferToString( buffer, from, to ) {
- if ( from === undefined ) from = 0;
- if ( to === undefined ) to = buffer.byteLength;
- var array = new Uint8Array( buffer, from, to );
- if ( window.TextDecoder !== undefined ) {
- return new TextDecoder().decode( array );
- }
- var s = '';
- for ( var i = 0, il = array.length; i < il; i ++ ) {
- s += String.fromCharCode( array[ i ] );
- }
- return s;
- }
- /**
- * Converts number from degrees into radians.
- * @param {number} value
- * @returns {number}
- */
- function degreeToRadian( value ) {
- return value * DEG2RAD;
- }
- var DEG2RAD = Math.PI / 180;
- //
- function findIndex( array, func ) {
- for ( var i = 0, l = array.length; i < l; i ++ ) {
- if ( func( array[ i ] ) ) return i;
- }
- return -1;
- }
- function append( a, b ) {
- for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
- a[ j ] = b[ i ];
- }
- }
- function slice( a, b, from, to ) {
- for ( var i = from, j = 0; i < to; i ++, j ++ ) {
- a[ j ] = b[ i ];
- }
- return a;
- }
- } )();
- },{}],3:[function(require,module,exports){
- /**
- * @author Wei Meng / http://about.me/menway
- *
- * Description: A THREE loader for PLY ASCII files (known as the Polygon File Format or the Stanford Triangle Format).
- *
- *
- * Limitations: ASCII decoding assumes file is UTF-8.
- *
- * Usage:
- * var loader = new THREE.PLYLoader();
- * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) {
- *
- * scene.add( new THREE.Mesh( geometry ) );
- *
- * } );
- *
- * If the PLY file uses non standard property names, they can be mapped while
- * loading. For example, the following maps the properties
- * “diffuse_(red|green|blue)” in the file to standard color names.
- *
- * loader.setPropertyNameMapping( {
- * diffuse_red: 'red',
- * diffuse_green: 'green',
- * diffuse_blue: 'blue'
- * } );
- *
- */
- module.exports = THREE.PLYLoader = function ( manager ) {
- this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
- this.propertyNameMapping = {};
- };
- THREE.PLYLoader.prototype = {
- constructor: THREE.PLYLoader,
- load: function ( url, onLoad, onProgress, onError ) {
- var scope = this;
- var loader = new THREE.XHRLoader( this.manager );
- loader.setResponseType( 'arraybuffer' );
- loader.load( url, function ( text ) {
- onLoad( scope.parse( text ) );
- }, onProgress, onError );
- },
- setPropertyNameMapping: function ( mapping ) {
- this.propertyNameMapping = mapping;
- },
- bin2str: function ( buf ) {
- var array_buffer = new Uint8Array( buf );
- var str = '';
- for ( var i = 0; i < buf.byteLength; i ++ ) {
- str += String.fromCharCode( array_buffer[ i ] ); // implicitly assumes little-endian
- }
- return str;
- },
- isASCII: function( data ) {
- var header = this.parseHeader( this.bin2str( data ) );
- return header.format === "ascii";
- },
- parse: function ( data ) {
- if ( data instanceof ArrayBuffer ) {
- return this.isASCII( data )
- ? this.parseASCII( this.bin2str( data ) )
- : this.parseBinary( data );
- } else {
- return this.parseASCII( data );
- }
- },
- parseHeader: function ( data ) {
- var patternHeader = /ply([\s\S]*)end_header\s/;
- var headerText = "";
- var headerLength = 0;
- var result = patternHeader.exec( data );
- if ( result !== null ) {
- headerText = result [ 1 ];
- headerLength = result[ 0 ].length;
- }
- var header = {
- comments: [],
- elements: [],
- headerLength: headerLength
- };
- var lines = headerText.split( '\n' );
- var currentElement = undefined;
- var lineType, lineValues;
- function make_ply_element_property( propertValues, propertyNameMapping ) {
- var property = {
- type: propertValues[ 0 ]
- };
- if ( property.type === 'list' ) {
- property.name = propertValues[ 3 ];
- property.countType = propertValues[ 1 ];
- property.itemType = propertValues[ 2 ];
- } else {
- property.name = propertValues[ 1 ];
- }
- if ( property.name in propertyNameMapping ) {
- property.name = propertyNameMapping[ property.name ];
- }
- return property;
- }
- for ( var i = 0; i < lines.length; i ++ ) {
- var line = lines[ i ];
- line = line.trim();
- if ( line === "" ) {
- continue;
- }
- lineValues = line.split( /\s+/ );
- lineType = lineValues.shift();
- line = lineValues.join( " " );
- switch ( lineType ) {
- case "format":
- header.format = lineValues[ 0 ];
- header.version = lineValues[ 1 ];
- break;
- case "comment":
- header.comments.push( line );
- break;
- case "element":
- if ( ! ( currentElement === undefined ) ) {
- header.elements.push( currentElement );
- }
- currentElement = Object();
- currentElement.name = lineValues[ 0 ];
- currentElement.count = parseInt( lineValues[ 1 ] );
- currentElement.properties = [];
- break;
- case "property":
- currentElement.properties.push( make_ply_element_property( lineValues, this.propertyNameMapping ) );
- break;
- default:
- console.log( "unhandled", lineType, lineValues );
- }
- }
- if ( ! ( currentElement === undefined ) ) {
- header.elements.push( currentElement );
- }
- return header;
- },
- parseASCIINumber: function ( n, type ) {
- switch ( type ) {
- case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
- case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
- return parseInt( n );
- case 'float': case 'double': case 'float32': case 'float64':
- return parseFloat( n );
- }
- },
- parseASCIIElement: function ( properties, line ) {
- var values = line.split( /\s+/ );
- var element = Object();
- for ( var i = 0; i < properties.length; i ++ ) {
- if ( properties[ i ].type === "list" ) {
- var list = [];
- var n = this.parseASCIINumber( values.shift(), properties[ i ].countType );
- for ( var j = 0; j < n; j ++ ) {
- list.push( this.parseASCIINumber( values.shift(), properties[ i ].itemType ) );
- }
- element[ properties[ i ].name ] = list;
- } else {
- element[ properties[ i ].name ] = this.parseASCIINumber( values.shift(), properties[ i ].type );
- }
- }
- return element;
- },
- parseASCII: function ( data ) {
- // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
- var geometry = new THREE.Geometry();
- var result;
- var header = this.parseHeader( data );
- var patternBody = /end_header\s([\s\S]*)$/;
- var body = "";
- if ( ( result = patternBody.exec( data ) ) !== null ) {
- body = result [ 1 ];
- }
- var lines = body.split( '\n' );
- var currentElement = 0;
- var currentElementCount = 0;
- geometry.useColor = false;
- for ( var i = 0; i < lines.length; i ++ ) {
- var line = lines[ i ];
- line = line.trim();
- if ( line === "" ) {
- continue;
- }
- if ( currentElementCount >= header.elements[ currentElement ].count ) {
- currentElement ++;
- currentElementCount = 0;
- }
- var element = this.parseASCIIElement( header.elements[ currentElement ].properties, line );
- this.handleElement( geometry, header.elements[ currentElement ].name, element );
- currentElementCount ++;
- }
- return this.postProcess( geometry );
- },
- postProcess: function ( geometry ) {
- if ( geometry.useColor ) {
- for ( var i = 0; i < geometry.faces.length; i ++ ) {
- geometry.faces[ i ].vertexColors = [
- geometry.colors[ geometry.faces[ i ].a ],
- geometry.colors[ geometry.faces[ i ].b ],
- geometry.colors[ geometry.faces[ i ].c ]
- ];
- }
- geometry.elementsNeedUpdate = true;
- }
- geometry.computeBoundingSphere();
- return geometry;
- },
- handleElement: function ( geometry, elementName, element ) {
- if ( elementName === "vertex" ) {
- geometry.vertices.push(
- new THREE.Vector3( element.x, element.y, element.z )
- );
- if ( 'red' in element && 'green' in element && 'blue' in element ) {
- geometry.useColor = true;
- var color = new THREE.Color();
- color.setRGB( element.red / 255.0, element.green / 255.0, element.blue / 255.0 );
- geometry.colors.push( color );
- }
- } else if ( elementName === "face" ) {
- // BEGIN: Edits by donmccurdy.
- var vertex_indices = element.vertex_indices || element.vertex_index;
- // END: Edits by donmccurdy.
- if ( vertex_indices.length === 3 ) {
- geometry.faces.push(
- new THREE.Face3( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] )
- );
- } else if ( vertex_indices.length === 4 ) {
- geometry.faces.push(
- new THREE.Face3( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] ),
- new THREE.Face3( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] )
- );
- }
- }
- },
- binaryRead: function ( dataview, at, type, little_endian ) {
- switch ( type ) {
- // corespondences for non-specific length types here match rply:
- case 'int8': case 'char': return [ dataview.getInt8( at ), 1 ];
- case 'uint8': case 'uchar': return [ dataview.getUint8( at ), 1 ];
- case 'int16': case 'short': return [ dataview.getInt16( at, little_endian ), 2 ];
- case 'uint16': case 'ushort': return [ dataview.getUint16( at, little_endian ), 2 ];
- case 'int32': case 'int': return [ dataview.getInt32( at, little_endian ), 4 ];
- case 'uint32': case 'uint': return [ dataview.getUint32( at, little_endian ), 4 ];
- case 'float32': case 'float': return [ dataview.getFloat32( at, little_endian ), 4 ];
- case 'float64': case 'double': return [ dataview.getFloat64( at, little_endian ), 8 ];
- }
- },
- binaryReadElement: function ( dataview, at, properties, little_endian ) {
- var element = Object();
- var result, read = 0;
- for ( var i = 0; i < properties.length; i ++ ) {
- if ( properties[ i ].type === "list" ) {
- var list = [];
- result = this.binaryRead( dataview, at + read, properties[ i ].countType, little_endian );
- var n = result[ 0 ];
- read += result[ 1 ];
- for ( var j = 0; j < n; j ++ ) {
- result = this.binaryRead( dataview, at + read, properties[ i ].itemType, little_endian );
- list.push( result[ 0 ] );
- read += result[ 1 ];
- }
- element[ properties[ i ].name ] = list;
- } else {
- result = this.binaryRead( dataview, at + read, properties[ i ].type, little_endian );
- element[ properties[ i ].name ] = result[ 0 ];
- read += result[ 1 ];
- }
- }
- return [ element, read ];
- },
- parseBinary: function ( data ) {
- var geometry = new THREE.Geometry();
- var header = this.parseHeader( this.bin2str( data ) );
- var little_endian = ( header.format === "binary_little_endian" );
- var body = new DataView( data, header.headerLength );
- var result, loc = 0;
- for ( var currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
- for ( var currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) {
- result = this.binaryReadElement( body, loc, header.elements[ currentElement ].properties, little_endian );
- loc += result[ 1 ];
- var element = result[ 0 ];
- this.handleElement( geometry, header.elements[ currentElement ].name, element );
- }
- }
- return this.postProcess( geometry );
- }
- };
- },{}],4:[function(require,module,exports){
- /**
- * Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
- */
- function getScriptId() {
- return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
- }
- function createScript(url, id) {
- var script = document.createElement('script');
- script.type = 'text/javascript';
- script.async = true;
- script.id = id;
- script.src = url;
- return script;
- }
- function removeScript(id) {
- const script = document.getElementById(id);
- const parent = script.parentNode;
- try {
- parent && parent.removeChild(script);
- } catch (e) {
- // ignore
- }
- }
- function appendScript(script) {
- const firstScript = document.getElementsByTagName('script')[0];
- firstScript.parentNode.insertBefore(script, firstScript);
- }
- function fetchScriptInternal(url, options, Promise) {
- return new Promise(function(resolve, reject) {
- const timeout = options.timeout || 5000;
- const scriptId = getScriptId();
- const script = createScript(url, scriptId);
- const timeoutId = setTimeout(function() {
- reject(new Error('Script request to ' + url + ' timed out'));
- removeScript(scriptId);
- }, timeout);
- const disableTimeout = function(timeoutId) { clearTimeout(timeoutId); };
- script.addEventListener('load', function(e) {
- resolve({ok: true});
- disableTimeout(timeoutId);
- removeScript(scriptId);
- });
- script.addEventListener('error', function(e) {
- reject(new Error('Script request to ' + url + ' failed ' + e));
- disableTimeout(timeoutId);
- removeScript(scriptId);
- });
- appendScript(script);
- });
- }
- function fetchScript(settings) {
- settings = settings || {};
- return function (url, options) {
- options = options || {};
- return fetchScriptInternal(url, options, settings.Promise || Promise);
- };
- }
- module.exports = fetchScript;
- },{}],5:[function(require,module,exports){
- var LoopMode = {
- once: THREE.LoopOnce,
- repeat: THREE.LoopRepeat,
- pingpong: THREE.LoopPingPong
- };
- /**
- * animation-mixer
- *
- * Player for animation clips. Intended to be compatible with any model format that supports
- * skeletal or morph animations through THREE.AnimationMixer.
- * See: https://threejs.org/docs/?q=animation#Reference/Animation/AnimationMixer
- */
- module.exports = {
- schema: {
- clip: {default: '*'},
- duration: {default: 0},
- crossFadeDuration: {default: 0},
- loop: {default: 'repeat', oneOf: Object.keys(LoopMode)},
- repetitions: {default: Infinity, min: 0}
- },
- init: function () {
- /** @type {THREE.Mesh} */
- this.model = null;
- /** @type {THREE.AnimationMixer} */
- this.mixer = null;
- /** @type {Array<THREE.AnimationAction>} */
- this.activeActions = [];
- var model = this.el.getObject3D('mesh');
- if (model) {
- this.load(model);
- } else {
- this.el.addEventListener('model-loaded', function(e) {
- this.load(e.detail.model);
- }.bind(this));
- }
- },
- load: function (model) {
- var el = this.el;
- this.model = model;
- this.mixer = new THREE.AnimationMixer(model);
- this.mixer.addEventListener('loop', function (e) {
- el.emit('animation-loop', {action: e.action, loopDelta: e.loopDelta});
- }.bind(this));
- this.mixer.addEventListener('finished', function (e) {
- el.emit('animation-finished', {action: e.action, direction: e.direction});
- }.bind(this));
- if (this.data.clip) this.update({});
- },
- remove: function () {
- if (this.mixer) this.mixer.stopAllAction();
- },
- update: function (previousData) {
- if (!previousData) return;
- this.stopAction();
- if (this.data.clip) {
- this.playAction();
- }
- },
- stopAction: function () {
- var data = this.data;
- for (var i = 0; i < this.activeActions.length; i++) {
- data.crossFadeDuration
- ? this.activeActions[i].fadeOut(data.crossFadeDuration)
- : this.activeActions[i].stop();
- }
- this.activeActions.length = 0;
- },
- playAction: function () {
- if (!this.mixer) return;
- var model = this.model,
- data = this.data,
- clips = model.animations || (model.geometry || {}).animations || [];
- if (!clips.length) return;
- var re = wildcardToRegExp(data.clip);
- for (var clip, i = 0; (clip = clips[i]); i++) {
- if (clip.name.match(re)) {
- var action = this.mixer.clipAction(clip, model);
- action.enabled = true;
- if (data.duration) action.setDuration(data.duration);
- action
- .setLoop(LoopMode[data.loop], data.repetitions)
- .fadeIn(data.crossFadeDuration)
- .play();
- this.activeActions.push(action);
- }
- }
- },
- tick: function (t, dt) {
- if (this.mixer && !isNaN(dt)) this.mixer.update(dt / 1000);
- }
- };
- /**
- * Creates a RegExp from the given string, converting asterisks to .* expressions,
- * and escaping all other characters.
- */
- function wildcardToRegExp (s) {
- return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$');
- }
- /**
- * RegExp-escapes all characters in the given string.
- */
- function regExpEscape (s) {
- return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
- }
- },{}],6:[function(require,module,exports){
- THREE.FBXLoader = require('../../lib/FBXLoader');
- /**
- * fbx-model
- *
- * Loader for FBX format. Supports ASCII, but *not* binary, models.
- */
- module.exports = {
- schema: {
- src: { type: 'asset' },
- crossorigin: { default: '' }
- },
- init: function () {
- this.model = null;
- },
- update: function () {
- var loader,
- data = this.data;
- if (!data.src) return;
- this.remove();
- loader = new THREE.FBXLoader();
- if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
- loader.load(data.src, this.load.bind(this));
- },
- load: function (model) {
- this.model = model;
- this.el.setObject3D('mesh', model);
- this.el.emit('model-loaded', {format: 'fbx', model: model});
- },
- remove: function () {
- if (this.model) this.el.removeObject3D('mesh');
- }
- };
- },{"../../lib/FBXLoader":2}],7:[function(require,module,exports){
- var fetchScript = require('../../lib/fetch-script')();
- var LOADER_SRC = 'https://rawgit.com/mrdoob/three.js/r86/examples/js/loaders/GLTFLoader.js';
- /**
- * Legacy loader for glTF 1.0 models.
- * Asynchronously loads THREE.GLTFLoader from rawgit.
- */
- module.exports = {
- schema: {type: 'model'},
- init: function () {
- this.model = null;
- this.loader = null;
- this.loaderPromise = loadLoader().then(function () {
- this.loader = new THREE.GLTFLoader();
- this.loader.setCrossOrigin('Anonymous');
- }.bind(this));
- },
- update: function () {
- var self = this;
- var el = this.el;
- var src = this.data;
- if (!src) { return; }
- this.remove();
- this.loaderPromise.then(function () {
- this.loader.load(src, function gltfLoaded (gltfModel) {
- self.model = gltfModel.scene;
- self.model.animations = gltfModel.animations;
- el.setObject3D('mesh', self.model);
- el.emit('model-loaded', {format: 'gltf', model: self.model});
- });
- }.bind(this));
- },
- remove: function () {
- if (!this.model) { return; }
- this.el.removeObject3D('mesh');
- }
- };
- var loadLoader = (function () {
- var promise;
- return function () {
- promise = promise || fetchScript(LOADER_SRC);
- return promise;
- };
- }());
- },{"../../lib/fetch-script":4}],8:[function(require,module,exports){
- module.exports = {
- 'animation-mixer': require('./animation-mixer'),
- 'fbx-model': require('./fbx-model'),
- 'gltf-model-legacy': require('./gltf-model-legacy'),
- 'json-model': require('./json-model'),
- 'object-model': require('./object-model'),
- 'ply-model': require('./ply-model'),
- registerAll: function (AFRAME) {
- if (this._registered) return;
- AFRAME = AFRAME || window.AFRAME;
- // THREE.AnimationMixer
- if (!AFRAME.components['animation-mixer']) {
- AFRAME.registerComponent('animation-mixer', this['animation-mixer']);
- }
- // THREE.PlyLoader
- if (!AFRAME.systems['ply-model']) {
- AFRAME.registerSystem('ply-model', this['ply-model'].System);
- }
- if (!AFRAME.components['ply-model']) {
- AFRAME.registerComponent('ply-model', this['ply-model'].Component);
- }
- // THREE.FBXLoader
- if (!AFRAME.components['fbx-model']) {
- AFRAME.registerComponent('fbx-model', this['fbx-model']);
- }
- // THREE.GLTFLoader
- if (!AFRAME.components['gltf-model-legacy']) {
- AFRAME.registerComponent('gltf-model-legacy', this['gltf-model-legacy']);
- }
- // THREE.JsonLoader
- if (!AFRAME.components['json-model']) {
- AFRAME.registerComponent('json-model', this['json-model']);
- }
- // THREE.ObjectLoader
- if (!AFRAME.components['object-model']) {
- AFRAME.registerComponent('object-model', this['object-model']);
- }
- this._registered = true;
- }
- };
- },{"./animation-mixer":5,"./fbx-model":6,"./gltf-model-legacy":7,"./json-model":9,"./object-model":10,"./ply-model":11}],9:[function(require,module,exports){
- /**
- * json-model
- *
- * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
- * both having the .json extension. This loader supports only THREE.JsonLoader, which typically
- * includes only a single mesh.
- *
- * Check the console for errors, if in doubt. You may need to use `object-model` or
- * `blend-character-model` for some .js and .json files.
- *
- * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
- */
- module.exports = {
- schema: {
- src: { type: 'asset' },
- crossorigin: { default: '' }
- },
- init: function () {
- this.model = null;
- },
- update: function () {
- var loader,
- data = this.data;
- if (!data.src) return;
- this.remove();
- loader = new THREE.JSONLoader();
- if (data.crossorigin) loader.crossOrigin = data.crossorigin;
- loader.load(data.src, function (geometry, materials) {
- // Attempt to automatically detect common material options.
- materials.forEach(function (mat) {
- mat.vertexColors = (geometry.faces[0] || {}).color ? THREE.FaceColors : THREE.NoColors;
- mat.skinning = !!(geometry.bones || []).length;
- mat.morphTargets = !!(geometry.morphTargets || []).length;
- mat.morphNormals = !!(geometry.morphNormals || []).length;
- });
- var model = (geometry.bones || []).length
- ? new THREE.SkinnedMesh(geometry, new THREE.MultiMaterial(materials))
- : new THREE.Mesh(geometry, new THREE.MultiMaterial(materials));
- this.load(model);
- }.bind(this));
- },
- load: function (model) {
- this.model = model;
- this.el.setObject3D('mesh', model);
- this.el.emit('model-loaded', {format: 'json', model: model});
- },
- remove: function () {
- if (this.model) this.el.removeObject3D('mesh');
- }
- };
- },{}],10:[function(require,module,exports){
- /**
- * object-model
- *
- * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
- * both having the .json extension. This loader supports only THREE.ObjectLoader, which typically
- * includes multiple meshes or an entire scene.
- *
- * Check the console for errors, if in doubt. You may need to use `json-model` or
- * `blend-character-model` for some .js and .json files.
- *
- * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
- */
- module.exports = {
- schema: {
- src: { type: 'asset' },
- crossorigin: { default: '' }
- },
- init: function () {
- this.model = null;
- },
- update: function () {
- var loader,
- data = this.data;
- if (!data.src) return;
- this.remove();
- loader = new THREE.ObjectLoader();
- if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
- loader.load(data.src, function(object) {
- // Enable skinning, if applicable.
- object.traverse(function(o) {
- if (o instanceof THREE.SkinnedMesh && o.material) {
- o.material.skinning = !!((o.geometry && o.geometry.bones) || []).length;
- }
- });
- this.load(object);
- }.bind(this));
- },
- load: function (model) {
- this.model = model;
- this.el.setObject3D('mesh', model);
- this.el.emit('model-loaded', {format: 'json', model: model});
- },
- remove: function () {
- if (this.model) this.el.removeObject3D('mesh');
- }
- };
- },{}],11:[function(require,module,exports){
- /**
- * ply-model
- *
- * Wraps THREE.PLYLoader.
- */
- THREE.PLYLoader = require('../../lib/PLYLoader');
- /**
- * Loads, caches, resolves geometries.
- *
- * @member cache - Promises that resolve geometries keyed by `src`.
- */
- module.exports.System = {
- init: function () {
- this.cache = {};
- },
- /**
- * @returns {Promise}
- */
- getOrLoadGeometry: function (src, skipCache) {
- var cache = this.cache;
- var cacheItem = cache[src];
- if (!skipCache && cacheItem) {
- return cacheItem;
- }
- cache[src] = new Promise(function (resolve) {
- var loader = new THREE.PLYLoader();
- loader.load(src, function (geometry) {
- resolve(geometry);
- });
- });
- return cache[src];
- },
- };
- module.exports.Component = {
- schema: {
- skipCache: {type: 'boolean', default: false},
- src: {type: 'asset'}
- },
- init: function () {
- this.model = null;
- },
- update: function () {
- var data = this.data;
- var el = this.el;
- var loader;
- if (!data.src) {
- console.warn('[%s] `src` property is required.', this.name);
- return;
- }
- // Get geometry from system, create and set mesh.
- this.system.getOrLoadGeometry(data.src, data.skipCache).then(function (geometry) {
- var model = createModel(geometry);
- el.setObject3D('mesh', model);
- el.emit('model-loaded', {format: 'ply', model: model});
- });
- },
- remove: function () {
- if (this.model) { this.el.removeObject3D('mesh'); }
- }
- };
- function createModel (geometry) {
- return new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({
- color: 0xFFFFFF,
- shading: THREE.FlatShading,
- vertexColors: THREE.VertexColors,
- shininess: 0
- }));
- }
- },{"../../lib/PLYLoader":3}]},{},[1]);
|