aframe-extras.js 252 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818
  1. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. 'use strict';
  3. require('./');
  4. },{"./":2}],2:[function(require,module,exports){
  5. 'use strict';
  6. require('./src/controls');
  7. require('./src/loaders');
  8. require('./src/misc');
  9. require('./src/pathfinding');
  10. require('./src/primitives');
  11. },{"./src/controls":13,"./src/loaders":21,"./src/misc":26,"./src/pathfinding":32,"./src/primitives":40}],3:[function(require,module,exports){
  12. 'use strict';
  13. var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  14. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  15. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  16. } : function (obj) {
  17. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  18. };
  19. /**
  20. * @author Kyle-Larson https://github.com/Kyle-Larson
  21. * @author Takahiro https://github.com/takahirox
  22. * @author Lewy Blue https://github.com/looeee
  23. *
  24. * Loader loads FBX file and generates Group representing FBX scene.
  25. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  26. * Versions lower than this may load but will probably have errors
  27. *
  28. * Needs Support:
  29. * Morph normals / blend shape normals
  30. *
  31. * FBX format references:
  32. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  33. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  34. *
  35. * Binary format specification:
  36. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  37. */
  38. // Monkeypatch for <r89
  39. THREE.LoaderUtils = {
  40. extractUrlBase: THREE.Loader.prototype.extractUrlBase,
  41. decodeText: function decodeText(array) {
  42. return new TextDecoder().decode(array);
  43. }
  44. };
  45. module.exports = THREE.FBXLoader = function () {
  46. var fbxTree;
  47. var connections;
  48. var sceneGraph;
  49. function FBXLoader(manager) {
  50. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  51. }
  52. FBXLoader.prototype = {
  53. constructor: FBXLoader,
  54. crossOrigin: 'anonymous',
  55. load: function load(url, onLoad, onProgress, onError) {
  56. var self = this;
  57. var resourceDirectory = THREE.LoaderUtils.extractUrlBase(url);
  58. var loader = new THREE.FileLoader(this.manager);
  59. loader.setResponseType('arraybuffer');
  60. loader.load(url, function (buffer) {
  61. try {
  62. var scene = self.parse(buffer, resourceDirectory);
  63. onLoad(scene);
  64. } catch (error) {
  65. setTimeout(function () {
  66. if (onError) onError(error);
  67. self.manager.itemError(url);
  68. }, 0);
  69. }
  70. }, onProgress, onError);
  71. },
  72. setCrossOrigin: function setCrossOrigin(value) {
  73. this.crossOrigin = value;
  74. return this;
  75. },
  76. parse: function parse(FBXBuffer, resourceDirectory) {
  77. if (isFbxFormatBinary(FBXBuffer)) {
  78. fbxTree = new BinaryParser().parse(FBXBuffer);
  79. } else {
  80. var FBXText = convertArrayBufferToString(FBXBuffer);
  81. if (!isFbxFormatASCII(FBXText)) {
  82. throw new Error('THREE.FBXLoader: Unknown format.');
  83. }
  84. if (getFbxVersion(FBXText) < 7000) {
  85. throw new Error('THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion(FBXText));
  86. }
  87. fbxTree = new TextParser().parse(FBXText);
  88. }
  89. //console.log( FBXTree );
  90. var textureLoader = new THREE.TextureLoader(this.manager).setPath(resourceDirectory).setCrossOrigin(this.crossOrigin);
  91. return new FBXTreeParser(textureLoader).parse(fbxTree);
  92. }
  93. };
  94. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  95. function FBXTreeParser(textureLoader) {
  96. this.textureLoader = textureLoader;
  97. }
  98. FBXTreeParser.prototype = {
  99. constructor: FBXTreeParser,
  100. parse: function parse() {
  101. connections = this.parseConnections();
  102. var images = this.parseImages();
  103. var textures = this.parseTextures(images);
  104. var materials = this.parseMaterials(textures);
  105. var deformers = this.parseDeformers();
  106. var geometryMap = new GeometryParser().parse(deformers);
  107. this.parseScene(deformers, geometryMap, materials);
  108. return sceneGraph;
  109. },
  110. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  111. // and details the connection type
  112. parseConnections: function parseConnections() {
  113. var connectionMap = new Map();
  114. if ('Connections' in fbxTree) {
  115. var rawConnections = fbxTree.Connections.connections;
  116. rawConnections.forEach(function (rawConnection) {
  117. var fromID = rawConnection[0];
  118. var toID = rawConnection[1];
  119. var relationship = rawConnection[2];
  120. if (!connectionMap.has(fromID)) {
  121. connectionMap.set(fromID, {
  122. parents: [],
  123. children: []
  124. });
  125. }
  126. var parentRelationship = { ID: toID, relationship: relationship };
  127. connectionMap.get(fromID).parents.push(parentRelationship);
  128. if (!connectionMap.has(toID)) {
  129. connectionMap.set(toID, {
  130. parents: [],
  131. children: []
  132. });
  133. }
  134. var childRelationship = { ID: fromID, relationship: relationship };
  135. connectionMap.get(toID).children.push(childRelationship);
  136. });
  137. }
  138. return connectionMap;
  139. },
  140. // Parse FBXTree.Objects.Video for embedded image data
  141. // These images are connected to textures in FBXTree.Objects.Textures
  142. // via FBXTree.Connections.
  143. parseImages: function parseImages() {
  144. var images = {};
  145. var blobs = {};
  146. if ('Video' in fbxTree.Objects) {
  147. var videoNodes = fbxTree.Objects.Video;
  148. for (var nodeID in videoNodes) {
  149. var videoNode = videoNodes[nodeID];
  150. var id = parseInt(nodeID);
  151. images[id] = videoNode.RelativeFilename || videoNode.Filename;
  152. // raw image data is in videoNode.Content
  153. if ('Content' in videoNode) {
  154. var arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
  155. var base64Content = typeof videoNode.Content === 'string' && videoNode.Content !== '';
  156. if (arrayBufferContent || base64Content) {
  157. var image = this.parseImage(videoNodes[nodeID]);
  158. blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
  159. }
  160. }
  161. }
  162. }
  163. for (var id in images) {
  164. var filename = images[id];
  165. if (blobs[filename] !== undefined) images[id] = blobs[filename];else images[id] = images[id].split('\\').pop();
  166. }
  167. return images;
  168. },
  169. // Parse embedded image data in FBXTree.Video.Content
  170. parseImage: function parseImage(videoNode) {
  171. var content = videoNode.Content;
  172. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  173. var extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
  174. var type;
  175. switch (extension) {
  176. case 'bmp':
  177. type = 'image/bmp';
  178. break;
  179. case 'jpg':
  180. case 'jpeg':
  181. type = 'image/jpeg';
  182. break;
  183. case 'png':
  184. type = 'image/png';
  185. break;
  186. case 'tif':
  187. type = 'image/tiff';
  188. break;
  189. case 'tga':
  190. if (typeof THREE.TGALoader !== 'function') {
  191. console.warn('FBXLoader: THREE.TGALoader is required to load TGA textures');
  192. return;
  193. } else {
  194. if (THREE.Loader.Handlers.get('.tga') === null) {
  195. THREE.Loader.Handlers.add(/\.tga$/i, new THREE.TGALoader());
  196. }
  197. type = 'image/tga';
  198. break;
  199. }
  200. default:
  201. console.warn('FBXLoader: Image type "' + extension + '" is not supported.');
  202. return;
  203. }
  204. if (typeof content === 'string') {
  205. // ASCII format
  206. return 'data:' + type + ';base64,' + content;
  207. } else {
  208. // Binary Format
  209. var array = new Uint8Array(content);
  210. return window.URL.createObjectURL(new Blob([array], { type: type }));
  211. }
  212. },
  213. // Parse nodes in FBXTree.Objects.Texture
  214. // These contain details such as UV scaling, cropping, rotation etc and are connected
  215. // to images in FBXTree.Objects.Video
  216. parseTextures: function parseTextures(images) {
  217. var textureMap = new Map();
  218. if ('Texture' in fbxTree.Objects) {
  219. var textureNodes = fbxTree.Objects.Texture;
  220. for (var nodeID in textureNodes) {
  221. var texture = this.parseTexture(textureNodes[nodeID], images);
  222. textureMap.set(parseInt(nodeID), texture);
  223. }
  224. }
  225. return textureMap;
  226. },
  227. // Parse individual node in FBXTree.Objects.Texture
  228. parseTexture: function parseTexture(textureNode, images) {
  229. var texture = this.loadTexture(textureNode, images);
  230. texture.ID = textureNode.id;
  231. texture.name = textureNode.attrName;
  232. var wrapModeU = textureNode.WrapModeU;
  233. var wrapModeV = textureNode.WrapModeV;
  234. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  235. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  236. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  237. // 0: repeat(default), 1: clamp
  238. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  239. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  240. if ('Scaling' in textureNode) {
  241. var values = textureNode.Scaling.value;
  242. texture.repeat.x = values[0];
  243. texture.repeat.y = values[1];
  244. }
  245. return texture;
  246. },
  247. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  248. loadTexture: function loadTexture(textureNode, images) {
  249. var fileName;
  250. var currentPath = this.textureLoader.path;
  251. var children = connections.get(textureNode.id).children;
  252. if (children !== undefined && children.length > 0 && images[children[0].ID] !== undefined) {
  253. fileName = images[children[0].ID];
  254. if (fileName.indexOf('blob:') === 0 || fileName.indexOf('data:') === 0) {
  255. this.textureLoader.setPath(undefined);
  256. }
  257. }
  258. var texture;
  259. var extension = textureNode.FileName.slice(-3).toLowerCase();
  260. if (extension === 'tga') {
  261. var loader = THREE.Loader.Handlers.get('.tga');
  262. if (loader === null) {
  263. console.warn('FBXLoader: TGALoader not found, creating empty placeholder texture for', fileName);
  264. texture = new THREE.Texture();
  265. } else {
  266. texture = loader.load(fileName);
  267. }
  268. } else if (extension === 'psd') {
  269. console.warn('FBXLoader: PSD textures are not supported, creating empty placeholder texture for', fileName);
  270. texture = new THREE.Texture();
  271. } else {
  272. texture = this.textureLoader.load(fileName);
  273. }
  274. this.textureLoader.setPath(currentPath);
  275. return texture;
  276. },
  277. // Parse nodes in FBXTree.Objects.Material
  278. parseMaterials: function parseMaterials(textureMap) {
  279. var materialMap = new Map();
  280. if ('Material' in fbxTree.Objects) {
  281. var materialNodes = fbxTree.Objects.Material;
  282. for (var nodeID in materialNodes) {
  283. var material = this.parseMaterial(materialNodes[nodeID], textureMap);
  284. if (material !== null) materialMap.set(parseInt(nodeID), material);
  285. }
  286. }
  287. return materialMap;
  288. },
  289. // Parse single node in FBXTree.Objects.Material
  290. // Materials are connected to texture maps in FBXTree.Objects.Textures
  291. // FBX format currently only supports Lambert and Phong shading models
  292. parseMaterial: function parseMaterial(materialNode, textureMap) {
  293. var ID = materialNode.id;
  294. var name = materialNode.attrName;
  295. var type = materialNode.ShadingModel;
  296. // Case where FBX wraps shading model in property object.
  297. if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object') {
  298. type = type.value;
  299. }
  300. // Ignore unused materials which don't have any connections.
  301. if (!connections.has(ID)) return null;
  302. var parameters = this.parseParameters(materialNode, textureMap, ID);
  303. var material;
  304. switch (type.toLowerCase()) {
  305. case 'phong':
  306. material = new THREE.MeshPhongMaterial();
  307. break;
  308. case 'lambert':
  309. material = new THREE.MeshLambertMaterial();
  310. break;
  311. default:
  312. console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type);
  313. material = new THREE.MeshPhongMaterial({ color: 0x3300ff });
  314. break;
  315. }
  316. material.setValues(parameters);
  317. material.name = name;
  318. return material;
  319. },
  320. // Parse FBX material and return parameters suitable for a three.js material
  321. // Also parse the texture map and return any textures associated with the material
  322. parseParameters: function parseParameters(materialNode, textureMap, ID) {
  323. var parameters = {};
  324. if (materialNode.BumpFactor) {
  325. parameters.bumpScale = materialNode.BumpFactor.value;
  326. }
  327. if (materialNode.Diffuse) {
  328. parameters.color = new THREE.Color().fromArray(materialNode.Diffuse.value);
  329. } else if (materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color') {
  330. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  331. parameters.color = new THREE.Color().fromArray(materialNode.DiffuseColor.value);
  332. }
  333. if (materialNode.DisplacementFactor) {
  334. parameters.displacementScale = materialNode.DisplacementFactor.value;
  335. }
  336. if (materialNode.Emissive) {
  337. parameters.emissive = new THREE.Color().fromArray(materialNode.Emissive.value);
  338. } else if (materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color') {
  339. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  340. parameters.emissive = new THREE.Color().fromArray(materialNode.EmissiveColor.value);
  341. }
  342. if (materialNode.EmissiveFactor) {
  343. parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value);
  344. }
  345. if (materialNode.Opacity) {
  346. parameters.opacity = parseFloat(materialNode.Opacity.value);
  347. }
  348. if (parameters.opacity < 1.0) {
  349. parameters.transparent = true;
  350. }
  351. if (materialNode.ReflectionFactor) {
  352. parameters.reflectivity = materialNode.ReflectionFactor.value;
  353. }
  354. if (materialNode.Shininess) {
  355. parameters.shininess = materialNode.Shininess.value;
  356. }
  357. if (materialNode.Specular) {
  358. parameters.specular = new THREE.Color().fromArray(materialNode.Specular.value);
  359. } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color') {
  360. // The blender exporter exports specular color here instead of in materialNode.Specular
  361. parameters.specular = new THREE.Color().fromArray(materialNode.SpecularColor.value);
  362. }
  363. var self = this;
  364. connections.get(ID).children.forEach(function (child) {
  365. var type = child.relationship;
  366. switch (type) {
  367. case 'Bump':
  368. parameters.bumpMap = self.getTexture(textureMap, child.ID);
  369. break;
  370. case 'DiffuseColor':
  371. parameters.map = self.getTexture(textureMap, child.ID);
  372. break;
  373. case 'DisplacementColor':
  374. parameters.displacementMap = self.getTexture(textureMap, child.ID);
  375. break;
  376. case 'EmissiveColor':
  377. parameters.emissiveMap = self.getTexture(textureMap, child.ID);
  378. break;
  379. case 'NormalMap':
  380. parameters.normalMap = self.getTexture(textureMap, child.ID);
  381. break;
  382. case 'ReflectionColor':
  383. parameters.envMap = self.getTexture(textureMap, child.ID);
  384. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  385. break;
  386. case 'SpecularColor':
  387. parameters.specularMap = self.getTexture(textureMap, child.ID);
  388. break;
  389. case 'TransparentColor':
  390. parameters.alphaMap = self.getTexture(textureMap, child.ID);
  391. parameters.transparent = true;
  392. break;
  393. case 'AmbientColor':
  394. case 'ShininessExponent': // AKA glossiness map
  395. case 'SpecularFactor': // AKA specularLevel
  396. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  397. default:
  398. console.warn('THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type);
  399. break;
  400. }
  401. });
  402. return parameters;
  403. },
  404. // get a texture from the textureMap for use by a material.
  405. getTexture: function getTexture(textureMap, id) {
  406. // if the texture is a layered texture, just use the first layer and issue a warning
  407. if ('LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) {
  408. console.warn('THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.');
  409. id = connections.get(id).children[0].ID;
  410. }
  411. return textureMap.get(id);
  412. },
  413. // Parse nodes in FBXTree.Objects.Deformer
  414. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  415. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  416. parseDeformers: function parseDeformers() {
  417. var skeletons = {};
  418. var morphTargets = {};
  419. if ('Deformer' in fbxTree.Objects) {
  420. var DeformerNodes = fbxTree.Objects.Deformer;
  421. for (var nodeID in DeformerNodes) {
  422. var deformerNode = DeformerNodes[nodeID];
  423. var relationships = connections.get(parseInt(nodeID));
  424. if (deformerNode.attrType === 'Skin') {
  425. var skeleton = this.parseSkeleton(relationships, DeformerNodes);
  426. skeleton.ID = nodeID;
  427. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: skeleton attached to more than one geometry is not supported.');
  428. skeleton.geometryID = relationships.parents[0].ID;
  429. skeletons[nodeID] = skeleton;
  430. } else if (deformerNode.attrType === 'BlendShape') {
  431. var morphTarget = {
  432. id: nodeID
  433. };
  434. morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes);
  435. morphTarget.id = nodeID;
  436. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: morph target attached to more than one geometry is not supported.');
  437. morphTargets[nodeID] = morphTarget;
  438. }
  439. }
  440. }
  441. return {
  442. skeletons: skeletons,
  443. morphTargets: morphTargets
  444. };
  445. },
  446. // Parse single nodes in FBXTree.Objects.Deformer
  447. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  448. // Each skin node represents a skeleton and each cluster node represents a bone
  449. parseSkeleton: function parseSkeleton(relationships, deformerNodes) {
  450. var rawBones = [];
  451. relationships.children.forEach(function (child) {
  452. var boneNode = deformerNodes[child.ID];
  453. if (boneNode.attrType !== 'Cluster') return;
  454. var rawBone = {
  455. ID: child.ID,
  456. indices: [],
  457. weights: [],
  458. transform: new THREE.Matrix4().fromArray(boneNode.Transform.a),
  459. transformLink: new THREE.Matrix4().fromArray(boneNode.TransformLink.a),
  460. linkMode: boneNode.Mode
  461. };
  462. if ('Indexes' in boneNode) {
  463. rawBone.indices = boneNode.Indexes.a;
  464. rawBone.weights = boneNode.Weights.a;
  465. }
  466. rawBones.push(rawBone);
  467. });
  468. return {
  469. rawBones: rawBones,
  470. bones: []
  471. };
  472. },
  473. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  474. parseMorphTargets: function parseMorphTargets(relationships, deformerNodes) {
  475. var rawMorphTargets = [];
  476. for (var i = 0; i < relationships.children.length; i++) {
  477. if (i === 8) {
  478. console.warn('FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.');
  479. break;
  480. }
  481. var child = relationships.children[i];
  482. var morphTargetNode = deformerNodes[child.ID];
  483. var rawMorphTarget = {
  484. name: morphTargetNode.attrName,
  485. initialWeight: morphTargetNode.DeformPercent,
  486. id: morphTargetNode.id,
  487. fullWeights: morphTargetNode.FullWeights.a
  488. };
  489. if (morphTargetNode.attrType !== 'BlendShapeChannel') return;
  490. var targetRelationships = connections.get(parseInt(child.ID));
  491. targetRelationships.children.forEach(function (child) {
  492. if (child.relationship === undefined) rawMorphTarget.geoID = child.ID;
  493. });
  494. rawMorphTargets.push(rawMorphTarget);
  495. }
  496. return rawMorphTargets;
  497. },
  498. // create the main THREE.Group() to be returned by the loader
  499. parseScene: function parseScene(deformers, geometryMap, materialMap) {
  500. sceneGraph = new THREE.Group();
  501. var modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap);
  502. var modelNodes = fbxTree.Objects.Model;
  503. var self = this;
  504. modelMap.forEach(function (model) {
  505. var modelNode = modelNodes[model.ID];
  506. self.setLookAtProperties(model, modelNode);
  507. var parentConnections = connections.get(model.ID).parents;
  508. parentConnections.forEach(function (connection) {
  509. var parent = modelMap.get(connection.ID);
  510. if (parent !== undefined) parent.add(model);
  511. });
  512. if (model.parent === null) {
  513. sceneGraph.add(model);
  514. }
  515. });
  516. this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
  517. this.createAmbientLight();
  518. this.setupMorphMaterials();
  519. var animations = new AnimationParser().parse();
  520. // if all the models where already combined in a single group, just return that
  521. if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
  522. sceneGraph.children[0].animations = animations;
  523. sceneGraph = sceneGraph.children[0];
  524. }
  525. sceneGraph.animations = animations;
  526. },
  527. // parse nodes in FBXTree.Objects.Model
  528. parseModels: function parseModels(skeletons, geometryMap, materialMap) {
  529. var modelMap = new Map();
  530. var modelNodes = fbxTree.Objects.Model;
  531. for (var nodeID in modelNodes) {
  532. var id = parseInt(nodeID);
  533. var node = modelNodes[nodeID];
  534. var relationships = connections.get(id);
  535. var model = this.buildSkeleton(relationships, skeletons, id, node.attrName);
  536. if (!model) {
  537. switch (node.attrType) {
  538. case 'Camera':
  539. model = this.createCamera(relationships);
  540. break;
  541. case 'Light':
  542. model = this.createLight(relationships);
  543. break;
  544. case 'Mesh':
  545. model = this.createMesh(relationships, geometryMap, materialMap);
  546. break;
  547. case 'NurbsCurve':
  548. model = this.createCurve(relationships, geometryMap);
  549. break;
  550. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  551. case 'Null':
  552. default:
  553. model = new THREE.Group();
  554. break;
  555. }
  556. model.name = THREE.PropertyBinding.sanitizeNodeName(node.attrName);
  557. model.ID = id;
  558. }
  559. this.setModelTransforms(model, node);
  560. modelMap.set(id, model);
  561. }
  562. return modelMap;
  563. },
  564. buildSkeleton: function buildSkeleton(relationships, skeletons, id, name) {
  565. var bone = null;
  566. relationships.parents.forEach(function (parent) {
  567. for (var ID in skeletons) {
  568. var skeleton = skeletons[ID];
  569. skeleton.rawBones.forEach(function (rawBone, i) {
  570. if (rawBone.ID === parent.ID) {
  571. var subBone = bone;
  572. bone = new THREE.Bone();
  573. bone.matrixWorld.copy(rawBone.transformLink);
  574. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  575. bone.name = THREE.PropertyBinding.sanitizeNodeName(name);
  576. bone.ID = id;
  577. skeleton.bones[i] = bone;
  578. // In cases where a bone is shared between multiple meshes
  579. // duplicate the bone here and and it as a child of the first bone
  580. if (subBone !== null) {
  581. bone.add(subBone);
  582. }
  583. }
  584. });
  585. }
  586. });
  587. return bone;
  588. },
  589. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  590. createCamera: function createCamera(relationships) {
  591. var model;
  592. var cameraAttribute;
  593. relationships.children.forEach(function (child) {
  594. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  595. if (attr !== undefined) {
  596. cameraAttribute = attr;
  597. }
  598. });
  599. if (cameraAttribute === undefined) {
  600. model = new THREE.Object3D();
  601. } else {
  602. var type = 0;
  603. if (cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1) {
  604. type = 1;
  605. }
  606. var nearClippingPlane = 1;
  607. if (cameraAttribute.NearPlane !== undefined) {
  608. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  609. }
  610. var farClippingPlane = 1000;
  611. if (cameraAttribute.FarPlane !== undefined) {
  612. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  613. }
  614. var width = window.innerWidth;
  615. var height = window.innerHeight;
  616. if (cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined) {
  617. width = cameraAttribute.AspectWidth.value;
  618. height = cameraAttribute.AspectHeight.value;
  619. }
  620. var aspect = width / height;
  621. var fov = 45;
  622. if (cameraAttribute.FieldOfView !== undefined) {
  623. fov = cameraAttribute.FieldOfView.value;
  624. }
  625. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  626. switch (type) {
  627. case 0:
  628. // Perspective
  629. model = new THREE.PerspectiveCamera(fov, aspect, nearClippingPlane, farClippingPlane);
  630. if (focalLength !== null) model.setFocalLength(focalLength);
  631. break;
  632. case 1:
  633. // Orthographic
  634. model = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane);
  635. break;
  636. default:
  637. console.warn('THREE.FBXLoader: Unknown camera type ' + type + '.');
  638. model = new THREE.Object3D();
  639. break;
  640. }
  641. }
  642. return model;
  643. },
  644. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  645. createLight: function createLight(relationships) {
  646. var model;
  647. var lightAttribute;
  648. relationships.children.forEach(function (child) {
  649. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  650. if (attr !== undefined) {
  651. lightAttribute = attr;
  652. }
  653. });
  654. if (lightAttribute === undefined) {
  655. model = new THREE.Object3D();
  656. } else {
  657. var type;
  658. // LightType can be undefined for Point lights
  659. if (lightAttribute.LightType === undefined) {
  660. type = 0;
  661. } else {
  662. type = lightAttribute.LightType.value;
  663. }
  664. var color = 0xffffff;
  665. if (lightAttribute.Color !== undefined) {
  666. color = new THREE.Color().fromArray(lightAttribute.Color.value);
  667. }
  668. var intensity = lightAttribute.Intensity === undefined ? 1 : lightAttribute.Intensity.value / 100;
  669. // light disabled
  670. if (lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0) {
  671. intensity = 0;
  672. }
  673. var distance = 0;
  674. if (lightAttribute.FarAttenuationEnd !== undefined) {
  675. if (lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0) {
  676. distance = 0;
  677. } else {
  678. distance = lightAttribute.FarAttenuationEnd.value;
  679. }
  680. }
  681. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  682. var decay = 1;
  683. switch (type) {
  684. case 0:
  685. // Point
  686. model = new THREE.PointLight(color, intensity, distance, decay);
  687. break;
  688. case 1:
  689. // Directional
  690. model = new THREE.DirectionalLight(color, intensity);
  691. break;
  692. case 2:
  693. // Spot
  694. var angle = Math.PI / 3;
  695. if (lightAttribute.InnerAngle !== undefined) {
  696. angle = THREE.Math.degToRad(lightAttribute.InnerAngle.value);
  697. }
  698. var penumbra = 0;
  699. if (lightAttribute.OuterAngle !== undefined) {
  700. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  701. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  702. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  703. penumbra = THREE.Math.degToRad(lightAttribute.OuterAngle.value);
  704. penumbra = Math.max(penumbra, 1);
  705. }
  706. model = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
  707. break;
  708. default:
  709. console.warn('THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.');
  710. model = new THREE.PointLight(color, intensity);
  711. break;
  712. }
  713. if (lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1) {
  714. model.castShadow = true;
  715. }
  716. }
  717. return model;
  718. },
  719. createMesh: function createMesh(relationships, geometryMap, materialMap) {
  720. var model;
  721. var geometry = null;
  722. var material = null;
  723. var materials = [];
  724. // get geometry and materials(s) from connections
  725. relationships.children.forEach(function (child) {
  726. if (geometryMap.has(child.ID)) {
  727. geometry = geometryMap.get(child.ID);
  728. }
  729. if (materialMap.has(child.ID)) {
  730. materials.push(materialMap.get(child.ID));
  731. }
  732. });
  733. if (materials.length > 1) {
  734. material = materials;
  735. } else if (materials.length > 0) {
  736. material = materials[0];
  737. } else {
  738. material = new THREE.MeshPhongMaterial({ color: 0xcccccc });
  739. materials.push(material);
  740. }
  741. if ('color' in geometry.attributes) {
  742. materials.forEach(function (material) {
  743. material.vertexColors = THREE.VertexColors;
  744. });
  745. }
  746. if (geometry.FBX_Deformer) {
  747. materials.forEach(function (material) {
  748. material.skinning = true;
  749. });
  750. model = new THREE.SkinnedMesh(geometry, material);
  751. } else {
  752. model = new THREE.Mesh(geometry, material);
  753. }
  754. return model;
  755. },
  756. createCurve: function createCurve(relationships, geometryMap) {
  757. var geometry = relationships.children.reduce(function (geo, child) {
  758. if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
  759. return geo;
  760. }, null);
  761. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  762. var material = new THREE.LineBasicMaterial({ color: 0x3300ff, linewidth: 1 });
  763. return new THREE.Line(geometry, material);
  764. },
  765. // parse the model node for transform details and apply them to the model
  766. setModelTransforms: function setModelTransforms(model, modelNode) {
  767. var transformData = {};
  768. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  769. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  770. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  771. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  772. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  773. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  774. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  775. var transform = generateTransform(transformData);
  776. model.applyMatrix(transform);
  777. },
  778. setLookAtProperties: function setLookAtProperties(model, modelNode) {
  779. if ('LookAtProperty' in modelNode) {
  780. var children = connections.get(model.ID).children;
  781. children.forEach(function (child) {
  782. if (child.relationship === 'LookAtProperty') {
  783. var lookAtTarget = fbxTree.Objects.Model[child.ID];
  784. if ('Lcl_Translation' in lookAtTarget) {
  785. var pos = lookAtTarget.Lcl_Translation.value;
  786. // DirectionalLight, SpotLight
  787. if (model.target !== undefined) {
  788. model.target.position.fromArray(pos);
  789. sceneGraph.add(model.target);
  790. } else {
  791. // Cameras and other Object3Ds
  792. model.lookAt(new THREE.Vector3().fromArray(pos));
  793. }
  794. }
  795. }
  796. });
  797. }
  798. },
  799. bindSkeleton: function bindSkeleton(skeletons, geometryMap, modelMap) {
  800. var bindMatrices = this.parsePoseNodes();
  801. for (var ID in skeletons) {
  802. var skeleton = skeletons[ID];
  803. var parents = connections.get(parseInt(skeleton.ID)).parents;
  804. parents.forEach(function (parent) {
  805. if (geometryMap.has(parent.ID)) {
  806. var geoID = parent.ID;
  807. var geoRelationships = connections.get(geoID);
  808. geoRelationships.parents.forEach(function (geoConnParent) {
  809. if (modelMap.has(geoConnParent.ID)) {
  810. var model = modelMap.get(geoConnParent.ID);
  811. model.bind(new THREE.Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]);
  812. }
  813. });
  814. }
  815. });
  816. }
  817. },
  818. parsePoseNodes: function parsePoseNodes() {
  819. var bindMatrices = {};
  820. if ('Pose' in fbxTree.Objects) {
  821. var BindPoseNode = fbxTree.Objects.Pose;
  822. for (var nodeID in BindPoseNode) {
  823. if (BindPoseNode[nodeID].attrType === 'BindPose') {
  824. var poseNodes = BindPoseNode[nodeID].PoseNode;
  825. if (Array.isArray(poseNodes)) {
  826. poseNodes.forEach(function (poseNode) {
  827. bindMatrices[poseNode.Node] = new THREE.Matrix4().fromArray(poseNode.Matrix.a);
  828. });
  829. } else {
  830. bindMatrices[poseNodes.Node] = new THREE.Matrix4().fromArray(poseNodes.Matrix.a);
  831. }
  832. }
  833. }
  834. }
  835. return bindMatrices;
  836. },
  837. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  838. createAmbientLight: function createAmbientLight() {
  839. if ('GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings) {
  840. var ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  841. var r = ambientColor[0];
  842. var g = ambientColor[1];
  843. var b = ambientColor[2];
  844. if (r !== 0 || g !== 0 || b !== 0) {
  845. var color = new THREE.Color(r, g, b);
  846. sceneGraph.add(new THREE.AmbientLight(color, 1));
  847. }
  848. }
  849. },
  850. setupMorphMaterials: function setupMorphMaterials() {
  851. sceneGraph.traverse(function (child) {
  852. if (child.isMesh) {
  853. if (child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal) {
  854. var uuid = child.uuid;
  855. var matUuid = child.material.uuid;
  856. // if a geometry has morph targets, it cannot share the material with other geometries
  857. var sharedMat = false;
  858. sceneGraph.traverse(function (child) {
  859. if (child.isMesh) {
  860. if (child.material.uuid === matUuid && child.uuid !== uuid) sharedMat = true;
  861. }
  862. });
  863. if (sharedMat === true) child.material = child.material.clone();
  864. child.material.morphTargets = true;
  865. }
  866. }
  867. });
  868. }
  869. };
  870. // parse Geometry data from FBXTree and return map of BufferGeometries
  871. function GeometryParser() {}
  872. GeometryParser.prototype = {
  873. constructor: GeometryParser,
  874. // Parse nodes in FBXTree.Objects.Geometry
  875. parse: function parse(deformers) {
  876. var geometryMap = new Map();
  877. if ('Geometry' in fbxTree.Objects) {
  878. var geoNodes = fbxTree.Objects.Geometry;
  879. for (var nodeID in geoNodes) {
  880. var relationships = connections.get(parseInt(nodeID));
  881. var geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers);
  882. geometryMap.set(parseInt(nodeID), geo);
  883. }
  884. }
  885. return geometryMap;
  886. },
  887. // Parse single node in FBXTree.Objects.Geometry
  888. parseGeometry: function parseGeometry(relationships, geoNode, deformers) {
  889. switch (geoNode.attrType) {
  890. case 'Mesh':
  891. return this.parseMeshGeometry(relationships, geoNode, deformers);
  892. break;
  893. case 'NurbsCurve':
  894. return this.parseNurbsGeometry(geoNode);
  895. break;
  896. }
  897. },
  898. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  899. parseMeshGeometry: function parseMeshGeometry(relationships, geoNode, deformers) {
  900. var skeletons = deformers.skeletons;
  901. var morphTargets = deformers.morphTargets;
  902. var modelNodes = relationships.parents.map(function (parent) {
  903. return fbxTree.Objects.Model[parent.ID];
  904. });
  905. // don't create geometry if it is not associated with any models
  906. if (modelNodes.length === 0) return;
  907. var skeleton = relationships.children.reduce(function (skeleton, child) {
  908. if (skeletons[child.ID] !== undefined) skeleton = skeletons[child.ID];
  909. return skeleton;
  910. }, null);
  911. var morphTarget = relationships.children.reduce(function (morphTarget, child) {
  912. if (morphTargets[child.ID] !== undefined) morphTarget = morphTargets[child.ID];
  913. return morphTarget;
  914. }, null);
  915. // TODO: if there is more than one model associated with the geometry, AND the models have
  916. // different geometric transforms, then this will cause problems
  917. // if ( modelNodes.length > 1 ) { }
  918. // For now just assume one model and get the preRotations from that
  919. var modelNode = modelNodes[0];
  920. var transformData = {};
  921. if ('RotationOrder' in modelNode) transformData.eulerOrder = modelNode.RotationOrder.value;
  922. if ('GeometricTranslation' in modelNode) transformData.translation = modelNode.GeometricTranslation.value;
  923. if ('GeometricRotation' in modelNode) transformData.rotation = modelNode.GeometricRotation.value;
  924. if ('GeometricScaling' in modelNode) transformData.scale = modelNode.GeometricScaling.value;
  925. var transform = generateTransform(transformData);
  926. return this.genGeometry(geoNode, skeleton, morphTarget, transform);
  927. },
  928. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  929. genGeometry: function genGeometry(geoNode, skeleton, morphTarget, preTransform) {
  930. var geo = new THREE.BufferGeometry();
  931. if (geoNode.attrName) geo.name = geoNode.attrName;
  932. var geoInfo = this.parseGeoNode(geoNode, skeleton);
  933. var buffers = this.genBuffers(geoInfo);
  934. var positionAttribute = new THREE.Float32BufferAttribute(buffers.vertex, 3);
  935. preTransform.applyToBufferAttribute(positionAttribute);
  936. geo.addAttribute('position', positionAttribute);
  937. if (buffers.colors.length > 0) {
  938. geo.addAttribute('color', new THREE.Float32BufferAttribute(buffers.colors, 3));
  939. }
  940. if (skeleton) {
  941. geo.addAttribute('skinIndex', new THREE.Uint16BufferAttribute(buffers.weightsIndices, 4));
  942. geo.addAttribute('skinWeight', new THREE.Float32BufferAttribute(buffers.vertexWeights, 4));
  943. // used later to bind the skeleton to the model
  944. geo.FBX_Deformer = skeleton;
  945. }
  946. if (buffers.normal.length > 0) {
  947. var normalAttribute = new THREE.Float32BufferAttribute(buffers.normal, 3);
  948. var normalMatrix = new THREE.Matrix3().getNormalMatrix(preTransform);
  949. normalMatrix.applyToBufferAttribute(normalAttribute);
  950. geo.addAttribute('normal', normalAttribute);
  951. }
  952. buffers.uvs.forEach(function (uvBuffer, i) {
  953. // subsequent uv buffers are called 'uv1', 'uv2', ...
  954. var name = 'uv' + (i + 1).toString();
  955. // the first uv buffer is just called 'uv'
  956. if (i === 0) {
  957. name = 'uv';
  958. }
  959. geo.addAttribute(name, new THREE.Float32BufferAttribute(buffers.uvs[i], 2));
  960. });
  961. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  962. // Convert the material indices of each vertex into rendering groups on the geometry.
  963. var prevMaterialIndex = buffers.materialIndex[0];
  964. var startIndex = 0;
  965. buffers.materialIndex.forEach(function (currentIndex, i) {
  966. if (currentIndex !== prevMaterialIndex) {
  967. geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
  968. prevMaterialIndex = currentIndex;
  969. startIndex = i;
  970. }
  971. });
  972. // the loop above doesn't add the last group, do that here.
  973. if (geo.groups.length > 0) {
  974. var lastGroup = geo.groups[geo.groups.length - 1];
  975. var lastIndex = lastGroup.start + lastGroup.count;
  976. if (lastIndex !== buffers.materialIndex.length) {
  977. geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex);
  978. }
  979. }
  980. // case where there are multiple materials but the whole geometry is only
  981. // using one of them
  982. if (geo.groups.length === 0) {
  983. geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
  984. }
  985. }
  986. this.addMorphTargets(geo, geoNode, morphTarget, preTransform);
  987. return geo;
  988. },
  989. parseGeoNode: function parseGeoNode(geoNode, skeleton) {
  990. var geoInfo = {};
  991. geoInfo.vertexPositions = geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  992. geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== undefined ? geoNode.PolygonVertexIndex.a : [];
  993. if (geoNode.LayerElementColor) {
  994. geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
  995. }
  996. if (geoNode.LayerElementMaterial) {
  997. geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]);
  998. }
  999. if (geoNode.LayerElementNormal) {
  1000. geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
  1001. }
  1002. if (geoNode.LayerElementUV) {
  1003. geoInfo.uv = [];
  1004. var i = 0;
  1005. while (geoNode.LayerElementUV[i]) {
  1006. geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
  1007. i++;
  1008. }
  1009. }
  1010. geoInfo.weightTable = {};
  1011. if (skeleton !== null) {
  1012. geoInfo.skeleton = skeleton;
  1013. skeleton.rawBones.forEach(function (rawBone, i) {
  1014. // loop over the bone's vertex indices and weights
  1015. rawBone.indices.forEach(function (index, j) {
  1016. if (geoInfo.weightTable[index] === undefined) geoInfo.weightTable[index] = [];
  1017. geoInfo.weightTable[index].push({
  1018. id: i,
  1019. weight: rawBone.weights[j]
  1020. });
  1021. });
  1022. });
  1023. }
  1024. return geoInfo;
  1025. },
  1026. genBuffers: function genBuffers(geoInfo) {
  1027. var buffers = {
  1028. vertex: [],
  1029. normal: [],
  1030. colors: [],
  1031. uvs: [],
  1032. materialIndex: [],
  1033. vertexWeights: [],
  1034. weightsIndices: []
  1035. };
  1036. var polygonIndex = 0;
  1037. var faceLength = 0;
  1038. var displayedWeightsWarning = false;
  1039. // these will hold data for a single face
  1040. var facePositionIndexes = [];
  1041. var faceNormals = [];
  1042. var faceColors = [];
  1043. var faceUVs = [];
  1044. var faceWeights = [];
  1045. var faceWeightIndices = [];
  1046. var self = this;
  1047. geoInfo.vertexIndices.forEach(function (vertexIndex, polygonVertexIndex) {
  1048. var endOfFace = false;
  1049. // Face index and vertex index arrays are combined in a single array
  1050. // A cube with quad faces looks like this:
  1051. // PolygonVertexIndex: *24 {
  1052. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  1053. // }
  1054. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1055. // to find index of last vertex bit shift the index: ^ - 1
  1056. if (vertexIndex < 0) {
  1057. vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1
  1058. endOfFace = true;
  1059. }
  1060. var weightIndices = [];
  1061. var weights = [];
  1062. facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2);
  1063. if (geoInfo.color) {
  1064. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color);
  1065. faceColors.push(data[0], data[1], data[2]);
  1066. }
  1067. if (geoInfo.skeleton) {
  1068. if (geoInfo.weightTable[vertexIndex] !== undefined) {
  1069. geoInfo.weightTable[vertexIndex].forEach(function (wt) {
  1070. weights.push(wt.weight);
  1071. weightIndices.push(wt.id);
  1072. });
  1073. }
  1074. if (weights.length > 4) {
  1075. if (!displayedWeightsWarning) {
  1076. console.warn('THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.');
  1077. displayedWeightsWarning = true;
  1078. }
  1079. var wIndex = [0, 0, 0, 0];
  1080. var Weight = [0, 0, 0, 0];
  1081. weights.forEach(function (weight, weightIndex) {
  1082. var currentWeight = weight;
  1083. var currentIndex = weightIndices[weightIndex];
  1084. Weight.forEach(function (comparedWeight, comparedWeightIndex, comparedWeightArray) {
  1085. if (currentWeight > comparedWeight) {
  1086. comparedWeightArray[comparedWeightIndex] = currentWeight;
  1087. currentWeight = comparedWeight;
  1088. var tmp = wIndex[comparedWeightIndex];
  1089. wIndex[comparedWeightIndex] = currentIndex;
  1090. currentIndex = tmp;
  1091. }
  1092. });
  1093. });
  1094. weightIndices = wIndex;
  1095. weights = Weight;
  1096. }
  1097. // if the weight array is shorter than 4 pad with 0s
  1098. while (weights.length < 4) {
  1099. weights.push(0);
  1100. weightIndices.push(0);
  1101. }
  1102. for (var i = 0; i < 4; ++i) {
  1103. faceWeights.push(weights[i]);
  1104. faceWeightIndices.push(weightIndices[i]);
  1105. }
  1106. }
  1107. if (geoInfo.normal) {
  1108. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal);
  1109. faceNormals.push(data[0], data[1], data[2]);
  1110. }
  1111. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  1112. var materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0];
  1113. }
  1114. if (geoInfo.uv) {
  1115. geoInfo.uv.forEach(function (uv, i) {
  1116. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv);
  1117. if (faceUVs[i] === undefined) {
  1118. faceUVs[i] = [];
  1119. }
  1120. faceUVs[i].push(data[0]);
  1121. faceUVs[i].push(data[1]);
  1122. });
  1123. }
  1124. faceLength++;
  1125. if (endOfFace) {
  1126. self.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);
  1127. polygonIndex++;
  1128. faceLength = 0;
  1129. // reset arrays for the next face
  1130. facePositionIndexes = [];
  1131. faceNormals = [];
  1132. faceColors = [];
  1133. faceUVs = [];
  1134. faceWeights = [];
  1135. faceWeightIndices = [];
  1136. }
  1137. });
  1138. return buffers;
  1139. },
  1140. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1141. genFace: function genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) {
  1142. for (var i = 2; i < faceLength; i++) {
  1143. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]);
  1144. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]);
  1145. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]);
  1146. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3]]);
  1147. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]);
  1148. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]);
  1149. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]);
  1150. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]);
  1151. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 2]]);
  1152. if (geoInfo.skeleton) {
  1153. buffers.vertexWeights.push(faceWeights[0]);
  1154. buffers.vertexWeights.push(faceWeights[1]);
  1155. buffers.vertexWeights.push(faceWeights[2]);
  1156. buffers.vertexWeights.push(faceWeights[3]);
  1157. buffers.vertexWeights.push(faceWeights[(i - 1) * 4]);
  1158. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]);
  1159. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]);
  1160. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]);
  1161. buffers.vertexWeights.push(faceWeights[i * 4]);
  1162. buffers.vertexWeights.push(faceWeights[i * 4 + 1]);
  1163. buffers.vertexWeights.push(faceWeights[i * 4 + 2]);
  1164. buffers.vertexWeights.push(faceWeights[i * 4 + 3]);
  1165. buffers.weightsIndices.push(faceWeightIndices[0]);
  1166. buffers.weightsIndices.push(faceWeightIndices[1]);
  1167. buffers.weightsIndices.push(faceWeightIndices[2]);
  1168. buffers.weightsIndices.push(faceWeightIndices[3]);
  1169. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4]);
  1170. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]);
  1171. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]);
  1172. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]);
  1173. buffers.weightsIndices.push(faceWeightIndices[i * 4]);
  1174. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]);
  1175. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]);
  1176. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]);
  1177. }
  1178. if (geoInfo.color) {
  1179. buffers.colors.push(faceColors[0]);
  1180. buffers.colors.push(faceColors[1]);
  1181. buffers.colors.push(faceColors[2]);
  1182. buffers.colors.push(faceColors[(i - 1) * 3]);
  1183. buffers.colors.push(faceColors[(i - 1) * 3 + 1]);
  1184. buffers.colors.push(faceColors[(i - 1) * 3 + 2]);
  1185. buffers.colors.push(faceColors[i * 3]);
  1186. buffers.colors.push(faceColors[i * 3 + 1]);
  1187. buffers.colors.push(faceColors[i * 3 + 2]);
  1188. }
  1189. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  1190. buffers.materialIndex.push(materialIndex);
  1191. buffers.materialIndex.push(materialIndex);
  1192. buffers.materialIndex.push(materialIndex);
  1193. }
  1194. if (geoInfo.normal) {
  1195. buffers.normal.push(faceNormals[0]);
  1196. buffers.normal.push(faceNormals[1]);
  1197. buffers.normal.push(faceNormals[2]);
  1198. buffers.normal.push(faceNormals[(i - 1) * 3]);
  1199. buffers.normal.push(faceNormals[(i - 1) * 3 + 1]);
  1200. buffers.normal.push(faceNormals[(i - 1) * 3 + 2]);
  1201. buffers.normal.push(faceNormals[i * 3]);
  1202. buffers.normal.push(faceNormals[i * 3 + 1]);
  1203. buffers.normal.push(faceNormals[i * 3 + 2]);
  1204. }
  1205. if (geoInfo.uv) {
  1206. geoInfo.uv.forEach(function (uv, j) {
  1207. if (buffers.uvs[j] === undefined) buffers.uvs[j] = [];
  1208. buffers.uvs[j].push(faceUVs[j][0]);
  1209. buffers.uvs[j].push(faceUVs[j][1]);
  1210. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2]);
  1211. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]);
  1212. buffers.uvs[j].push(faceUVs[j][i * 2]);
  1213. buffers.uvs[j].push(faceUVs[j][i * 2 + 1]);
  1214. });
  1215. }
  1216. }
  1217. },
  1218. addMorphTargets: function addMorphTargets(parentGeo, parentGeoNode, morphTarget, preTransform) {
  1219. if (morphTarget === null) return;
  1220. parentGeo.morphAttributes.position = [];
  1221. parentGeo.morphAttributes.normal = [];
  1222. var self = this;
  1223. morphTarget.rawTargets.forEach(function (rawTarget) {
  1224. var morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
  1225. if (morphGeoNode !== undefined) {
  1226. self.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform);
  1227. }
  1228. });
  1229. },
  1230. // a morph geometry node is similar to a standard node, and the node is also contained
  1231. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1232. // and a special attribute Index defining which vertices of the original geometry are affected
  1233. // Normal and position attributes only have data for the vertices that are affected by the morph
  1234. genMorphGeometry: function genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform) {
  1235. var morphGeo = new THREE.BufferGeometry();
  1236. if (morphGeoNode.attrName) morphGeo.name = morphGeoNode.attrName;
  1237. var vertexIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
  1238. // make a copy of the parent's vertex positions
  1239. var vertexPositions = parentGeoNode.Vertices !== undefined ? parentGeoNode.Vertices.a.slice() : [];
  1240. var morphPositions = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  1241. var indices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  1242. for (var i = 0; i < indices.length; i++) {
  1243. var morphIndex = indices[i] * 3;
  1244. // FBX format uses blend shapes rather than morph targets. This can be converted
  1245. // by additively combining the blend shape positions with the original geometry's positions
  1246. vertexPositions[morphIndex] += morphPositions[i * 3];
  1247. vertexPositions[morphIndex + 1] += morphPositions[i * 3 + 1];
  1248. vertexPositions[morphIndex + 2] += morphPositions[i * 3 + 2];
  1249. }
  1250. // TODO: add morph normal support
  1251. var morphGeoInfo = {
  1252. vertexIndices: vertexIndices,
  1253. vertexPositions: vertexPositions
  1254. };
  1255. var morphBuffers = this.genBuffers(morphGeoInfo);
  1256. var positionAttribute = new THREE.Float32BufferAttribute(morphBuffers.vertex, 3);
  1257. positionAttribute.name = morphGeoNode.attrName;
  1258. preTransform.applyToBufferAttribute(positionAttribute);
  1259. parentGeo.morphAttributes.position.push(positionAttribute);
  1260. },
  1261. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1262. parseNormals: function parseNormals(NormalNode) {
  1263. var mappingType = NormalNode.MappingInformationType;
  1264. var referenceType = NormalNode.ReferenceInformationType;
  1265. var buffer = NormalNode.Normals.a;
  1266. var indexBuffer = [];
  1267. if (referenceType === 'IndexToDirect') {
  1268. if ('NormalIndex' in NormalNode) {
  1269. indexBuffer = NormalNode.NormalIndex.a;
  1270. } else if ('NormalsIndex' in NormalNode) {
  1271. indexBuffer = NormalNode.NormalsIndex.a;
  1272. }
  1273. }
  1274. return {
  1275. dataSize: 3,
  1276. buffer: buffer,
  1277. indices: indexBuffer,
  1278. mappingType: mappingType,
  1279. referenceType: referenceType
  1280. };
  1281. },
  1282. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1283. parseUVs: function parseUVs(UVNode) {
  1284. var mappingType = UVNode.MappingInformationType;
  1285. var referenceType = UVNode.ReferenceInformationType;
  1286. var buffer = UVNode.UV.a;
  1287. var indexBuffer = [];
  1288. if (referenceType === 'IndexToDirect') {
  1289. indexBuffer = UVNode.UVIndex.a;
  1290. }
  1291. return {
  1292. dataSize: 2,
  1293. buffer: buffer,
  1294. indices: indexBuffer,
  1295. mappingType: mappingType,
  1296. referenceType: referenceType
  1297. };
  1298. },
  1299. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1300. parseVertexColors: function parseVertexColors(ColorNode) {
  1301. var mappingType = ColorNode.MappingInformationType;
  1302. var referenceType = ColorNode.ReferenceInformationType;
  1303. var buffer = ColorNode.Colors.a;
  1304. var indexBuffer = [];
  1305. if (referenceType === 'IndexToDirect') {
  1306. indexBuffer = ColorNode.ColorIndex.a;
  1307. }
  1308. return {
  1309. dataSize: 4,
  1310. buffer: buffer,
  1311. indices: indexBuffer,
  1312. mappingType: mappingType,
  1313. referenceType: referenceType
  1314. };
  1315. },
  1316. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1317. parseMaterialIndices: function parseMaterialIndices(MaterialNode) {
  1318. var mappingType = MaterialNode.MappingInformationType;
  1319. var referenceType = MaterialNode.ReferenceInformationType;
  1320. if (mappingType === 'NoMappingInformation') {
  1321. return {
  1322. dataSize: 1,
  1323. buffer: [0],
  1324. indices: [0],
  1325. mappingType: 'AllSame',
  1326. referenceType: referenceType
  1327. };
  1328. }
  1329. var materialIndexBuffer = MaterialNode.Materials.a;
  1330. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1331. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1332. // for conforming with the other functions we've written for other data.
  1333. var materialIndices = [];
  1334. for (var i = 0; i < materialIndexBuffer.length; ++i) {
  1335. materialIndices.push(i);
  1336. }
  1337. return {
  1338. dataSize: 1,
  1339. buffer: materialIndexBuffer,
  1340. indices: materialIndices,
  1341. mappingType: mappingType,
  1342. referenceType: referenceType
  1343. };
  1344. },
  1345. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1346. parseNurbsGeometry: function parseNurbsGeometry(geoNode) {
  1347. if (THREE.NURBSCurve === undefined) {
  1348. console.error('THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.');
  1349. return new THREE.BufferGeometry();
  1350. }
  1351. var order = parseInt(geoNode.Order);
  1352. if (isNaN(order)) {
  1353. console.error('THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id);
  1354. return new THREE.BufferGeometry();
  1355. }
  1356. var degree = order - 1;
  1357. var knots = geoNode.KnotVector.a;
  1358. var controlPoints = [];
  1359. var pointsValues = geoNode.Points.a;
  1360. for (var i = 0, l = pointsValues.length; i < l; i += 4) {
  1361. controlPoints.push(new THREE.Vector4().fromArray(pointsValues, i));
  1362. }
  1363. var startKnot, endKnot;
  1364. if (geoNode.Form === 'Closed') {
  1365. controlPoints.push(controlPoints[0]);
  1366. } else if (geoNode.Form === 'Periodic') {
  1367. startKnot = degree;
  1368. endKnot = knots.length - 1 - startKnot;
  1369. for (var i = 0; i < degree; ++i) {
  1370. controlPoints.push(controlPoints[i]);
  1371. }
  1372. }
  1373. var curve = new THREE.NURBSCurve(degree, knots, controlPoints, startKnot, endKnot);
  1374. var vertices = curve.getPoints(controlPoints.length * 7);
  1375. var positions = new Float32Array(vertices.length * 3);
  1376. vertices.forEach(function (vertex, i) {
  1377. vertex.toArray(positions, i * 3);
  1378. });
  1379. var geometry = new THREE.BufferGeometry();
  1380. geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
  1381. return geometry;
  1382. }
  1383. };
  1384. // parse animation data from FBXTree
  1385. function AnimationParser() {}
  1386. AnimationParser.prototype = {
  1387. constructor: AnimationParser,
  1388. // take raw animation clips and turn them into three.js animation clips
  1389. parse: function parse() {
  1390. var animationClips = [];
  1391. var rawClips = this.parseClips();
  1392. if (rawClips === undefined) return animationClips;
  1393. for (var key in rawClips) {
  1394. var rawClip = rawClips[key];
  1395. var clip = this.addClip(rawClip);
  1396. animationClips.push(clip);
  1397. }
  1398. return animationClips;
  1399. },
  1400. parseClips: function parseClips() {
  1401. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1402. // if this is undefined we can safely assume there are no animations
  1403. if (fbxTree.Objects.AnimationCurve === undefined) return undefined;
  1404. var curveNodesMap = this.parseAnimationCurveNodes();
  1405. this.parseAnimationCurves(curveNodesMap);
  1406. var layersMap = this.parseAnimationLayers(curveNodesMap);
  1407. var rawClips = this.parseAnimStacks(layersMap);
  1408. return rawClips;
  1409. },
  1410. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1411. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1412. // and is referenced by an AnimationLayer
  1413. parseAnimationCurveNodes: function parseAnimationCurveNodes() {
  1414. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1415. var curveNodesMap = new Map();
  1416. for (var nodeID in rawCurveNodes) {
  1417. var rawCurveNode = rawCurveNodes[nodeID];
  1418. if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
  1419. var curveNode = {
  1420. id: rawCurveNode.id,
  1421. attr: rawCurveNode.attrName,
  1422. curves: {}
  1423. };
  1424. curveNodesMap.set(curveNode.id, curveNode);
  1425. }
  1426. }
  1427. return curveNodesMap;
  1428. },
  1429. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1430. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1431. // axis ( e.g. times and values of x rotation)
  1432. parseAnimationCurves: function parseAnimationCurves(curveNodesMap) {
  1433. var rawCurves = fbxTree.Objects.AnimationCurve;
  1434. // TODO: Many values are identical up to roundoff error, but won't be optimised
  1435. // e.g. position times: [0, 0.4, 0. 8]
  1436. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1437. // clearly, this should be optimised to
  1438. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1439. // this shows up in nearly every FBX file, and generally time array is length > 100
  1440. for (var nodeID in rawCurves) {
  1441. var animationCurve = {
  1442. id: rawCurves[nodeID].id,
  1443. times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
  1444. values: rawCurves[nodeID].KeyValueFloat.a
  1445. };
  1446. var relationships = connections.get(animationCurve.id);
  1447. if (relationships !== undefined) {
  1448. var animationCurveID = relationships.parents[0].ID;
  1449. var animationCurveRelationship = relationships.parents[0].relationship;
  1450. if (animationCurveRelationship.match(/X/)) {
  1451. curveNodesMap.get(animationCurveID).curves['x'] = animationCurve;
  1452. } else if (animationCurveRelationship.match(/Y/)) {
  1453. curveNodesMap.get(animationCurveID).curves['y'] = animationCurve;
  1454. } else if (animationCurveRelationship.match(/Z/)) {
  1455. curveNodesMap.get(animationCurveID).curves['z'] = animationCurve;
  1456. } else if (animationCurveRelationship.match(/d|DeformPercent/) && curveNodesMap.has(animationCurveID)) {
  1457. curveNodesMap.get(animationCurveID).curves['morph'] = animationCurve;
  1458. }
  1459. }
  1460. }
  1461. },
  1462. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1463. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1464. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1465. parseAnimationLayers: function parseAnimationLayers(curveNodesMap) {
  1466. var rawLayers = fbxTree.Objects.AnimationLayer;
  1467. var layersMap = new Map();
  1468. for (var nodeID in rawLayers) {
  1469. var layerCurveNodes = [];
  1470. var connection = connections.get(parseInt(nodeID));
  1471. if (connection !== undefined) {
  1472. // all the animationCurveNodes used in the layer
  1473. var children = connection.children;
  1474. var self = this;
  1475. children.forEach(function (child, i) {
  1476. if (curveNodesMap.has(child.ID)) {
  1477. var curveNode = curveNodesMap.get(child.ID);
  1478. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1479. if (curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined) {
  1480. if (layerCurveNodes[i] === undefined) {
  1481. var modelID;
  1482. connections.get(child.ID).parents.forEach(function (parent) {
  1483. if (parent.relationship !== undefined) modelID = parent.ID;
  1484. });
  1485. var rawModel = fbxTree.Objects.Model[modelID.toString()];
  1486. var node = {
  1487. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  1488. initialPosition: [0, 0, 0],
  1489. initialRotation: [0, 0, 0],
  1490. initialScale: [1, 1, 1],
  1491. transform: self.getModelAnimTransform(rawModel)
  1492. };
  1493. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1494. // animation value as well
  1495. if ('PreRotation' in rawModel) node.preRotations = rawModel.PreRotation.value;
  1496. if ('PostRotation' in rawModel) node.postRotations = rawModel.PostRotation.value;
  1497. layerCurveNodes[i] = node;
  1498. }
  1499. layerCurveNodes[i][curveNode.attr] = curveNode;
  1500. } else if (curveNode.curves.morph !== undefined) {
  1501. if (layerCurveNodes[i] === undefined) {
  1502. var deformerID;
  1503. connections.get(child.ID).parents.forEach(function (parent) {
  1504. if (parent.relationship !== undefined) deformerID = parent.ID;
  1505. });
  1506. var morpherID = connections.get(deformerID).parents[0].ID;
  1507. var geoID = connections.get(morpherID).parents[0].ID;
  1508. // assuming geometry is not used in more than one model
  1509. var modelID = connections.get(geoID).parents[0].ID;
  1510. var rawModel = fbxTree.Objects.Model[modelID];
  1511. var node = {
  1512. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  1513. morphName: fbxTree.Objects.Deformer[deformerID].attrName
  1514. };
  1515. layerCurveNodes[i] = node;
  1516. }
  1517. layerCurveNodes[i][curveNode.attr] = curveNode;
  1518. }
  1519. }
  1520. });
  1521. layersMap.set(parseInt(nodeID), layerCurveNodes);
  1522. }
  1523. }
  1524. return layersMap;
  1525. },
  1526. getModelAnimTransform: function getModelAnimTransform(modelNode) {
  1527. var transformData = {};
  1528. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  1529. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  1530. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  1531. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  1532. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  1533. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  1534. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  1535. return generateTransform(transformData);
  1536. },
  1537. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1538. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  1539. parseAnimStacks: function parseAnimStacks(layersMap) {
  1540. var rawStacks = fbxTree.Objects.AnimationStack;
  1541. // connect the stacks (clips) up to the layers
  1542. var rawClips = {};
  1543. for (var nodeID in rawStacks) {
  1544. var children = connections.get(parseInt(nodeID)).children;
  1545. if (children.length > 1) {
  1546. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1547. // where there are multiple layers per stack, we'll display a warning
  1548. console.warn('THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.');
  1549. }
  1550. var layer = layersMap.get(children[0].ID);
  1551. rawClips[nodeID] = {
  1552. name: rawStacks[nodeID].attrName,
  1553. layer: layer
  1554. };
  1555. }
  1556. return rawClips;
  1557. },
  1558. addClip: function addClip(rawClip) {
  1559. var tracks = [];
  1560. var self = this;
  1561. rawClip.layer.forEach(function (rawTracks) {
  1562. tracks = tracks.concat(self.generateTracks(rawTracks));
  1563. });
  1564. return new THREE.AnimationClip(rawClip.name, -1, tracks);
  1565. },
  1566. generateTracks: function generateTracks(rawTracks) {
  1567. var tracks = [];
  1568. var initialPosition = new THREE.Vector3();
  1569. var initialRotation = new THREE.Quaternion();
  1570. var initialScale = new THREE.Vector3();
  1571. if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, initialRotation, initialScale);
  1572. initialPosition = initialPosition.toArray();
  1573. initialRotation = new THREE.Euler().setFromQuaternion(initialRotation).toArray(); // todo: euler order
  1574. initialScale = initialScale.toArray();
  1575. if (rawTracks.T !== undefined && Object.keys(rawTracks.T.curves).length > 0) {
  1576. var positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position');
  1577. if (positionTrack !== undefined) tracks.push(positionTrack);
  1578. }
  1579. if (rawTracks.R !== undefined && Object.keys(rawTracks.R.curves).length > 0) {
  1580. var rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations);
  1581. if (rotationTrack !== undefined) tracks.push(rotationTrack);
  1582. }
  1583. if (rawTracks.S !== undefined && Object.keys(rawTracks.S.curves).length > 0) {
  1584. var scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale');
  1585. if (scaleTrack !== undefined) tracks.push(scaleTrack);
  1586. }
  1587. if (rawTracks.DeformPercent !== undefined) {
  1588. var morphTrack = this.generateMorphTrack(rawTracks);
  1589. if (morphTrack !== undefined) tracks.push(morphTrack);
  1590. }
  1591. return tracks;
  1592. },
  1593. generateVectorTrack: function generateVectorTrack(modelName, curves, initialValue, type) {
  1594. var times = this.getTimesForAllAxes(curves);
  1595. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  1596. return new THREE.VectorKeyframeTrack(modelName + '.' + type, times, values);
  1597. },
  1598. generateRotationTrack: function generateRotationTrack(modelName, curves, initialValue, preRotations, postRotations) {
  1599. if (curves.x !== undefined) {
  1600. this.interpolateRotations(curves.x);
  1601. curves.x.values = curves.x.values.map(THREE.Math.degToRad);
  1602. }
  1603. if (curves.y !== undefined) {
  1604. this.interpolateRotations(curves.y);
  1605. curves.y.values = curves.y.values.map(THREE.Math.degToRad);
  1606. }
  1607. if (curves.z !== undefined) {
  1608. this.interpolateRotations(curves.z);
  1609. curves.z.values = curves.z.values.map(THREE.Math.degToRad);
  1610. }
  1611. var times = this.getTimesForAllAxes(curves);
  1612. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  1613. if (preRotations !== undefined) {
  1614. preRotations = preRotations.map(THREE.Math.degToRad);
  1615. preRotations.push('ZYX');
  1616. preRotations = new THREE.Euler().fromArray(preRotations);
  1617. preRotations = new THREE.Quaternion().setFromEuler(preRotations);
  1618. }
  1619. if (postRotations !== undefined) {
  1620. postRotations = postRotations.map(THREE.Math.degToRad);
  1621. postRotations.push('ZYX');
  1622. postRotations = new THREE.Euler().fromArray(postRotations);
  1623. postRotations = new THREE.Quaternion().setFromEuler(postRotations).inverse();
  1624. }
  1625. var quaternion = new THREE.Quaternion();
  1626. var euler = new THREE.Euler();
  1627. var quaternionValues = [];
  1628. for (var i = 0; i < values.length; i += 3) {
  1629. euler.set(values[i], values[i + 1], values[i + 2], 'ZYX');
  1630. quaternion.setFromEuler(euler);
  1631. if (preRotations !== undefined) quaternion.premultiply(preRotations);
  1632. if (postRotations !== undefined) quaternion.multiply(postRotations);
  1633. quaternion.toArray(quaternionValues, i / 3 * 4);
  1634. }
  1635. return new THREE.QuaternionKeyframeTrack(modelName + '.quaternion', times, quaternionValues);
  1636. },
  1637. generateMorphTrack: function generateMorphTrack(rawTracks) {
  1638. var curves = rawTracks.DeformPercent.curves.morph;
  1639. var values = curves.values.map(function (val) {
  1640. return val / 100;
  1641. });
  1642. var morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];
  1643. return new THREE.NumberKeyframeTrack(rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values);
  1644. },
  1645. // For all animated objects, times are defined separately for each axis
  1646. // Here we'll combine the times into one sorted array without duplicates
  1647. getTimesForAllAxes: function getTimesForAllAxes(curves) {
  1648. var times = [];
  1649. // first join together the times for each axis, if defined
  1650. if (curves.x !== undefined) times = times.concat(curves.x.times);
  1651. if (curves.y !== undefined) times = times.concat(curves.y.times);
  1652. if (curves.z !== undefined) times = times.concat(curves.z.times);
  1653. // then sort them and remove duplicates
  1654. times = times.sort(function (a, b) {
  1655. return a - b;
  1656. }).filter(function (elem, index, array) {
  1657. return array.indexOf(elem) == index;
  1658. });
  1659. return times;
  1660. },
  1661. getKeyframeTrackValues: function getKeyframeTrackValues(times, curves, initialValue) {
  1662. var prevValue = initialValue;
  1663. var values = [];
  1664. var xIndex = -1;
  1665. var yIndex = -1;
  1666. var zIndex = -1;
  1667. times.forEach(function (time) {
  1668. if (curves.x) xIndex = curves.x.times.indexOf(time);
  1669. if (curves.y) yIndex = curves.y.times.indexOf(time);
  1670. if (curves.z) zIndex = curves.z.times.indexOf(time);
  1671. // if there is an x value defined for this frame, use that
  1672. if (xIndex !== -1) {
  1673. var xValue = curves.x.values[xIndex];
  1674. values.push(xValue);
  1675. prevValue[0] = xValue;
  1676. } else {
  1677. // otherwise use the x value from the previous frame
  1678. values.push(prevValue[0]);
  1679. }
  1680. if (yIndex !== -1) {
  1681. var yValue = curves.y.values[yIndex];
  1682. values.push(yValue);
  1683. prevValue[1] = yValue;
  1684. } else {
  1685. values.push(prevValue[1]);
  1686. }
  1687. if (zIndex !== -1) {
  1688. var zValue = curves.z.values[zIndex];
  1689. values.push(zValue);
  1690. prevValue[2] = zValue;
  1691. } else {
  1692. values.push(prevValue[2]);
  1693. }
  1694. });
  1695. return values;
  1696. },
  1697. // Rotations are defined as Euler angles which can have values of any size
  1698. // These will be converted to quaternions which don't support values greater than
  1699. // PI, so we'll interpolate large rotations
  1700. interpolateRotations: function interpolateRotations(curve) {
  1701. for (var i = 1; i < curve.values.length; i++) {
  1702. var initialValue = curve.values[i - 1];
  1703. var valuesSpan = curve.values[i] - initialValue;
  1704. var absoluteSpan = Math.abs(valuesSpan);
  1705. if (absoluteSpan >= 180) {
  1706. var numSubIntervals = absoluteSpan / 180;
  1707. var step = valuesSpan / numSubIntervals;
  1708. var nextValue = initialValue + step;
  1709. var initialTime = curve.times[i - 1];
  1710. var timeSpan = curve.times[i] - initialTime;
  1711. var interval = timeSpan / numSubIntervals;
  1712. var nextTime = initialTime + interval;
  1713. var interpolatedTimes = [];
  1714. var interpolatedValues = [];
  1715. while (nextTime < curve.times[i]) {
  1716. interpolatedTimes.push(nextTime);
  1717. nextTime += interval;
  1718. interpolatedValues.push(nextValue);
  1719. nextValue += step;
  1720. }
  1721. curve.times = inject(curve.times, i, interpolatedTimes);
  1722. curve.values = inject(curve.values, i, interpolatedValues);
  1723. }
  1724. }
  1725. }
  1726. };
  1727. // parse an FBX file in ASCII format
  1728. function TextParser() {}
  1729. TextParser.prototype = {
  1730. constructor: TextParser,
  1731. getPrevNode: function getPrevNode() {
  1732. return this.nodeStack[this.currentIndent - 2];
  1733. },
  1734. getCurrentNode: function getCurrentNode() {
  1735. return this.nodeStack[this.currentIndent - 1];
  1736. },
  1737. getCurrentProp: function getCurrentProp() {
  1738. return this.currentProp;
  1739. },
  1740. pushStack: function pushStack(node) {
  1741. this.nodeStack.push(node);
  1742. this.currentIndent += 1;
  1743. },
  1744. popStack: function popStack() {
  1745. this.nodeStack.pop();
  1746. this.currentIndent -= 1;
  1747. },
  1748. setCurrentProp: function setCurrentProp(val, name) {
  1749. this.currentProp = val;
  1750. this.currentPropName = name;
  1751. },
  1752. parse: function parse(text) {
  1753. this.currentIndent = 0;
  1754. console.log("FBXTree: ", FBXTree);
  1755. this.allNodes = new FBXTree();
  1756. this.nodeStack = [];
  1757. this.currentProp = [];
  1758. this.currentPropName = '';
  1759. var self = this;
  1760. var split = text.split(/[\r\n]+/);
  1761. split.forEach(function (line, i) {
  1762. var matchComment = line.match(/^[\s\t]*;/);
  1763. var matchEmpty = line.match(/^[\s\t]*$/);
  1764. if (matchComment || matchEmpty) return;
  1765. var matchBeginning = line.match('^\\t{' + self.currentIndent + '}(\\w+):(.*){', '');
  1766. var matchProperty = line.match('^\\t{' + self.currentIndent + '}(\\w+):[\\s\\t\\r\\n](.*)');
  1767. var matchEnd = line.match('^\\t{' + (self.currentIndent - 1) + '}}');
  1768. if (matchBeginning) {
  1769. self.parseNodeBegin(line, matchBeginning);
  1770. } else if (matchProperty) {
  1771. self.parseNodeProperty(line, matchProperty, split[++i]);
  1772. } else if (matchEnd) {
  1773. self.popStack();
  1774. } else if (line.match(/^[^\s\t}]/)) {
  1775. // large arrays are split over multiple lines terminated with a ',' character
  1776. // if this is encountered the line needs to be joined to the previous line
  1777. self.parseNodePropertyContinued(line);
  1778. }
  1779. });
  1780. return this.allNodes;
  1781. },
  1782. parseNodeBegin: function parseNodeBegin(line, property) {
  1783. var nodeName = property[1].trim().replace(/^"/, '').replace(/"$/, '');
  1784. var nodeAttrs = property[2].split(',').map(function (attr) {
  1785. return attr.trim().replace(/^"/, '').replace(/"$/, '');
  1786. });
  1787. var node = { name: nodeName };
  1788. var attrs = this.parseNodeAttr(nodeAttrs);
  1789. var currentNode = this.getCurrentNode();
  1790. // a top node
  1791. if (this.currentIndent === 0) {
  1792. this.allNodes.add(nodeName, node);
  1793. } else {
  1794. // a subnode
  1795. // if the subnode already exists, append it
  1796. if (nodeName in currentNode) {
  1797. // special case Pose needs PoseNodes as an array
  1798. if (nodeName === 'PoseNode') {
  1799. currentNode.PoseNode.push(node);
  1800. } else if (currentNode[nodeName].id !== undefined) {
  1801. currentNode[nodeName] = {};
  1802. currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName];
  1803. }
  1804. if (attrs.id !== '') currentNode[nodeName][attrs.id] = node;
  1805. } else if (typeof attrs.id === 'number') {
  1806. currentNode[nodeName] = {};
  1807. currentNode[nodeName][attrs.id] = node;
  1808. } else if (nodeName !== 'Properties70') {
  1809. if (nodeName === 'PoseNode') currentNode[nodeName] = [node];else currentNode[nodeName] = node;
  1810. }
  1811. }
  1812. if (typeof attrs.id === 'number') node.id = attrs.id;
  1813. if (attrs.name !== '') node.attrName = attrs.name;
  1814. if (attrs.type !== '') node.attrType = attrs.type;
  1815. this.pushStack(node);
  1816. },
  1817. parseNodeAttr: function parseNodeAttr(attrs) {
  1818. var id = attrs[0];
  1819. if (attrs[0] !== '') {
  1820. id = parseInt(attrs[0]);
  1821. if (isNaN(id)) {
  1822. id = attrs[0];
  1823. }
  1824. }
  1825. var name = '',
  1826. type = '';
  1827. if (attrs.length > 1) {
  1828. name = attrs[1].replace(/^(\w+)::/, '');
  1829. type = attrs[2];
  1830. }
  1831. return { id: id, name: name, type: type };
  1832. },
  1833. parseNodeProperty: function parseNodeProperty(line, property, contentLine) {
  1834. var propName = property[1].replace(/^"/, '').replace(/"$/, '').trim();
  1835. var propValue = property[2].replace(/^"/, '').replace(/"$/, '').trim();
  1836. // for special case: base64 image data follows "Content: ," line
  1837. // Content: ,
  1838. // "/9j/4RDaRXhpZgAATU0A..."
  1839. if (propName === 'Content' && propValue === ',') {
  1840. propValue = contentLine.replace(/"/g, '').replace(/,$/, '').trim();
  1841. }
  1842. var currentNode = this.getCurrentNode();
  1843. var parentName = currentNode.name;
  1844. if (parentName === 'Properties70') {
  1845. this.parseNodeSpecialProperty(line, propName, propValue);
  1846. return;
  1847. }
  1848. // Connections
  1849. if (propName === 'C') {
  1850. var connProps = propValue.split(',').slice(1);
  1851. var from = parseInt(connProps[0]);
  1852. var to = parseInt(connProps[1]);
  1853. var rest = propValue.split(',').slice(3);
  1854. rest = rest.map(function (elem) {
  1855. return elem.trim().replace(/^"/, '');
  1856. });
  1857. propName = 'connections';
  1858. propValue = [from, to];
  1859. append(propValue, rest);
  1860. if (currentNode[propName] === undefined) {
  1861. currentNode[propName] = [];
  1862. }
  1863. }
  1864. // Node
  1865. if (propName === 'Node') currentNode.id = propValue;
  1866. // connections
  1867. if (propName in currentNode && Array.isArray(currentNode[propName])) {
  1868. currentNode[propName].push(propValue);
  1869. } else {
  1870. if (propName !== 'a') currentNode[propName] = propValue;else currentNode.a = propValue;
  1871. }
  1872. this.setCurrentProp(currentNode, propName);
  1873. // convert string to array, unless it ends in ',' in which case more will be added to it
  1874. if (propName === 'a' && propValue.slice(-1) !== ',') {
  1875. currentNode.a = parseNumberArray(propValue);
  1876. }
  1877. },
  1878. parseNodePropertyContinued: function parseNodePropertyContinued(line) {
  1879. var currentNode = this.getCurrentNode();
  1880. currentNode.a += line;
  1881. // if the line doesn't end in ',' we have reached the end of the property value
  1882. // so convert the string to an array
  1883. if (line.slice(-1) !== ',') {
  1884. currentNode.a = parseNumberArray(currentNode.a);
  1885. }
  1886. },
  1887. // parse "Property70"
  1888. parseNodeSpecialProperty: function parseNodeSpecialProperty(line, propName, propValue) {
  1889. // split this
  1890. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1891. // into array like below
  1892. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1893. var props = propValue.split('",').map(function (prop) {
  1894. return prop.trim().replace(/^\"/, '').replace(/\s/, '_');
  1895. });
  1896. var innerPropName = props[0];
  1897. var innerPropType1 = props[1];
  1898. var innerPropType2 = props[2];
  1899. var innerPropFlag = props[3];
  1900. var innerPropValue = props[4];
  1901. // cast values where needed, otherwise leave as strings
  1902. switch (innerPropType1) {
  1903. case 'int':
  1904. case 'enum':
  1905. case 'bool':
  1906. case 'ULongLong':
  1907. case 'double':
  1908. case 'Number':
  1909. case 'FieldOfView':
  1910. innerPropValue = parseFloat(innerPropValue);
  1911. break;
  1912. case 'Color':
  1913. case 'ColorRGB':
  1914. case 'Vector3D':
  1915. case 'Lcl_Translation':
  1916. case 'Lcl_Rotation':
  1917. case 'Lcl_Scaling':
  1918. innerPropValue = parseNumberArray(innerPropValue);
  1919. break;
  1920. }
  1921. // CAUTION: these props must append to parent's parent
  1922. this.getPrevNode()[innerPropName] = {
  1923. 'type': innerPropType1,
  1924. 'type2': innerPropType2,
  1925. 'flag': innerPropFlag,
  1926. 'value': innerPropValue
  1927. };
  1928. this.setCurrentProp(this.getPrevNode(), innerPropName);
  1929. }
  1930. };
  1931. // Parse an FBX file in Binary format
  1932. function BinaryParser() {}
  1933. BinaryParser.prototype = {
  1934. constructor: BinaryParser,
  1935. parse: function parse(buffer) {
  1936. var reader = new BinaryReader(buffer);
  1937. reader.skip(23); // skip magic 23 bytes
  1938. var version = reader.getUint32();
  1939. console.log('THREE.FBXLoader: FBX binary version: ' + version);
  1940. var allNodes = new FBXTree();
  1941. while (!this.endOfContent(reader)) {
  1942. var node = this.parseNode(reader, version);
  1943. if (node !== null) allNodes.add(node.name, node);
  1944. }
  1945. return allNodes;
  1946. },
  1947. // Check if reader has reached the end of content.
  1948. endOfContent: function endOfContent(reader) {
  1949. // footer size: 160bytes + 16-byte alignment padding
  1950. // - 16bytes: magic
  1951. // - padding til 16-byte alignment (at least 1byte?)
  1952. // (seems like some exporters embed fixed 15 or 16bytes?)
  1953. // - 4bytes: magic
  1954. // - 4bytes: version
  1955. // - 120bytes: zero
  1956. // - 16bytes: magic
  1957. if (reader.size() % 16 === 0) {
  1958. return (reader.getOffset() + 160 + 16 & ~0xf) >= reader.size();
  1959. } else {
  1960. return reader.getOffset() + 160 + 16 >= reader.size();
  1961. }
  1962. },
  1963. // recursively parse nodes until the end of the file is reached
  1964. parseNode: function parseNode(reader, version) {
  1965. var node = {};
  1966. // The first three data sizes depends on version.
  1967. var endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1968. var numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1969. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  1970. var propertyListLen = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1971. var nameLen = reader.getUint8();
  1972. var name = reader.getString(nameLen);
  1973. // Regards this node as NULL-record if endOffset is zero
  1974. if (endOffset === 0) return null;
  1975. var propertyList = [];
  1976. for (var i = 0; i < numProperties; i++) {
  1977. propertyList.push(this.parseProperty(reader));
  1978. }
  1979. // Regards the first three elements in propertyList as id, attrName, and attrType
  1980. var id = propertyList.length > 0 ? propertyList[0] : '';
  1981. var attrName = propertyList.length > 1 ? propertyList[1] : '';
  1982. var attrType = propertyList.length > 2 ? propertyList[2] : '';
  1983. // check if this node represents just a single property
  1984. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1985. node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  1986. while (endOffset > reader.getOffset()) {
  1987. var subNode = this.parseNode(reader, version);
  1988. if (subNode !== null) this.parseSubNode(name, node, subNode);
  1989. }
  1990. node.propertyList = propertyList; // raw property list used by parent
  1991. if (typeof id === 'number') node.id = id;
  1992. if (attrName !== '') node.attrName = attrName;
  1993. if (attrType !== '') node.attrType = attrType;
  1994. if (name !== '') node.name = name;
  1995. return node;
  1996. },
  1997. parseSubNode: function parseSubNode(name, node, subNode) {
  1998. // special case: child node is single property
  1999. if (subNode.singleProperty === true) {
  2000. var value = subNode.propertyList[0];
  2001. if (Array.isArray(value)) {
  2002. node[subNode.name] = subNode;
  2003. subNode.a = value;
  2004. } else {
  2005. node[subNode.name] = value;
  2006. }
  2007. } else if (name === 'Connections' && subNode.name === 'C') {
  2008. var array = [];
  2009. subNode.propertyList.forEach(function (property, i) {
  2010. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  2011. if (i !== 0) array.push(property);
  2012. });
  2013. if (node.connections === undefined) {
  2014. node.connections = [];
  2015. }
  2016. node.connections.push(array);
  2017. } else if (subNode.name === 'Properties70') {
  2018. var keys = Object.keys(subNode);
  2019. keys.forEach(function (key) {
  2020. node[key] = subNode[key];
  2021. });
  2022. } else if (name === 'Properties70' && subNode.name === 'P') {
  2023. var innerPropName = subNode.propertyList[0];
  2024. var innerPropType1 = subNode.propertyList[1];
  2025. var innerPropType2 = subNode.propertyList[2];
  2026. var innerPropFlag = subNode.propertyList[3];
  2027. var innerPropValue;
  2028. if (innerPropName.indexOf('Lcl ') === 0) innerPropName = innerPropName.replace('Lcl ', 'Lcl_');
  2029. if (innerPropType1.indexOf('Lcl ') === 0) innerPropType1 = innerPropType1.replace('Lcl ', 'Lcl_');
  2030. if (innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf('Lcl_') === 0) {
  2031. innerPropValue = [subNode.propertyList[4], subNode.propertyList[5], subNode.propertyList[6]];
  2032. } else {
  2033. innerPropValue = subNode.propertyList[4];
  2034. }
  2035. // this will be copied to parent, see above
  2036. node[innerPropName] = {
  2037. 'type': innerPropType1,
  2038. 'type2': innerPropType2,
  2039. 'flag': innerPropFlag,
  2040. 'value': innerPropValue
  2041. };
  2042. } else if (node[subNode.name] === undefined) {
  2043. if (typeof subNode.id === 'number') {
  2044. node[subNode.name] = {};
  2045. node[subNode.name][subNode.id] = subNode;
  2046. } else {
  2047. node[subNode.name] = subNode;
  2048. }
  2049. } else {
  2050. if (subNode.name === 'PoseNode') {
  2051. if (!Array.isArray(node[subNode.name])) {
  2052. node[subNode.name] = [node[subNode.name]];
  2053. }
  2054. node[subNode.name].push(subNode);
  2055. } else if (node[subNode.name][subNode.id] === undefined) {
  2056. node[subNode.name][subNode.id] = subNode;
  2057. }
  2058. }
  2059. },
  2060. parseProperty: function parseProperty(reader) {
  2061. var type = reader.getString(1);
  2062. switch (type) {
  2063. case 'C':
  2064. return reader.getBoolean();
  2065. case 'D':
  2066. return reader.getFloat64();
  2067. case 'F':
  2068. return reader.getFloat32();
  2069. case 'I':
  2070. return reader.getInt32();
  2071. case 'L':
  2072. return reader.getInt64();
  2073. case 'R':
  2074. var length = reader.getUint32();
  2075. return reader.getArrayBuffer(length);
  2076. case 'S':
  2077. var length = reader.getUint32();
  2078. return reader.getString(length);
  2079. case 'Y':
  2080. return reader.getInt16();
  2081. case 'b':
  2082. case 'c':
  2083. case 'd':
  2084. case 'f':
  2085. case 'i':
  2086. case 'l':
  2087. var arrayLength = reader.getUint32();
  2088. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2089. var compressedLength = reader.getUint32();
  2090. if (encoding === 0) {
  2091. switch (type) {
  2092. case 'b':
  2093. case 'c':
  2094. return reader.getBooleanArray(arrayLength);
  2095. case 'd':
  2096. return reader.getFloat64Array(arrayLength);
  2097. case 'f':
  2098. return reader.getFloat32Array(arrayLength);
  2099. case 'i':
  2100. return reader.getInt32Array(arrayLength);
  2101. case 'l':
  2102. return reader.getInt64Array(arrayLength);
  2103. }
  2104. }
  2105. if (typeof Zlib === 'undefined') {
  2106. console.error('THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js');
  2107. }
  2108. var inflate = new Zlib.Inflate(new Uint8Array(reader.getArrayBuffer(compressedLength))); // eslint-disable-line no-undef
  2109. var reader2 = new BinaryReader(inflate.decompress().buffer);
  2110. switch (type) {
  2111. case 'b':
  2112. case 'c':
  2113. return reader2.getBooleanArray(arrayLength);
  2114. case 'd':
  2115. return reader2.getFloat64Array(arrayLength);
  2116. case 'f':
  2117. return reader2.getFloat32Array(arrayLength);
  2118. case 'i':
  2119. return reader2.getInt32Array(arrayLength);
  2120. case 'l':
  2121. return reader2.getInt64Array(arrayLength);
  2122. }
  2123. default:
  2124. throw new Error('THREE.FBXLoader: Unknown property type ' + type);
  2125. }
  2126. }
  2127. };
  2128. function BinaryReader(buffer, littleEndian) {
  2129. this.dv = new DataView(buffer);
  2130. this.offset = 0;
  2131. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  2132. }
  2133. BinaryReader.prototype = {
  2134. constructor: BinaryReader,
  2135. getOffset: function getOffset() {
  2136. return this.offset;
  2137. },
  2138. size: function size() {
  2139. return this.dv.buffer.byteLength;
  2140. },
  2141. skip: function skip(length) {
  2142. this.offset += length;
  2143. },
  2144. // seems like true/false representation depends on exporter.
  2145. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2146. // then sees LSB.
  2147. getBoolean: function getBoolean() {
  2148. return (this.getUint8() & 1) === 1;
  2149. },
  2150. getBooleanArray: function getBooleanArray(size) {
  2151. var a = [];
  2152. for (var i = 0; i < size; i++) {
  2153. a.push(this.getBoolean());
  2154. }
  2155. return a;
  2156. },
  2157. getUint8: function getUint8() {
  2158. var value = this.dv.getUint8(this.offset);
  2159. this.offset += 1;
  2160. return value;
  2161. },
  2162. getInt16: function getInt16() {
  2163. var value = this.dv.getInt16(this.offset, this.littleEndian);
  2164. this.offset += 2;
  2165. return value;
  2166. },
  2167. getInt32: function getInt32() {
  2168. var value = this.dv.getInt32(this.offset, this.littleEndian);
  2169. this.offset += 4;
  2170. return value;
  2171. },
  2172. getInt32Array: function getInt32Array(size) {
  2173. var a = [];
  2174. for (var i = 0; i < size; i++) {
  2175. a.push(this.getInt32());
  2176. }
  2177. return a;
  2178. },
  2179. getUint32: function getUint32() {
  2180. var value = this.dv.getUint32(this.offset, this.littleEndian);
  2181. this.offset += 4;
  2182. return value;
  2183. },
  2184. // JavaScript doesn't support 64-bit integer so calculate this here
  2185. // 1 << 32 will return 1 so using multiply operation instead here.
  2186. // There's a possibility that this method returns wrong value if the value
  2187. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2188. // TODO: safely handle 64-bit integer
  2189. getInt64: function getInt64() {
  2190. var low, high;
  2191. if (this.littleEndian) {
  2192. low = this.getUint32();
  2193. high = this.getUint32();
  2194. } else {
  2195. high = this.getUint32();
  2196. low = this.getUint32();
  2197. }
  2198. // calculate negative value
  2199. if (high & 0x80000000) {
  2200. high = ~high & 0xFFFFFFFF;
  2201. low = ~low & 0xFFFFFFFF;
  2202. if (low === 0xFFFFFFFF) high = high + 1 & 0xFFFFFFFF;
  2203. low = low + 1 & 0xFFFFFFFF;
  2204. return -(high * 0x100000000 + low);
  2205. }
  2206. return high * 0x100000000 + low;
  2207. },
  2208. getInt64Array: function getInt64Array(size) {
  2209. var a = [];
  2210. for (var i = 0; i < size; i++) {
  2211. a.push(this.getInt64());
  2212. }
  2213. return a;
  2214. },
  2215. // Note: see getInt64() comment
  2216. getUint64: function getUint64() {
  2217. var low, high;
  2218. if (this.littleEndian) {
  2219. low = this.getUint32();
  2220. high = this.getUint32();
  2221. } else {
  2222. high = this.getUint32();
  2223. low = this.getUint32();
  2224. }
  2225. return high * 0x100000000 + low;
  2226. },
  2227. getFloat32: function getFloat32() {
  2228. var value = this.dv.getFloat32(this.offset, this.littleEndian);
  2229. this.offset += 4;
  2230. return value;
  2231. },
  2232. getFloat32Array: function getFloat32Array(size) {
  2233. var a = [];
  2234. for (var i = 0; i < size; i++) {
  2235. a.push(this.getFloat32());
  2236. }
  2237. return a;
  2238. },
  2239. getFloat64: function getFloat64() {
  2240. var value = this.dv.getFloat64(this.offset, this.littleEndian);
  2241. this.offset += 8;
  2242. return value;
  2243. },
  2244. getFloat64Array: function getFloat64Array(size) {
  2245. var a = [];
  2246. for (var i = 0; i < size; i++) {
  2247. a.push(this.getFloat64());
  2248. }
  2249. return a;
  2250. },
  2251. getArrayBuffer: function getArrayBuffer(size) {
  2252. var value = this.dv.buffer.slice(this.offset, this.offset + size);
  2253. this.offset += size;
  2254. return value;
  2255. },
  2256. getString: function getString(size) {
  2257. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  2258. var a = [];
  2259. for (var i = 0; i < size; i++) {
  2260. a[i] = this.getUint8();
  2261. }
  2262. var nullByte = a.indexOf(0);
  2263. if (nullByte >= 0) a = a.slice(0, nullByte);
  2264. return THREE.LoaderUtils.decodeText(new Uint8Array(a));
  2265. }
  2266. };
  2267. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2268. // and BinaryParser( FBX Binary format)
  2269. function FBXTree() {}
  2270. FBXTree.prototype = {
  2271. constructor: FBXTree,
  2272. add: function add(key, val) {
  2273. this[key] = val;
  2274. }
  2275. };
  2276. // ************** UTILITY FUNCTIONS **************
  2277. function isFbxFormatBinary(buffer) {
  2278. var CORRECT = 'Kaydara FBX Binary \0';
  2279. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length);
  2280. }
  2281. function isFbxFormatASCII(text) {
  2282. var CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];
  2283. var cursor = 0;
  2284. function read(offset) {
  2285. var result = text[offset - 1];
  2286. text = text.slice(cursor + offset);
  2287. cursor++;
  2288. return result;
  2289. }
  2290. for (var i = 0; i < CORRECT.length; ++i) {
  2291. var num = read(1);
  2292. if (num === CORRECT[i]) {
  2293. return false;
  2294. }
  2295. }
  2296. return true;
  2297. }
  2298. function getFbxVersion(text) {
  2299. var versionRegExp = /FBXVersion: (\d+)/;
  2300. var match = text.match(versionRegExp);
  2301. if (match) {
  2302. var version = parseInt(match[1]);
  2303. return version;
  2304. }
  2305. throw new Error('THREE.FBXLoader: Cannot find the version number for the file given.');
  2306. }
  2307. // Converts FBX ticks into real time seconds.
  2308. function convertFBXTimeToSeconds(time) {
  2309. return time / 46186158000;
  2310. }
  2311. var dataArray = [];
  2312. // extracts the data from the correct position in the FBX array based on indexing type
  2313. function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  2314. var index;
  2315. switch (infoObject.mappingType) {
  2316. case 'ByPolygonVertex':
  2317. index = polygonVertexIndex;
  2318. break;
  2319. case 'ByPolygon':
  2320. index = polygonIndex;
  2321. break;
  2322. case 'ByVertice':
  2323. index = vertexIndex;
  2324. break;
  2325. case 'AllSame':
  2326. index = infoObject.indices[0];
  2327. break;
  2328. default:
  2329. console.warn('THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType);
  2330. }
  2331. if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index];
  2332. var from = index * infoObject.dataSize;
  2333. var to = from + infoObject.dataSize;
  2334. return slice(dataArray, infoObject.buffer, from, to);
  2335. }
  2336. var tempMat = new THREE.Matrix4();
  2337. var tempEuler = new THREE.Euler();
  2338. var tempVec = new THREE.Vector3();
  2339. var translation = new THREE.Vector3();
  2340. var rotation = new THREE.Matrix4();
  2341. // generate transformation from FBX transform data
  2342. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2343. // transformData = {
  2344. // eulerOrder: int,
  2345. // translation: [],
  2346. // rotationOffset: [],
  2347. // preRotation
  2348. // rotation
  2349. // postRotation
  2350. // scale
  2351. // }
  2352. // all entries are optional
  2353. function generateTransform(transformData) {
  2354. var transform = new THREE.Matrix4();
  2355. translation.set(0, 0, 0);
  2356. rotation.identity();
  2357. var order = transformData.eulerOrder ? getEulerOrder(transformData.eulerOrder) : getEulerOrder(0);
  2358. if (transformData.translation) translation.fromArray(transformData.translation);
  2359. if (transformData.rotationOffset) translation.add(tempVec.fromArray(transformData.rotationOffset));
  2360. if (transformData.rotation) {
  2361. var array = transformData.rotation.map(THREE.Math.degToRad);
  2362. array.push(order);
  2363. rotation.makeRotationFromEuler(tempEuler.fromArray(array));
  2364. }
  2365. if (transformData.preRotation) {
  2366. var array = transformData.preRotation.map(THREE.Math.degToRad);
  2367. array.push(order);
  2368. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  2369. rotation.premultiply(tempMat);
  2370. }
  2371. if (transformData.postRotation) {
  2372. var array = transformData.postRotation.map(THREE.Math.degToRad);
  2373. array.push(order);
  2374. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  2375. tempMat.getInverse(tempMat);
  2376. rotation.multiply(tempMat);
  2377. }
  2378. if (transformData.scale) transform.scale(tempVec.fromArray(transformData.scale));
  2379. transform.setPosition(translation);
  2380. transform.multiply(rotation);
  2381. return transform;
  2382. }
  2383. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  2384. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2385. function getEulerOrder(order) {
  2386. var enums = ['ZYX', // -> XYZ extrinsic
  2387. 'YZX', // -> XZY extrinsic
  2388. 'XZY', // -> YZX extrinsic
  2389. 'ZXY', // -> YXZ extrinsic
  2390. 'YXZ', // -> ZXY extrinsic
  2391. 'XYZ'];
  2392. if (order === 6) {
  2393. console.warn('THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.');
  2394. return enums[0];
  2395. }
  2396. return enums[order];
  2397. }
  2398. // Parses comma separated list of numbers and returns them an array.
  2399. // Used internally by the TextParser
  2400. function parseNumberArray(value) {
  2401. var array = value.split(',').map(function (val) {
  2402. return parseFloat(val);
  2403. });
  2404. return array;
  2405. }
  2406. function convertArrayBufferToString(buffer, from, to) {
  2407. if (from === undefined) from = 0;
  2408. if (to === undefined) to = buffer.byteLength;
  2409. return THREE.LoaderUtils.decodeText(new Uint8Array(buffer, from, to));
  2410. }
  2411. function append(a, b) {
  2412. for (var i = 0, j = a.length, l = b.length; i < l; i++, j++) {
  2413. a[j] = b[i];
  2414. }
  2415. }
  2416. function slice(a, b, from, to) {
  2417. for (var i = from, j = 0; i < to; i++, j++) {
  2418. a[j] = b[i];
  2419. }
  2420. return a;
  2421. }
  2422. // inject array a2 into array a1 at index
  2423. function inject(a1, index, a2) {
  2424. return a1.slice(0, index).concat(a2).concat(a1.slice(index));
  2425. }
  2426. return FBXLoader;
  2427. }();
  2428. },{}],4:[function(require,module,exports){
  2429. "use strict";
  2430. module.exports = Object.assign(function GamepadButton() {}, {
  2431. FACE_1: 0,
  2432. FACE_2: 1,
  2433. FACE_3: 2,
  2434. FACE_4: 3,
  2435. L_SHOULDER_1: 4,
  2436. R_SHOULDER_1: 5,
  2437. L_SHOULDER_2: 6,
  2438. R_SHOULDER_2: 7,
  2439. SELECT: 8,
  2440. START: 9,
  2441. DPAD_UP: 12,
  2442. DPAD_DOWN: 13,
  2443. DPAD_LEFT: 14,
  2444. DPAD_RIGHT: 15,
  2445. VENDOR: 16
  2446. });
  2447. },{}],5:[function(require,module,exports){
  2448. "use strict";
  2449. function GamepadButtonEvent(type, index, details) {
  2450. this.type = type;
  2451. this.index = index;
  2452. this.pressed = details.pressed;
  2453. this.value = details.value;
  2454. }
  2455. module.exports = GamepadButtonEvent;
  2456. },{}],6:[function(require,module,exports){
  2457. "use strict";
  2458. module.exports = {
  2459. "size": 5,
  2460. "cellSize": 10,
  2461. "extrudeSettings": {
  2462. "amount": 1,
  2463. "bevelEnabled": true,
  2464. "bevelSegments": 1,
  2465. "steps": 1,
  2466. "bevelSize": 0.5,
  2467. "bevelThickness": 0.5
  2468. },
  2469. "autogenerated": true,
  2470. "cells": [{
  2471. "q": -1,
  2472. "r": 0,
  2473. "s": 1,
  2474. "h": 1,
  2475. "walkable": true,
  2476. "userData": {}
  2477. }, {
  2478. "q": 0,
  2479. "r": -1,
  2480. "s": 1,
  2481. "h": 1,
  2482. "walkable": true,
  2483. "userData": {}
  2484. }, {
  2485. "q": 0,
  2486. "r": 0,
  2487. "s": 0,
  2488. "h": 1,
  2489. "walkable": true,
  2490. "userData": {}
  2491. }, {
  2492. "q": 1,
  2493. "r": -1,
  2494. "s": 0,
  2495. "h": 1,
  2496. "walkable": true,
  2497. "userData": {}
  2498. }, {
  2499. "q": -1,
  2500. "r": 1,
  2501. "s": 0,
  2502. "h": 0,
  2503. "walkable": true,
  2504. "userData": {}
  2505. }, {
  2506. "q": 0,
  2507. "r": 1,
  2508. "s": -1,
  2509. "h": 0,
  2510. "walkable": true,
  2511. "userData": {}
  2512. }, {
  2513. "q": 1,
  2514. "r": 0,
  2515. "s": -1,
  2516. "h": 0,
  2517. "walkable": true,
  2518. "userData": {}
  2519. }]
  2520. };
  2521. },{}],7:[function(require,module,exports){
  2522. 'use strict';
  2523. /**
  2524. * Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
  2525. */
  2526. function getScriptId() {
  2527. return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
  2528. }
  2529. function createScript(url, id) {
  2530. var script = document.createElement('script');
  2531. script.type = 'text/javascript';
  2532. script.async = true;
  2533. script.id = id;
  2534. script.src = url;
  2535. return script;
  2536. }
  2537. function removeScript(id) {
  2538. var script = document.getElementById(id);
  2539. var parent = script.parentNode;
  2540. try {
  2541. parent && parent.removeChild(script);
  2542. } catch (e) {
  2543. // ignore
  2544. }
  2545. }
  2546. function appendScript(script) {
  2547. var firstScript = document.getElementsByTagName('script')[0];
  2548. firstScript.parentNode.insertBefore(script, firstScript);
  2549. }
  2550. function fetchScriptInternal(url, options, Promise) {
  2551. return new Promise(function (resolve, reject) {
  2552. var timeout = options.timeout || 5000;
  2553. var scriptId = getScriptId();
  2554. var script = createScript(url, scriptId);
  2555. var timeoutId = setTimeout(function () {
  2556. reject(new Error('Script request to ' + url + ' timed out'));
  2557. removeScript(scriptId);
  2558. }, timeout);
  2559. var disableTimeout = function disableTimeout(timeoutId) {
  2560. clearTimeout(timeoutId);
  2561. };
  2562. script.addEventListener('load', function (e) {
  2563. resolve({ ok: true });
  2564. disableTimeout(timeoutId);
  2565. removeScript(scriptId);
  2566. });
  2567. script.addEventListener('error', function (e) {
  2568. reject(new Error('Script request to ' + url + ' failed ' + e));
  2569. disableTimeout(timeoutId);
  2570. removeScript(scriptId);
  2571. });
  2572. appendScript(script);
  2573. });
  2574. }
  2575. function fetchScript(settings) {
  2576. settings = settings || {};
  2577. return function (url, options) {
  2578. options = options || {};
  2579. return fetchScriptInternal(url, options, settings.Promise || Promise);
  2580. };
  2581. }
  2582. module.exports = fetchScript;
  2583. },{}],8:[function(require,module,exports){
  2584. "use strict";
  2585. var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2586. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  2587. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2588. } : function (obj) {
  2589. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2590. };
  2591. var vg = module.exports = { VERSION: "0.1.1", PI: Math.PI, TAU: 2 * Math.PI, DEG_TO_RAD: .0174532925, RAD_TO_DEG: 57.2957795, SQRT3: Math.sqrt(3), TILE: "tile", ENT: "entity", STR: "structure", HEX: "hex", SQR: "square", ABS: "abstract" };vg.Board = function (e, t) {
  2592. if (!e) throw new Error("You must pass in a grid system for the board to use.");this.tiles = [], this.tileGroup = null, this.group = new THREE.Object3D(), this.grid = null, this.overlay = null, this.finder = new vg.AStarFinder(t), vg.Loader.init(), this.setGrid(e);
  2593. }, vg.Board.prototype = { setEntityOnTile: function setEntityOnTile(e, t) {
  2594. var i = this.grid.cellToPixel(t.cell);e.position.copy(i), e.position.y += e.heightOffset || 0, e.tile && (e.tile.entity = null), e.tile = t, t.entity = e;
  2595. }, addTile: function addTile(e) {
  2596. var t = this.tiles.indexOf(e);-1 === t && (this.tiles.push(e), this.snapTileToGrid(e), e.position.y = 0, this.tileGroup.add(e.mesh), this.grid.add(e.cell), e.cell.tile = e);
  2597. }, removeTile: function removeTile(e) {
  2598. if (e) {
  2599. var t = this.tiles.indexOf(e);this.grid.remove(e.cell), -1 !== t && this.tiles.splice(t, 1), e.dispose();
  2600. }
  2601. }, removeAllTiles: function removeAllTiles() {
  2602. if (this.tileGroup) for (var e = this.tileGroup.children, t = 0; t < e.length; t++) {
  2603. this.tileGroup.remove(e[t]);
  2604. }
  2605. }, getTileAtCell: function getTileAtCell(e) {
  2606. var t = this.grid.cellToHash(e);return e.tile || ("undefined" != typeof this.grid.cells[t] ? this.grid.cells[t].tile : null);
  2607. }, snapToGrid: function snapToGrid(e) {
  2608. var t = this.grid.pixelToCell(e);e.copy(this.grid.cellToPixel(t));
  2609. }, snapTileToGrid: function snapTileToGrid(e) {
  2610. if (e.cell) e.position.copy(this.grid.cellToPixel(e.cell));else {
  2611. var t = this.grid.pixelToCell(e.position);e.position.copy(this.grid.cellToPixel(t));
  2612. }return e;
  2613. }, getRandomTile: function getRandomTile() {
  2614. var e = vg.Tools.randomInt(0, this.tiles.length - 1);return this.tiles[e];
  2615. }, findPath: function findPath(e, t, i) {
  2616. return this.finder.findPath(e.cell, t.cell, i, this.grid);
  2617. }, setGrid: function setGrid(e) {
  2618. this.group.remove(this.tileGroup), this.grid && e !== this.grid && (this.removeAllTiles(), this.tiles.forEach(function (e) {
  2619. this.grid.remove(e.cell), e.dispose();
  2620. }), this.grid.dispose()), this.grid = e, this.tiles = [], this.tileGroup = new THREE.Object3D(), this.group.add(this.tileGroup);
  2621. }, generateOverlay: function generateOverlay(e) {
  2622. var t = new THREE.LineBasicMaterial({ color: 0, opacity: .3 });this.overlay && this.group.remove(this.overlay), this.overlay = new THREE.Object3D(), this.grid.generateOverlay(e, this.overlay, t), this.group.add(this.overlay);
  2623. }, generateTilemap: function generateTilemap(e) {
  2624. this.reset();var t = this.grid.generateTiles(e);this.tiles = t, this.tileGroup = new THREE.Object3D();for (var i = 0; i < t.length; i++) {
  2625. this.tileGroup.add(t[i].mesh);
  2626. }this.group.add(this.tileGroup);
  2627. }, reset: function reset() {
  2628. this.removeAllTiles(), this.tileGroup && this.group.remove(this.tileGroup);
  2629. } }, vg.Board.prototype.constructor = vg.Board, vg.Cell = function (e, t, i, s) {
  2630. this.q = e || 0, this.r = t || 0, this.s = i || 0, this.h = s || 1, this.tile = null, this.userData = {}, this.walkable = !0, this._calcCost = 0, this._priority = 0, this._visited = !1, this._parent = null, this.uniqueID = vg.LinkedList.generateID();
  2631. }, vg.Cell.prototype = { set: function set(e, t, i) {
  2632. return this.q = e, this.r = t, this.s = i, this;
  2633. }, copy: function copy(e) {
  2634. return this.q = e.q, this.r = e.r, this.s = e.s, this.h = e.h, this.tile = e.tile || null, this.userData = e.userData || {}, this.walkable = e.walkable, this;
  2635. }, add: function add(e) {
  2636. return this.q += e.q, this.r += e.r, this.s += e.s, this;
  2637. }, equals: function equals(e) {
  2638. return this.q === e.q && this.r === e.r && this.s === e.s;
  2639. } }, vg.Cell.prototype.constructor = vg.Cell, vg.HexGrid = function (e) {
  2640. e = e || {}, this.type = vg.HEX, this.size = 5, this.cellSize = "undefined" == typeof e.cellSize ? 10 : e.cellSize, this.cells = {}, this.numCells = 0, this.extrudeSettings = null, this.autogenerated = !1;var t,
  2641. i = [];for (t = 0; 6 > t; t++) {
  2642. i.push(this._createVertex(t));
  2643. }for (this.cellShape = new THREE.Shape(), this.cellShape.moveTo(i[0].x, i[0].y), t = 1; 6 > t; t++) {
  2644. this.cellShape.lineTo(i[t].x, i[t].y);
  2645. }this.cellShape.lineTo(i[0].x, i[0].y), this.cellShape.autoClose = !0, this.cellGeo = new THREE.Geometry(), this.cellGeo.vertices = i, this.cellGeo.verticesNeedUpdate = !0, this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape), this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this._hashDelimeter = ".", this._directions = [new vg.Cell(1, -1, 0), new vg.Cell(1, 0, -1), new vg.Cell(0, 1, -1), new vg.Cell(-1, 1, 0), new vg.Cell(-1, 0, 1), new vg.Cell(0, -1, 1)], this._diagonals = [new vg.Cell(2, -1, -1), new vg.Cell(1, 1, -2), new vg.Cell(-1, 2, -1), new vg.Cell(-2, 1, 1), new vg.Cell(-1, -1, 2), new vg.Cell(1, -2, 1)], this._list = [], this._vec3 = new THREE.Vector3(), this._cel = new vg.Cell(), this._conversionVec = new THREE.Vector3(), this._geoCache = [], this._matCache = [];
  2646. }, vg.HexGrid.TWO_THIRDS = 2 / 3, vg.HexGrid.prototype = { cellToPixel: function cellToPixel(e) {
  2647. return this._vec3.x = e.q * this._cellWidth * .75, this._vec3.y = e.h, this._vec3.z = -((e.s - e.r) * this._cellLength * .5), this._vec3;
  2648. }, pixelToCell: function pixelToCell(e) {
  2649. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  2650. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel);
  2651. }, getCellAt: function getCellAt(e) {
  2652. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  2653. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel), this.cells[this.cellToHash(this._cel)];
  2654. }, getNeighbors: function getNeighbors(e, t, i) {
  2655. var s,
  2656. n,
  2657. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  2658. this._cel.copy(e), this._cel.add(this._directions[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  2659. }if (t) for (s = 0; l > s; s++) {
  2660. this._cel.copy(e), this._cel.add(this._diagonals[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  2661. }return this._list;
  2662. }, getRandomCell: function getRandomCell() {
  2663. var e,
  2664. t = 0,
  2665. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  2666. if (t === i) return this.cells[e];t++;
  2667. }return this.cells[e];
  2668. }, cellToHash: function cellToHash(e) {
  2669. return e.q + this._hashDelimeter + e.r + this._hashDelimeter + e.s;
  2670. }, distance: function distance(e, t) {
  2671. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r), Math.abs(e.s - t.s));return i += t.h - e.h;
  2672. }, clearPath: function clearPath() {
  2673. var e, t;for (e in this.cells) {
  2674. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  2675. }
  2676. }, traverse: function traverse(e) {
  2677. var t;for (t in this.cells) {
  2678. e(this.cells[t]);
  2679. }
  2680. }, generateTile: function generateTile(e, t, i) {
  2681. var s = Math.abs(e.h);1 > s && (s = 1);var n = this._geoCache[s];n || (this.extrudeSettings.amount = s, n = new THREE.ExtrudeGeometry(this.cellShape, this.extrudeSettings), this._geoCache[s] = n);var l = new vg.Tile({ size: this.cellSize, scale: t, cell: e, geometry: n, material: i });return e.tile = l, l;
  2682. }, generateTiles: function generateTiles(e) {
  2683. e = e || {};var t = [],
  2684. i = { tileScale: .95, cellSize: this.cellSize, material: null, extrudeSettings: { amount: 1, bevelEnabled: !0, bevelSegments: 1, steps: 1, bevelSize: .5, bevelThickness: .5 } };i = vg.Tools.merge(i, e), this.cellSize = i.cellSize, this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this.autogenerated = !0, this.extrudeSettings = i.extrudeSettings;var s, n, l;for (s in this.cells) {
  2685. l = this.cells[s], n = this.generateTile(l, i.tileScale, i.material), n.position.copy(this.cellToPixel(l)), n.position.y = 0, t.push(n);
  2686. }return t;
  2687. }, generateTilePoly: function generateTilePoly(e) {
  2688. e || (e = new THREE.MeshBasicMaterial({ color: 2405631 }));var t = new THREE.Mesh(this.cellShapeGeo, e);return this._vec3.set(1, 0, 0), t.rotateOnAxis(this._vec3, vg.PI / 2), t;
  2689. }, generate: function generate(e) {
  2690. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t, i, s, n;for (t = -this.size; t < this.size + 1; t++) {
  2691. for (i = -this.size; i < this.size + 1; i++) {
  2692. s = -t - i, Math.abs(t) <= this.size && Math.abs(i) <= this.size && Math.abs(s) <= this.size && (n = new vg.Cell(t, i, s), this.add(n));
  2693. }
  2694. }
  2695. }, generateOverlay: function generateOverlay(e, t, i) {
  2696. var s,
  2697. n,
  2698. l,
  2699. r = this.cellShape.createPointsGeometry();for (s = -e; e + 1 > s; s++) {
  2700. for (n = -e; e + 1 > n; n++) {
  2701. if (l = -s - n, Math.abs(s) <= e && Math.abs(n) <= e && Math.abs(l) <= e) {
  2702. this._cel.set(s, n, l);var h = new THREE.Line(r, i);h.position.copy(this.cellToPixel(this._cel)), h.rotation.x = 90 * vg.DEG_TO_RAD, t.add(h);
  2703. }
  2704. }
  2705. }
  2706. }, add: function add(e) {
  2707. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  2708. }, remove: function remove(e) {
  2709. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  2710. }, dispose: function dispose() {
  2711. this.cells = null, this.numCells = 0, this.cellShape = null, this.cellGeo.dispose(), this.cellGeo = null, this.cellShapeGeo.dispose(), this.cellShapeGeo = null, this._list = null, this._vec3 = null, this._conversionVec = null, this._geoCache = null, this._matCache = null;
  2712. }, load: function load(e, t, i) {
  2713. var s = this;vg.Tools.getJSON({ url: e, callback: function callback(e) {
  2714. s.fromJSON(e), t.call(i || null, e);
  2715. }, cache: !1, scope: s });
  2716. }, fromJSON: function fromJSON(e) {
  2717. var t,
  2718. i,
  2719. s = e.cells;for (this.cells = {}, this.numCells = 0, this.size = e.size, this.cellSize = e.cellSize, this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this.extrudeSettings = e.extrudeSettings, this.autogenerated = e.autogenerated, t = 0; t < s.length; t++) {
  2720. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  2721. }
  2722. }, toJSON: function toJSON() {
  2723. var e,
  2724. t,
  2725. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  2726. s = [];for (t in this.cells) {
  2727. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  2728. }return i.cells = s, i;
  2729. }, _createVertex: function _createVertex(e) {
  2730. var t = vg.TAU / 6 * e;return new THREE.Vector3(this.cellSize * Math.cos(t), this.cellSize * Math.sin(t), 0);
  2731. }, _cubeRound: function _cubeRound(e) {
  2732. var t = Math.round(e.q),
  2733. i = Math.round(e.r),
  2734. s = Math.round(e.s),
  2735. n = Math.abs(t - e.q),
  2736. l = Math.abs(i - e.r),
  2737. r = Math.abs(s - e.s);return n > l && n > r ? t = -i - s : l > r ? i = -t - s : s = -t - i, this._cel.set(t, i, s);
  2738. } }, vg.HexGrid.prototype.constructor = vg.HexGrid, vg.SqrGrid = function (e) {
  2739. e = e || {}, this.type = vg.SQR, this.size = 5, this.cellSize = "undefined" == typeof e.cellSize ? 10 : e.cellSize, this.cells = {}, this.numCells = 0, this.extrudeSettings = null, this.autogenerated = !1;var t = [];t.push(new THREE.Vector3()), t.push(new THREE.Vector3(-this.cellSize, this.cellSize)), t.push(new THREE.Vector3(this.cellSize, this.cellSize)), t.push(new THREE.Vector3(this.cellSize, -this.cellSize)), this.cellShape = new THREE.Shape(), this.cellShape.moveTo(-this.cellSize, -this.cellSize), this.cellShape.lineTo(-this.cellSize, this.cellSize), this.cellShape.lineTo(this.cellSize, this.cellSize), this.cellShape.lineTo(this.cellSize, -this.cellSize), this.cellShape.lineTo(-this.cellSize, -this.cellSize), this.cellGeo = new THREE.Geometry(), this.cellGeo.vertices = t, this.cellGeo.verticesNeedUpdate = !0, this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape), this._fullCellSize = 2 * this.cellSize, this._hashDelimeter = ".", this._directions = [new vg.Cell(1, 0, 0), new vg.Cell(0, -1, 0), new vg.Cell(-1, 0, 0), new vg.Cell(0, 1, 0)], this._diagonals = [new vg.Cell(-1, -1, 0), new vg.Cell(-1, 1, 0), new vg.Cell(1, 1, 0), new vg.Cell(1, -1, 0)], this._list = [], this._vec3 = new THREE.Vector3(), this._cel = new vg.Cell(), this._conversionVec = new THREE.Vector3(), this._geoCache = [], this._matCache = [];
  2740. }, vg.SqrGrid.prototype = { cellToPixel: function cellToPixel(e) {
  2741. return this._vec3.x = e.q * this._fullCellSize, this._vec3.y = e.h, this._vec3.z = e.r * this._fullCellSize, this._vec3;
  2742. }, pixelToCell: function pixelToCell(e) {
  2743. var t = Math.round(e.x / this._fullCellSize),
  2744. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i, 0);
  2745. }, getCellAt: function getCellAt(e) {
  2746. var t = Math.round(e.x / this._fullCellSize),
  2747. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i), this.cells[this.cellToHash(this._cel)];
  2748. }, getNeighbors: function getNeighbors(e, t, i) {
  2749. var s,
  2750. n,
  2751. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  2752. this._cel.copy(e), this._cel.add(this._directions[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  2753. }if (t) for (s = 0; l > s; s++) {
  2754. this._cel.copy(e), this._cel.add(this._diagonals[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  2755. }return this._list;
  2756. }, getRandomCell: function getRandomCell() {
  2757. var e,
  2758. t = 0,
  2759. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  2760. if (t === i) return this.cells[e];t++;
  2761. }return this.cells[e];
  2762. }, cellToHash: function cellToHash(e) {
  2763. return e.q + this._hashDelimeter + e.r;
  2764. }, distance: function distance(e, t) {
  2765. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r));return i += t.h - e.h;
  2766. }, clearPath: function clearPath() {
  2767. var e, t;for (e in this.cells) {
  2768. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  2769. }
  2770. }, traverse: function traverse(e) {
  2771. var t;for (t in this.cells) {
  2772. e(this.cells[t]);
  2773. }
  2774. }, generateTile: function generateTile(e, t, i) {
  2775. var s = Math.abs(e.h);1 > s && (s = 1);var n = this._geoCache[s];n || (this.extrudeSettings.amount = s, n = new THREE.ExtrudeGeometry(this.cellShape, this.extrudeSettings), this._geoCache[s] = n);var l = new vg.Tile({ size: this.cellSize, scale: t, cell: e, geometry: n, material: i });return e.tile = l, l;
  2776. }, generateTiles: function generateTiles(e) {
  2777. e = e || {};var t = [],
  2778. i = { tileScale: .95, cellSize: this.cellSize, material: null, extrudeSettings: { amount: 1, bevelEnabled: !0, bevelSegments: 1, steps: 1, bevelSize: .5, bevelThickness: .5 } };i = vg.Tools.merge(i, e), this.cellSize = i.cellSize, this._fullCellSize = 2 * this.cellSize, this.autogenerated = !0, this.extrudeSettings = i.extrudeSettings;var s, n, l;for (s in this.cells) {
  2779. l = this.cells[s], n = this.generateTile(l, i.tileScale, i.material), n.position.copy(this.cellToPixel(l)), n.position.y = 0, t.push(n);
  2780. }return t;
  2781. }, generateTilePoly: function generateTilePoly(e) {
  2782. e || (e = new THREE.MeshBasicMaterial({ color: 2405631 }));var t = new THREE.Mesh(this.cellShapeGeo, e);return this._vec3.set(1, 0, 0), t.rotateOnAxis(this._vec3, vg.PI / 2), t;
  2783. }, generate: function generate(e) {
  2784. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t,
  2785. i,
  2786. s,
  2787. n = Math.ceil(this.size / 2);for (t = -n; n > t; t++) {
  2788. for (i = -n; n > i; i++) {
  2789. s = new vg.Cell(t, i + 1), this.add(s);
  2790. }
  2791. }
  2792. }, generateOverlay: function generateOverlay(e, t, i) {
  2793. var s,
  2794. n,
  2795. l = Math.ceil(e / 2);for (s = -l; l > s; s++) {
  2796. for (n = -l; l > n; n++) {
  2797. this._cel.set(s, n);var r = new THREE.Line(this.cellGeo, i);r.position.copy(this.cellToPixel(this._cel)), r.rotation.x = 90 * vg.DEG_TO_RAD, t.add(r);
  2798. }
  2799. }
  2800. }, add: function add(e) {
  2801. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  2802. }, remove: function remove(e) {
  2803. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  2804. }, dispose: function dispose() {
  2805. this.cells = null, this.numCells = 0, this.cellShape = null, this.cellGeo.dispose(), this.cellGeo = null, this.cellShapeGeo.dispose(), this.cellShapeGeo = null, this._list = null, this._vec3 = null, this._conversionVec = null, this._geoCache = null, this._matCache = null;
  2806. }, load: function load(e, t, i) {
  2807. vg.Tools.getJSON({ url: e, callback: function callback(e) {
  2808. this.fromJSON(e), t.call(i || null, e);
  2809. }, cache: !1, scope: this });
  2810. }, fromJSON: function fromJSON(e) {
  2811. var t,
  2812. i,
  2813. s = e.cells;for (this.cells = {}, this.numCells = 0, this.size = e.size, this.cellSize = e.cellSize, this._fullCellSize = 2 * this.cellSize, this.extrudeSettings = e.extrudeSettings, this.autogenerated = e.autogenerated, t = 0; t < s.length; t++) {
  2814. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  2815. }
  2816. }, toJSON: function toJSON() {
  2817. var e,
  2818. t,
  2819. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  2820. s = [];for (t in this.cells) {
  2821. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  2822. }return i.cells = s, i;
  2823. } }, vg.SqrGrid.prototype.constructor = vg.SqrGrid, vg.Tile = function (e) {
  2824. e = e || {};var t = { cell: null, geometry: null, material: null };if (t = vg.Tools.merge(t, e), !t.cell || !t.geometry) throw new Error("Missing vg.Tile configuration");this.cell = t.cell, this.cell.tile && this.cell.tile !== this && this.cell.tile.dispose(), this.cell.tile = this, this.uniqueID = vg.Tools.generateID(), this.geometry = t.geometry, this.material = t.material, this.material || (this.material = new THREE.MeshPhongMaterial({ color: vg.Tools.randomizeRGB("30, 30, 30", 13) })), this.objectType = vg.TILE, this.entity = null, this.userData = {}, this.selected = !1, this.highlight = "0x0084cc", this.mesh = new THREE.Mesh(this.geometry, this.material), this.mesh.userData.structure = this, this.position = this.mesh.position, this.rotation = this.mesh.rotation, this.rotation.x = -90 * vg.DEG_TO_RAD, this.mesh.scale.set(t.scale, t.scale, 1), this.material.emissive ? this._emissive = this.material.emissive.getHex() : this._emissive = null;
  2825. }, vg.Tile.prototype = { select: function select() {
  2826. return this.material.emissive && this.material.emissive.setHex(this.highlight), this.selected = !0, this;
  2827. }, deselect: function deselect() {
  2828. return null !== this._emissive && this.material.emissive && this.material.emissive.setHex(this._emissive), this.selected = !1, this;
  2829. }, toggle: function toggle() {
  2830. return this.selected ? this.deselect() : this.select(), this;
  2831. }, dispose: function dispose() {
  2832. this.cell && this.cell.tile && (this.cell.tile = null), this.cell = null, this.position = null, this.rotation = null, this.mesh.parent && this.mesh.parent.remove(this.mesh), this.mesh.userData.structure = null, this.mesh = null, this.material = null, this.userData = null, this.entity = null, this.geometry = null, this._emissive = null;
  2833. } }, vg.Tile.prototype.constructor = vg.Tile, function () {
  2834. var e = function e() {
  2835. this.obj = null, this.next = null, this.prev = null, this.free = !0;
  2836. },
  2837. t = function t() {
  2838. this.first = null, this.last = null, this.length = 0, this.objToNodeMap = {}, this.uniqueID = Date.now() + "" + Math.floor(1e3 * Math.random()), this.sortArray = [];
  2839. };t.generateID = function () {
  2840. return Math.random().toString(36).slice(2) + Date.now();
  2841. }, t.prototype = { getNode: function getNode(e) {
  2842. return this.objToNodeMap[e.uniqueID];
  2843. }, addNode: function addNode(i) {
  2844. var s = new e();if (!i.uniqueID) try {
  2845. i.uniqueID = t.generateID();
  2846. } catch (n) {
  2847. return console.error("[LinkedList.addNode] obj passed is immutable: cannot attach necessary identifier"), null;
  2848. }return s.obj = i, s.free = !1, this.objToNodeMap[i.uniqueID] = s, s;
  2849. }, swapObjects: function swapObjects(e, t) {
  2850. this.objToNodeMap[e.obj.uniqueID] = null, this.objToNodeMap[t.uniqueID] = e, e.obj = t;
  2851. }, add: function add(e) {
  2852. var t = this.objToNodeMap[e.uniqueID];if (t) {
  2853. if (t.free === !1) return;t.obj = e, t.free = !1, t.next = null, t.prev = null;
  2854. } else t = this.addNode(e);if (this.first) {
  2855. if (!this.last) throw new Error("[LinkedList.add] No last in the list -- that shouldn't happen here");this.last.next = t, t.prev = this.last, this.last = t, t.next = null;
  2856. } else this.first = t, this.last = t, t.next = null, t.prev = null;this.length++, this.showDebug && this.dump("after add");
  2857. }, has: function has(e) {
  2858. return !!this.objToNodeMap[e.uniqueID];
  2859. }, moveUp: function moveUp(e) {
  2860. this.dump("before move up");var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.prev) {
  2861. var i = t.prev,
  2862. s = i.prev;t == this.last && (this.last = i);var n = t.next;s && (s.next = t), t.next = i, t.prev = i.prev, i.next = n, i.prev = t, this.first == i && (this.first = t);
  2863. }
  2864. }, moveDown: function moveDown(e) {
  2865. var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.next) {
  2866. var i = t.next;this.moveUp(i.obj), this.last == i && (this.last = t);
  2867. }
  2868. }, sort: function sort(e) {
  2869. var t,
  2870. i,
  2871. s = this.sortArray,
  2872. n = this.first;for (s.length = 0; n;) {
  2873. s.push(n.obj), n = n.next;
  2874. }for (this.clear(), s.sort(e), i = s.length, t = 0; i > t; t++) {
  2875. this.add(s[t]);
  2876. }
  2877. }, remove: function remove(e) {
  2878. var t = this.getNode(e);return !t || t.free ? !1 : (t.prev && (t.prev.next = t.next), t.next && (t.next.prev = t.prev), t.prev || (this.first = t.next), t.next || (this.last = t.prev), t.free = !0, t.prev = null, t.next = null, this.length--, !0);
  2879. }, shift: function shift() {
  2880. var e = this.first;return 0 === this.length ? null : (e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), this.first = e.next, e.next || (this.last = null), e.free = !0, e.prev = null, e.next = null, this.length--, e.obj);
  2881. }, pop: function pop() {
  2882. var e = this.last;return 0 === this.length ? null : (e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), this.last = e.prev, e.prev || (this.first = null), e.free = !0, e.prev = null, e.next = null, this.length--, e.obj);
  2883. }, concat: function concat(e) {
  2884. for (var t = e.first; t;) {
  2885. this.add(t.obj), t = t.next;
  2886. }
  2887. }, clear: function clear() {
  2888. for (var e = this.first; e;) {
  2889. e.free = !0, e = e.next;
  2890. }this.first = null, this.length = 0;
  2891. }, dispose: function dispose() {
  2892. for (var e = this.first; e;) {
  2893. e.obj = null, e = e.next;
  2894. }this.first = null, this.objToNodeMap = null;
  2895. }, dump: function dump(e) {
  2896. console.log("====================" + e + "=====================");for (var t = this.first; t;) {
  2897. console.log("{" + t.obj.toString() + "} previous=" + (t.prev ? t.prev.obj : "NULL")), t = t.next();
  2898. }console.log("==================================="), console.log("Last: {" + (this.last ? this.last.obj : "NULL") + "} First: {" + (this.first ? this.first.obj : "NULL") + "}");
  2899. } }, t.prototype.constructor = t, vg.LinkedList = t;
  2900. }(), function () {
  2901. var e = function e(_e, t, i, s, n) {
  2902. this._listener = t, this.isOnce = i, this.context = s, this.signal = _e, this._priority = n || 0;
  2903. };e.prototype = { active: !0, params: null, execute: function execute(e) {
  2904. var t, i;return this.active && this._listener && (i = this.params ? this.params.concat(e) : e, t = this._listener.apply(this.context, i), this.isOnce && this.detach()), t;
  2905. }, detach: function detach() {
  2906. return this.isBound() ? this.signal.remove(this._listener, this.context) : null;
  2907. }, isBound: function isBound() {
  2908. return !!this.signal && !!this._listener;
  2909. }, _destroy: function _destroy() {
  2910. delete this.signal, delete this._listener, delete this.context;
  2911. }, toString: function toString() {
  2912. return "[SignalBinding isOnce:" + this.isOnce + ", isBound:" + this.isBound() + ", active:" + this.active + "]";
  2913. } }, e.prototype.constructor = e;var t = function t() {
  2914. this._bindings = [], this._prevParams = null;var e = this;this.dispatch = function () {
  2915. t.prototype.dispatch.apply(e, arguments);
  2916. };
  2917. };t.prototype = { memorize: !1, _shouldPropagate: !0, active: !0, validateListener: function validateListener(e, t) {
  2918. if ("function" != typeof e) throw new Error("Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}", t));
  2919. }, _registerListener: function _registerListener(t, i, s, n) {
  2920. var l,
  2921. r = this._indexOfListener(t, s);if (-1 !== r) {
  2922. if (l = this._bindings[r], l.isOnce !== i) throw new Error("You cannot add" + (i ? "" : "Once") + "() then add" + (i ? "Once" : "") + "() the same listener without removing the relationship first.");
  2923. } else l = new e(this, t, i, s, n), this._addBinding(l);return this.memorize && this._prevParams && l.execute(this._prevParams), l;
  2924. }, _addBinding: function _addBinding(e) {
  2925. var t = this._bindings.length;do {
  2926. t--;
  2927. } while (this._bindings[t] && e._priority <= this._bindings[t]._priority);this._bindings.splice(t + 1, 0, e);
  2928. }, _indexOfListener: function _indexOfListener(e, t) {
  2929. for (var i, s = this._bindings.length; s--;) {
  2930. if (i = this._bindings[s], i._listener === e && i.context === t) return s;
  2931. }return -1;
  2932. }, has: function has(e, t) {
  2933. return -1 !== this._indexOfListener(e, t);
  2934. }, add: function add(e, t, i) {
  2935. return this.validateListener(e, "add"), this._registerListener(e, !1, t, i);
  2936. }, addOnce: function addOnce(e, t, i) {
  2937. return this.validateListener(e, "addOnce"), this._registerListener(e, !0, t, i);
  2938. }, remove: function remove(e, t) {
  2939. this.validateListener(e, "remove");var i = this._indexOfListener(e, t);return -1 !== i && (this._bindings[i]._destroy(), this._bindings.splice(i, 1)), e;
  2940. }, removeAll: function removeAll(e) {
  2941. "undefined" == typeof e && (e = null);for (var t = this._bindings.length; t--;) {
  2942. e ? this._bindings[t].context === e && (this._bindings[t]._destroy(), this._bindings.splice(t, 1)) : this._bindings[t]._destroy();
  2943. }e || (this._bindings.length = 0);
  2944. }, getNumListeners: function getNumListeners() {
  2945. return this._bindings.length;
  2946. }, halt: function halt() {
  2947. this._shouldPropagate = !1;
  2948. }, dispatch: function dispatch() {
  2949. if (this.active) {
  2950. var e,
  2951. t = Array.prototype.slice.call(arguments),
  2952. i = this._bindings.length;if (this.memorize && (this._prevParams = t), i) {
  2953. e = this._bindings.slice(), this._shouldPropagate = !0;do {
  2954. i--;
  2955. } while (e[i] && this._shouldPropagate && e[i].execute(t) !== !1);
  2956. }
  2957. }
  2958. }, forget: function forget() {
  2959. this._prevParams = null;
  2960. }, dispose: function dispose() {
  2961. this.removeAll(), delete this._bindings, delete this._prevParams;
  2962. }, toString: function toString() {
  2963. return "[Signal active:" + this.active + " numListeners:" + this.getNumListeners() + "]";
  2964. } }, t.prototype.constructor = t, vg.Signal = t;
  2965. }(), vg.AStarFinder = function (e) {
  2966. e = e || {};var t = { allowDiagonal: !1, heuristicFilter: null };t = vg.Tools.merge(t, e), this.allowDiagonal = t.allowDiagonal, this.heuristicFilter = t.heuristicFilter, this.list = new vg.LinkedList();
  2967. }, vg.AStarFinder.prototype = { findPath: function findPath(e, t, i, s) {
  2968. var n, l, r, h, o, a;for (i = i || this.heuristicFilter, s.clearPath(), this.list.clear(), this.list.add(e); this.list.length > 0;) {
  2969. if (this.list.sort(this.compare), n = this.list.shift(), n._visited = !0, n === t) return vg.PathUtil.backtrace(t);for (r = s.getNeighbors(n, this.allowDiagonal, i), o = 0, a = r.length; a > o; o++) {
  2970. if (h = r[o], h.walkable && (l = n._calcCost + s.distance(n, h), !h._visited || l < h._calcCost)) {
  2971. if (h._visited = !0, h._parent = n, h._calcCost = l, h._priority = l + s.distance(t, h), h === t) return vg.PathUtil.backtrace(t);this.list.add(h);
  2972. }
  2973. }
  2974. }return null;
  2975. }, compare: function compare(e, t) {
  2976. return e._priority - t._priority;
  2977. } }, vg.AStarFinder.prototype.constructor = vg.AStarFinder, vg.PathUtil = { backtrace: function backtrace(e) {
  2978. for (var t = [e]; e._parent;) {
  2979. e = e._parent, t.push(e);
  2980. }return t.reverse();
  2981. }, biBacktrace: function biBacktrace(e, t) {
  2982. var i = this.backtrace(e),
  2983. s = this.backtrace(t);return i.concat(s.reverse());
  2984. }, pathLength: function pathLength(e) {
  2985. var t,
  2986. i,
  2987. s,
  2988. n,
  2989. l,
  2990. r = 0;for (t = 1; t < e.length; ++t) {
  2991. i = e[t - 1], s = e[t], n = i[0] - s[0], l = i[1] - s[1], r += Math.sqrt(n * n + l * l);
  2992. }return r;
  2993. }, interpolate: function interpolate(e, t, i, s) {
  2994. var n,
  2995. l,
  2996. r,
  2997. h,
  2998. o,
  2999. a,
  3000. c = Math.abs,
  3001. u = [];for (r = c(i - e), h = c(s - t), n = i > e ? 1 : -1, l = s > t ? 1 : -1, o = r - h; e !== i || t !== s;) {
  3002. u.push([e, t]), a = 2 * o, a > -h && (o -= h, e += n), r > a && (o += r, t += l);
  3003. }return u;
  3004. }, expandPath: function expandPath(e) {
  3005. var t,
  3006. i,
  3007. s,
  3008. n,
  3009. l,
  3010. r,
  3011. h = [],
  3012. o = e.length;if (2 > o) return h;for (l = 0; o - 1 > l; ++l) {
  3013. for (t = e[l], i = e[l + 1], s = this.interpolate(t[0], t[1], i[0], i[1]), n = s.length, r = 0; n - 1 > r; ++r) {
  3014. h.push(s[r]);
  3015. }
  3016. }return h.push(e[o - 1]), h;
  3017. }, smoothenPath: function smoothenPath(e, t) {
  3018. var i,
  3019. s,
  3020. n,
  3021. l,
  3022. r,
  3023. h,
  3024. o,
  3025. a,
  3026. c,
  3027. u,
  3028. d,
  3029. g,
  3030. p = t.length,
  3031. v = t[0][0],
  3032. f = t[0][1],
  3033. m = t[p - 1][0],
  3034. _ = t[p - 1][1];for (i = v, s = f, r = [[i, s]], o = 2; p > o; ++o) {
  3035. for (c = t[o], n = c[0], l = c[1], u = this.interpolate(i, s, n, l), g = !1, a = 1; a < u.length; ++a) {
  3036. if (d = u[a], !e.isWalkableAt(d[0], d[1])) {
  3037. g = !0;break;
  3038. }
  3039. }g && (h = t[o - 1], r.push(h), i = h[0], s = h[1]);
  3040. }return r.push([m, _]), r;
  3041. }, compressPath: function compressPath(e) {
  3042. if (e.length < 3) return e;var t,
  3043. i,
  3044. s,
  3045. n,
  3046. l,
  3047. r,
  3048. h = [],
  3049. o = e[0][0],
  3050. a = e[0][1],
  3051. c = e[1][0],
  3052. u = e[1][1],
  3053. d = c - o,
  3054. g = u - a;for (l = Math.sqrt(d * d + g * g), d /= l, g /= l, h.push([o, a]), r = 2; r < e.length; r++) {
  3055. t = c, i = u, s = d, n = g, c = e[r][0], u = e[r][1], d = c - t, g = u - i, l = Math.sqrt(d * d + g * g), d /= l, g /= l, (d !== s || g !== n) && h.push([t, i]);
  3056. }return h.push([c, u]), h;
  3057. } }, vg.Loader = { manager: null, imageLoader: null, crossOrigin: !1, init: function init(e) {
  3058. this.crossOrigin = e || !1, this.manager = new THREE.LoadingManager(function () {}, function () {}, function () {
  3059. console.warn("Error loading images");
  3060. }), this.imageLoader = new THREE.ImageLoader(this.manager), this.imageLoader.crossOrigin = e;
  3061. }, loadTexture: function loadTexture(e, t, i, s) {
  3062. var n = new THREE.Texture(null, t);return this.imageLoader.load(e, function (e) {
  3063. n.image = e, n.needsUpdate = !0, i && i(n);
  3064. }, null, function (e) {
  3065. s && s(e);
  3066. }), n.sourceFile = e, n;
  3067. } }, vg.MouseCaster = function (e, t, i) {
  3068. this.down = !1, this.rightDown = !1, this.pickedObject = null, this.selectedObject = null, this.allHits = null, this.active = !0, this.shift = !1, this.ctrl = !1, this.wheel = 0, this.position = new THREE.Vector3(), this.screenPosition = new THREE.Vector2(), this.signal = new vg.Signal(), this.group = e, this._camera = t, this._raycaster = new THREE.Raycaster(), this._preventDefault = !1, i = i || document, i.addEventListener("mousemove", this._onDocumentMouseMove.bind(this), !1), i.addEventListener("mousedown", this._onDocumentMouseDown.bind(this), !1), i.addEventListener("mouseup", this._onDocumentMouseUp.bind(this), !1), i.addEventListener("mousewheel", this._onMouseWheel.bind(this), !1), i.addEventListener("DOMMouseScroll", this._onMouseWheel.bind(this), !1);
  3069. }, vg.MouseCaster.OVER = "over", vg.MouseCaster.OUT = "out", vg.MouseCaster.DOWN = "down", vg.MouseCaster.UP = "up", vg.MouseCaster.CLICK = "click", vg.MouseCaster.WHEEL = "wheel", vg.MouseCaster.prototype = { update: function update() {
  3070. if (this.active) {
  3071. this._raycaster.setFromCamera(this.screenPosition, this._camera);var e,
  3072. t,
  3073. i = this._raycaster.intersectObject(this.group, !0);i.length > 0 ? (e = i[0], t = e.object.userData.structure, this.pickedObject != t && (this.pickedObject && this.signal.dispatch(vg.MouseCaster.OUT, this.pickedObject), this.pickedObject = t, this.selectedObject = null, this.signal.dispatch(vg.MouseCaster.OVER, this.pickedObject)), this.position.copy(e.point), this.screenPosition.z = e.distance) : (this.pickedObject && this.signal.dispatch(vg.MouseCaster.OUT, this.pickedObject), this.pickedObject = null, this.selectedObject = null), this.allHits = i;
  3074. }
  3075. }, preventDefault: function preventDefault() {
  3076. this._preventDefault = !0;
  3077. }, _onDocumentMouseDown: function _onDocumentMouseDown(e) {
  3078. return e = e || window.event, e.preventDefault(), this._preventDefault ? (this._preventDefault = !1, !1) : (this.pickedObject && (this.selectedObject = this.pickedObject), this.shift = e.shiftKey, this.ctrl = e.ctrlKey, this.down = 1 === e.which, this.rightDown = 3 === e.which, void this.signal.dispatch(vg.MouseCaster.DOWN, this.pickedObject));
  3079. }, _onDocumentMouseUp: function _onDocumentMouseUp(e) {
  3080. return e.preventDefault(), this._preventDefault ? (this._preventDefault = !1, !1) : (this.shift = e.shiftKey, this.ctrl = e.ctrlKey, this.signal.dispatch(vg.MouseCaster.UP, this.pickedObject), this.selectedObject && this.pickedObject && this.selectedObject.uniqueID === this.pickedObject.uniqueID && this.signal.dispatch(vg.MouseCaster.CLICK, this.pickedObject), this.down = 1 === e.which ? !1 : this.down, void (this.rightDown = 3 === e.which ? !1 : this.rightDown));
  3081. }, _onDocumentMouseMove: function _onDocumentMouseMove(e) {
  3082. e.preventDefault(), this.screenPosition.x = e.clientX / window.innerWidth * 2 - 1, this.screenPosition.y = 2 * -(e.clientY / window.innerHeight) + 1;
  3083. }, _onMouseWheel: function _onMouseWheel(e) {
  3084. if (this.active) {
  3085. e.preventDefault(), e.stopPropagation();var t = 0;void 0 !== e.wheelDelta ? t = e.wheelDelta : void 0 !== e.detail && (t = -e.detail), t > 0 ? this.wheel++ : this.wheel--, this.signal.dispatch(vg.MouseCaster.WHEEL, this.wheel);
  3086. }
  3087. } }, vg.MouseCaster.prototype.constructor = vg.MouseCaster, vg.Scene = function (e, t) {
  3088. var i = { element: document.body, alpha: !0, antialias: !0, clearColor: "#fff", sortObjects: !1, fog: null, light: new THREE.DirectionalLight(16777215), lightPosition: null, cameraType: "PerspectiveCamera", cameraPosition: null, orthoZoom: 4 },
  3089. s = { minDistance: 100, maxDistance: 1e3, zoomSpeed: 2, noZoom: !1 };if (i = vg.Tools.merge(i, e), "boolean" != typeof t && (s = vg.Tools.merge(s, t)), this.renderer = new THREE.WebGLRenderer({ alpha: i.alpha, antialias: i.antialias }), this.renderer.setClearColor(i.clearColor, 0), this.renderer.sortObjects = i.sortObjects, this.width = window.innerWidth, this.height = window.innerHeight, this.orthoZoom = i.orthoZoom, this.container = new THREE.Scene(), this.container.fog = i.fog, this.container.add(new THREE.AmbientLight(14540253)), i.lightPosition || i.light.position.set(-1, 1, -1).normalize(), this.container.add(i.light), "OrthographicCamera" === i.cameraType) {
  3090. var n = window.innerWidth / this.orthoZoom,
  3091. l = window.innerHeight / this.orthoZoom;this.camera = new THREE.OrthographicCamera(n / -2, n / 2, l / 2, l / -2, 1, 5e3);
  3092. } else this.camera = new THREE.PerspectiveCamera(50, this.width / this.height, 1, 5e3);this.contolled = !!t, this.contolled && (this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement), this.controls.minDistance = s.minDistance, this.controls.maxDistance = s.maxDistance, this.controls.zoomSpeed = s.zoomSpeed, this.controls.noZoom = s.noZoom), i.cameraPosition && this.camera.position.copy(i.cameraPosition), window.addEventListener("resize", function () {
  3093. if (this.width = window.innerWidth, this.height = window.innerHeight, "OrthographicCamera" === this.camera.type) {
  3094. var e = this.width / this.orthoZoom,
  3095. t = this.height / this.orthoZoom;this.camera.left = e / -2, this.camera.right = e / 2, this.camera.top = t / 2, this.camera.bottom = t / -2;
  3096. } else this.camera.aspect = this.width / this.height;this.camera.updateProjectionMatrix(), this.renderer.setSize(this.width, this.height);
  3097. }.bind(this), !1), this.attachTo(i.element);
  3098. }, vg.Scene.prototype = { attachTo: function attachTo(e) {
  3099. e.style.width = this.width + "px", e.style.height = this.height + "px", this.renderer.setPixelRatio(window.devicePixelRatio), this.renderer.setSize(this.width, this.height), e.appendChild(this.renderer.domElement);
  3100. }, add: function add(e) {
  3101. this.container.add(e);
  3102. }, remove: function remove(e) {
  3103. this.container.remove(e);
  3104. }, render: function render() {
  3105. this.contolled && this.controls.update(), this.renderer.render(this.container, this.camera);
  3106. }, updateOrthoZoom: function updateOrthoZoom() {
  3107. if (this.orthoZoom <= 0) return void (this.orthoZoom = 0);var e = this.width / this.orthoZoom,
  3108. t = this.height / this.orthoZoom;this.camera.left = e / -2, this.camera.right = e / 2, this.camera.top = t / 2, this.camera.bottom = t / -2, this.camera.updateProjectionMatrix();
  3109. }, focusOn: function focusOn(e) {
  3110. this.camera.lookAt(e.position);
  3111. } }, vg.Scene.prototype.constructor = vg.Scene, vg.SelectionManager = function (e) {
  3112. this.mouse = e, this.onSelect = new vg.Signal(), this.onDeselect = new vg.Signal(), this.selected = null, this.toggleSelection = !1, this.mouse.signal.add(this.onMouse, this);
  3113. }, vg.SelectionManager.prototype = { select: function select(e, t) {
  3114. e && (t = t || !0, this.selected !== e && this.clearSelection(t), e.selected ? this.toggleSelection && (t && this.onDeselect.dispatch(e), e.deselect()) : e.select(), this.selected = e, t && this.onSelect.dispatch(e));
  3115. }, clearSelection: function clearSelection(e) {
  3116. e = e || !0, this.selected && (e && this.onDeselect.dispatch(this.selected), this.selected.deselect()), this.selected = null;
  3117. }, onMouse: function onMouse(e, t) {
  3118. switch (e) {case vg.MouseCaster.DOWN:
  3119. t || this.clearSelection();break;case vg.MouseCaster.CLICK:
  3120. this.select(t);}
  3121. } }, vg.SelectionManager.prototype.constructor = vg.SelectionManager, vg.Tools = { clamp: function clamp(e, t, i) {
  3122. return Math.max(t, Math.min(i, e));
  3123. }, sign: function sign(e) {
  3124. return e && e / Math.abs(e);
  3125. }, random: function random(e, t) {
  3126. return 1 === arguments.length ? Math.random() * e - .5 * e : Math.random() * (t - e) + e;
  3127. }, randomInt: function randomInt(e, t) {
  3128. return 1 === arguments.length ? Math.random() * e - .5 * e | 0 : Math.random() * (t - e + 1) + e | 0;
  3129. }, normalize: function normalize(e, t, i) {
  3130. return (e - t) / (i - t);
  3131. }, getShortRotation: function getShortRotation(e) {
  3132. return e %= this.TAU, e > this.PI ? e -= this.TAU : e < -this.PI && (e += this.TAU), e;
  3133. }, generateID: function generateID() {
  3134. return Math.random().toString(36).slice(2) + Date.now();
  3135. }, isPlainObject: function isPlainObject(e) {
  3136. if ("object" != (typeof e === "undefined" ? "undefined" : _typeof(e)) || e.nodeType || e === e.window) return !1;try {
  3137. if (e.constructor && !Object.prototype.hasOwnProperty.call(e.constructor.prototype, "isPrototypeOf")) return !1;
  3138. } catch (t) {
  3139. return !1;
  3140. }return !0;
  3141. }, merge: function merge(e, t) {
  3142. var i = this,
  3143. s = Array.isArray(t),
  3144. n = s && [] || {};return s ? (e = e || [], n = n.concat(e), t.forEach(function (t, s) {
  3145. "undefined" == typeof n[s] ? n[s] = t : i.isPlainObject(t) ? n[s] = i.merge(e[s], t) : -1 === e.indexOf(t) && n.push(t);
  3146. }), n) : (e && i.isPlainObject(e) && Object.keys(e).forEach(function (t) {
  3147. n[t] = e[t];
  3148. }), Object.keys(t).forEach(function (s) {
  3149. t[s] && i.isPlainObject(t[s]) && e[s] ? n[s] = i.merge(e[s], t[s]) : n[s] = t[s];
  3150. }), n);
  3151. }, now: function now() {
  3152. return window.nwf ? window.nwf.system.Performance.elapsedTime : window.performance.now();
  3153. }, empty: function empty(e) {
  3154. for (; e.lastChild;) {
  3155. e.removeChild(e.lastChild);
  3156. }
  3157. }, radixSort: function radixSort(e, t, i, s) {
  3158. if (t = t || 0, i = i || e.length, s = s || 31, !(t >= i - 1 || 0 > s)) {
  3159. for (var n = t, l = i, r = 1 << s; l > n;) {
  3160. if (e[n] & r) {
  3161. --l;var h = e[n];e[n] = e[l], e[l] = h;
  3162. } else ++n;
  3163. }this.radixSort(e, t, l, s - 1), this.radixSort(e, l, i, s - 1);
  3164. }
  3165. }, randomizeRGB: function randomizeRGB(e, t) {
  3166. var i,
  3167. s,
  3168. n = e.split(","),
  3169. l = "rgb(";for (t = this.randomInt(t), i = 0; 3 > i; i++) {
  3170. s = parseInt(n[i]) + t, 0 > s ? s = 0 : s > 255 && (s = 255), l += s + ",";
  3171. }return l = l.substring(0, l.length - 1), l += ")";
  3172. }, getJSON: function getJSON(e) {
  3173. var t = new XMLHttpRequest(),
  3174. i = "undefined" == typeof e.cache ? !1 : e.cache,
  3175. s = i ? e.url : e.url + "?t=" + Math.floor(1e4 * Math.random()) + Date.now();t.onreadystatechange = function () {
  3176. if (200 === this.status) {
  3177. var t = null;try {
  3178. t = JSON.parse(this.responseText);
  3179. } catch (i) {
  3180. return;
  3181. }return void e.callback.call(e.scope || null, t);
  3182. }0 !== this.status && console.warn("[Tools.getJSON] Error: " + this.status + " (" + this.statusText + ") :: " + e.url);
  3183. }, t.open("GET", s, !0), t.setRequestHeader("Accept", "application/json"), t.setRequestHeader("Content-Type", "application/json"), t.send("");
  3184. } };
  3185. },{}],9:[function(require,module,exports){
  3186. 'use strict';
  3187. /**
  3188. * Polyfill for the additional KeyboardEvent properties defined in the D3E and
  3189. * D4E draft specifications, by @inexorabletash.
  3190. *
  3191. * See: https://github.com/inexorabletash/polyfill
  3192. */
  3193. (function (global) {
  3194. var nativeKeyboardEvent = 'KeyboardEvent' in global;
  3195. if (!nativeKeyboardEvent) global.KeyboardEvent = function KeyboardEvent() {
  3196. throw TypeError('Illegal constructor');
  3197. };
  3198. if (!('DOM_KEY_LOCATION_STANDARD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_STANDARD = 0x00; // Default or unknown location
  3199. if (!('DOM_KEY_LOCATION_LEFT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_LEFT = 0x01; // e.g. Left Alt key
  3200. if (!('DOM_KEY_LOCATION_RIGHT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_RIGHT = 0x02; // e.g. Right Alt key
  3201. if (!('DOM_KEY_LOCATION_NUMPAD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD = 0x03; // e.g. Numpad 0 or +
  3202. var STANDARD = window.KeyboardEvent.DOM_KEY_LOCATION_STANDARD,
  3203. LEFT = window.KeyboardEvent.DOM_KEY_LOCATION_LEFT,
  3204. RIGHT = window.KeyboardEvent.DOM_KEY_LOCATION_RIGHT,
  3205. NUMPAD = window.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD;
  3206. //--------------------------------------------------------------------
  3207. //
  3208. // Utilities
  3209. //
  3210. //--------------------------------------------------------------------
  3211. function contains(s, ss) {
  3212. return String(s).indexOf(ss) !== -1;
  3213. }
  3214. var os = function () {
  3215. if (contains(navigator.platform, 'Win')) {
  3216. return 'win';
  3217. }
  3218. if (contains(navigator.platform, 'Mac')) {
  3219. return 'mac';
  3220. }
  3221. if (contains(navigator.platform, 'CrOS')) {
  3222. return 'cros';
  3223. }
  3224. if (contains(navigator.platform, 'Linux')) {
  3225. return 'linux';
  3226. }
  3227. if (contains(navigator.userAgent, 'iPad') || contains(navigator.platform, 'iPod') || contains(navigator.platform, 'iPhone')) {
  3228. return 'ios';
  3229. }
  3230. return '';
  3231. }();
  3232. var browser = function () {
  3233. if (contains(navigator.userAgent, 'Chrome/')) {
  3234. return 'chrome';
  3235. }
  3236. if (contains(navigator.vendor, 'Apple')) {
  3237. return 'safari';
  3238. }
  3239. if (contains(navigator.userAgent, 'MSIE')) {
  3240. return 'ie';
  3241. }
  3242. if (contains(navigator.userAgent, 'Gecko/')) {
  3243. return 'moz';
  3244. }
  3245. if (contains(navigator.userAgent, 'Opera/')) {
  3246. return 'opera';
  3247. }
  3248. return '';
  3249. }();
  3250. var browser_os = browser + '-' + os;
  3251. function mergeIf(baseTable, select, table) {
  3252. if (browser_os === select || browser === select || os === select) {
  3253. Object.keys(table).forEach(function (keyCode) {
  3254. baseTable[keyCode] = table[keyCode];
  3255. });
  3256. }
  3257. }
  3258. function remap(o, key) {
  3259. var r = {};
  3260. Object.keys(o).forEach(function (k) {
  3261. var item = o[k];
  3262. if (key in item) {
  3263. r[item[key]] = item;
  3264. }
  3265. });
  3266. return r;
  3267. }
  3268. function invert(o) {
  3269. var r = {};
  3270. Object.keys(o).forEach(function (k) {
  3271. r[o[k]] = k;
  3272. });
  3273. return r;
  3274. }
  3275. //--------------------------------------------------------------------
  3276. //
  3277. // Generic Mappings
  3278. //
  3279. //--------------------------------------------------------------------
  3280. // "keyInfo" is a dictionary:
  3281. // code: string - name from DOM Level 3 KeyboardEvent code Values
  3282. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-code.html
  3283. // location (optional): number - one of the DOM_KEY_LOCATION values
  3284. // keyCap (optional): string - keyboard label in en-US locale
  3285. // USB code Usage ID from page 0x07 unless otherwise noted (Informative)
  3286. // Map of keyCode to keyInfo
  3287. var keyCodeToInfoTable = {
  3288. // 0x01 - VK_LBUTTON
  3289. // 0x02 - VK_RBUTTON
  3290. 0x03: { code: 'Cancel' }, // [USB: 0x9b] char \x0018 ??? (Not in D3E)
  3291. // 0x04 - VK_MBUTTON
  3292. // 0x05 - VK_XBUTTON1
  3293. // 0x06 - VK_XBUTTON2
  3294. 0x06: { code: 'Help' }, // [USB: 0x75] ???
  3295. // 0x07 - undefined
  3296. 0x08: { code: 'Backspace' }, // [USB: 0x2a] Labelled Delete on Macintosh keyboards.
  3297. 0x09: { code: 'Tab' }, // [USB: 0x2b]
  3298. // 0x0A-0x0B - reserved
  3299. 0X0C: { code: 'Clear' }, // [USB: 0x9c] NumPad Center (Not in D3E)
  3300. 0X0D: { code: 'Enter' }, // [USB: 0x28]
  3301. // 0x0E-0x0F - undefined
  3302. 0x10: { code: 'Shift' },
  3303. 0x11: { code: 'Control' },
  3304. 0x12: { code: 'Alt' },
  3305. 0x13: { code: 'Pause' }, // [USB: 0x48]
  3306. 0x14: { code: 'CapsLock' }, // [USB: 0x39]
  3307. 0x15: { code: 'KanaMode' }, // [USB: 0x88] - "HangulMode" for Korean layout
  3308. 0x16: { code: 'HangulMode' }, // [USB: 0x90] 0x15 as well in MSDN VK table ???
  3309. 0x17: { code: 'JunjaMode' }, // (Not in D3E)
  3310. 0x18: { code: 'FinalMode' }, // (Not in D3E)
  3311. 0x19: { code: 'KanjiMode' }, // [USB: 0x91] - "HanjaMode" for Korean layout
  3312. // 0x1A - undefined
  3313. 0x1B: { code: 'Escape' }, // [USB: 0x29]
  3314. 0x1C: { code: 'Convert' }, // [USB: 0x8a]
  3315. 0x1D: { code: 'NonConvert' }, // [USB: 0x8b]
  3316. 0x1E: { code: 'Accept' }, // (Not in D3E)
  3317. 0x1F: { code: 'ModeChange' }, // (Not in D3E)
  3318. 0x20: { code: 'Space' }, // [USB: 0x2c]
  3319. 0x21: { code: 'PageUp' }, // [USB: 0x4b]
  3320. 0x22: { code: 'PageDown' }, // [USB: 0x4e]
  3321. 0x23: { code: 'End' }, // [USB: 0x4d]
  3322. 0x24: { code: 'Home' }, // [USB: 0x4a]
  3323. 0x25: { code: 'ArrowLeft' }, // [USB: 0x50]
  3324. 0x26: { code: 'ArrowUp' }, // [USB: 0x52]
  3325. 0x27: { code: 'ArrowRight' }, // [USB: 0x4f]
  3326. 0x28: { code: 'ArrowDown' }, // [USB: 0x51]
  3327. 0x29: { code: 'Select' }, // (Not in D3E)
  3328. 0x2A: { code: 'Print' }, // (Not in D3E)
  3329. 0x2B: { code: 'Execute' }, // [USB: 0x74] (Not in D3E)
  3330. 0x2C: { code: 'PrintScreen' }, // [USB: 0x46]
  3331. 0x2D: { code: 'Insert' }, // [USB: 0x49]
  3332. 0x2E: { code: 'Delete' }, // [USB: 0x4c]
  3333. 0x2F: { code: 'Help' }, // [USB: 0x75] ???
  3334. 0x30: { code: 'Digit0', keyCap: '0' }, // [USB: 0x27] 0)
  3335. 0x31: { code: 'Digit1', keyCap: '1' }, // [USB: 0x1e] 1!
  3336. 0x32: { code: 'Digit2', keyCap: '2' }, // [USB: 0x1f] 2@
  3337. 0x33: { code: 'Digit3', keyCap: '3' }, // [USB: 0x20] 3#
  3338. 0x34: { code: 'Digit4', keyCap: '4' }, // [USB: 0x21] 4$
  3339. 0x35: { code: 'Digit5', keyCap: '5' }, // [USB: 0x22] 5%
  3340. 0x36: { code: 'Digit6', keyCap: '6' }, // [USB: 0x23] 6^
  3341. 0x37: { code: 'Digit7', keyCap: '7' }, // [USB: 0x24] 7&
  3342. 0x38: { code: 'Digit8', keyCap: '8' }, // [USB: 0x25] 8*
  3343. 0x39: { code: 'Digit9', keyCap: '9' }, // [USB: 0x26] 9(
  3344. // 0x3A-0x40 - undefined
  3345. 0x41: { code: 'KeyA', keyCap: 'a' }, // [USB: 0x04]
  3346. 0x42: { code: 'KeyB', keyCap: 'b' }, // [USB: 0x05]
  3347. 0x43: { code: 'KeyC', keyCap: 'c' }, // [USB: 0x06]
  3348. 0x44: { code: 'KeyD', keyCap: 'd' }, // [USB: 0x07]
  3349. 0x45: { code: 'KeyE', keyCap: 'e' }, // [USB: 0x08]
  3350. 0x46: { code: 'KeyF', keyCap: 'f' }, // [USB: 0x09]
  3351. 0x47: { code: 'KeyG', keyCap: 'g' }, // [USB: 0x0a]
  3352. 0x48: { code: 'KeyH', keyCap: 'h' }, // [USB: 0x0b]
  3353. 0x49: { code: 'KeyI', keyCap: 'i' }, // [USB: 0x0c]
  3354. 0x4A: { code: 'KeyJ', keyCap: 'j' }, // [USB: 0x0d]
  3355. 0x4B: { code: 'KeyK', keyCap: 'k' }, // [USB: 0x0e]
  3356. 0x4C: { code: 'KeyL', keyCap: 'l' }, // [USB: 0x0f]
  3357. 0x4D: { code: 'KeyM', keyCap: 'm' }, // [USB: 0x10]
  3358. 0x4E: { code: 'KeyN', keyCap: 'n' }, // [USB: 0x11]
  3359. 0x4F: { code: 'KeyO', keyCap: 'o' }, // [USB: 0x12]
  3360. 0x50: { code: 'KeyP', keyCap: 'p' }, // [USB: 0x13]
  3361. 0x51: { code: 'KeyQ', keyCap: 'q' }, // [USB: 0x14]
  3362. 0x52: { code: 'KeyR', keyCap: 'r' }, // [USB: 0x15]
  3363. 0x53: { code: 'KeyS', keyCap: 's' }, // [USB: 0x16]
  3364. 0x54: { code: 'KeyT', keyCap: 't' }, // [USB: 0x17]
  3365. 0x55: { code: 'KeyU', keyCap: 'u' }, // [USB: 0x18]
  3366. 0x56: { code: 'KeyV', keyCap: 'v' }, // [USB: 0x19]
  3367. 0x57: { code: 'KeyW', keyCap: 'w' }, // [USB: 0x1a]
  3368. 0x58: { code: 'KeyX', keyCap: 'x' }, // [USB: 0x1b]
  3369. 0x59: { code: 'KeyY', keyCap: 'y' }, // [USB: 0x1c]
  3370. 0x5A: { code: 'KeyZ', keyCap: 'z' }, // [USB: 0x1d]
  3371. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  3372. 0x5C: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  3373. 0x5D: { code: 'ContextMenu' }, // [USB: 0x65] Context Menu
  3374. // 0x5E - reserved
  3375. 0x5F: { code: 'Standby' }, // [USB: 0x82] Sleep
  3376. 0x60: { code: 'Numpad0', keyCap: '0', location: NUMPAD }, // [USB: 0x62]
  3377. 0x61: { code: 'Numpad1', keyCap: '1', location: NUMPAD }, // [USB: 0x59]
  3378. 0x62: { code: 'Numpad2', keyCap: '2', location: NUMPAD }, // [USB: 0x5a]
  3379. 0x63: { code: 'Numpad3', keyCap: '3', location: NUMPAD }, // [USB: 0x5b]
  3380. 0x64: { code: 'Numpad4', keyCap: '4', location: NUMPAD }, // [USB: 0x5c]
  3381. 0x65: { code: 'Numpad5', keyCap: '5', location: NUMPAD }, // [USB: 0x5d]
  3382. 0x66: { code: 'Numpad6', keyCap: '6', location: NUMPAD }, // [USB: 0x5e]
  3383. 0x67: { code: 'Numpad7', keyCap: '7', location: NUMPAD }, // [USB: 0x5f]
  3384. 0x68: { code: 'Numpad8', keyCap: '8', location: NUMPAD }, // [USB: 0x60]
  3385. 0x69: { code: 'Numpad9', keyCap: '9', location: NUMPAD }, // [USB: 0x61]
  3386. 0x6A: { code: 'NumpadMultiply', keyCap: '*', location: NUMPAD }, // [USB: 0x55]
  3387. 0x6B: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  3388. 0x6C: { code: 'NumpadComma', keyCap: ',', location: NUMPAD }, // [USB: 0x85]
  3389. 0x6D: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD }, // [USB: 0x56]
  3390. 0x6E: { code: 'NumpadDecimal', keyCap: '.', location: NUMPAD }, // [USB: 0x63]
  3391. 0x6F: { code: 'NumpadDivide', keyCap: '/', location: NUMPAD }, // [USB: 0x54]
  3392. 0x70: { code: 'F1' }, // [USB: 0x3a]
  3393. 0x71: { code: 'F2' }, // [USB: 0x3b]
  3394. 0x72: { code: 'F3' }, // [USB: 0x3c]
  3395. 0x73: { code: 'F4' }, // [USB: 0x3d]
  3396. 0x74: { code: 'F5' }, // [USB: 0x3e]
  3397. 0x75: { code: 'F6' }, // [USB: 0x3f]
  3398. 0x76: { code: 'F7' }, // [USB: 0x40]
  3399. 0x77: { code: 'F8' }, // [USB: 0x41]
  3400. 0x78: { code: 'F9' }, // [USB: 0x42]
  3401. 0x79: { code: 'F10' }, // [USB: 0x43]
  3402. 0x7A: { code: 'F11' }, // [USB: 0x44]
  3403. 0x7B: { code: 'F12' }, // [USB: 0x45]
  3404. 0x7C: { code: 'F13' }, // [USB: 0x68]
  3405. 0x7D: { code: 'F14' }, // [USB: 0x69]
  3406. 0x7E: { code: 'F15' }, // [USB: 0x6a]
  3407. 0x7F: { code: 'F16' }, // [USB: 0x6b]
  3408. 0x80: { code: 'F17' }, // [USB: 0x6c]
  3409. 0x81: { code: 'F18' }, // [USB: 0x6d]
  3410. 0x82: { code: 'F19' }, // [USB: 0x6e]
  3411. 0x83: { code: 'F20' }, // [USB: 0x6f]
  3412. 0x84: { code: 'F21' }, // [USB: 0x70]
  3413. 0x85: { code: 'F22' }, // [USB: 0x71]
  3414. 0x86: { code: 'F23' }, // [USB: 0x72]
  3415. 0x87: { code: 'F24' }, // [USB: 0x73]
  3416. // 0x88-0x8F - unassigned
  3417. 0x90: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  3418. 0x91: { code: 'ScrollLock' }, // [USB: 0x47]
  3419. // 0x92-0x96 - OEM specific
  3420. // 0x97-0x9F - unassigned
  3421. // NOTE: 0xA0-0xA5 usually mapped to 0x10-0x12 in browsers
  3422. 0xA0: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  3423. 0xA1: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  3424. 0xA2: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  3425. 0xA3: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  3426. 0xA4: { code: 'AltLeft', location: LEFT }, // [USB: 0xe2]
  3427. 0xA5: { code: 'AltRight', location: RIGHT }, // [USB: 0xe6]
  3428. 0xA6: { code: 'BrowserBack' }, // [USB: 0x0c/0x0224]
  3429. 0xA7: { code: 'BrowserForward' }, // [USB: 0x0c/0x0225]
  3430. 0xA8: { code: 'BrowserRefresh' }, // [USB: 0x0c/0x0227]
  3431. 0xA9: { code: 'BrowserStop' }, // [USB: 0x0c/0x0226]
  3432. 0xAA: { code: 'BrowserSearch' }, // [USB: 0x0c/0x0221]
  3433. 0xAB: { code: 'BrowserFavorites' }, // [USB: 0x0c/0x0228]
  3434. 0xAC: { code: 'BrowserHome' }, // [USB: 0x0c/0x0222]
  3435. 0xAD: { code: 'VolumeMute' }, // [USB: 0x7f]
  3436. 0xAE: { code: 'VolumeDown' }, // [USB: 0x81]
  3437. 0xAF: { code: 'VolumeUp' }, // [USB: 0x80]
  3438. 0xB0: { code: 'MediaTrackNext' }, // [USB: 0x0c/0x00b5]
  3439. 0xB1: { code: 'MediaTrackPrevious' }, // [USB: 0x0c/0x00b6]
  3440. 0xB2: { code: 'MediaStop' }, // [USB: 0x0c/0x00b7]
  3441. 0xB3: { code: 'MediaPlayPause' }, // [USB: 0x0c/0x00cd]
  3442. 0xB4: { code: 'LaunchMail' }, // [USB: 0x0c/0x018a]
  3443. 0xB5: { code: 'MediaSelect' },
  3444. 0xB6: { code: 'LaunchApp1' },
  3445. 0xB7: { code: 'LaunchApp2' },
  3446. // 0xB8-0xB9 - reserved
  3447. 0xBA: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  3448. 0xBB: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  3449. 0xBC: { code: 'Comma', keyCap: ',' }, // [USB: 0x36] ,<
  3450. 0xBD: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  3451. 0xBE: { code: 'Period', keyCap: '.' }, // [USB: 0x37] .>
  3452. 0xBF: { code: 'Slash', keyCap: '/' }, // [USB: 0x38] /? (US Standard 101)
  3453. 0xC0: { code: 'Backquote', keyCap: '`' }, // [USB: 0x35] `~ (US Standard 101)
  3454. // 0xC1-0xCF - reserved
  3455. // 0xD0-0xD7 - reserved
  3456. // 0xD8-0xDA - unassigned
  3457. 0xDB: { code: 'BracketLeft', keyCap: '[' }, // [USB: 0x2f] [{ (US Standard 101)
  3458. 0xDC: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  3459. 0xDD: { code: 'BracketRight', keyCap: ']' }, // [USB: 0x30] ]} (US Standard 101)
  3460. 0xDE: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  3461. // 0xDF - miscellaneous/varies
  3462. // 0xE0 - reserved
  3463. // 0xE1 - OEM specific
  3464. 0xE2: { code: 'IntlBackslash', keyCap: '\\' }, // [USB: 0x64] \| (UK Standard 102)
  3465. // 0xE3-0xE4 - OEM specific
  3466. 0xE5: { code: 'Process' }, // (Not in D3E)
  3467. // 0xE6 - OEM specific
  3468. // 0xE7 - VK_PACKET
  3469. // 0xE8 - unassigned
  3470. // 0xE9-0xEF - OEM specific
  3471. // 0xF0-0xF5 - OEM specific
  3472. 0xF6: { code: 'Attn' }, // [USB: 0x9a] (Not in D3E)
  3473. 0xF7: { code: 'CrSel' }, // [USB: 0xa3] (Not in D3E)
  3474. 0xF8: { code: 'ExSel' }, // [USB: 0xa4] (Not in D3E)
  3475. 0xF9: { code: 'EraseEof' }, // (Not in D3E)
  3476. 0xFA: { code: 'Play' }, // (Not in D3E)
  3477. 0xFB: { code: 'ZoomToggle' }, // (Not in D3E)
  3478. // 0xFC - VK_NONAME - reserved
  3479. // 0xFD - VK_PA1
  3480. 0xFE: { code: 'Clear' // [USB: 0x9c] (Not in D3E)
  3481. } };
  3482. // No legacy keyCode, but listed in D3E:
  3483. // code: usb
  3484. // 'IntlHash': 0x070032,
  3485. // 'IntlRo': 0x070087,
  3486. // 'IntlYen': 0x070089,
  3487. // 'NumpadBackspace': 0x0700bb,
  3488. // 'NumpadClear': 0x0700d8,
  3489. // 'NumpadClearEntry': 0x0700d9,
  3490. // 'NumpadMemoryAdd': 0x0700d3,
  3491. // 'NumpadMemoryClear': 0x0700d2,
  3492. // 'NumpadMemoryRecall': 0x0700d1,
  3493. // 'NumpadMemoryStore': 0x0700d0,
  3494. // 'NumpadMemorySubtract': 0x0700d4,
  3495. // 'NumpadParenLeft': 0x0700b6,
  3496. // 'NumpadParenRight': 0x0700b7,
  3497. //--------------------------------------------------------------------
  3498. //
  3499. // Browser/OS Specific Mappings
  3500. //
  3501. //--------------------------------------------------------------------
  3502. mergeIf(keyCodeToInfoTable, 'moz', {
  3503. 0x3B: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  3504. 0x3D: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  3505. 0x6B: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  3506. 0x6D: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  3507. 0xBB: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  3508. 0xBD: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD // [USB: 0x56]
  3509. } });
  3510. mergeIf(keyCodeToInfoTable, 'moz-mac', {
  3511. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  3512. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  3513. } });
  3514. mergeIf(keyCodeToInfoTable, 'moz-win', {
  3515. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  3516. } });
  3517. mergeIf(keyCodeToInfoTable, 'chrome-mac', {
  3518. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3519. } });
  3520. // Windows via Bootcamp (!)
  3521. if (0) {
  3522. mergeIf(keyCodeToInfoTable, 'chrome-win', {
  3523. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  3524. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  3525. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  3526. } });
  3527. mergeIf(keyCodeToInfoTable, 'ie', {
  3528. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  3529. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  3530. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  3531. } });
  3532. }
  3533. mergeIf(keyCodeToInfoTable, 'safari', {
  3534. 0x03: { code: 'Enter' }, // [USB: 0x28] old Safari
  3535. 0x19: { code: 'Tab' // [USB: 0x2b] old Safari for Shift+Tab
  3536. } });
  3537. mergeIf(keyCodeToInfoTable, 'ios', {
  3538. 0x0A: { code: 'Enter', location: STANDARD // [USB: 0x28]
  3539. } });
  3540. mergeIf(keyCodeToInfoTable, 'safari-mac', {
  3541. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  3542. 0x5D: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  3543. 0xE5: { code: 'KeyQ', keyCap: 'Q' // [USB: 0x14] On alternate presses, Ctrl+Q sends this
  3544. } });
  3545. //--------------------------------------------------------------------
  3546. //
  3547. // Identifier Mappings
  3548. //
  3549. //--------------------------------------------------------------------
  3550. // Cases where newer-ish browsers send keyIdentifier which can be
  3551. // used to disambiguate keys.
  3552. // keyIdentifierTable[keyIdentifier] -> keyInfo
  3553. var keyIdentifierTable = {};
  3554. if ('cros' === os) {
  3555. keyIdentifierTable['U+00A0'] = { code: 'ShiftLeft', location: LEFT };
  3556. keyIdentifierTable['U+00A1'] = { code: 'ShiftRight', location: RIGHT };
  3557. keyIdentifierTable['U+00A2'] = { code: 'ControlLeft', location: LEFT };
  3558. keyIdentifierTable['U+00A3'] = { code: 'ControlRight', location: RIGHT };
  3559. keyIdentifierTable['U+00A4'] = { code: 'AltLeft', location: LEFT };
  3560. keyIdentifierTable['U+00A5'] = { code: 'AltRight', location: RIGHT };
  3561. }
  3562. if ('chrome-mac' === browser_os) {
  3563. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  3564. }
  3565. if ('safari-mac' === browser_os) {
  3566. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  3567. }
  3568. if ('ios' === os) {
  3569. // These only generate keyup events
  3570. keyIdentifierTable['U+0010'] = { code: 'Function' };
  3571. keyIdentifierTable['U+001C'] = { code: 'ArrowLeft' };
  3572. keyIdentifierTable['U+001D'] = { code: 'ArrowRight' };
  3573. keyIdentifierTable['U+001E'] = { code: 'ArrowUp' };
  3574. keyIdentifierTable['U+001F'] = { code: 'ArrowDown' };
  3575. keyIdentifierTable['U+0001'] = { code: 'Home' }; // [USB: 0x4a] Fn + ArrowLeft
  3576. keyIdentifierTable['U+0004'] = { code: 'End' }; // [USB: 0x4d] Fn + ArrowRight
  3577. keyIdentifierTable['U+000B'] = { code: 'PageUp' }; // [USB: 0x4b] Fn + ArrowUp
  3578. keyIdentifierTable['U+000C'] = { code: 'PageDown' }; // [USB: 0x4e] Fn + ArrowDown
  3579. }
  3580. //--------------------------------------------------------------------
  3581. //
  3582. // Location Mappings
  3583. //
  3584. //--------------------------------------------------------------------
  3585. // Cases where newer-ish browsers send location/keyLocation which
  3586. // can be used to disambiguate keys.
  3587. // locationTable[location][keyCode] -> keyInfo
  3588. var locationTable = [];
  3589. locationTable[LEFT] = {
  3590. 0x10: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  3591. 0x11: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  3592. 0x12: { code: 'AltLeft', location: LEFT // [USB: 0xe2]
  3593. } };
  3594. locationTable[RIGHT] = {
  3595. 0x10: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  3596. 0x11: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  3597. 0x12: { code: 'AltRight', location: RIGHT // [USB: 0xe6]
  3598. } };
  3599. locationTable[NUMPAD] = {
  3600. 0x0D: { code: 'NumpadEnter', location: NUMPAD // [USB: 0x58]
  3601. } };
  3602. mergeIf(locationTable[NUMPAD], 'moz', {
  3603. 0x6D: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  3604. 0x6B: { code: 'NumpadAdd', location: NUMPAD // [USB: 0x57]
  3605. } });
  3606. mergeIf(locationTable[LEFT], 'moz-mac', {
  3607. 0xE0: { code: 'OSLeft', location: LEFT // [USB: 0xe3]
  3608. } });
  3609. mergeIf(locationTable[RIGHT], 'moz-mac', {
  3610. 0xE0: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3611. } });
  3612. mergeIf(locationTable[RIGHT], 'moz-win', {
  3613. 0x5B: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3614. } });
  3615. mergeIf(locationTable[RIGHT], 'mac', {
  3616. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3617. } });
  3618. mergeIf(locationTable[NUMPAD], 'chrome-mac', {
  3619. 0x0C: { code: 'NumLock', location: NUMPAD // [USB: 0x53]
  3620. } });
  3621. mergeIf(locationTable[NUMPAD], 'safari-mac', {
  3622. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  3623. 0xBB: { code: 'NumpadAdd', location: NUMPAD }, // [USB: 0x57]
  3624. 0xBD: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  3625. 0xBE: { code: 'NumpadDecimal', location: NUMPAD }, // [USB: 0x63]
  3626. 0xBF: { code: 'NumpadDivide', location: NUMPAD // [USB: 0x54]
  3627. } });
  3628. //--------------------------------------------------------------------
  3629. //
  3630. // Key Values
  3631. //
  3632. //--------------------------------------------------------------------
  3633. // Mapping from `code` values to `key` values. Values defined at:
  3634. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-key.html
  3635. // Entries are only provided when `key` differs from `code`. If
  3636. // printable, `shiftKey` has the shifted printable character. This
  3637. // assumes US Standard 101 layout
  3638. var codeToKeyTable = {
  3639. // Modifier Keys
  3640. ShiftLeft: { key: 'Shift' },
  3641. ShiftRight: { key: 'Shift' },
  3642. ControlLeft: { key: 'Control' },
  3643. ControlRight: { key: 'Control' },
  3644. AltLeft: { key: 'Alt' },
  3645. AltRight: { key: 'Alt' },
  3646. OSLeft: { key: 'OS' },
  3647. OSRight: { key: 'OS' },
  3648. // Whitespace Keys
  3649. NumpadEnter: { key: 'Enter' },
  3650. Space: { key: ' ' },
  3651. // Printable Keys
  3652. Digit0: { key: '0', shiftKey: ')' },
  3653. Digit1: { key: '1', shiftKey: '!' },
  3654. Digit2: { key: '2', shiftKey: '@' },
  3655. Digit3: { key: '3', shiftKey: '#' },
  3656. Digit4: { key: '4', shiftKey: '$' },
  3657. Digit5: { key: '5', shiftKey: '%' },
  3658. Digit6: { key: '6', shiftKey: '^' },
  3659. Digit7: { key: '7', shiftKey: '&' },
  3660. Digit8: { key: '8', shiftKey: '*' },
  3661. Digit9: { key: '9', shiftKey: '(' },
  3662. KeyA: { key: 'a', shiftKey: 'A' },
  3663. KeyB: { key: 'b', shiftKey: 'B' },
  3664. KeyC: { key: 'c', shiftKey: 'C' },
  3665. KeyD: { key: 'd', shiftKey: 'D' },
  3666. KeyE: { key: 'e', shiftKey: 'E' },
  3667. KeyF: { key: 'f', shiftKey: 'F' },
  3668. KeyG: { key: 'g', shiftKey: 'G' },
  3669. KeyH: { key: 'h', shiftKey: 'H' },
  3670. KeyI: { key: 'i', shiftKey: 'I' },
  3671. KeyJ: { key: 'j', shiftKey: 'J' },
  3672. KeyK: { key: 'k', shiftKey: 'K' },
  3673. KeyL: { key: 'l', shiftKey: 'L' },
  3674. KeyM: { key: 'm', shiftKey: 'M' },
  3675. KeyN: { key: 'n', shiftKey: 'N' },
  3676. KeyO: { key: 'o', shiftKey: 'O' },
  3677. KeyP: { key: 'p', shiftKey: 'P' },
  3678. KeyQ: { key: 'q', shiftKey: 'Q' },
  3679. KeyR: { key: 'r', shiftKey: 'R' },
  3680. KeyS: { key: 's', shiftKey: 'S' },
  3681. KeyT: { key: 't', shiftKey: 'T' },
  3682. KeyU: { key: 'u', shiftKey: 'U' },
  3683. KeyV: { key: 'v', shiftKey: 'V' },
  3684. KeyW: { key: 'w', shiftKey: 'W' },
  3685. KeyX: { key: 'x', shiftKey: 'X' },
  3686. KeyY: { key: 'y', shiftKey: 'Y' },
  3687. KeyZ: { key: 'z', shiftKey: 'Z' },
  3688. Numpad0: { key: '0' },
  3689. Numpad1: { key: '1' },
  3690. Numpad2: { key: '2' },
  3691. Numpad3: { key: '3' },
  3692. Numpad4: { key: '4' },
  3693. Numpad5: { key: '5' },
  3694. Numpad6: { key: '6' },
  3695. Numpad7: { key: '7' },
  3696. Numpad8: { key: '8' },
  3697. Numpad9: { key: '9' },
  3698. NumpadMultiply: { key: '*' },
  3699. NumpadAdd: { key: '+' },
  3700. NumpadComma: { key: ',' },
  3701. NumpadSubtract: { key: '-' },
  3702. NumpadDecimal: { key: '.' },
  3703. NumpadDivide: { key: '/' },
  3704. Semicolon: { key: ';', shiftKey: ':' },
  3705. Equal: { key: '=', shiftKey: '+' },
  3706. Comma: { key: ',', shiftKey: '<' },
  3707. Minus: { key: '-', shiftKey: '_' },
  3708. Period: { key: '.', shiftKey: '>' },
  3709. Slash: { key: '/', shiftKey: '?' },
  3710. Backquote: { key: '`', shiftKey: '~' },
  3711. BracketLeft: { key: '[', shiftKey: '{' },
  3712. Backslash: { key: '\\', shiftKey: '|' },
  3713. BracketRight: { key: ']', shiftKey: '}' },
  3714. Quote: { key: '\'', shiftKey: '"' },
  3715. IntlBackslash: { key: '\\', shiftKey: '|' }
  3716. };
  3717. mergeIf(codeToKeyTable, 'mac', {
  3718. OSLeft: { key: 'Meta' },
  3719. OSRight: { key: 'Meta' }
  3720. });
  3721. // Corrections for 'key' names in older browsers (e.g. FF36-)
  3722. // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.key#Key_values
  3723. var keyFixTable = {
  3724. Esc: 'Escape',
  3725. Nonconvert: 'NonConvert',
  3726. Left: 'ArrowLeft',
  3727. Up: 'ArrowUp',
  3728. Right: 'ArrowRight',
  3729. Down: 'ArrowDown',
  3730. Del: 'Delete',
  3731. Menu: 'ContextMenu',
  3732. MediaNextTrack: 'MediaTrackNext',
  3733. MediaPreviousTrack: 'MediaTrackPrevious',
  3734. SelectMedia: 'MediaSelect',
  3735. HalfWidth: 'Hankaku',
  3736. FullWidth: 'Zenkaku',
  3737. RomanCharacters: 'Romaji',
  3738. Crsel: 'CrSel',
  3739. Exsel: 'ExSel',
  3740. Zoom: 'ZoomToggle'
  3741. };
  3742. //--------------------------------------------------------------------
  3743. //
  3744. // Exported Functions
  3745. //
  3746. //--------------------------------------------------------------------
  3747. var codeTable = remap(keyCodeToInfoTable, 'code');
  3748. try {
  3749. var nativeLocation = nativeKeyboardEvent && 'location' in new KeyboardEvent('');
  3750. } catch (_) {}
  3751. function keyInfoForEvent(event) {
  3752. var keyCode = 'keyCode' in event ? event.keyCode : 'which' in event ? event.which : 0;
  3753. var keyInfo = function () {
  3754. if (nativeLocation || 'keyLocation' in event) {
  3755. var location = nativeLocation ? event.location : event.keyLocation;
  3756. if (location && keyCode in locationTable[location]) {
  3757. return locationTable[location][keyCode];
  3758. }
  3759. }
  3760. if ('keyIdentifier' in event && event.keyIdentifier in keyIdentifierTable) {
  3761. return keyIdentifierTable[event.keyIdentifier];
  3762. }
  3763. if (keyCode in keyCodeToInfoTable) {
  3764. return keyCodeToInfoTable[keyCode];
  3765. }
  3766. return null;
  3767. }();
  3768. // TODO: Track these down and move to general tables
  3769. if (0) {
  3770. // TODO: Map these for newerish browsers?
  3771. // TODO: iOS only?
  3772. // TODO: Override with more common keyIdentifier name?
  3773. switch (event.keyIdentifier) {
  3774. case 'U+0010':
  3775. keyInfo = { code: 'Function' };break;
  3776. case 'U+001C':
  3777. keyInfo = { code: 'ArrowLeft' };break;
  3778. case 'U+001D':
  3779. keyInfo = { code: 'ArrowRight' };break;
  3780. case 'U+001E':
  3781. keyInfo = { code: 'ArrowUp' };break;
  3782. case 'U+001F':
  3783. keyInfo = { code: 'ArrowDown' };break;
  3784. }
  3785. }
  3786. if (!keyInfo) return null;
  3787. var key = function () {
  3788. var entry = codeToKeyTable[keyInfo.code];
  3789. if (!entry) return keyInfo.code;
  3790. return event.shiftKey && 'shiftKey' in entry ? entry.shiftKey : entry.key;
  3791. }();
  3792. return {
  3793. code: keyInfo.code,
  3794. key: key,
  3795. location: keyInfo.location,
  3796. keyCap: keyInfo.keyCap
  3797. };
  3798. }
  3799. function queryKeyCap(code, locale) {
  3800. code = String(code);
  3801. if (!codeTable.hasOwnProperty(code)) return 'Undefined';
  3802. if (locale && String(locale).toLowerCase() !== 'en-us') throw Error('Unsupported locale');
  3803. var keyInfo = codeTable[code];
  3804. return keyInfo.keyCap || keyInfo.code || 'Undefined';
  3805. }
  3806. if ('KeyboardEvent' in global && 'defineProperty' in Object) {
  3807. (function () {
  3808. function define(o, p, v) {
  3809. if (p in o) return;
  3810. Object.defineProperty(o, p, v);
  3811. }
  3812. define(KeyboardEvent.prototype, 'code', { get: function get() {
  3813. var keyInfo = keyInfoForEvent(this);
  3814. return keyInfo ? keyInfo.code : '';
  3815. } });
  3816. // Fix for nonstandard `key` values (FF36-)
  3817. if ('key' in KeyboardEvent.prototype) {
  3818. var desc = Object.getOwnPropertyDescriptor(KeyboardEvent.prototype, 'key');
  3819. Object.defineProperty(KeyboardEvent.prototype, 'key', { get: function get() {
  3820. var key = desc.get.call(this);
  3821. return keyFixTable.hasOwnProperty(key) ? keyFixTable[key] : key;
  3822. } });
  3823. }
  3824. define(KeyboardEvent.prototype, 'key', { get: function get() {
  3825. var keyInfo = keyInfoForEvent(this);
  3826. return keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  3827. } });
  3828. define(KeyboardEvent.prototype, 'location', { get: function get() {
  3829. var keyInfo = keyInfoForEvent(this);
  3830. return keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  3831. } });
  3832. define(KeyboardEvent.prototype, 'locale', { get: function get() {
  3833. return '';
  3834. } });
  3835. })();
  3836. }
  3837. if (!('queryKeyCap' in global.KeyboardEvent)) global.KeyboardEvent.queryKeyCap = queryKeyCap;
  3838. // Helper for IE8-
  3839. global.identifyKey = function (event) {
  3840. if ('code' in event) return;
  3841. var keyInfo = keyInfoForEvent(event);
  3842. event.code = keyInfo ? keyInfo.code : '';
  3843. event.key = keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  3844. event.location = 'location' in event ? event.location : 'keyLocation' in event ? event.keyLocation : keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  3845. event.locale = '';
  3846. };
  3847. })(window);
  3848. },{}],10:[function(require,module,exports){
  3849. var e=function(){};e.computeCentroids=function(e){var t,n,r;for(t=0,n=e.faces.length;t<n;t++)(r=e.faces[t]).centroid=new THREE.Vector3(0,0,0),r.centroid.add(e.vertices[r.a]),r.centroid.add(e.vertices[r.b]),r.centroid.add(e.vertices[r.c]),r.centroid.divideScalar(3)},e.roundNumber=function(e,t){return Number(e.toFixed(t))},e.sample=function(e){return e[Math.floor(Math.random()*e.length)]},e.mergeVertexIds=function(e,t){var n=[];if(e.forEach(function(e){t.indexOf(e)>=0&&n.push(e)}),n.length<2)return[];n.includes(e[0])&&n.includes(e[e.length-1])&&e.push(e.shift()),n.includes(t[0])&&n.includes(t[t.length-1])&&t.push(t.shift()),n=[],e.forEach(function(e){t.includes(e)&&n.push(e)});for(var r=n[1],o=n[0],i=e.slice();i[0]!==r;)i.push(i.shift());for(var s=0,u=t.slice();u[0]!==o;)if(u.push(u.shift()),s++>10)throw new Error("Unexpected state");return u.shift(),u.pop(),i=i.concat(u)},e.setPolygonCentroid=function(e,t){var n=new THREE.Vector3,r=t.vertices;e.vertexIds.forEach(function(e){n.add(r[e])}),n.divideScalar(e.vertexIds.length),e.centroid.copy(n)},e.cleanPolygon=function(e,t){for(var n=[],r=t.vertices,o=0;o<e.vertexIds.length;o++){var i,s,u,c=r[e.vertexIds[o]];0===o?(i=e.vertexIds[1],s=e.vertexIds[e.vertexIds.length-1]):o===e.vertexIds.length-1?(i=e.vertexIds[0],s=e.vertexIds[e.vertexIds.length-2]):(i=e.vertexIds[o+1],s=e.vertexIds[o-1]),u=r[s];var h=r[i].clone().sub(c),a=u.clone().sub(c),d=h.angleTo(a);if(d>Math.PI-.01&&d<Math.PI+.01){var f=[];e.neighbours.forEach(function(t){t.vertexIds.includes(e.vertexIds[o])||f.push(t)}),e.neighbours=f}else n.push(e.vertexIds[o])}e.vertexIds=n,this.setPolygonCentroid(e,t)},e.isConvex=function(e,t){var n=t.vertices;if(e.vertexIds.length<3)return!1;for(var r=!0,o=[],i=0;i<e.vertexIds.length;i++){var s,u,c=n[e.vertexIds[i]];0===i?(s=n[e.vertexIds[1]],u=n[e.vertexIds[e.vertexIds.length-1]]):i===e.vertexIds.length-1?(s=n[e.vertexIds[0]],u=n[e.vertexIds[e.vertexIds.length-2]]):(s=n[e.vertexIds[i+1]],u=n[e.vertexIds[i-1]]);var h=s.clone().sub(c),a=u.clone().sub(c),d=h.angleTo(a);if(d===Math.PI||0===d)return!1;var f=h.cross(a).y;o.push(f)}return o.forEach(function(e){0===e&&(r=!1)}),o.forEach(o[0]>0?function(e){e<0&&(r=!1)}:function(e){e>0&&(r=!1)}),r},e.distanceToSquared=function(e,t){var n=e.x-t.x,r=e.y-t.y,o=e.z-t.z;return n*n+r*r+o*o},e.isPointInPoly=function(e,t){for(var n=!1,r=-1,o=e.length,i=o-1;++r<o;i=r)(e[r].z<=t.z&&t.z<e[i].z||e[i].z<=t.z&&t.z<e[r].z)&&t.x<(e[i].x-e[r].x)*(t.z-e[r].z)/(e[i].z-e[r].z)+e[r].x&&(n=!n);return n},e.isVectorInPolygon=function(e,t,n){var r=1e5,o=-1e5,i=[];return t.vertexIds.forEach(function(e){r=Math.min(n[e].y,r),o=Math.max(n[e].y,o),i.push(n[e])}),!!(e.y<o+.5&&e.y>r-.5&&this.isPointInPoly(i,e))},e.triarea2=function(e,t,n){return(n.x-e.x)*(t.z-e.z)-(t.x-e.x)*(n.z-e.z)},e.vequal=function(e,t){return this.distanceToSquared(e,t)<1e-5};var t=function(e){this.content=[],this.scoreFunction=e};t.prototype.push=function(e){this.content.push(e),this.sinkDown(this.content.length-1)},t.prototype.pop=function(){var e=this.content[0],t=this.content.pop();return this.content.length>0&&(this.content[0]=t,this.bubbleUp(0)),e},t.prototype.remove=function(e){var t=this.content.indexOf(e),n=this.content.pop();t!==this.content.length-1&&(this.content[t]=n,this.scoreFunction(n)<this.scoreFunction(e)?this.sinkDown(t):this.bubbleUp(t))},t.prototype.size=function(){return this.content.length},t.prototype.rescoreElement=function(e){this.sinkDown(this.content.indexOf(e))},t.prototype.sinkDown=function(e){for(var t=this.content[e];e>0;){var n=(e+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(t)<this.scoreFunction(r)))break;this.content[n]=t,this.content[e]=r,e=n}},t.prototype.bubbleUp=function(e){for(var t=this.content.length,n=this.content[e],r=this.scoreFunction(n);;){var o=e+1<<1,i=o-1,s=null,u=void 0;if(i<t)(u=this.scoreFunction(this.content[i]))<r&&(s=i);if(o<t)this.scoreFunction(this.content[o])<(null===s?r:u)&&(s=o);if(null===s)break;this.content[e]=this.content[s],this.content[s]=n,e=s}};var n=function(){};n.init=function(e){for(var t=0;t<e.length;t++){var n=e[t];n.f=0,n.g=0,n.h=0,n.cost=1,n.visited=!1,n.closed=!1,n.parent=null}},n.cleanUp=function(e){for(var t=0;t<e.length;t++){var n=e[t];delete n.f,delete n.g,delete n.h,delete n.cost,delete n.visited,delete n.closed,delete n.parent}},n.heap=function(){return new t(function(e){return e.f})},n.search=function(e,t,n){this.init(e);var r=this.heap();for(r.push(t);r.size()>0;){var o=r.pop();if(o===n){for(var i=o,s=[];i.parent;)s.push(i),i=i.parent;return this.cleanUp(s),s.reverse()}o.closed=!0;for(var u=this.neighbours(e,o),c=0,h=u.length;c<h;c++){var a=u[c];if(!a.closed){var d=o.g+a.cost,f=a.visited;if(!f||d<a.g){if(a.visited=!0,a.parent=o,!a.centroid||!n.centroid)throw new Error("Unexpected state");a.h=a.h||this.heuristic(a.centroid,n.centroid),a.g=d,a.f=a.g+a.h,f?r.rescoreElement(a):r.push(a)}}}}return[]},n.heuristic=function(t,n){return e.distanceToSquared(t,n)},n.neighbours=function(e,t){for(var n=[],r=0;r<t.neighbours.length;r++)n.push(e[t.neighbours[r]]);return n};var r=1,o=function(){};o.buildZone=function(t){var n=this,r=this._buildNavigationMesh(t),o={};r.vertices.forEach(function(t){t.x=e.roundNumber(t.x,2),t.y=e.roundNumber(t.y,2),t.z=e.roundNumber(t.z,2)}),o.vertices=r.vertices;var i=this._buildPolygonGroups(r);o.groups=[];var s=function(e,t){for(var n=0;n<e.length;n++)if(t===e[n])return n};return i.forEach(function(t){var r=[];t.forEach(function(o){var i=o.neighbours.map(function(e){return s(t,e)}),u=o.neighbours.map(function(e){return n._getSharedVerticesInOrder(o,e)});o.centroid.x=e.roundNumber(o.centroid.x,2),o.centroid.y=e.roundNumber(o.centroid.y,2),o.centroid.z=e.roundNumber(o.centroid.z,2),r.push({id:s(t,o),neighbours:i,vertexIds:o.vertexIds,centroid:o.centroid,portals:u})}),o.groups.push(r)}),o},o._buildNavigationMesh=function(t){return e.computeCentroids(t),t.mergeVertices(),this._buildPolygonsFromGeometry(t)},o._buildPolygonGroups=function(e){var t=[],n=0,r=function(e){e.neighbours.forEach(function(t){void 0===t.group&&(t.group=e.group,r(t))})};return e.polygons.forEach(function(e){void 0===e.group&&(e.group=n++,r(e)),t[e.group]||(t[e.group]=[]),t[e.group].push(e)}),t},o._buildPolygonNeighbours=function(e,t,n){var r=new Set,o=n.get(e.vertexIds[0]),i=n.get(e.vertexIds[1]),s=n.get(e.vertexIds[2]);o.forEach(function(e){(i.has(e)||s.has(e))&&r.add(t.polygons[e])}),i.forEach(function(e){s.has(e)&&r.add(t.polygons[e])}),e.neighbours=Array.from(r)},o._buildPolygonsFromGeometry=function(e){for(var t=this,n=[],o=e.vertices,i=e.faceVertexUvs,s=new Map,u=0;u<o.length;u++)s.set(u,new Set);e.faces.forEach(function(e){n.push({id:r++,vertexIds:[e.a,e.b,e.c],centroid:e.centroid,normal:e.normal,neighbours:[]}),s.get(e.a).add(n.length-1),s.get(e.b).add(n.length-1),s.get(e.c).add(n.length-1)});var c={polygons:n,vertices:o,faceVertexUvs:i};return n.forEach(function(e){t._buildPolygonNeighbours(e,c,s)}),c},o._getSharedVerticesInOrder=function(e,t){var n=e.vertexIds,r=t.vertexIds,o=new Set;if(n.forEach(function(e){r.includes(e)&&o.add(e)}),o.size<2)return[];o.has(n[0])&&o.has(n[n.length-1])&&n.push(n.shift()),o.has(r[0])&&o.has(r[r.length-1])&&r.push(r.shift());var i=[];return n.forEach(function(e){r.includes(e)&&i.push(e)}),i};var i=function(){this.portals=[]};i.prototype.push=function(e,t){void 0===t&&(t=e),this.portals.push({left:e,right:t})},i.prototype.stringPull=function(){var t,n,r,o=this.portals,i=[],s=0,u=0,c=0;n=o[0].left,r=o[0].right,i.push(t=o[0].left);for(var h=1;h<o.length;h++){var a=o[h].left,d=o[h].right;if(e.triarea2(t,r,d)<=0){if(!(e.vequal(t,r)||e.triarea2(t,n,d)>0)){i.push(n),n=t=n,r=t,u=s=u,c=s,h=s;continue}r=d,c=h}if(e.triarea2(t,n,a)>=0){if(!(e.vequal(t,n)||e.triarea2(t,r,a)<0)){i.push(r),n=t=r,r=t,u=s=c,c=s,h=s;continue}n=a,u=h}}return 0!==i.length&&e.vequal(i[i.length-1],o[o.length-1].left)||i.push(o[o.length-1].left),this.path=i,i};var s,u,c,h,a,d,f=function(){this.zones={}};f.createZone=function(e){return o.buildZone(e)},f.prototype.setZoneData=function(e,t){this.zones[e]=t},f.prototype.getGroup=function(t,n){if(!this.zones[t])return null;var r=null,o=Math.pow(50,2);return this.zones[t].groups.forEach(function(t,i){t.forEach(function(t){var s=e.distanceToSquared(t.centroid,n);s<o&&(r=i,o=s)})}),r},f.prototype.getRandomNode=function(t,n,r,o){if(!this.zones[t])return new THREE.Vector3;r=r||null,o=o||0;var i=[];return this.zones[t].groups[n].forEach(function(t){r&&o?e.distanceToSquared(r,t.centroid)<o*o&&i.push(t.centroid):i.push(t.centroid)}),e.sample(i)||new THREE.Vector3},f.prototype.getClosestNode=function(t,n,r,o){void 0===o&&(o=!1);var i=this.zones[n].vertices,s=null,u=Infinity;return this.zones[n].groups[r].forEach(function(n){var r=e.distanceToSquared(n.centroid,t);r<u&&(!o||e.isVectorInPolygon(t,n,i))&&(s=n,u=r)}),s},f.prototype.findPath=function(e,t,r,o){var s=this.zones[r].groups[o],u=this.zones[r].vertices,c=this.getClosestNode(e,r,o),h=this.getClosestNode(t,r,o,!0);if(!c||!h)return null;var a=n.search(s,c,h),d=function(e,t){for(var n=0;n<e.neighbours.length;n++)if(e.neighbours[n]===t.id)return e.portals[n]},f=new i;f.push(e);for(var l=0;l<a.length;l++){var v=a[l+1];if(v){var p=d(a[l],v);f.push(u[p[0]],u[p[1]])}}f.push(t),f.stringPull();var g=f.path.map(function(e){return new THREE.Vector3(e.x,e.y,e.z)});return g.shift(),g},f.prototype.clampStep=(c=new THREE.Vector3,h=new THREE.Plane,a=new THREE.Triangle,d=new THREE.Vector3,function(e,t,n,r,o,i){var f=this.zones[r].vertices,l=this.zones[r].groups[o],v=[n],p={};p[n.id]=0,s=void 0,d.set(0,0,0),u=Infinity,h.setFromCoplanarPoints(f[n.vertexIds[0]],f[n.vertexIds[1]],f[n.vertexIds[2]]),h.projectPoint(t,c),t.copy(c);for(var g=v.pop();g;g=v.pop()){a.set(f[g.vertexIds[0]],f[g.vertexIds[1]],f[g.vertexIds[2]]),a.closestPointToPoint(t,c),c.distanceToSquared(t)<u&&(s=g,d.copy(c),u=c.distanceToSquared(t));var x=p[g];if(!(x>2))for(var I=0;I<g.neighbours.length;I++){var b=l[g.neighbours[I]];b.id in p||(v.push(b),p[b.id]=x+1)}}return i.copy(d),s}),exports.Pathfinding=f;
  3850. },{}],11:[function(require,module,exports){
  3851. 'use strict';
  3852. var EPS = 0.1;
  3853. module.exports = AFRAME.registerComponent('checkpoint-controls', {
  3854. schema: {
  3855. enabled: { default: true },
  3856. mode: { default: 'teleport', oneOf: ['teleport', 'animate'] },
  3857. animateSpeed: { default: 3.0 }
  3858. },
  3859. init: function init() {
  3860. this.active = true;
  3861. this.checkpoint = null;
  3862. this.isNavMeshConstrained = false;
  3863. this.offset = new THREE.Vector3();
  3864. this.position = new THREE.Vector3();
  3865. this.targetPosition = new THREE.Vector3();
  3866. },
  3867. play: function play() {
  3868. this.active = true;
  3869. },
  3870. pause: function pause() {
  3871. this.active = false;
  3872. },
  3873. setCheckpoint: function setCheckpoint(checkpoint) {
  3874. var el = this.el;
  3875. if (!this.active) return;
  3876. if (this.checkpoint === checkpoint) return;
  3877. if (this.checkpoint) {
  3878. el.emit('navigation-end', { checkpoint: this.checkpoint });
  3879. }
  3880. this.checkpoint = checkpoint;
  3881. this.sync();
  3882. // Ignore new checkpoint if we're already there.
  3883. if (this.position.distanceTo(this.targetPosition) < EPS) {
  3884. this.checkpoint = null;
  3885. return;
  3886. }
  3887. el.emit('navigation-start', { checkpoint: checkpoint });
  3888. if (this.data.mode === 'teleport') {
  3889. this.el.setAttribute('position', this.targetPosition);
  3890. this.checkpoint = null;
  3891. el.emit('navigation-end', { checkpoint: checkpoint });
  3892. el.components['movement-controls'].updateNavLocation();
  3893. }
  3894. },
  3895. isVelocityActive: function isVelocityActive() {
  3896. return !!(this.active && this.checkpoint);
  3897. },
  3898. getVelocity: function getVelocity() {
  3899. if (!this.active) return;
  3900. var data = this.data;
  3901. var offset = this.offset;
  3902. var position = this.position;
  3903. var targetPosition = this.targetPosition;
  3904. var checkpoint = this.checkpoint;
  3905. this.sync();
  3906. if (position.distanceTo(targetPosition) < EPS) {
  3907. this.checkpoint = null;
  3908. this.el.emit('navigation-end', { checkpoint: checkpoint });
  3909. return offset.set(0, 0, 0);
  3910. }
  3911. offset.setLength(data.animateSpeed);
  3912. return offset;
  3913. },
  3914. sync: function sync() {
  3915. var offset = this.offset;
  3916. var position = this.position;
  3917. var targetPosition = this.targetPosition;
  3918. position.copy(this.el.getAttribute('position'));
  3919. targetPosition.copy(this.checkpoint.object3D.getWorldPosition());
  3920. targetPosition.add(this.checkpoint.components.checkpoint.getOffset());
  3921. offset.copy(targetPosition).sub(position);
  3922. }
  3923. });
  3924. },{}],12:[function(require,module,exports){
  3925. 'use strict';
  3926. /**
  3927. * Gamepad controls for A-Frame.
  3928. *
  3929. * Stripped-down version of: https://github.com/donmccurdy/aframe-gamepad-controls
  3930. *
  3931. * For more information about the Gamepad API, see:
  3932. * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
  3933. */
  3934. var GamepadButton = require('../../lib/GamepadButton'),
  3935. GamepadButtonEvent = require('../../lib/GamepadButtonEvent');
  3936. var JOYSTICK_EPS = 0.2;
  3937. module.exports = AFRAME.registerComponent('gamepad-controls', {
  3938. /*******************************************************************
  3939. * Statics
  3940. */
  3941. GamepadButton: GamepadButton,
  3942. /*******************************************************************
  3943. * Schema
  3944. */
  3945. schema: {
  3946. // Controller 0-3
  3947. controller: { default: 0, oneOf: [0, 1, 2, 3] },
  3948. // Enable/disable features
  3949. enabled: { default: true },
  3950. // Debugging
  3951. debug: { default: false },
  3952. // Heading element for rotation
  3953. camera: { default: '[camera]', type: 'selector' },
  3954. // Rotation sensitivity
  3955. rotationSensitivity: { default: 2.0 }
  3956. },
  3957. /*******************************************************************
  3958. * Core
  3959. */
  3960. /**
  3961. * Called once when component is attached. Generally for initial setup.
  3962. */
  3963. init: function init() {
  3964. var scene = this.el.sceneEl;
  3965. this.prevTime = window.performance.now();
  3966. // Button state
  3967. this.buttons = {};
  3968. // Rotation
  3969. var rotation = this.el.object3D.rotation;
  3970. this.pitch = new THREE.Object3D();
  3971. this.pitch.rotation.x = THREE.Math.degToRad(rotation.x);
  3972. this.yaw = new THREE.Object3D();
  3973. this.yaw.position.y = 10;
  3974. this.yaw.rotation.y = THREE.Math.degToRad(rotation.y);
  3975. this.yaw.add(this.pitch);
  3976. scene.addBehavior(this);
  3977. },
  3978. /**
  3979. * Called when component is attached and when component data changes.
  3980. * Generally modifies the entity based on the data.
  3981. */
  3982. update: function update() {
  3983. this.tick();
  3984. },
  3985. /**
  3986. * Called on each iteration of main render loop.
  3987. */
  3988. tick: function tick(t, dt) {
  3989. this.updateButtonState();
  3990. this.updateRotation(dt);
  3991. },
  3992. /**
  3993. * Called when a component is removed (e.g., via removeAttribute).
  3994. * Generally undoes all modifications to the entity.
  3995. */
  3996. remove: function remove() {},
  3997. /*******************************************************************
  3998. * Movement
  3999. */
  4000. isVelocityActive: function isVelocityActive() {
  4001. if (!this.data.enabled || !this.isConnected()) return false;
  4002. var dpad = this.getDpad(),
  4003. joystick0 = this.getJoystick(0),
  4004. inputX = dpad.x || joystick0.x,
  4005. inputY = dpad.y || joystick0.y;
  4006. return Math.abs(inputX) > JOYSTICK_EPS || Math.abs(inputY) > JOYSTICK_EPS;
  4007. },
  4008. getVelocityDelta: function getVelocityDelta() {
  4009. var dpad = this.getDpad(),
  4010. joystick0 = this.getJoystick(0),
  4011. inputX = dpad.x || joystick0.x,
  4012. inputY = dpad.y || joystick0.y,
  4013. dVelocity = new THREE.Vector3();
  4014. if (Math.abs(inputX) > JOYSTICK_EPS) {
  4015. dVelocity.x += inputX;
  4016. }
  4017. if (Math.abs(inputY) > JOYSTICK_EPS) {
  4018. dVelocity.z += inputY;
  4019. }
  4020. return dVelocity;
  4021. },
  4022. /*******************************************************************
  4023. * Rotation
  4024. */
  4025. isRotationActive: function isRotationActive() {
  4026. if (!this.data.enabled || !this.isConnected()) return false;
  4027. var joystick1 = this.getJoystick(1);
  4028. return Math.abs(joystick1.x) > JOYSTICK_EPS || Math.abs(joystick1.y) > JOYSTICK_EPS;
  4029. },
  4030. updateRotation: function updateRotation(dt) {
  4031. if (!this.isRotationActive()) return;
  4032. var data = this.data;
  4033. var yaw = this.yaw;
  4034. var pitch = this.pitch;
  4035. var lookControls = data.camera.components['look-controls'];
  4036. var hasLookControls = lookControls && lookControls.pitchObject && lookControls.yawObject;
  4037. // Sync with look-controls pitch/yaw if available.
  4038. if (hasLookControls) {
  4039. pitch.rotation.copy(lookControls.pitchObject.rotation);
  4040. yaw.rotation.copy(lookControls.yawObject.rotation);
  4041. }
  4042. var lookVector = this.getJoystick(1);
  4043. if (Math.abs(lookVector.x) <= JOYSTICK_EPS) lookVector.x = 0;
  4044. if (Math.abs(lookVector.y) <= JOYSTICK_EPS) lookVector.y = 0;
  4045. lookVector.multiplyScalar(data.rotationSensitivity * dt / 1000);
  4046. yaw.rotation.y -= lookVector.x;
  4047. pitch.rotation.x -= lookVector.y;
  4048. pitch.rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, pitch.rotation.x));
  4049. data.camera.object3D.rotation.set(pitch.rotation.x, yaw.rotation.y, 0);
  4050. // Sync with look-controls pitch/yaw if available.
  4051. if (hasLookControls) {
  4052. lookControls.pitchObject.rotation.copy(pitch.rotation);
  4053. lookControls.yawObject.rotation.copy(yaw.rotation);
  4054. }
  4055. },
  4056. /*******************************************************************
  4057. * Button events
  4058. */
  4059. updateButtonState: function updateButtonState() {
  4060. var gamepad = this.getGamepad();
  4061. if (this.data.enabled && gamepad) {
  4062. // Fire DOM events for button state changes.
  4063. for (var i = 0; i < gamepad.buttons.length; i++) {
  4064. if (gamepad.buttons[i].pressed && !this.buttons[i]) {
  4065. this.emit(new GamepadButtonEvent('gamepadbuttondown', i, gamepad.buttons[i]));
  4066. } else if (!gamepad.buttons[i].pressed && this.buttons[i]) {
  4067. this.emit(new GamepadButtonEvent('gamepadbuttonup', i, gamepad.buttons[i]));
  4068. }
  4069. this.buttons[i] = gamepad.buttons[i].pressed;
  4070. }
  4071. } else if (Object.keys(this.buttons)) {
  4072. // Reset state if controls are disabled or controller is lost.
  4073. this.buttons = {};
  4074. }
  4075. },
  4076. emit: function emit(event) {
  4077. // Emit original event.
  4078. this.el.emit(event.type, event);
  4079. // Emit convenience event, identifying button index.
  4080. this.el.emit(event.type + ':' + event.index, new GamepadButtonEvent(event.type, event.index, event));
  4081. },
  4082. /*******************************************************************
  4083. * Gamepad state
  4084. */
  4085. /**
  4086. * Returns the Gamepad instance attached to the component. If connected,
  4087. * a proxy-controls component may provide access to Gamepad input from a
  4088. * remote device.
  4089. *
  4090. * @return {Gamepad}
  4091. */
  4092. getGamepad: function getGamepad() {
  4093. var localGamepad = navigator.getGamepads && navigator.getGamepads()[this.data.controller],
  4094. proxyControls = this.el.sceneEl.components['proxy-controls'],
  4095. proxyGamepad = proxyControls && proxyControls.isConnected() && proxyControls.getGamepad(this.data.controller);
  4096. return proxyGamepad || localGamepad;
  4097. },
  4098. /**
  4099. * Returns the state of the given button.
  4100. * @param {number} index The button (0-N) for which to find state.
  4101. * @return {GamepadButton}
  4102. */
  4103. getButton: function getButton(index) {
  4104. return this.getGamepad().buttons[index];
  4105. },
  4106. /**
  4107. * Returns state of the given axis. Axes are labelled 0-N, where 0-1 will
  4108. * represent X/Y on the first joystick, and 2-3 X/Y on the second.
  4109. * @param {number} index The axis (0-N) for which to find state.
  4110. * @return {number} On the interval [-1,1].
  4111. */
  4112. getAxis: function getAxis(index) {
  4113. return this.getGamepad().axes[index];
  4114. },
  4115. /**
  4116. * Returns the state of the given joystick (0 or 1) as a THREE.Vector2.
  4117. * @param {number} id The joystick (0, 1) for which to find state.
  4118. * @return {THREE.Vector2}
  4119. */
  4120. getJoystick: function getJoystick(index) {
  4121. var gamepad = this.getGamepad();
  4122. switch (index) {
  4123. case 0:
  4124. return new THREE.Vector2(gamepad.axes[0], gamepad.axes[1]);
  4125. case 1:
  4126. return new THREE.Vector2(gamepad.axes[2], gamepad.axes[3]);
  4127. default:
  4128. throw new Error('Unexpected joystick index "%d".', index);
  4129. }
  4130. },
  4131. /**
  4132. * Returns the state of the dpad as a THREE.Vector2.
  4133. * @return {THREE.Vector2}
  4134. */
  4135. getDpad: function getDpad() {
  4136. var gamepad = this.getGamepad();
  4137. if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
  4138. return new THREE.Vector2();
  4139. }
  4140. return new THREE.Vector2((gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0) + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0), (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0) + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0));
  4141. },
  4142. /**
  4143. * Returns true if the gamepad is currently connected to the system.
  4144. * @return {boolean}
  4145. */
  4146. isConnected: function isConnected() {
  4147. var gamepad = this.getGamepad();
  4148. return !!(gamepad && gamepad.connected);
  4149. },
  4150. /**
  4151. * Returns a string containing some information about the controller. Result
  4152. * may vary across browsers, for a given controller.
  4153. * @return {string}
  4154. */
  4155. getID: function getID() {
  4156. return this.getGamepad().id;
  4157. }
  4158. });
  4159. },{"../../lib/GamepadButton":4,"../../lib/GamepadButtonEvent":5}],13:[function(require,module,exports){
  4160. 'use strict';
  4161. require('./checkpoint-controls');
  4162. require('./gamepad-controls');
  4163. require('./keyboard-controls');
  4164. require('./touch-controls');
  4165. require('./movement-controls');
  4166. require('./trackpad-controls');
  4167. },{"./checkpoint-controls":11,"./gamepad-controls":12,"./keyboard-controls":14,"./movement-controls":15,"./touch-controls":16,"./trackpad-controls":17}],14:[function(require,module,exports){
  4168. 'use strict';
  4169. require('../../lib/keyboard.polyfill');
  4170. var MAX_DELTA = 0.2,
  4171. PROXY_FLAG = '__keyboard-controls-proxy';
  4172. var KeyboardEvent = window.KeyboardEvent;
  4173. /**
  4174. * Keyboard Controls component.
  4175. *
  4176. * Stripped-down version of: https://github.com/donmccurdy/aframe-keyboard-controls
  4177. *
  4178. * Bind keyboard events to components, or control your entities with the WASD keys.
  4179. *
  4180. * Why use KeyboardEvent.code? "This is set to a string representing the key that was pressed to
  4181. * generate the KeyboardEvent, without taking the current keyboard layout (e.g., QWERTY vs.
  4182. * Dvorak), locale (e.g., English vs. French), or any modifier keys into account. This is useful
  4183. * when you care about which physical key was pressed, rather thanwhich character it corresponds
  4184. * to. For example, if you’re a writing a game, you might want a certain set of keys to move the
  4185. * player in different directions, and that mapping should ideally be independent of keyboard
  4186. * layout. See: https://developers.google.com/web/updates/2016/04/keyboardevent-keys-codes
  4187. *
  4188. * @namespace wasd-controls
  4189. * keys the entity moves and if you release it will stop. Easing simulates friction.
  4190. * to the entity when pressing the keys.
  4191. * @param {bool} [enabled=true] - To completely enable or disable the controls
  4192. */
  4193. module.exports = AFRAME.registerComponent('keyboard-controls', {
  4194. schema: {
  4195. enabled: { default: true },
  4196. debug: { default: false }
  4197. },
  4198. init: function init() {
  4199. this.dVelocity = new THREE.Vector3();
  4200. this.localKeys = {};
  4201. this.listeners = {
  4202. keydown: this.onKeyDown.bind(this),
  4203. keyup: this.onKeyUp.bind(this),
  4204. blur: this.onBlur.bind(this)
  4205. };
  4206. this.attachEventListeners();
  4207. },
  4208. /*******************************************************************
  4209. * Movement
  4210. */
  4211. isVelocityActive: function isVelocityActive() {
  4212. return this.data.enabled && !!Object.keys(this.getKeys()).length;
  4213. },
  4214. getVelocityDelta: function getVelocityDelta() {
  4215. var data = this.data,
  4216. keys = this.getKeys();
  4217. this.dVelocity.set(0, 0, 0);
  4218. if (data.enabled) {
  4219. if (keys.KeyW || keys.ArrowUp) {
  4220. this.dVelocity.z -= 1;
  4221. }
  4222. if (keys.KeyA || keys.ArrowLeft) {
  4223. this.dVelocity.x -= 1;
  4224. }
  4225. if (keys.KeyS || keys.ArrowDown) {
  4226. this.dVelocity.z += 1;
  4227. }
  4228. if (keys.KeyD || keys.ArrowRight) {
  4229. this.dVelocity.x += 1;
  4230. }
  4231. }
  4232. return this.dVelocity.clone();
  4233. },
  4234. /*******************************************************************
  4235. * Events
  4236. */
  4237. play: function play() {
  4238. this.attachEventListeners();
  4239. },
  4240. pause: function pause() {
  4241. this.removeEventListeners();
  4242. },
  4243. remove: function remove() {
  4244. this.pause();
  4245. },
  4246. attachEventListeners: function attachEventListeners() {
  4247. window.addEventListener('keydown', this.listeners.keydown, false);
  4248. window.addEventListener('keyup', this.listeners.keyup, false);
  4249. window.addEventListener('blur', this.listeners.blur, false);
  4250. },
  4251. removeEventListeners: function removeEventListeners() {
  4252. window.removeEventListener('keydown', this.listeners.keydown);
  4253. window.removeEventListener('keyup', this.listeners.keyup);
  4254. window.removeEventListener('blur', this.listeners.blur);
  4255. },
  4256. onKeyDown: function onKeyDown(event) {
  4257. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  4258. this.localKeys[event.code] = true;
  4259. this.emit(event);
  4260. }
  4261. },
  4262. onKeyUp: function onKeyUp(event) {
  4263. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  4264. delete this.localKeys[event.code];
  4265. this.emit(event);
  4266. }
  4267. },
  4268. onBlur: function onBlur() {
  4269. for (var code in this.localKeys) {
  4270. if (this.localKeys.hasOwnProperty(code)) {
  4271. delete this.localKeys[code];
  4272. }
  4273. }
  4274. },
  4275. emit: function emit(event) {
  4276. // TODO - keydown only initially?
  4277. // TODO - where the f is the spacebar
  4278. // Emit original event.
  4279. if (PROXY_FLAG in event) {
  4280. // TODO - Method never triggered.
  4281. this.el.emit(event.type, event);
  4282. }
  4283. // Emit convenience event, identifying key.
  4284. this.el.emit(event.type + ':' + event.code, new KeyboardEvent(event.type, event));
  4285. if (this.data.debug) console.log(event.type + ':' + event.code);
  4286. },
  4287. /*******************************************************************
  4288. * Accessors
  4289. */
  4290. isPressed: function isPressed(code) {
  4291. return code in this.getKeys();
  4292. },
  4293. getKeys: function getKeys() {
  4294. if (this.isProxied()) {
  4295. return this.el.sceneEl.components['proxy-controls'].getKeyboard();
  4296. }
  4297. return this.localKeys;
  4298. },
  4299. isProxied: function isProxied() {
  4300. var proxyControls = this.el.sceneEl.components['proxy-controls'];
  4301. return proxyControls && proxyControls.isConnected();
  4302. }
  4303. });
  4304. },{"../../lib/keyboard.polyfill":9}],15:[function(require,module,exports){
  4305. 'use strict';
  4306. /**
  4307. * Movement Controls
  4308. *
  4309. * @author Don McCurdy <dm@donmccurdy.com>
  4310. */
  4311. var COMPONENT_SUFFIX = '-controls',
  4312. MAX_DELTA = 0.2,
  4313. // ms
  4314. EPS = 10e-6;
  4315. module.exports = AFRAME.registerComponent('movement-controls', {
  4316. /*******************************************************************
  4317. * Schema
  4318. */
  4319. dependencies: ['rotation'],
  4320. schema: {
  4321. enabled: { default: true },
  4322. controls: { default: ['gamepad', 'trackpad', 'keyboard', 'touch'] },
  4323. speed: { default: 0.3, min: 0 },
  4324. fly: { default: false },
  4325. constrainToNavMesh: { default: false },
  4326. camera: { default: '[camera]', type: 'selector' }
  4327. },
  4328. /*******************************************************************
  4329. * Lifecycle
  4330. */
  4331. init: function init() {
  4332. var el = this.el;
  4333. this.velocityCtrl = null;
  4334. this.velocity = new THREE.Vector3();
  4335. this.heading = new THREE.Quaternion();
  4336. // Navigation
  4337. this.navGroup = null;
  4338. this.navNode = null;
  4339. if (el.sceneEl.hasLoaded) {
  4340. this.injectControls();
  4341. } else {
  4342. el.sceneEl.addEventListener('loaded', this.injectControls.bind(this));
  4343. }
  4344. },
  4345. update: function update(prevData) {
  4346. var el = this.el;
  4347. var data = this.data;
  4348. var nav = el.sceneEl.systems.nav;
  4349. if (el.sceneEl.hasLoaded) {
  4350. this.injectControls();
  4351. }
  4352. if (nav && data.constrainToNavMesh !== prevData.constrainToNavMesh) {
  4353. data.constrainToNavMesh ? nav.addAgent(this) : nav.removeAgent(this);
  4354. }
  4355. },
  4356. injectControls: function injectControls() {
  4357. var data = this.data;
  4358. var name;
  4359. for (var i = 0; i < data.controls.length; i++) {
  4360. name = data.controls[i] + COMPONENT_SUFFIX;
  4361. if (!this.el.components[name]) {
  4362. this.el.setAttribute(name, '');
  4363. }
  4364. }
  4365. },
  4366. updateNavLocation: function updateNavLocation() {
  4367. this.navGroup = null;
  4368. this.navNode = null;
  4369. },
  4370. /*******************************************************************
  4371. * Tick
  4372. */
  4373. tick: function () {
  4374. var start = new THREE.Vector3();
  4375. var end = new THREE.Vector3();
  4376. var clampedEnd = new THREE.Vector3();
  4377. return function (t, dt) {
  4378. if (!dt) return;
  4379. var el = this.el;
  4380. var data = this.data;
  4381. if (!data.enabled) return;
  4382. this.updateVelocityCtrl();
  4383. var velocityCtrl = this.velocityCtrl;
  4384. var velocity = this.velocity;
  4385. if (!velocityCtrl) return;
  4386. // Update velocity. If FPS is too low, reset.
  4387. if (dt / 1000 > MAX_DELTA) {
  4388. velocity.set(0, 0, 0);
  4389. } else {
  4390. this.updateVelocity(dt);
  4391. }
  4392. if (data.constrainToNavMesh && velocityCtrl.isNavMeshConstrained !== false) {
  4393. if (velocity.lengthSq() < EPS) return;
  4394. start.copy(el.object3D.position);
  4395. end.copy(velocity).multiplyScalar(dt / 1000).add(start);
  4396. var nav = el.sceneEl.systems.nav;
  4397. this.navGroup = this.navGroup === null ? nav.getGroup(start) : this.navGroup;
  4398. this.navNode = this.navNode || nav.getNode(start, this.navGroup);
  4399. this.navNode = nav.clampStep(start, end, this.navGroup, this.navNode, clampedEnd);
  4400. el.object3D.position.copy(clampedEnd);
  4401. } else if (el.hasAttribute('velocity')) {
  4402. el.setAttribute('velocity', velocity);
  4403. } else {
  4404. el.object3D.position.x += velocity.x * dt / 1000;
  4405. el.object3D.position.y += velocity.y * dt / 1000;
  4406. el.object3D.position.z += velocity.z * dt / 1000;
  4407. }
  4408. };
  4409. }(),
  4410. /*******************************************************************
  4411. * Movement
  4412. */
  4413. updateVelocityCtrl: function updateVelocityCtrl() {
  4414. var data = this.data;
  4415. if (data.enabled) {
  4416. for (var i = 0, l = data.controls.length; i < l; i++) {
  4417. var control = this.el.components[data.controls[i] + COMPONENT_SUFFIX];
  4418. if (control && control.isVelocityActive()) {
  4419. this.velocityCtrl = control;
  4420. return;
  4421. }
  4422. }
  4423. this.velocityCtrl = null;
  4424. }
  4425. },
  4426. updateVelocity: function () {
  4427. var vector2 = new THREE.Vector2();
  4428. var quaternion = new THREE.Quaternion();
  4429. return function (dt) {
  4430. var dVelocity = void 0;
  4431. var el = this.el;
  4432. var control = this.velocityCtrl;
  4433. var velocity = this.velocity;
  4434. var data = this.data;
  4435. if (control) {
  4436. if (control.getVelocityDelta) {
  4437. dVelocity = control.getVelocityDelta(dt);
  4438. } else if (control.getVelocity) {
  4439. velocity.copy(control.getVelocity());
  4440. return;
  4441. } else if (control.getPositionDelta) {
  4442. velocity.copy(control.getPositionDelta(dt).multiplyScalar(1000 / dt));
  4443. return;
  4444. } else {
  4445. throw new Error('Incompatible movement controls: ', control);
  4446. }
  4447. }
  4448. if (el.hasAttribute('velocity') && !data.constrainToNavMesh) {
  4449. velocity.copy(this.el.getAttribute('velocity'));
  4450. }
  4451. if (dVelocity && data.enabled) {
  4452. var cameraEl = data.camera;
  4453. // Rotate to heading
  4454. quaternion.copy(cameraEl.object3D.quaternion);
  4455. quaternion.premultiply(el.object3D.quaternion);
  4456. dVelocity.applyQuaternion(quaternion);
  4457. var factor = dVelocity.length();
  4458. if (data.fly) {
  4459. velocity.copy(dVelocity);
  4460. velocity.multiplyScalar(this.data.speed * 16.66667);
  4461. } else {
  4462. vector2.set(dVelocity.x, dVelocity.z);
  4463. vector2.setLength(factor * this.data.speed * 16.66667);
  4464. velocity.x = vector2.x;
  4465. velocity.z = vector2.y;
  4466. }
  4467. }
  4468. };
  4469. }()
  4470. });
  4471. },{}],16:[function(require,module,exports){
  4472. 'use strict';
  4473. /**
  4474. * Touch-to-move-forward controls for mobile.
  4475. */
  4476. module.exports = AFRAME.registerComponent('touch-controls', {
  4477. schema: {
  4478. enabled: { default: true },
  4479. reverseEnabled: { default: true }
  4480. },
  4481. init: function init() {
  4482. this.dVelocity = new THREE.Vector3();
  4483. this.bindMethods();
  4484. this.direction = 0;
  4485. },
  4486. play: function play() {
  4487. this.addEventListeners();
  4488. },
  4489. pause: function pause() {
  4490. this.removeEventListeners();
  4491. this.dVelocity.set(0, 0, 0);
  4492. },
  4493. remove: function remove() {
  4494. this.pause();
  4495. },
  4496. addEventListeners: function addEventListeners() {
  4497. var sceneEl = this.el.sceneEl;
  4498. var canvasEl = sceneEl.canvas;
  4499. if (!canvasEl) {
  4500. sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this));
  4501. return;
  4502. }
  4503. canvasEl.addEventListener('touchstart', this.onTouchStart);
  4504. canvasEl.addEventListener('touchend', this.onTouchEnd);
  4505. },
  4506. removeEventListeners: function removeEventListeners() {
  4507. var canvasEl = this.el.sceneEl && this.el.sceneEl.canvas;
  4508. if (!canvasEl) {
  4509. return;
  4510. }
  4511. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  4512. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  4513. },
  4514. isVelocityActive: function isVelocityActive() {
  4515. return this.data.enabled && !!this.direction;
  4516. },
  4517. getVelocityDelta: function getVelocityDelta() {
  4518. this.dVelocity.z = this.direction;
  4519. return this.dVelocity.clone();
  4520. },
  4521. bindMethods: function bindMethods() {
  4522. this.onTouchStart = this.onTouchStart.bind(this);
  4523. this.onTouchEnd = this.onTouchEnd.bind(this);
  4524. },
  4525. onTouchStart: function onTouchStart(e) {
  4526. this.direction = -1;
  4527. if (this.data.reverseEnabled && e.touches.length === 2) {
  4528. this.direction = 1;
  4529. }
  4530. e.preventDefault();
  4531. },
  4532. onTouchEnd: function onTouchEnd(e) {
  4533. this.direction = 0;
  4534. e.preventDefault();
  4535. }
  4536. });
  4537. },{}],17:[function(require,module,exports){
  4538. 'use strict';
  4539. /**
  4540. * 3dof (Gear VR, Daydream) controls for mobile.
  4541. */
  4542. module.exports = AFRAME.registerComponent('trackpad-controls', {
  4543. schema: {
  4544. enabled: { default: true },
  4545. enableNegX: { default: true },
  4546. enablePosX: { default: true },
  4547. enableNegZ: { default: true },
  4548. enablePosZ: { default: true },
  4549. mode: { default: 'touch', oneOf: ['swipe', 'touch', 'press'] }
  4550. },
  4551. init: function init() {
  4552. this.dVelocity = new THREE.Vector3();
  4553. this.zVel = 0;
  4554. this.xVel = 0;
  4555. this.bindMethods();
  4556. },
  4557. play: function play() {
  4558. this.addEventListeners();
  4559. },
  4560. pause: function pause() {
  4561. this.removeEventListeners();
  4562. this.dVelocity.set(0, 0, 0);
  4563. },
  4564. remove: function remove() {
  4565. this.pause();
  4566. },
  4567. addEventListeners: function addEventListeners() {
  4568. var data = this.data;
  4569. var sceneEl = this.el.sceneEl;
  4570. sceneEl.addEventListener('axismove', this.onAxisMove);
  4571. switch (data.mode) {
  4572. case 'swipe':
  4573. case 'touch':
  4574. sceneEl.addEventListener('trackpadtouchstart', this.onTouchStart);
  4575. sceneEl.addEventListener('trackpadtouchend', this.onTouchEnd);
  4576. break;
  4577. case 'press':
  4578. sceneEl.addEventListener('trackpaddown', this.onTouchStart);
  4579. sceneEl.addEventListener('trackpadup', this.onTouchEnd);
  4580. break;
  4581. }
  4582. },
  4583. removeEventListeners: function removeEventListeners() {
  4584. var sceneEl = this.el.sceneEl;
  4585. sceneEl.removeEventListener('axismove', this.onAxisMove);
  4586. sceneEl.removeEventListener('trackpadtouchstart', this.onTouchStart);
  4587. sceneEl.removeEventListener('trackpadtouchend', this.onTouchEnd);
  4588. sceneEl.removeEventListener('trackpaddown', this.onTouchStart);
  4589. sceneEl.removeEventListener('trackpadup', this.onTouchEnd);
  4590. },
  4591. isVelocityActive: function isVelocityActive() {
  4592. return this.data.enabled && this.isMoving;
  4593. },
  4594. getVelocityDelta: function getVelocityDelta() {
  4595. this.dVelocity.z = this.isMoving ? -this.zVel : 1;
  4596. this.dVelocity.x = this.isMoving ? this.xVel : 1;
  4597. return this.dVelocity.clone();
  4598. },
  4599. bindMethods: function bindMethods() {
  4600. this.onTouchStart = this.onTouchStart.bind(this);
  4601. this.onTouchEnd = this.onTouchEnd.bind(this);
  4602. this.onAxisMove = this.onAxisMove.bind(this);
  4603. },
  4604. onTouchStart: function onTouchStart(e) {
  4605. switch (this.data.mode) {
  4606. case 'swipe':
  4607. this.canRecordAxis = true;
  4608. this.startingAxisData = [];
  4609. break;
  4610. case 'touch':
  4611. this.isMoving = true;
  4612. break;
  4613. case 'press':
  4614. this.isMoving = true;
  4615. break;
  4616. }
  4617. e.preventDefault();
  4618. },
  4619. onTouchEnd: function onTouchEnd(e) {
  4620. if (this.data.mode == 'swipe') {
  4621. this.startingAxisData = [];
  4622. }
  4623. this.isMoving = false;
  4624. e.preventDefault();
  4625. },
  4626. onAxisMove: function onAxisMove(e) {
  4627. switch (this.data.mode) {
  4628. case 'swipe':
  4629. return this.handleSwipeAxis(e);
  4630. case 'touch':
  4631. case 'press':
  4632. return this.handleTouchAxis(e);
  4633. }
  4634. },
  4635. handleSwipeAxis: function handleSwipeAxis(e) {
  4636. var data = this.data;
  4637. var axisData = e.detail.axis;
  4638. if (this.startingAxisData.length === 0 && this.canRecordAxis) {
  4639. this.canRecordAxis = false;
  4640. this.startingAxisData[0] = axisData[0];
  4641. this.startingAxisData[1] = axisData[1];
  4642. }
  4643. if (this.startingAxisData.length > 0) {
  4644. var velX = 0;
  4645. var velZ = 0;
  4646. if (data.enableNegX && axisData[0] < this.startingAxisData[0]) {
  4647. velX = -1;
  4648. }
  4649. if (data.enablePosX && axisData[0] > this.startingAxisData[0]) {
  4650. velX = 1;
  4651. }
  4652. if (data.enablePosZ && axisData[1] > this.startingAxisData[1]) {
  4653. velZ = -1;
  4654. }
  4655. if (data.enableNegZ && axisData[1] < this.startingAxisData[1]) {
  4656. velZ = 1;
  4657. }
  4658. var absChangeZ = Math.abs(this.startingAxisData[1] - axisData[1]);
  4659. var absChangeX = Math.abs(this.startingAxisData[0] - axisData[0]);
  4660. if (absChangeX > absChangeZ) {
  4661. this.zVel = 0;
  4662. this.xVel = velX;
  4663. this.isMoving = true;
  4664. } else {
  4665. this.xVel = 0;
  4666. this.zVel = velZ;
  4667. this.isMoving = true;
  4668. }
  4669. }
  4670. },
  4671. handleTouchAxis: function handleTouchAxis(e) {
  4672. var data = this.data;
  4673. var axisData = e.detail.axis;
  4674. var velX = 0;
  4675. var velZ = 0;
  4676. if (data.enableNegX && axisData[0] < 0) {
  4677. velX = -1;
  4678. }
  4679. if (data.enablePosX && axisData[0] > 0) {
  4680. velX = 1;
  4681. }
  4682. if (data.enablePosZ && axisData[1] > 0) {
  4683. velZ = -1;
  4684. }
  4685. if (data.enableNegZ && axisData[1] < 0) {
  4686. velZ = 1;
  4687. }
  4688. if (Math.abs(axisData[0]) > Math.abs(axisData[1])) {
  4689. this.zVel = 0;
  4690. this.xVel = velX;
  4691. } else {
  4692. this.xVel = 0;
  4693. this.zVel = velZ;
  4694. }
  4695. }
  4696. });
  4697. },{}],18:[function(require,module,exports){
  4698. 'use strict';
  4699. var LoopMode = {
  4700. once: THREE.LoopOnce,
  4701. repeat: THREE.LoopRepeat,
  4702. pingpong: THREE.LoopPingPong
  4703. };
  4704. /**
  4705. * animation-mixer
  4706. *
  4707. * Player for animation clips. Intended to be compatible with any model format that supports
  4708. * skeletal or morph animations through THREE.AnimationMixer.
  4709. * See: https://threejs.org/docs/?q=animation#Reference/Animation/AnimationMixer
  4710. */
  4711. module.exports = AFRAME.registerComponent('animation-mixer', {
  4712. schema: {
  4713. clip: { default: '*' },
  4714. duration: { default: 0 },
  4715. clampWhenFinished: { default: false, type: 'boolean' },
  4716. crossFadeDuration: { default: 0 },
  4717. loop: { default: 'repeat', oneOf: Object.keys(LoopMode) },
  4718. repetitions: { default: Infinity, min: 0 },
  4719. timeScale: { default: 1 }
  4720. },
  4721. init: function init() {
  4722. var _this = this;
  4723. /** @type {THREE.Mesh} */
  4724. this.model = null;
  4725. /** @type {THREE.AnimationMixer} */
  4726. this.mixer = null;
  4727. /** @type {Array<THREE.AnimationAction>} */
  4728. this.activeActions = [];
  4729. var model = this.el.getObject3D('mesh');
  4730. if (model) {
  4731. this.load(model);
  4732. } else {
  4733. this.el.addEventListener('model-loaded', function (e) {
  4734. _this.load(e.detail.model);
  4735. });
  4736. }
  4737. },
  4738. load: function load(model) {
  4739. var el = this.el;
  4740. this.model = model;
  4741. this.mixer = new THREE.AnimationMixer(model);
  4742. this.mixer.addEventListener('loop', function (e) {
  4743. el.emit('animation-loop', { action: e.action, loopDelta: e.loopDelta });
  4744. });
  4745. this.mixer.addEventListener('finished', function (e) {
  4746. el.emit('animation-finished', { action: e.action, direction: e.direction });
  4747. });
  4748. if (this.data.clip) this.update({});
  4749. },
  4750. remove: function remove() {
  4751. if (this.mixer) this.mixer.stopAllAction();
  4752. },
  4753. update: function update(prevData) {
  4754. if (!prevData) return;
  4755. var data = this.data;
  4756. var changes = AFRAME.utils.diff(data, prevData);
  4757. // If selected clips have changed, restart animation.
  4758. if ('clip' in changes) {
  4759. this.stopAction();
  4760. if (data.clip) this.playAction();
  4761. return;
  4762. }
  4763. // Otherwise, modify running actions.
  4764. this.activeActions.forEach(function (action) {
  4765. if ('duration' in changes && data.duration) {
  4766. action.setDuration(data.duration);
  4767. }
  4768. if ('clampWhenFinished' in changes) {
  4769. action.clampWhenFinished = data.clampWhenFinished;
  4770. }
  4771. if ('loop' in changes || 'repetitions' in changes) {
  4772. action.setLoop(LoopMode[data.loop], data.repetitions);
  4773. }
  4774. if ('timeScale' in changes) {
  4775. action.setEffectiveTimeScale(data.timeScale);
  4776. }
  4777. });
  4778. },
  4779. stopAction: function stopAction() {
  4780. var data = this.data;
  4781. for (var i = 0; i < this.activeActions.length; i++) {
  4782. data.crossFadeDuration ? this.activeActions[i].fadeOut(data.crossFadeDuration) : this.activeActions[i].stop();
  4783. }
  4784. this.activeActions.length = 0;
  4785. },
  4786. playAction: function playAction() {
  4787. if (!this.mixer) return;
  4788. var model = this.model,
  4789. data = this.data,
  4790. clips = model.animations || (model.geometry || {}).animations || [];
  4791. if (!clips.length) return;
  4792. var re = wildcardToRegExp(data.clip);
  4793. for (var clip, i = 0; clip = clips[i]; i++) {
  4794. if (clip.name.match(re)) {
  4795. var action = this.mixer.clipAction(clip, model);
  4796. action.enabled = true;
  4797. action.clampWhenFinished = data.clampWhenFinished;
  4798. if (data.duration) action.setDuration(data.duration);
  4799. if (data.timeScale !== 1) action.setEffectiveTimeScale(data.timeScale);
  4800. action.setLoop(LoopMode[data.loop], data.repetitions).fadeIn(data.crossFadeDuration).play();
  4801. this.activeActions.push(action);
  4802. }
  4803. }
  4804. },
  4805. tick: function tick(t, dt) {
  4806. if (this.mixer && !isNaN(dt)) this.mixer.update(dt / 1000);
  4807. }
  4808. });
  4809. /**
  4810. * Creates a RegExp from the given string, converting asterisks to .* expressions,
  4811. * and escaping all other characters.
  4812. */
  4813. function wildcardToRegExp(s) {
  4814. return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$');
  4815. }
  4816. /**
  4817. * RegExp-escapes all characters in the given string.
  4818. */
  4819. function regExpEscape(s) {
  4820. return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  4821. }
  4822. },{}],19:[function(require,module,exports){
  4823. 'use strict';
  4824. THREE.FBXLoader = require('../../lib/FBXLoader');
  4825. /**
  4826. * fbx-model
  4827. *
  4828. * Loader for FBX format. Supports ASCII, but *not* binary, models.
  4829. */
  4830. module.exports = AFRAME.registerComponent('fbx-model', {
  4831. schema: {
  4832. src: { type: 'asset' },
  4833. crossorigin: { default: '' }
  4834. },
  4835. init: function init() {
  4836. this.model = null;
  4837. },
  4838. update: function update() {
  4839. var data = this.data;
  4840. if (!data.src) return;
  4841. this.remove();
  4842. var loader = new THREE.FBXLoader();
  4843. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  4844. loader.load(data.src, this.load.bind(this));
  4845. },
  4846. load: function load(model) {
  4847. this.model = model;
  4848. this.el.setObject3D('mesh', model);
  4849. this.el.emit('model-loaded', { format: 'fbx', model: model });
  4850. },
  4851. remove: function remove() {
  4852. if (this.model) this.el.removeObject3D('mesh');
  4853. }
  4854. });
  4855. },{"../../lib/FBXLoader":3}],20:[function(require,module,exports){
  4856. 'use strict';
  4857. var fetchScript = require('../../lib/fetch-script')();
  4858. var LOADER_SRC = 'https://rawgit.com/mrdoob/three.js/r86/examples/js/loaders/GLTFLoader.js';
  4859. var loadLoader = function () {
  4860. var promise = void 0;
  4861. return function () {
  4862. promise = promise || fetchScript(LOADER_SRC);
  4863. return promise;
  4864. };
  4865. }();
  4866. /**
  4867. * Legacy loader for glTF 1.0 models.
  4868. * Asynchronously loads THREE.GLTFLoader from rawgit.
  4869. */
  4870. module.exports = AFRAME.registerComponent('gltf-model-legacy', {
  4871. schema: { type: 'model' },
  4872. init: function init() {
  4873. var _this = this;
  4874. this.model = null;
  4875. this.loader = null;
  4876. this.loaderPromise = loadLoader().then(function () {
  4877. _this.loader = new THREE.GLTFLoader();
  4878. _this.loader.setCrossOrigin('Anonymous');
  4879. });
  4880. },
  4881. update: function update() {
  4882. var _this2 = this;
  4883. var self = this;
  4884. var el = this.el;
  4885. var src = this.data;
  4886. if (!src) {
  4887. return;
  4888. }
  4889. this.remove();
  4890. this.loaderPromise.then(function () {
  4891. _this2.loader.load(src, function gltfLoaded(gltfModel) {
  4892. self.model = gltfModel.scene;
  4893. self.model.animations = gltfModel.animations;
  4894. el.setObject3D('mesh', self.model);
  4895. el.emit('model-loaded', { format: 'gltf', model: self.model });
  4896. });
  4897. });
  4898. },
  4899. remove: function remove() {
  4900. if (!this.model) {
  4901. return;
  4902. }
  4903. this.el.removeObject3D('mesh');
  4904. }
  4905. });
  4906. },{"../../lib/fetch-script":7}],21:[function(require,module,exports){
  4907. 'use strict';
  4908. require('./animation-mixer');
  4909. require('./fbx-model');
  4910. require('./gltf-model-legacy');
  4911. require('./object-model');
  4912. },{"./animation-mixer":18,"./fbx-model":19,"./gltf-model-legacy":20,"./object-model":22}],22:[function(require,module,exports){
  4913. 'use strict';
  4914. /**
  4915. * object-model
  4916. *
  4917. * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
  4918. * both having the .json extension. This loader supports only THREE.ObjectLoader, which typically
  4919. * includes multiple meshes or an entire scene.
  4920. *
  4921. * Check the console for errors, if in doubt. You may need to use `json-model` or
  4922. * `blend-character-model` for some .js and .json files.
  4923. *
  4924. * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
  4925. */
  4926. module.exports = AFRAME.registerComponent('object-model', {
  4927. schema: {
  4928. src: { type: 'asset' },
  4929. crossorigin: { default: '' }
  4930. },
  4931. init: function init() {
  4932. this.model = null;
  4933. },
  4934. update: function update() {
  4935. var _this = this;
  4936. var loader = void 0;
  4937. var data = this.data;
  4938. if (!data.src) return;
  4939. this.remove();
  4940. loader = new THREE.ObjectLoader();
  4941. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  4942. loader.load(data.src, function (object) {
  4943. // Enable skinning, if applicable.
  4944. object.traverse(function (o) {
  4945. if (o instanceof THREE.SkinnedMesh && o.material) {
  4946. o.material.skinning = !!(o.geometry && o.geometry.bones || []).length;
  4947. }
  4948. });
  4949. _this.load(object);
  4950. });
  4951. },
  4952. load: function load(model) {
  4953. this.model = model;
  4954. this.el.setObject3D('mesh', model);
  4955. this.el.emit('model-loaded', { format: 'json', model: model });
  4956. },
  4957. remove: function remove() {
  4958. if (this.model) this.el.removeObject3D('mesh');
  4959. }
  4960. });
  4961. },{}],23:[function(require,module,exports){
  4962. 'use strict';
  4963. module.exports = AFRAME.registerComponent('checkpoint', {
  4964. schema: {
  4965. offset: { default: { x: 0, y: 0, z: 0 }, type: 'vec3' }
  4966. },
  4967. init: function init() {
  4968. this.active = false;
  4969. this.targetEl = null;
  4970. this.fire = this.fire.bind(this);
  4971. this.offset = new THREE.Vector3();
  4972. },
  4973. update: function update() {
  4974. this.offset.copy(this.data.offset);
  4975. },
  4976. play: function play() {
  4977. this.el.addEventListener('click', this.fire);
  4978. },
  4979. pause: function pause() {
  4980. this.el.removeEventListener('click', this.fire);
  4981. },
  4982. remove: function remove() {
  4983. this.pause();
  4984. },
  4985. fire: function fire() {
  4986. var targetEl = this.el.sceneEl.querySelector('[checkpoint-controls]');
  4987. if (!targetEl) {
  4988. throw new Error('No `checkpoint-controls` component found.');
  4989. }
  4990. targetEl.components['checkpoint-controls'].setCheckpoint(this.el);
  4991. },
  4992. getOffset: function getOffset() {
  4993. return this.offset.copy(this.data.offset);
  4994. }
  4995. });
  4996. },{}],24:[function(require,module,exports){
  4997. 'use strict';
  4998. /**
  4999. * @param {Array<THREE.Material>|THREE.Material} material
  5000. * @return {Array<THREE.Material>}
  5001. */
  5002. function ensureMaterialArray(material) {
  5003. if (!material) {
  5004. return [];
  5005. } else if (Array.isArray(material)) {
  5006. return material;
  5007. } else if (material.materials) {
  5008. return material.materials;
  5009. } else {
  5010. return [material];
  5011. }
  5012. }
  5013. /**
  5014. * @param {THREE.Object3D} mesh
  5015. * @param {Array<string>} materialNames
  5016. * @param {THREE.Texture} envMap
  5017. * @param {number} reflectivity [description]
  5018. */
  5019. function applyEnvMap(mesh, materialNames, envMap, reflectivity) {
  5020. if (!mesh) return;
  5021. materialNames = materialNames || [];
  5022. mesh.traverse(function (node) {
  5023. if (!node.isMesh) return;
  5024. var meshMaterials = ensureMaterialArray(node.material);
  5025. meshMaterials.forEach(function (material) {
  5026. if (material && !('envMap' in material)) return;
  5027. if (materialNames.length && materialNames.indexOf(material.name) === -1) return;
  5028. material.envMap = envMap;
  5029. material.reflectivity = reflectivity;
  5030. material.needsUpdate = true;
  5031. });
  5032. });
  5033. }
  5034. /**
  5035. * Specifies an envMap on an entity, without replacing any existing material
  5036. * properties.
  5037. */
  5038. module.exports = AFRAME.registerComponent('cube-env-map', {
  5039. multiple: true,
  5040. schema: {
  5041. path: { default: '' },
  5042. extension: { default: 'jpg', oneOf: ['jpg', 'png'] },
  5043. format: { default: 'RGBFormat', oneOf: ['RGBFormat', 'RGBAFormat'] },
  5044. enableBackground: { default: false },
  5045. reflectivity: { default: 1, min: 0, max: 1 },
  5046. materials: { default: [] }
  5047. },
  5048. init: function init() {
  5049. var _this = this;
  5050. var data = this.data;
  5051. this.texture = new THREE.CubeTextureLoader().load([data.path + 'posx.' + data.extension, data.path + 'negx.' + data.extension, data.path + 'posy.' + data.extension, data.path + 'negy.' + data.extension, data.path + 'posz.' + data.extension, data.path + 'negz.' + data.extension]);
  5052. this.texture.format = THREE[data.format];
  5053. this.object3dsetHandler = function () {
  5054. var mesh = _this.el.getObject3D('mesh');
  5055. var data = _this.data;
  5056. applyEnvMap(mesh, data.materials, _this.texture, data.reflectivity);
  5057. };
  5058. this.el.addEventListener('object3dset', this.object3dsetHandler);
  5059. },
  5060. update: function update(oldData) {
  5061. var data = this.data;
  5062. var mesh = this.el.getObject3D('mesh');
  5063. var addedMaterialNames = [];
  5064. var removedMaterialNames = [];
  5065. if (data.materials.length) {
  5066. if (oldData.materials) {
  5067. addedMaterialNames = data.materials.filter(function (name) {
  5068. return !oldData.materials.includes(name);
  5069. });
  5070. removedMaterialNames = oldData.materials.filter(function (name) {
  5071. return !data.materials.includes(name);
  5072. });
  5073. } else {
  5074. addedMaterialNames = data.materials;
  5075. }
  5076. }
  5077. if (addedMaterialNames.length) {
  5078. applyEnvMap(mesh, addedMaterialNames, this.texture, data.reflectivity);
  5079. }
  5080. if (removedMaterialNames.length) {
  5081. applyEnvMap(mesh, removedMaterialNames, null, 1);
  5082. }
  5083. if (oldData.materials && data.reflectivity !== oldData.reflectivity) {
  5084. var maintainedMaterialNames = data.materials.filter(function (name) {
  5085. return oldData.materials.includes(name);
  5086. });
  5087. if (maintainedMaterialNames.length) {
  5088. applyEnvMap(mesh, maintainedMaterialNames, this.texture, data.reflectivity);
  5089. }
  5090. }
  5091. if (this.data.enableBackground && !oldData.enableBackground) {
  5092. this.setBackground(this.texture);
  5093. } else if (!this.data.enableBackground && oldData.enableBackground) {
  5094. this.setBackground(null);
  5095. }
  5096. },
  5097. remove: function remove() {
  5098. this.el.removeEventListener('object3dset', this.object3dsetHandler);
  5099. var mesh = this.el.getObject3D('mesh');
  5100. var data = this.data;
  5101. applyEnvMap(mesh, data.materials, null, 1);
  5102. if (data.enableBackground) this.setBackground(null);
  5103. },
  5104. setBackground: function setBackground(texture) {
  5105. this.el.sceneEl.object3D.background = texture;
  5106. }
  5107. });
  5108. },{}],25:[function(require,module,exports){
  5109. 'use strict';
  5110. /* global CANNON */
  5111. /**
  5112. * Based on aframe/examples/showcase/tracked-controls.
  5113. *
  5114. * Handles events coming from the hand-controls.
  5115. * Determines if the entity is grabbed or released.
  5116. * Updates its position to move along the controller.
  5117. */
  5118. module.exports = AFRAME.registerComponent('grab', {
  5119. init: function init() {
  5120. this.system = this.el.sceneEl.systems.physics;
  5121. this.GRABBED_STATE = 'grabbed';
  5122. this.grabbing = false;
  5123. this.hitEl = /** @type {AFRAME.Element} */null;
  5124. this.physics = /** @type {AFRAME.System} */this.el.sceneEl.systems.physics;
  5125. this.constraint = /** @type {CANNON.Constraint} */null;
  5126. // Bind event handlers
  5127. this.onHit = this.onHit.bind(this);
  5128. this.onGripOpen = this.onGripOpen.bind(this);
  5129. this.onGripClose = this.onGripClose.bind(this);
  5130. },
  5131. play: function play() {
  5132. var el = this.el;
  5133. el.addEventListener('hit', this.onHit);
  5134. el.addEventListener('gripdown', this.onGripClose);
  5135. el.addEventListener('gripup', this.onGripOpen);
  5136. el.addEventListener('trackpaddown', this.onGripClose);
  5137. el.addEventListener('trackpadup', this.onGripOpen);
  5138. el.addEventListener('triggerdown', this.onGripClose);
  5139. el.addEventListener('triggerup', this.onGripOpen);
  5140. },
  5141. pause: function pause() {
  5142. var el = this.el;
  5143. el.removeEventListener('hit', this.onHit);
  5144. el.removeEventListener('gripdown', this.onGripClose);
  5145. el.removeEventListener('gripup', this.onGripOpen);
  5146. el.removeEventListener('trackpaddown', this.onGripClose);
  5147. el.removeEventListener('trackpadup', this.onGripOpen);
  5148. el.removeEventListener('triggerdown', this.onGripClose);
  5149. el.removeEventListener('triggerup', this.onGripOpen);
  5150. },
  5151. onGripClose: function onGripClose() {
  5152. this.grabbing = true;
  5153. },
  5154. onGripOpen: function onGripOpen() {
  5155. var hitEl = this.hitEl;
  5156. this.grabbing = false;
  5157. if (!hitEl) {
  5158. return;
  5159. }
  5160. hitEl.removeState(this.GRABBED_STATE);
  5161. this.hitEl = undefined;
  5162. this.system.removeConstraint(this.constraint);
  5163. this.constraint = null;
  5164. },
  5165. onHit: function onHit(evt) {
  5166. var hitEl = evt.detail.el;
  5167. // If the element is already grabbed (it could be grabbed by another controller).
  5168. // If the hand is not grabbing the element does not stick.
  5169. // If we're already grabbing something you can't grab again.
  5170. if (!hitEl || hitEl.is(this.GRABBED_STATE) || !this.grabbing || this.hitEl) {
  5171. return;
  5172. }
  5173. hitEl.addState(this.GRABBED_STATE);
  5174. this.hitEl = hitEl;
  5175. this.constraint = new CANNON.LockConstraint(this.el.body, hitEl.body);
  5176. this.system.addConstraint(this.constraint);
  5177. }
  5178. });
  5179. },{}],26:[function(require,module,exports){
  5180. 'use strict';
  5181. require('./checkpoint');
  5182. require('./cube-env-map');
  5183. require('./grab');
  5184. require('./jump-ability');
  5185. require('./kinematic-body');
  5186. require('./mesh-smooth');
  5187. require('./normal-material');
  5188. require('./sphere-collider');
  5189. },{"./checkpoint":23,"./cube-env-map":24,"./grab":25,"./jump-ability":27,"./kinematic-body":28,"./mesh-smooth":29,"./normal-material":30,"./sphere-collider":31}],27:[function(require,module,exports){
  5190. 'use strict';
  5191. var ACCEL_G = -9.8,
  5192. // m/s^2
  5193. EASING = -15; // m/s^2
  5194. /**
  5195. * Jump ability.
  5196. */
  5197. module.exports = AFRAME.registerComponent('jump-ability', {
  5198. dependencies: ['velocity'],
  5199. /* Schema
  5200. ——————————————————————————————————————————————*/
  5201. schema: {
  5202. on: { default: 'keydown:Space gamepadbuttondown:0' },
  5203. playerHeight: { default: 1.764 },
  5204. maxJumps: { default: 1 },
  5205. distance: { default: 5 },
  5206. debug: { default: false }
  5207. },
  5208. init: function init() {
  5209. this.velocity = 0;
  5210. this.numJumps = 0;
  5211. var beginJump = this.beginJump.bind(this),
  5212. events = this.data.on.split(' ');
  5213. this.bindings = {};
  5214. for (var i = 0; i < events.length; i++) {
  5215. this.bindings[events[i]] = beginJump;
  5216. this.el.addEventListener(events[i], beginJump);
  5217. }
  5218. this.bindings.collide = this.onCollide.bind(this);
  5219. this.el.addEventListener('collide', this.bindings.collide);
  5220. },
  5221. remove: function remove() {
  5222. for (var event in this.bindings) {
  5223. if (this.bindings.hasOwnProperty(event)) {
  5224. this.el.removeEventListener(event, this.bindings[event]);
  5225. delete this.bindings[event];
  5226. }
  5227. }
  5228. this.el.removeEventListener('collide', this.bindings.collide);
  5229. delete this.bindings.collide;
  5230. },
  5231. beginJump: function beginJump() {
  5232. if (this.numJumps < this.data.maxJumps) {
  5233. var data = this.data,
  5234. initialVelocity = Math.sqrt(-2 * data.distance * (ACCEL_G + EASING)),
  5235. v = this.el.getAttribute('velocity');
  5236. this.el.setAttribute('velocity', { x: v.x, y: initialVelocity, z: v.z });
  5237. this.numJumps++;
  5238. this.el.emit('jumpstart');
  5239. }
  5240. },
  5241. onCollide: function onCollide() {
  5242. if (this.numJumps > 0) this.el.emit('jumpend');
  5243. this.numJumps = 0;
  5244. }
  5245. });
  5246. },{}],28:[function(require,module,exports){
  5247. 'use strict';
  5248. /* global CANNON */
  5249. /**
  5250. * Kinematic body.
  5251. *
  5252. * Managed dynamic body, which moves but is not affected (directly) by the
  5253. * physics engine. This is not a true kinematic body, in the sense that we are
  5254. * letting the physics engine _compute_ collisions against it and selectively
  5255. * applying those collisions to the object. The physics engine does not decide
  5256. * the position/velocity/rotation of the element.
  5257. *
  5258. * Used for the camera object, because full physics simulation would create
  5259. * movement that feels unnatural to the player. Bipedal movement does not
  5260. * translate nicely to rigid body physics.
  5261. *
  5262. * See: http://www.learn-cocos2d.com/2013/08/physics-engine-platformer-terrible-idea/
  5263. * And: http://oxleygamedev.blogspot.com/2011/04/player-physics-part-2.html
  5264. */
  5265. var EPS = 0.000001;
  5266. module.exports = AFRAME.registerComponent('kinematic-body', {
  5267. dependencies: ['velocity'],
  5268. /*******************************************************************
  5269. * Schema
  5270. */
  5271. schema: {
  5272. mass: { default: 5 },
  5273. radius: { default: 1.3 },
  5274. linearDamping: { default: 0.05 },
  5275. enableSlopes: { default: true },
  5276. enableJumps: { default: false }
  5277. },
  5278. /*******************************************************************
  5279. * Lifecycle
  5280. */
  5281. init: function init() {
  5282. this.system = this.el.sceneEl.systems.physics;
  5283. this.system.addComponent(this);
  5284. var el = this.el,
  5285. data = this.data,
  5286. position = new CANNON.Vec3().copy(el.object3D.getWorldPosition(new THREE.Vector3()));
  5287. this.body = new CANNON.Body({
  5288. material: this.system.getMaterial('staticMaterial'),
  5289. position: position,
  5290. mass: data.mass,
  5291. linearDamping: data.linearDamping,
  5292. fixedRotation: true
  5293. });
  5294. this.body.addShape(new CANNON.Sphere(data.radius), new CANNON.Vec3(0, data.radius, 0));
  5295. this.body.el = this.el;
  5296. this.el.body = this.body;
  5297. this.system.addBody(this.body);
  5298. if (el.hasAttribute('wasd-controls')) {
  5299. console.warn('[kinematic-body] Not compatible with wasd-controls, use movement-controls.');
  5300. }
  5301. },
  5302. remove: function remove() {
  5303. this.system.removeBody(this.body);
  5304. this.system.removeComponent(this);
  5305. delete this.el.body;
  5306. },
  5307. /*******************************************************************
  5308. * Update
  5309. */
  5310. /**
  5311. * Checks CANNON.World for collisions and attempts to apply them to the
  5312. * element automatically, in a player-friendly way.
  5313. *
  5314. * There's extra logic for horizontal surfaces here. The basic requirements:
  5315. * (1) Only apply gravity when not in contact with _any_ horizontal surface.
  5316. * (2) When moving, project the velocity against exactly one ground surface.
  5317. * If in contact with two ground surfaces (e.g. ground + ramp), choose
  5318. * the one that collides with current velocity, if any.
  5319. */
  5320. beforeStep: function beforeStep(t, dt) {
  5321. if (!dt) return;
  5322. var el = this.el;
  5323. var data = this.data;
  5324. var body = this.body;
  5325. if (!data.enableJumps) body.velocity.set(0, 0, 0);
  5326. body.position.copy(el.getAttribute('position'));
  5327. },
  5328. step: function () {
  5329. var velocity = new THREE.Vector3(),
  5330. normalizedVelocity = new THREE.Vector3(),
  5331. currentSurfaceNormal = new THREE.Vector3(),
  5332. groundNormal = new THREE.Vector3();
  5333. return function (t, dt) {
  5334. if (!dt) return;
  5335. var body = this.body,
  5336. data = this.data,
  5337. didCollide = false,
  5338. height = void 0,
  5339. groundHeight = -Infinity,
  5340. groundBody = void 0,
  5341. contacts = this.system.getContacts();
  5342. dt = Math.min(dt, this.system.data.maxInterval * 1000);
  5343. groundNormal.set(0, 0, 0);
  5344. velocity.copy(this.el.getAttribute('velocity'));
  5345. body.velocity.copy(velocity);
  5346. for (var i = 0, contact; contact = contacts[i]; i++) {
  5347. // 1. Find any collisions involving this element. Get the contact
  5348. // normal, and make sure it's oriented _out_ of the other object and
  5349. // enabled (body.collisionReponse is true for both bodies)
  5350. if (!contact.enabled) {
  5351. continue;
  5352. }
  5353. if (body.id === contact.bi.id) {
  5354. contact.ni.negate(currentSurfaceNormal);
  5355. } else if (body.id === contact.bj.id) {
  5356. currentSurfaceNormal.copy(contact.ni);
  5357. } else {
  5358. continue;
  5359. }
  5360. didCollide = body.velocity.dot(currentSurfaceNormal) < -EPS;
  5361. if (didCollide && currentSurfaceNormal.y <= 0.5) {
  5362. // 2. If current trajectory attempts to move _through_ another
  5363. // object, project the velocity against the collision plane to
  5364. // prevent passing through.
  5365. velocity.projectOnPlane(currentSurfaceNormal);
  5366. } else if (currentSurfaceNormal.y > 0.5) {
  5367. // 3. If in contact with something roughly horizontal (+/- 45º) then
  5368. // consider that the current ground. Only the highest qualifying
  5369. // ground is retained.
  5370. height = body.id === contact.bi.id ? Math.abs(contact.rj.y + contact.bj.position.y) : Math.abs(contact.ri.y + contact.bi.position.y);
  5371. if (height > groundHeight) {
  5372. groundHeight = height;
  5373. groundNormal.copy(currentSurfaceNormal);
  5374. groundBody = body.id === contact.bi.id ? contact.bj : contact.bi;
  5375. }
  5376. }
  5377. }
  5378. normalizedVelocity.copy(velocity).normalize();
  5379. if (groundBody && (!data.enableJumps || normalizedVelocity.y < 0.5)) {
  5380. if (!data.enableSlopes) {
  5381. groundNormal.set(0, 1, 0);
  5382. } else if (groundNormal.y < 1 - EPS) {
  5383. groundNormal.copy(this.raycastToGround(groundBody, groundNormal));
  5384. }
  5385. // 4. Project trajectory onto the top-most ground object, unless
  5386. // trajectory is > 45º.
  5387. velocity.projectOnPlane(groundNormal);
  5388. } else if (this.system.driver.world) {
  5389. // 5. If not in contact with anything horizontal, apply world gravity.
  5390. // TODO - Why is the 4x scalar necessary.
  5391. // NOTE: Does not work if physics runs on a worker.
  5392. velocity.add(this.system.driver.world.gravity.scale(dt * 4.0 / 1000));
  5393. }
  5394. body.velocity.copy(velocity);
  5395. this.el.setAttribute('velocity', body.velocity);
  5396. this.el.setAttribute('position', body.position);
  5397. };
  5398. }(),
  5399. /**
  5400. * When walking on complex surfaces (trimeshes, borders between two shapes),
  5401. * the collision normals returned for the player sphere can be very
  5402. * inconsistent. To address this, raycast straight down, find the collision
  5403. * normal, and return whichever normal is more vertical.
  5404. * @param {CANNON.Body} groundBody
  5405. * @param {CANNON.Vec3} groundNormal
  5406. * @return {CANNON.Vec3}
  5407. */
  5408. raycastToGround: function raycastToGround(groundBody, groundNormal) {
  5409. var ray = void 0,
  5410. hitNormal = void 0,
  5411. vFrom = this.body.position,
  5412. vTo = this.body.position.clone();
  5413. ray = new CANNON.Ray(vFrom, vTo);
  5414. ray._updateDirection(); // TODO - Report bug.
  5415. ray.intersectBody(groundBody);
  5416. if (!ray.hasHit) return groundNormal;
  5417. // Compare ABS, in case we're projecting against the inside of the face.
  5418. hitNormal = ray.result.hitNormalWorld;
  5419. return Math.abs(hitNormal.y) > Math.abs(groundNormal.y) ? hitNormal : groundNormal;
  5420. }
  5421. });
  5422. },{}],29:[function(require,module,exports){
  5423. 'use strict';
  5424. /**
  5425. * Apply this component to models that looks "blocky", to have Three.js compute
  5426. * vertex normals on the fly for a "smoother" look.
  5427. */
  5428. module.exports = AFRAME.registerComponent('mesh-smooth', {
  5429. init: function init() {
  5430. this.el.addEventListener('model-loaded', function (e) {
  5431. e.detail.model.traverse(function (node) {
  5432. if (node.isMesh) node.geometry.computeVertexNormals();
  5433. });
  5434. });
  5435. }
  5436. });
  5437. },{}],30:[function(require,module,exports){
  5438. 'use strict';
  5439. /**
  5440. * Recursively applies a MeshNormalMaterial to the entity, such that
  5441. * face colors are determined by their orientation. Helpful for
  5442. * debugging geometry
  5443. */
  5444. module.exports = AFRAME.registerComponent('normal-material', {
  5445. init: function init() {
  5446. this.material = new THREE.MeshNormalMaterial({ flatShading: true });
  5447. this.applyMaterial = this.applyMaterial.bind(this);
  5448. this.el.addEventListener('object3dset', this.applyMaterial);
  5449. },
  5450. remove: function remove() {
  5451. this.el.removeEventListener('object3dset', this.applyMaterial);
  5452. },
  5453. applyMaterial: function applyMaterial() {
  5454. var _this = this;
  5455. this.el.object3D.traverse(function (node) {
  5456. if (node.isMesh) node.material = _this.material;
  5457. });
  5458. }
  5459. });
  5460. },{}],31:[function(require,module,exports){
  5461. 'use strict';
  5462. /**
  5463. * Based on aframe/examples/showcase/tracked-controls.
  5464. *
  5465. * Implement bounding sphere collision detection for entities with a mesh.
  5466. * Sets the specified state on the intersected entities.
  5467. *
  5468. * @property {string} objects - Selector of the entities to test for collision.
  5469. * @property {string} state - State to set on collided entities.
  5470. *
  5471. */
  5472. module.exports = AFRAME.registerComponent('sphere-collider', {
  5473. schema: {
  5474. objects: { default: '' },
  5475. state: { default: 'collided' },
  5476. radius: { default: 0.05 },
  5477. watch: { default: true }
  5478. },
  5479. init: function init() {
  5480. /** @type {MutationObserver} */
  5481. this.observer = null;
  5482. /** @type {Array<Element>} Elements to watch for collisions. */
  5483. this.els = [];
  5484. /** @type {Array<Element>} Elements currently in collision state. */
  5485. this.collisions = [];
  5486. this.handleHit = this.handleHit.bind(this);
  5487. this.handleHitEnd = this.handleHitEnd.bind(this);
  5488. },
  5489. remove: function remove() {
  5490. this.pause();
  5491. },
  5492. play: function play() {
  5493. var sceneEl = this.el.sceneEl;
  5494. if (this.data.watch) {
  5495. this.observer = new MutationObserver(this.update.bind(this, null));
  5496. this.observer.observe(sceneEl, { childList: true, subtree: true });
  5497. }
  5498. },
  5499. pause: function pause() {
  5500. if (this.observer) {
  5501. this.observer.disconnect();
  5502. this.observer = null;
  5503. }
  5504. },
  5505. /**
  5506. * Update list of entities to test for collision.
  5507. */
  5508. update: function update() {
  5509. var data = this.data;
  5510. var objectEls = void 0;
  5511. // Push entities into list of els to intersect.
  5512. if (data.objects) {
  5513. objectEls = this.el.sceneEl.querySelectorAll(data.objects);
  5514. } else {
  5515. // If objects not defined, intersect with everything.
  5516. objectEls = this.el.sceneEl.children;
  5517. }
  5518. // Convert from NodeList to Array
  5519. this.els = Array.prototype.slice.call(objectEls);
  5520. },
  5521. tick: function () {
  5522. var position = new THREE.Vector3(),
  5523. meshPosition = new THREE.Vector3(),
  5524. colliderScale = new THREE.Vector3(),
  5525. distanceMap = new Map();
  5526. return function () {
  5527. var el = this.el,
  5528. data = this.data,
  5529. mesh = el.getObject3D('mesh'),
  5530. collisions = [];
  5531. var colliderRadius = void 0;
  5532. if (!mesh) {
  5533. return;
  5534. }
  5535. distanceMap.clear();
  5536. position.copy(el.object3D.getWorldPosition());
  5537. el.object3D.getWorldScale(colliderScale);
  5538. colliderRadius = data.radius * scaleFactor(colliderScale);
  5539. // Update collision list.
  5540. this.els.forEach(intersect);
  5541. // Emit events and add collision states, in order of distance.
  5542. collisions.sort(function (a, b) {
  5543. return distanceMap.get(a) > distanceMap.get(b) ? 1 : -1;
  5544. }).forEach(this.handleHit);
  5545. // Remove collision state from current element.
  5546. if (collisions.length === 0) {
  5547. el.emit('hit', { el: null });
  5548. }
  5549. // Remove collision state from other elements.
  5550. this.collisions.filter(function (el) {
  5551. return !distanceMap.has(el);
  5552. }).forEach(this.handleHitEnd);
  5553. // Store new collisions
  5554. this.collisions = collisions;
  5555. // Bounding sphere collision detection
  5556. function intersect(el) {
  5557. var radius = void 0,
  5558. mesh = void 0,
  5559. distance = void 0,
  5560. box = void 0,
  5561. extent = void 0,
  5562. size = void 0;
  5563. if (!el.isEntity) {
  5564. return;
  5565. }
  5566. mesh = el.getObject3D('mesh');
  5567. if (!mesh) {
  5568. return;
  5569. }
  5570. box = new THREE.Box3().setFromObject(mesh);
  5571. size = box.getSize();
  5572. extent = Math.max(size.x, size.y, size.z) / 2;
  5573. radius = Math.sqrt(2 * extent * extent);
  5574. box.getCenter(meshPosition);
  5575. if (!radius) {
  5576. return;
  5577. }
  5578. distance = position.distanceTo(meshPosition);
  5579. if (distance < radius + colliderRadius) {
  5580. collisions.push(el);
  5581. distanceMap.set(el, distance);
  5582. }
  5583. }
  5584. // use max of scale factors to maintain bounding sphere collision
  5585. function scaleFactor(scaleVec) {
  5586. return Math.max.apply(null, scaleVec.toArray());
  5587. }
  5588. };
  5589. }(),
  5590. handleHit: function handleHit(targetEl) {
  5591. targetEl.emit('hit');
  5592. targetEl.addState(this.data.state);
  5593. this.el.emit('hit', { el: targetEl });
  5594. },
  5595. handleHitEnd: function handleHitEnd(targetEl) {
  5596. targetEl.emit('hitend');
  5597. targetEl.removeState(this.data.state);
  5598. this.el.emit('hitend', { el: targetEl });
  5599. }
  5600. });
  5601. },{}],32:[function(require,module,exports){
  5602. 'use strict';
  5603. require('./nav-mesh');
  5604. require('./nav-agent');
  5605. require('./system');
  5606. },{"./nav-agent":33,"./nav-mesh":34,"./system":35}],33:[function(require,module,exports){
  5607. 'use strict';
  5608. module.exports = AFRAME.registerComponent('nav-agent', {
  5609. schema: {
  5610. destination: { type: 'vec3' },
  5611. active: { default: false },
  5612. speed: { default: 2 }
  5613. },
  5614. init: function init() {
  5615. this.system = this.el.sceneEl.systems.nav;
  5616. this.system.addAgent(this);
  5617. this.group = null;
  5618. this.path = [];
  5619. this.raycaster = new THREE.Raycaster();
  5620. },
  5621. remove: function remove() {
  5622. this.system.removeAgent(this);
  5623. },
  5624. update: function update() {
  5625. this.path.length = 0;
  5626. },
  5627. updateNavLocation: function updateNavLocation() {
  5628. this.group = null;
  5629. this.path = [];
  5630. },
  5631. tick: function () {
  5632. var vDest = new THREE.Vector3();
  5633. var vDelta = new THREE.Vector3();
  5634. var vNext = new THREE.Vector3();
  5635. return function (t, dt) {
  5636. var el = this.el;
  5637. var data = this.data;
  5638. var raycaster = this.raycaster;
  5639. var speed = data.speed * dt / 1000;
  5640. if (!data.active) return;
  5641. // Use PatrolJS pathfinding system to get shortest path to target.
  5642. if (!this.path.length) {
  5643. var position = this.el.object3D.position;
  5644. this.group = this.group || this.system.getGroup(position);
  5645. this.path = this.system.getPath(position, vDest.copy(data.destination), this.group) || [];
  5646. el.emit('navigation-start');
  5647. }
  5648. // If no path is found, exit.
  5649. if (!this.path.length) {
  5650. console.warn('[nav] Unable to find path to %o.', data.destination);
  5651. this.el.setAttribute('nav-agent', { active: false });
  5652. el.emit('navigation-end');
  5653. return;
  5654. }
  5655. // Current segment is a vector from current position to next waypoint.
  5656. var vCurrent = el.object3D.position;
  5657. var vWaypoint = this.path[0];
  5658. vDelta.subVectors(vWaypoint, vCurrent);
  5659. var distance = vDelta.length();
  5660. var gazeTarget = void 0;
  5661. if (distance < speed) {
  5662. // If <1 step from current waypoint, discard it and move toward next.
  5663. this.path.shift();
  5664. // After discarding the last waypoint, exit pathfinding.
  5665. if (!this.path.length) {
  5666. this.el.setAttribute('nav-agent', { active: false });
  5667. el.emit('navigation-end');
  5668. return;
  5669. }
  5670. vNext.copy(vCurrent);
  5671. gazeTarget = this.path[0];
  5672. } else {
  5673. // If still far away from next waypoint, find next position for
  5674. // the current frame.
  5675. vNext.copy(vDelta.setLength(speed)).add(vCurrent);
  5676. gazeTarget = vWaypoint;
  5677. }
  5678. // Look at the next waypoint.
  5679. gazeTarget.y = vCurrent.y;
  5680. el.object3D.lookAt(gazeTarget);
  5681. // Raycast against the nav mesh, to keep the agent moving along the
  5682. // ground, not traveling in a straight line from higher to lower waypoints.
  5683. raycaster.ray.origin.copy(vNext);
  5684. raycaster.ray.origin.y += 1.5;
  5685. raycaster.ray.direction.y = -1;
  5686. var intersections = raycaster.intersectObject(this.system.getNavMesh());
  5687. if (!intersections.length) {
  5688. // Raycasting failed. Step toward the waypoint and hope for the best.
  5689. vCurrent.copy(vNext);
  5690. } else {
  5691. // Re-project next position onto nav mesh.
  5692. vDelta.subVectors(intersections[0].point, vCurrent);
  5693. vCurrent.add(vDelta.setLength(speed));
  5694. }
  5695. };
  5696. }()
  5697. });
  5698. },{}],34:[function(require,module,exports){
  5699. 'use strict';
  5700. /**
  5701. * nav-mesh
  5702. *
  5703. * Waits for a mesh to be loaded on the current entity, then sets it as the
  5704. * nav mesh in the pathfinding system.
  5705. */
  5706. module.exports = AFRAME.registerComponent('nav-mesh', {
  5707. init: function init() {
  5708. this.system = this.el.sceneEl.systems.nav;
  5709. this.hasLoadedNavMesh = false;
  5710. this.el.addEventListener('object3dset', this.loadNavMesh.bind(this));
  5711. },
  5712. play: function play() {
  5713. if (!this.hasLoadedNavMesh) this.loadNavMesh();
  5714. },
  5715. loadNavMesh: function loadNavMesh() {
  5716. var object = this.el.getObject3D('mesh');
  5717. var scene = this.el.sceneEl.object3D;
  5718. if (!object) return;
  5719. var navMesh = void 0;
  5720. object.traverse(function (node) {
  5721. if (node.isMesh) navMesh = node;
  5722. });
  5723. if (!navMesh) return;
  5724. var navMeshGeometry = navMesh.geometry.isBufferGeometry ? new THREE.Geometry().fromBufferGeometry(navMesh.geometry) : navMesh.geometry.clone();
  5725. scene.updateMatrixWorld();
  5726. navMeshGeometry.applyMatrix(navMesh.matrixWorld);
  5727. this.system.setNavMeshGeometry(navMeshGeometry);
  5728. this.hasLoadedNavMesh = true;
  5729. }
  5730. });
  5731. },{}],35:[function(require,module,exports){
  5732. 'use strict';
  5733. var _require = require('three-pathfinding'),
  5734. Pathfinding = _require.Pathfinding;
  5735. var pathfinder = new Pathfinding();
  5736. var ZONE = 'level';
  5737. /**
  5738. * nav
  5739. *
  5740. * Pathfinding system, using PatrolJS.
  5741. */
  5742. module.exports = AFRAME.registerSystem('nav', {
  5743. init: function init() {
  5744. this.navMesh = null;
  5745. this.agents = new Set();
  5746. },
  5747. /**
  5748. * @param {THREE.Geometry} geometry
  5749. */
  5750. setNavMeshGeometry: function setNavMeshGeometry(geometry) {
  5751. this.navMesh = new THREE.Mesh(geometry);
  5752. pathfinder.setZoneData(ZONE, Pathfinding.createZone(geometry));
  5753. Array.from(this.agents).forEach(function (agent) {
  5754. return agent.updateNavLocation();
  5755. });
  5756. },
  5757. /**
  5758. * @return {THREE.Mesh}
  5759. */
  5760. getNavMesh: function getNavMesh() {
  5761. return this.navMesh;
  5762. },
  5763. /**
  5764. * @param {NavAgent} ctrl
  5765. */
  5766. addAgent: function addAgent(ctrl) {
  5767. this.agents.add(ctrl);
  5768. },
  5769. /**
  5770. * @param {NavAgent} ctrl
  5771. */
  5772. removeAgent: function removeAgent(ctrl) {
  5773. this.agents.delete(ctrl);
  5774. },
  5775. /**
  5776. * @param {THREE.Vector3} start
  5777. * @param {THREE.Vector3} end
  5778. * @param {number} groupID
  5779. * @return {Array<THREE.Vector3>}
  5780. */
  5781. getPath: function getPath(start, end, groupID) {
  5782. return this.navMesh ? pathfinder.findPath(start, end, ZONE, groupID) : null;
  5783. },
  5784. /**
  5785. * @param {THREE.Vector3} position
  5786. * @return {number}
  5787. */
  5788. getGroup: function getGroup(position) {
  5789. return this.navMesh ? pathfinder.getGroup(ZONE, position) : null;
  5790. },
  5791. /**
  5792. * @param {THREE.Vector3} position
  5793. * @param {number} groupID
  5794. * @return {Node}
  5795. */
  5796. getNode: function getNode(position, groupID) {
  5797. return this.navMesh ? pathfinder.getClosestNode(position, ZONE, groupID, true) : null;
  5798. },
  5799. /**
  5800. * @param {THREE.Vector3} start Starting position.
  5801. * @param {THREE.Vector3} end Desired ending position.
  5802. * @param {number} groupID
  5803. * @param {Node} node
  5804. * @param {THREE.Vector3} endTarget (Output) Adjusted step end position.
  5805. * @return {Node} Current node, after step is taken.
  5806. */
  5807. clampStep: function clampStep(start, end, groupID, node, endTarget) {
  5808. if (!this.navMesh) {
  5809. endTarget.copy(end);
  5810. return null;
  5811. } else if (!node) {
  5812. endTarget.copy(end);
  5813. return this.getNode(end, groupID);
  5814. }
  5815. return pathfinder.clampStep(start, end, node, ZONE, groupID, endTarget);
  5816. }
  5817. });
  5818. },{"three-pathfinding":10}],36:[function(require,module,exports){
  5819. 'use strict';
  5820. /**
  5821. * Flat grid.
  5822. *
  5823. * Defaults to 75x75.
  5824. */
  5825. module.exports = AFRAME.registerPrimitive('a-grid', {
  5826. defaultComponents: {
  5827. geometry: {
  5828. primitive: 'plane',
  5829. width: 75,
  5830. height: 75
  5831. },
  5832. rotation: { x: -90, y: 0, z: 0 },
  5833. material: {
  5834. src: 'url(https://cdn.rawgit.com/donmccurdy/aframe-extras/v1.16.3/assets/grid.png)',
  5835. repeat: '75 75'
  5836. }
  5837. },
  5838. mappings: {
  5839. width: 'geometry.width',
  5840. height: 'geometry.height',
  5841. src: 'material.src'
  5842. }
  5843. });
  5844. },{}],37:[function(require,module,exports){
  5845. 'use strict';
  5846. var vg = require('../../lib/hex-grid.min.js');
  5847. var defaultHexGrid = require('../../lib/default-hex-grid');
  5848. /**
  5849. * Hex grid.
  5850. */
  5851. module.exports.Primitive = AFRAME.registerPrimitive('a-hexgrid', {
  5852. defaultComponents: {
  5853. 'hexgrid': {}
  5854. },
  5855. mappings: {
  5856. src: 'hexgrid.src'
  5857. }
  5858. });
  5859. module.exports.Component = AFRAME.registerComponent('hexgrid', {
  5860. dependencies: ['material'],
  5861. schema: {
  5862. src: { type: 'asset' }
  5863. },
  5864. init: function init() {
  5865. var _this = this;
  5866. var data = this.data;
  5867. if (data.src) {
  5868. fetch(data.src).then(function (response) {
  5869. return response.json();
  5870. }).then(function (json) {
  5871. return _this.addMesh(json);
  5872. });
  5873. } else {
  5874. this.addMesh(defaultHexGrid);
  5875. }
  5876. },
  5877. addMesh: function addMesh(json) {
  5878. var grid = new vg.HexGrid();
  5879. grid.fromJSON(json);
  5880. var board = new vg.Board(grid);
  5881. board.generateTilemap();
  5882. this.el.setObject3D('mesh', board.group);
  5883. this.addMaterial();
  5884. },
  5885. addMaterial: function addMaterial() {
  5886. var materialComponent = this.el.components.material;
  5887. var material = (materialComponent || {}).material;
  5888. if (!material) return;
  5889. this.el.object3D.traverse(function (node) {
  5890. if (node.isMesh) {
  5891. node.material = material;
  5892. }
  5893. });
  5894. },
  5895. remove: function remove() {
  5896. this.el.removeObject3D('mesh');
  5897. }
  5898. });
  5899. },{"../../lib/default-hex-grid":6,"../../lib/hex-grid.min.js":8}],38:[function(require,module,exports){
  5900. 'use strict';
  5901. /**
  5902. * Flat-shaded ocean primitive.
  5903. *
  5904. * Based on a Codrops tutorial:
  5905. * http://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/
  5906. */
  5907. module.exports.Primitive = AFRAME.registerPrimitive('a-ocean', {
  5908. defaultComponents: {
  5909. ocean: {},
  5910. rotation: { x: -90, y: 0, z: 0 }
  5911. },
  5912. mappings: {
  5913. width: 'ocean.width',
  5914. depth: 'ocean.depth',
  5915. density: 'ocean.density',
  5916. amplitude: 'ocean.amplitude',
  5917. amplitudeVariance: 'ocean.amplitudeVariance',
  5918. speed: 'ocean.speed',
  5919. speedVariance: 'ocean.speedVariance',
  5920. color: 'ocean.color',
  5921. opacity: 'ocean.opacity'
  5922. }
  5923. });
  5924. module.exports.Component = AFRAME.registerComponent('ocean', {
  5925. schema: {
  5926. // Dimensions of the ocean area.
  5927. width: { default: 10, min: 0 },
  5928. depth: { default: 10, min: 0 },
  5929. // Density of waves.
  5930. density: { default: 10 },
  5931. // Wave amplitude and variance.
  5932. amplitude: { default: 0.1 },
  5933. amplitudeVariance: { default: 0.3 },
  5934. // Wave speed and variance.
  5935. speed: { default: 1 },
  5936. speedVariance: { default: 2 },
  5937. // Material.
  5938. color: { default: '#7AD2F7', type: 'color' },
  5939. opacity: { default: 0.8 }
  5940. },
  5941. /**
  5942. * Use play() instead of init(), because component mappings – unavailable as dependencies – are
  5943. * not guaranteed to have parsed when this component is initialized.
  5944. */
  5945. play: function play() {
  5946. var el = this.el,
  5947. data = this.data;
  5948. var material = el.components.material;
  5949. var geometry = new THREE.PlaneGeometry(data.width, data.depth, data.density, data.density);
  5950. geometry.mergeVertices();
  5951. this.waves = [];
  5952. for (var v, i = 0, l = geometry.vertices.length; i < l; i++) {
  5953. v = geometry.vertices[i];
  5954. this.waves.push({
  5955. z: v.z,
  5956. ang: Math.random() * Math.PI * 2,
  5957. amp: data.amplitude + Math.random() * data.amplitudeVariance,
  5958. speed: (data.speed + Math.random() * data.speedVariance) / 1000 // radians / frame
  5959. });
  5960. }
  5961. if (!material) {
  5962. material = {};
  5963. material.material = new THREE.MeshPhongMaterial({
  5964. color: data.color,
  5965. transparent: data.opacity < 1,
  5966. opacity: data.opacity,
  5967. shading: THREE.FlatShading
  5968. });
  5969. }
  5970. this.mesh = new THREE.Mesh(geometry, material.material);
  5971. el.setObject3D('mesh', this.mesh);
  5972. },
  5973. remove: function remove() {
  5974. this.el.removeObject3D('mesh');
  5975. },
  5976. tick: function tick(t, dt) {
  5977. if (!dt) return;
  5978. var verts = this.mesh.geometry.vertices;
  5979. for (var v, vprops, i = 0; v = verts[i]; i++) {
  5980. vprops = this.waves[i];
  5981. v.z = vprops.z + Math.sin(vprops.ang) * vprops.amp;
  5982. vprops.ang += vprops.speed * dt;
  5983. }
  5984. this.mesh.geometry.verticesNeedUpdate = true;
  5985. }
  5986. });
  5987. },{}],39:[function(require,module,exports){
  5988. 'use strict';
  5989. /**
  5990. * Tube following a custom path.
  5991. *
  5992. * Usage:
  5993. *
  5994. * ```html
  5995. * <a-tube path="5 0 5, 5 0 -5, -5 0 -5" radius="0.5"></a-tube>
  5996. * ```
  5997. */
  5998. module.exports.Primitive = AFRAME.registerPrimitive('a-tube', {
  5999. defaultComponents: {
  6000. tube: {}
  6001. },
  6002. mappings: {
  6003. path: 'tube.path',
  6004. segments: 'tube.segments',
  6005. radius: 'tube.radius',
  6006. 'radial-segments': 'tube.radialSegments',
  6007. closed: 'tube.closed'
  6008. }
  6009. });
  6010. module.exports.Component = AFRAME.registerComponent('tube', {
  6011. schema: {
  6012. path: { default: [] },
  6013. segments: { default: 64 },
  6014. radius: { default: 1 },
  6015. radialSegments: { default: 8 },
  6016. closed: { default: false }
  6017. },
  6018. init: function init() {
  6019. var el = this.el,
  6020. data = this.data;
  6021. var material = el.components.material;
  6022. if (!data.path.length) {
  6023. console.error('[a-tube] `path` property expected but not found.');
  6024. return;
  6025. }
  6026. var curve = new THREE.CatmullRomCurve3(data.path.map(function (point) {
  6027. point = point.split(' ');
  6028. return new THREE.Vector3(Number(point[0]), Number(point[1]), Number(point[2]));
  6029. }));
  6030. var geometry = new THREE.TubeGeometry(curve, data.segments, data.radius, data.radialSegments, data.closed);
  6031. if (!material) {
  6032. material = {};
  6033. material.material = new THREE.MeshPhongMaterial();
  6034. }
  6035. this.mesh = new THREE.Mesh(geometry, material.material);
  6036. this.el.setObject3D('mesh', this.mesh);
  6037. },
  6038. update: function update(prevData) {
  6039. if (!Object.keys(prevData).length) return;
  6040. this.remove();
  6041. this.init();
  6042. },
  6043. remove: function remove() {
  6044. if (this.mesh) this.el.removeObject3D('mesh');
  6045. }
  6046. });
  6047. },{}],40:[function(require,module,exports){
  6048. 'use strict';
  6049. require('./a-grid');
  6050. require('./a-hexgrid');
  6051. require('./a-ocean');
  6052. require('./a-tube');
  6053. },{"./a-grid":36,"./a-hexgrid":37,"./a-ocean":38,"./a-tube":39}]},{},[1]);