aframe-master.js 2.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AFRAME = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
  2. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. module.exports = function numtype(num, def) {
  13. return typeof num === 'number'
  14. ? num
  15. : (typeof def === 'number' ? def : 0)
  16. }
  17. },{}],3:[function(_dereq_,module,exports){
  18. 'use strict'
  19. exports.byteLength = byteLength
  20. exports.toByteArray = toByteArray
  21. exports.fromByteArray = fromByteArray
  22. var lookup = []
  23. var revLookup = []
  24. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  25. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  26. for (var i = 0, len = code.length; i < len; ++i) {
  27. lookup[i] = code[i]
  28. revLookup[code.charCodeAt(i)] = i
  29. }
  30. // Support decoding URL-safe base64 strings, as Node.js does.
  31. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  32. revLookup['-'.charCodeAt(0)] = 62
  33. revLookup['_'.charCodeAt(0)] = 63
  34. function getLens (b64) {
  35. var len = b64.length
  36. if (len % 4 > 0) {
  37. throw new Error('Invalid string. Length must be a multiple of 4')
  38. }
  39. // Trim off extra bytes after placeholder bytes are found
  40. // See: https://github.com/beatgammit/base64-js/issues/42
  41. var validLen = b64.indexOf('=')
  42. if (validLen === -1) validLen = len
  43. var placeHoldersLen = validLen === len
  44. ? 0
  45. : 4 - (validLen % 4)
  46. return [validLen, placeHoldersLen]
  47. }
  48. // base64 is 4/3 + up to two characters of the original data
  49. function byteLength (b64) {
  50. var lens = getLens(b64)
  51. var validLen = lens[0]
  52. var placeHoldersLen = lens[1]
  53. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  54. }
  55. function _byteLength (b64, validLen, placeHoldersLen) {
  56. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  57. }
  58. function toByteArray (b64) {
  59. var tmp
  60. var lens = getLens(b64)
  61. var validLen = lens[0]
  62. var placeHoldersLen = lens[1]
  63. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  64. var curByte = 0
  65. // if there are placeholders, only get up to the last complete 4 chars
  66. var len = placeHoldersLen > 0
  67. ? validLen - 4
  68. : validLen
  69. for (var i = 0; i < len; i += 4) {
  70. tmp =
  71. (revLookup[b64.charCodeAt(i)] << 18) |
  72. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  73. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  74. revLookup[b64.charCodeAt(i + 3)]
  75. arr[curByte++] = (tmp >> 16) & 0xFF
  76. arr[curByte++] = (tmp >> 8) & 0xFF
  77. arr[curByte++] = tmp & 0xFF
  78. }
  79. if (placeHoldersLen === 2) {
  80. tmp =
  81. (revLookup[b64.charCodeAt(i)] << 2) |
  82. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  83. arr[curByte++] = tmp & 0xFF
  84. }
  85. if (placeHoldersLen === 1) {
  86. tmp =
  87. (revLookup[b64.charCodeAt(i)] << 10) |
  88. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  89. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  90. arr[curByte++] = (tmp >> 8) & 0xFF
  91. arr[curByte++] = tmp & 0xFF
  92. }
  93. return arr
  94. }
  95. function tripletToBase64 (num) {
  96. return lookup[num >> 18 & 0x3F] +
  97. lookup[num >> 12 & 0x3F] +
  98. lookup[num >> 6 & 0x3F] +
  99. lookup[num & 0x3F]
  100. }
  101. function encodeChunk (uint8, start, end) {
  102. var tmp
  103. var output = []
  104. for (var i = start; i < end; i += 3) {
  105. tmp =
  106. ((uint8[i] << 16) & 0xFF0000) +
  107. ((uint8[i + 1] << 8) & 0xFF00) +
  108. (uint8[i + 2] & 0xFF)
  109. output.push(tripletToBase64(tmp))
  110. }
  111. return output.join('')
  112. }
  113. function fromByteArray (uint8) {
  114. var tmp
  115. var len = uint8.length
  116. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  117. var parts = []
  118. var maxChunkLength = 16383 // must be multiple of 3
  119. // go through the array every three bytes, we'll deal with trailing stuff later
  120. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  121. parts.push(encodeChunk(
  122. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  123. ))
  124. }
  125. // pad the end with zeros, but make sure to not forget the extra bytes
  126. if (extraBytes === 1) {
  127. tmp = uint8[len - 1]
  128. parts.push(
  129. lookup[tmp >> 2] +
  130. lookup[(tmp << 4) & 0x3F] +
  131. '=='
  132. )
  133. } else if (extraBytes === 2) {
  134. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  135. parts.push(
  136. lookup[tmp >> 10] +
  137. lookup[(tmp >> 4) & 0x3F] +
  138. lookup[(tmp << 2) & 0x3F] +
  139. '='
  140. )
  141. }
  142. return parts.join('')
  143. }
  144. },{}],4:[function(_dereq_,module,exports){
  145. 'use strict';
  146. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  147. module.exports = {
  148. // Create a <link> tag with optional data attributes
  149. createLink: function(href, attributes) {
  150. var head = document.head || document.getElementsByTagName('head')[0];
  151. var link = document.createElement('link');
  152. link.href = href;
  153. link.rel = 'stylesheet';
  154. for (var key in attributes) {
  155. if ( ! attributes.hasOwnProperty(key)) {
  156. continue;
  157. }
  158. var value = attributes[key];
  159. link.setAttribute('data-' + key, value);
  160. }
  161. head.appendChild(link);
  162. },
  163. // Create a <style> tag with optional data attributes
  164. createStyle: function(cssText, attributes) {
  165. var head = document.head || document.getElementsByTagName('head')[0],
  166. style = document.createElement('style');
  167. style.type = 'text/css';
  168. for (var key in attributes) {
  169. if ( ! attributes.hasOwnProperty(key)) {
  170. continue;
  171. }
  172. var value = attributes[key];
  173. style.setAttribute('data-' + key, value);
  174. }
  175. if (style.sheet) { // for jsdom and IE9+
  176. style.innerHTML = cssText;
  177. style.sheet.cssText = cssText;
  178. head.appendChild(style);
  179. } else if (style.styleSheet) { // for IE8 and below
  180. head.appendChild(style);
  181. style.styleSheet.cssText = cssText;
  182. } else { // for Chrome, Firefox, and Safari
  183. style.appendChild(document.createTextNode(cssText));
  184. head.appendChild(style);
  185. }
  186. }
  187. };
  188. },{}],5:[function(_dereq_,module,exports){
  189. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  190. module.exports = function (a, b) {
  191. if (!Buffer.isBuffer(a)) return undefined;
  192. if (!Buffer.isBuffer(b)) return undefined;
  193. if (typeof a.equals === 'function') return a.equals(b);
  194. if (a.length !== b.length) return false;
  195. for (var i = 0; i < a.length; i++) {
  196. if (a[i] !== b[i]) return false;
  197. }
  198. return true;
  199. };
  200. },{"buffer":6}],6:[function(_dereq_,module,exports){
  201. (function (global,Buffer){
  202. /*!
  203. * The buffer module from node.js, for the browser.
  204. *
  205. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  206. * @license MIT
  207. */
  208. /* eslint-disable no-proto */
  209. 'use strict'
  210. var base64 = _dereq_('base64-js')
  211. var ieee754 = _dereq_('ieee754')
  212. var isArray = _dereq_('isarray')
  213. exports.Buffer = Buffer
  214. exports.SlowBuffer = SlowBuffer
  215. exports.INSPECT_MAX_BYTES = 50
  216. /**
  217. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  218. * === true Use Uint8Array implementation (fastest)
  219. * === false Use Object implementation (most compatible, even IE6)
  220. *
  221. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  222. * Opera 11.6+, iOS 4.2+.
  223. *
  224. * Due to various browser bugs, sometimes the Object implementation will be used even
  225. * when the browser supports typed arrays.
  226. *
  227. * Note:
  228. *
  229. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  230. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  231. *
  232. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  233. *
  234. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  235. * incorrect length in some situations.
  236. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  237. * get the Object implementation, which is slower but behaves correctly.
  238. */
  239. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  240. ? global.TYPED_ARRAY_SUPPORT
  241. : typedArraySupport()
  242. /*
  243. * Export kMaxLength after typed array support is determined.
  244. */
  245. exports.kMaxLength = kMaxLength()
  246. function typedArraySupport () {
  247. try {
  248. var arr = new Uint8Array(1)
  249. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  250. return arr.foo() === 42 && // typed array instances can be augmented
  251. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  252. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  253. } catch (e) {
  254. return false
  255. }
  256. }
  257. function kMaxLength () {
  258. return Buffer.TYPED_ARRAY_SUPPORT
  259. ? 0x7fffffff
  260. : 0x3fffffff
  261. }
  262. function createBuffer (that, length) {
  263. if (kMaxLength() < length) {
  264. throw new RangeError('Invalid typed array length')
  265. }
  266. if (Buffer.TYPED_ARRAY_SUPPORT) {
  267. // Return an augmented `Uint8Array` instance, for best performance
  268. that = new Uint8Array(length)
  269. that.__proto__ = Buffer.prototype
  270. } else {
  271. // Fallback: Return an object instance of the Buffer class
  272. if (that === null) {
  273. that = new Buffer(length)
  274. }
  275. that.length = length
  276. }
  277. return that
  278. }
  279. /**
  280. * The Buffer constructor returns instances of `Uint8Array` that have their
  281. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  282. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  283. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  284. * returns a single octet.
  285. *
  286. * The `Uint8Array` prototype remains unmodified.
  287. */
  288. function Buffer (arg, encodingOrOffset, length) {
  289. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  290. return new Buffer(arg, encodingOrOffset, length)
  291. }
  292. // Common case.
  293. if (typeof arg === 'number') {
  294. if (typeof encodingOrOffset === 'string') {
  295. throw new Error(
  296. 'If encoding is specified then the first argument must be a string'
  297. )
  298. }
  299. return allocUnsafe(this, arg)
  300. }
  301. return from(this, arg, encodingOrOffset, length)
  302. }
  303. Buffer.poolSize = 8192 // not used by this implementation
  304. // TODO: Legacy, not needed anymore. Remove in next major version.
  305. Buffer._augment = function (arr) {
  306. arr.__proto__ = Buffer.prototype
  307. return arr
  308. }
  309. function from (that, value, encodingOrOffset, length) {
  310. if (typeof value === 'number') {
  311. throw new TypeError('"value" argument must not be a number')
  312. }
  313. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  314. return fromArrayBuffer(that, value, encodingOrOffset, length)
  315. }
  316. if (typeof value === 'string') {
  317. return fromString(that, value, encodingOrOffset)
  318. }
  319. return fromObject(that, value)
  320. }
  321. /**
  322. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  323. * if value is a number.
  324. * Buffer.from(str[, encoding])
  325. * Buffer.from(array)
  326. * Buffer.from(buffer)
  327. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  328. **/
  329. Buffer.from = function (value, encodingOrOffset, length) {
  330. return from(null, value, encodingOrOffset, length)
  331. }
  332. if (Buffer.TYPED_ARRAY_SUPPORT) {
  333. Buffer.prototype.__proto__ = Uint8Array.prototype
  334. Buffer.__proto__ = Uint8Array
  335. if (typeof Symbol !== 'undefined' && Symbol.species &&
  336. Buffer[Symbol.species] === Buffer) {
  337. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  338. Object.defineProperty(Buffer, Symbol.species, {
  339. value: null,
  340. configurable: true
  341. })
  342. }
  343. }
  344. function assertSize (size) {
  345. if (typeof size !== 'number') {
  346. throw new TypeError('"size" argument must be a number')
  347. } else if (size < 0) {
  348. throw new RangeError('"size" argument must not be negative')
  349. }
  350. }
  351. function alloc (that, size, fill, encoding) {
  352. assertSize(size)
  353. if (size <= 0) {
  354. return createBuffer(that, size)
  355. }
  356. if (fill !== undefined) {
  357. // Only pay attention to encoding if it's a string. This
  358. // prevents accidentally sending in a number that would
  359. // be interpretted as a start offset.
  360. return typeof encoding === 'string'
  361. ? createBuffer(that, size).fill(fill, encoding)
  362. : createBuffer(that, size).fill(fill)
  363. }
  364. return createBuffer(that, size)
  365. }
  366. /**
  367. * Creates a new filled Buffer instance.
  368. * alloc(size[, fill[, encoding]])
  369. **/
  370. Buffer.alloc = function (size, fill, encoding) {
  371. return alloc(null, size, fill, encoding)
  372. }
  373. function allocUnsafe (that, size) {
  374. assertSize(size)
  375. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  376. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  377. for (var i = 0; i < size; ++i) {
  378. that[i] = 0
  379. }
  380. }
  381. return that
  382. }
  383. /**
  384. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  385. * */
  386. Buffer.allocUnsafe = function (size) {
  387. return allocUnsafe(null, size)
  388. }
  389. /**
  390. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  391. */
  392. Buffer.allocUnsafeSlow = function (size) {
  393. return allocUnsafe(null, size)
  394. }
  395. function fromString (that, string, encoding) {
  396. if (typeof encoding !== 'string' || encoding === '') {
  397. encoding = 'utf8'
  398. }
  399. if (!Buffer.isEncoding(encoding)) {
  400. throw new TypeError('"encoding" must be a valid string encoding')
  401. }
  402. var length = byteLength(string, encoding) | 0
  403. that = createBuffer(that, length)
  404. var actual = that.write(string, encoding)
  405. if (actual !== length) {
  406. // Writing a hex string, for example, that contains invalid characters will
  407. // cause everything after the first invalid character to be ignored. (e.g.
  408. // 'abxxcd' will be treated as 'ab')
  409. that = that.slice(0, actual)
  410. }
  411. return that
  412. }
  413. function fromArrayLike (that, array) {
  414. var length = array.length < 0 ? 0 : checked(array.length) | 0
  415. that = createBuffer(that, length)
  416. for (var i = 0; i < length; i += 1) {
  417. that[i] = array[i] & 255
  418. }
  419. return that
  420. }
  421. function fromArrayBuffer (that, array, byteOffset, length) {
  422. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  423. if (byteOffset < 0 || array.byteLength < byteOffset) {
  424. throw new RangeError('\'offset\' is out of bounds')
  425. }
  426. if (array.byteLength < byteOffset + (length || 0)) {
  427. throw new RangeError('\'length\' is out of bounds')
  428. }
  429. if (byteOffset === undefined && length === undefined) {
  430. array = new Uint8Array(array)
  431. } else if (length === undefined) {
  432. array = new Uint8Array(array, byteOffset)
  433. } else {
  434. array = new Uint8Array(array, byteOffset, length)
  435. }
  436. if (Buffer.TYPED_ARRAY_SUPPORT) {
  437. // Return an augmented `Uint8Array` instance, for best performance
  438. that = array
  439. that.__proto__ = Buffer.prototype
  440. } else {
  441. // Fallback: Return an object instance of the Buffer class
  442. that = fromArrayLike(that, array)
  443. }
  444. return that
  445. }
  446. function fromObject (that, obj) {
  447. if (Buffer.isBuffer(obj)) {
  448. var len = checked(obj.length) | 0
  449. that = createBuffer(that, len)
  450. if (that.length === 0) {
  451. return that
  452. }
  453. obj.copy(that, 0, 0, len)
  454. return that
  455. }
  456. if (obj) {
  457. if ((typeof ArrayBuffer !== 'undefined' &&
  458. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  459. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  460. return createBuffer(that, 0)
  461. }
  462. return fromArrayLike(that, obj)
  463. }
  464. if (obj.type === 'Buffer' && isArray(obj.data)) {
  465. return fromArrayLike(that, obj.data)
  466. }
  467. }
  468. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  469. }
  470. function checked (length) {
  471. // Note: cannot use `length < kMaxLength()` here because that fails when
  472. // length is NaN (which is otherwise coerced to zero.)
  473. if (length >= kMaxLength()) {
  474. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  475. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  476. }
  477. return length | 0
  478. }
  479. function SlowBuffer (length) {
  480. if (+length != length) { // eslint-disable-line eqeqeq
  481. length = 0
  482. }
  483. return Buffer.alloc(+length)
  484. }
  485. Buffer.isBuffer = function isBuffer (b) {
  486. return !!(b != null && b._isBuffer)
  487. }
  488. Buffer.compare = function compare (a, b) {
  489. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  490. throw new TypeError('Arguments must be Buffers')
  491. }
  492. if (a === b) return 0
  493. var x = a.length
  494. var y = b.length
  495. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  496. if (a[i] !== b[i]) {
  497. x = a[i]
  498. y = b[i]
  499. break
  500. }
  501. }
  502. if (x < y) return -1
  503. if (y < x) return 1
  504. return 0
  505. }
  506. Buffer.isEncoding = function isEncoding (encoding) {
  507. switch (String(encoding).toLowerCase()) {
  508. case 'hex':
  509. case 'utf8':
  510. case 'utf-8':
  511. case 'ascii':
  512. case 'latin1':
  513. case 'binary':
  514. case 'base64':
  515. case 'ucs2':
  516. case 'ucs-2':
  517. case 'utf16le':
  518. case 'utf-16le':
  519. return true
  520. default:
  521. return false
  522. }
  523. }
  524. Buffer.concat = function concat (list, length) {
  525. if (!isArray(list)) {
  526. throw new TypeError('"list" argument must be an Array of Buffers')
  527. }
  528. if (list.length === 0) {
  529. return Buffer.alloc(0)
  530. }
  531. var i
  532. if (length === undefined) {
  533. length = 0
  534. for (i = 0; i < list.length; ++i) {
  535. length += list[i].length
  536. }
  537. }
  538. var buffer = Buffer.allocUnsafe(length)
  539. var pos = 0
  540. for (i = 0; i < list.length; ++i) {
  541. var buf = list[i]
  542. if (!Buffer.isBuffer(buf)) {
  543. throw new TypeError('"list" argument must be an Array of Buffers')
  544. }
  545. buf.copy(buffer, pos)
  546. pos += buf.length
  547. }
  548. return buffer
  549. }
  550. function byteLength (string, encoding) {
  551. if (Buffer.isBuffer(string)) {
  552. return string.length
  553. }
  554. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  555. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  556. return string.byteLength
  557. }
  558. if (typeof string !== 'string') {
  559. string = '' + string
  560. }
  561. var len = string.length
  562. if (len === 0) return 0
  563. // Use a for loop to avoid recursion
  564. var loweredCase = false
  565. for (;;) {
  566. switch (encoding) {
  567. case 'ascii':
  568. case 'latin1':
  569. case 'binary':
  570. return len
  571. case 'utf8':
  572. case 'utf-8':
  573. case undefined:
  574. return utf8ToBytes(string).length
  575. case 'ucs2':
  576. case 'ucs-2':
  577. case 'utf16le':
  578. case 'utf-16le':
  579. return len * 2
  580. case 'hex':
  581. return len >>> 1
  582. case 'base64':
  583. return base64ToBytes(string).length
  584. default:
  585. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  586. encoding = ('' + encoding).toLowerCase()
  587. loweredCase = true
  588. }
  589. }
  590. }
  591. Buffer.byteLength = byteLength
  592. function slowToString (encoding, start, end) {
  593. var loweredCase = false
  594. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  595. // property of a typed array.
  596. // This behaves neither like String nor Uint8Array in that we set start/end
  597. // to their upper/lower bounds if the value passed is out of range.
  598. // undefined is handled specially as per ECMA-262 6th Edition,
  599. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  600. if (start === undefined || start < 0) {
  601. start = 0
  602. }
  603. // Return early if start > this.length. Done here to prevent potential uint32
  604. // coercion fail below.
  605. if (start > this.length) {
  606. return ''
  607. }
  608. if (end === undefined || end > this.length) {
  609. end = this.length
  610. }
  611. if (end <= 0) {
  612. return ''
  613. }
  614. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  615. end >>>= 0
  616. start >>>= 0
  617. if (end <= start) {
  618. return ''
  619. }
  620. if (!encoding) encoding = 'utf8'
  621. while (true) {
  622. switch (encoding) {
  623. case 'hex':
  624. return hexSlice(this, start, end)
  625. case 'utf8':
  626. case 'utf-8':
  627. return utf8Slice(this, start, end)
  628. case 'ascii':
  629. return asciiSlice(this, start, end)
  630. case 'latin1':
  631. case 'binary':
  632. return latin1Slice(this, start, end)
  633. case 'base64':
  634. return base64Slice(this, start, end)
  635. case 'ucs2':
  636. case 'ucs-2':
  637. case 'utf16le':
  638. case 'utf-16le':
  639. return utf16leSlice(this, start, end)
  640. default:
  641. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  642. encoding = (encoding + '').toLowerCase()
  643. loweredCase = true
  644. }
  645. }
  646. }
  647. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  648. // Buffer instances.
  649. Buffer.prototype._isBuffer = true
  650. function swap (b, n, m) {
  651. var i = b[n]
  652. b[n] = b[m]
  653. b[m] = i
  654. }
  655. Buffer.prototype.swap16 = function swap16 () {
  656. var len = this.length
  657. if (len % 2 !== 0) {
  658. throw new RangeError('Buffer size must be a multiple of 16-bits')
  659. }
  660. for (var i = 0; i < len; i += 2) {
  661. swap(this, i, i + 1)
  662. }
  663. return this
  664. }
  665. Buffer.prototype.swap32 = function swap32 () {
  666. var len = this.length
  667. if (len % 4 !== 0) {
  668. throw new RangeError('Buffer size must be a multiple of 32-bits')
  669. }
  670. for (var i = 0; i < len; i += 4) {
  671. swap(this, i, i + 3)
  672. swap(this, i + 1, i + 2)
  673. }
  674. return this
  675. }
  676. Buffer.prototype.swap64 = function swap64 () {
  677. var len = this.length
  678. if (len % 8 !== 0) {
  679. throw new RangeError('Buffer size must be a multiple of 64-bits')
  680. }
  681. for (var i = 0; i < len; i += 8) {
  682. swap(this, i, i + 7)
  683. swap(this, i + 1, i + 6)
  684. swap(this, i + 2, i + 5)
  685. swap(this, i + 3, i + 4)
  686. }
  687. return this
  688. }
  689. Buffer.prototype.toString = function toString () {
  690. var length = this.length | 0
  691. if (length === 0) return ''
  692. if (arguments.length === 0) return utf8Slice(this, 0, length)
  693. return slowToString.apply(this, arguments)
  694. }
  695. Buffer.prototype.equals = function equals (b) {
  696. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  697. if (this === b) return true
  698. return Buffer.compare(this, b) === 0
  699. }
  700. Buffer.prototype.inspect = function inspect () {
  701. var str = ''
  702. var max = exports.INSPECT_MAX_BYTES
  703. if (this.length > 0) {
  704. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  705. if (this.length > max) str += ' ... '
  706. }
  707. return '<Buffer ' + str + '>'
  708. }
  709. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  710. if (!Buffer.isBuffer(target)) {
  711. throw new TypeError('Argument must be a Buffer')
  712. }
  713. if (start === undefined) {
  714. start = 0
  715. }
  716. if (end === undefined) {
  717. end = target ? target.length : 0
  718. }
  719. if (thisStart === undefined) {
  720. thisStart = 0
  721. }
  722. if (thisEnd === undefined) {
  723. thisEnd = this.length
  724. }
  725. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  726. throw new RangeError('out of range index')
  727. }
  728. if (thisStart >= thisEnd && start >= end) {
  729. return 0
  730. }
  731. if (thisStart >= thisEnd) {
  732. return -1
  733. }
  734. if (start >= end) {
  735. return 1
  736. }
  737. start >>>= 0
  738. end >>>= 0
  739. thisStart >>>= 0
  740. thisEnd >>>= 0
  741. if (this === target) return 0
  742. var x = thisEnd - thisStart
  743. var y = end - start
  744. var len = Math.min(x, y)
  745. var thisCopy = this.slice(thisStart, thisEnd)
  746. var targetCopy = target.slice(start, end)
  747. for (var i = 0; i < len; ++i) {
  748. if (thisCopy[i] !== targetCopy[i]) {
  749. x = thisCopy[i]
  750. y = targetCopy[i]
  751. break
  752. }
  753. }
  754. if (x < y) return -1
  755. if (y < x) return 1
  756. return 0
  757. }
  758. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  759. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  760. //
  761. // Arguments:
  762. // - buffer - a Buffer to search
  763. // - val - a string, Buffer, or number
  764. // - byteOffset - an index into `buffer`; will be clamped to an int32
  765. // - encoding - an optional encoding, relevant is val is a string
  766. // - dir - true for indexOf, false for lastIndexOf
  767. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  768. // Empty buffer means no match
  769. if (buffer.length === 0) return -1
  770. // Normalize byteOffset
  771. if (typeof byteOffset === 'string') {
  772. encoding = byteOffset
  773. byteOffset = 0
  774. } else if (byteOffset > 0x7fffffff) {
  775. byteOffset = 0x7fffffff
  776. } else if (byteOffset < -0x80000000) {
  777. byteOffset = -0x80000000
  778. }
  779. byteOffset = +byteOffset // Coerce to Number.
  780. if (isNaN(byteOffset)) {
  781. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  782. byteOffset = dir ? 0 : (buffer.length - 1)
  783. }
  784. // Normalize byteOffset: negative offsets start from the end of the buffer
  785. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  786. if (byteOffset >= buffer.length) {
  787. if (dir) return -1
  788. else byteOffset = buffer.length - 1
  789. } else if (byteOffset < 0) {
  790. if (dir) byteOffset = 0
  791. else return -1
  792. }
  793. // Normalize val
  794. if (typeof val === 'string') {
  795. val = Buffer.from(val, encoding)
  796. }
  797. // Finally, search either indexOf (if dir is true) or lastIndexOf
  798. if (Buffer.isBuffer(val)) {
  799. // Special case: looking for empty string/buffer always fails
  800. if (val.length === 0) {
  801. return -1
  802. }
  803. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  804. } else if (typeof val === 'number') {
  805. val = val & 0xFF // Search for a byte value [0-255]
  806. if (Buffer.TYPED_ARRAY_SUPPORT &&
  807. typeof Uint8Array.prototype.indexOf === 'function') {
  808. if (dir) {
  809. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  810. } else {
  811. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  812. }
  813. }
  814. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  815. }
  816. throw new TypeError('val must be string, number or Buffer')
  817. }
  818. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  819. var indexSize = 1
  820. var arrLength = arr.length
  821. var valLength = val.length
  822. if (encoding !== undefined) {
  823. encoding = String(encoding).toLowerCase()
  824. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  825. encoding === 'utf16le' || encoding === 'utf-16le') {
  826. if (arr.length < 2 || val.length < 2) {
  827. return -1
  828. }
  829. indexSize = 2
  830. arrLength /= 2
  831. valLength /= 2
  832. byteOffset /= 2
  833. }
  834. }
  835. function read (buf, i) {
  836. if (indexSize === 1) {
  837. return buf[i]
  838. } else {
  839. return buf.readUInt16BE(i * indexSize)
  840. }
  841. }
  842. var i
  843. if (dir) {
  844. var foundIndex = -1
  845. for (i = byteOffset; i < arrLength; i++) {
  846. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  847. if (foundIndex === -1) foundIndex = i
  848. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  849. } else {
  850. if (foundIndex !== -1) i -= i - foundIndex
  851. foundIndex = -1
  852. }
  853. }
  854. } else {
  855. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  856. for (i = byteOffset; i >= 0; i--) {
  857. var found = true
  858. for (var j = 0; j < valLength; j++) {
  859. if (read(arr, i + j) !== read(val, j)) {
  860. found = false
  861. break
  862. }
  863. }
  864. if (found) return i
  865. }
  866. }
  867. return -1
  868. }
  869. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  870. return this.indexOf(val, byteOffset, encoding) !== -1
  871. }
  872. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  873. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  874. }
  875. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  876. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  877. }
  878. function hexWrite (buf, string, offset, length) {
  879. offset = Number(offset) || 0
  880. var remaining = buf.length - offset
  881. if (!length) {
  882. length = remaining
  883. } else {
  884. length = Number(length)
  885. if (length > remaining) {
  886. length = remaining
  887. }
  888. }
  889. // must be an even number of digits
  890. var strLen = string.length
  891. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  892. if (length > strLen / 2) {
  893. length = strLen / 2
  894. }
  895. for (var i = 0; i < length; ++i) {
  896. var parsed = parseInt(string.substr(i * 2, 2), 16)
  897. if (isNaN(parsed)) return i
  898. buf[offset + i] = parsed
  899. }
  900. return i
  901. }
  902. function utf8Write (buf, string, offset, length) {
  903. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  904. }
  905. function asciiWrite (buf, string, offset, length) {
  906. return blitBuffer(asciiToBytes(string), buf, offset, length)
  907. }
  908. function latin1Write (buf, string, offset, length) {
  909. return asciiWrite(buf, string, offset, length)
  910. }
  911. function base64Write (buf, string, offset, length) {
  912. return blitBuffer(base64ToBytes(string), buf, offset, length)
  913. }
  914. function ucs2Write (buf, string, offset, length) {
  915. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  916. }
  917. Buffer.prototype.write = function write (string, offset, length, encoding) {
  918. // Buffer#write(string)
  919. if (offset === undefined) {
  920. encoding = 'utf8'
  921. length = this.length
  922. offset = 0
  923. // Buffer#write(string, encoding)
  924. } else if (length === undefined && typeof offset === 'string') {
  925. encoding = offset
  926. length = this.length
  927. offset = 0
  928. // Buffer#write(string, offset[, length][, encoding])
  929. } else if (isFinite(offset)) {
  930. offset = offset | 0
  931. if (isFinite(length)) {
  932. length = length | 0
  933. if (encoding === undefined) encoding = 'utf8'
  934. } else {
  935. encoding = length
  936. length = undefined
  937. }
  938. // legacy write(string, encoding, offset, length) - remove in v0.13
  939. } else {
  940. throw new Error(
  941. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  942. )
  943. }
  944. var remaining = this.length - offset
  945. if (length === undefined || length > remaining) length = remaining
  946. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  947. throw new RangeError('Attempt to write outside buffer bounds')
  948. }
  949. if (!encoding) encoding = 'utf8'
  950. var loweredCase = false
  951. for (;;) {
  952. switch (encoding) {
  953. case 'hex':
  954. return hexWrite(this, string, offset, length)
  955. case 'utf8':
  956. case 'utf-8':
  957. return utf8Write(this, string, offset, length)
  958. case 'ascii':
  959. return asciiWrite(this, string, offset, length)
  960. case 'latin1':
  961. case 'binary':
  962. return latin1Write(this, string, offset, length)
  963. case 'base64':
  964. // Warning: maxLength not taken into account in base64Write
  965. return base64Write(this, string, offset, length)
  966. case 'ucs2':
  967. case 'ucs-2':
  968. case 'utf16le':
  969. case 'utf-16le':
  970. return ucs2Write(this, string, offset, length)
  971. default:
  972. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  973. encoding = ('' + encoding).toLowerCase()
  974. loweredCase = true
  975. }
  976. }
  977. }
  978. Buffer.prototype.toJSON = function toJSON () {
  979. return {
  980. type: 'Buffer',
  981. data: Array.prototype.slice.call(this._arr || this, 0)
  982. }
  983. }
  984. function base64Slice (buf, start, end) {
  985. if (start === 0 && end === buf.length) {
  986. return base64.fromByteArray(buf)
  987. } else {
  988. return base64.fromByteArray(buf.slice(start, end))
  989. }
  990. }
  991. function utf8Slice (buf, start, end) {
  992. end = Math.min(buf.length, end)
  993. var res = []
  994. var i = start
  995. while (i < end) {
  996. var firstByte = buf[i]
  997. var codePoint = null
  998. var bytesPerSequence = (firstByte > 0xEF) ? 4
  999. : (firstByte > 0xDF) ? 3
  1000. : (firstByte > 0xBF) ? 2
  1001. : 1
  1002. if (i + bytesPerSequence <= end) {
  1003. var secondByte, thirdByte, fourthByte, tempCodePoint
  1004. switch (bytesPerSequence) {
  1005. case 1:
  1006. if (firstByte < 0x80) {
  1007. codePoint = firstByte
  1008. }
  1009. break
  1010. case 2:
  1011. secondByte = buf[i + 1]
  1012. if ((secondByte & 0xC0) === 0x80) {
  1013. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1014. if (tempCodePoint > 0x7F) {
  1015. codePoint = tempCodePoint
  1016. }
  1017. }
  1018. break
  1019. case 3:
  1020. secondByte = buf[i + 1]
  1021. thirdByte = buf[i + 2]
  1022. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1023. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1024. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1025. codePoint = tempCodePoint
  1026. }
  1027. }
  1028. break
  1029. case 4:
  1030. secondByte = buf[i + 1]
  1031. thirdByte = buf[i + 2]
  1032. fourthByte = buf[i + 3]
  1033. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1034. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1035. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1036. codePoint = tempCodePoint
  1037. }
  1038. }
  1039. }
  1040. }
  1041. if (codePoint === null) {
  1042. // we did not generate a valid codePoint so insert a
  1043. // replacement char (U+FFFD) and advance only 1 byte
  1044. codePoint = 0xFFFD
  1045. bytesPerSequence = 1
  1046. } else if (codePoint > 0xFFFF) {
  1047. // encode to utf16 (surrogate pair dance)
  1048. codePoint -= 0x10000
  1049. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1050. codePoint = 0xDC00 | codePoint & 0x3FF
  1051. }
  1052. res.push(codePoint)
  1053. i += bytesPerSequence
  1054. }
  1055. return decodeCodePointsArray(res)
  1056. }
  1057. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1058. // the lowest limit is Chrome, with 0x10000 args.
  1059. // We go 1 magnitude less, for safety
  1060. var MAX_ARGUMENTS_LENGTH = 0x1000
  1061. function decodeCodePointsArray (codePoints) {
  1062. var len = codePoints.length
  1063. if (len <= MAX_ARGUMENTS_LENGTH) {
  1064. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1065. }
  1066. // Decode in chunks to avoid "call stack size exceeded".
  1067. var res = ''
  1068. var i = 0
  1069. while (i < len) {
  1070. res += String.fromCharCode.apply(
  1071. String,
  1072. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1073. )
  1074. }
  1075. return res
  1076. }
  1077. function asciiSlice (buf, start, end) {
  1078. var ret = ''
  1079. end = Math.min(buf.length, end)
  1080. for (var i = start; i < end; ++i) {
  1081. ret += String.fromCharCode(buf[i] & 0x7F)
  1082. }
  1083. return ret
  1084. }
  1085. function latin1Slice (buf, start, end) {
  1086. var ret = ''
  1087. end = Math.min(buf.length, end)
  1088. for (var i = start; i < end; ++i) {
  1089. ret += String.fromCharCode(buf[i])
  1090. }
  1091. return ret
  1092. }
  1093. function hexSlice (buf, start, end) {
  1094. var len = buf.length
  1095. if (!start || start < 0) start = 0
  1096. if (!end || end < 0 || end > len) end = len
  1097. var out = ''
  1098. for (var i = start; i < end; ++i) {
  1099. out += toHex(buf[i])
  1100. }
  1101. return out
  1102. }
  1103. function utf16leSlice (buf, start, end) {
  1104. var bytes = buf.slice(start, end)
  1105. var res = ''
  1106. for (var i = 0; i < bytes.length; i += 2) {
  1107. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1108. }
  1109. return res
  1110. }
  1111. Buffer.prototype.slice = function slice (start, end) {
  1112. var len = this.length
  1113. start = ~~start
  1114. end = end === undefined ? len : ~~end
  1115. if (start < 0) {
  1116. start += len
  1117. if (start < 0) start = 0
  1118. } else if (start > len) {
  1119. start = len
  1120. }
  1121. if (end < 0) {
  1122. end += len
  1123. if (end < 0) end = 0
  1124. } else if (end > len) {
  1125. end = len
  1126. }
  1127. if (end < start) end = start
  1128. var newBuf
  1129. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1130. newBuf = this.subarray(start, end)
  1131. newBuf.__proto__ = Buffer.prototype
  1132. } else {
  1133. var sliceLen = end - start
  1134. newBuf = new Buffer(sliceLen, undefined)
  1135. for (var i = 0; i < sliceLen; ++i) {
  1136. newBuf[i] = this[i + start]
  1137. }
  1138. }
  1139. return newBuf
  1140. }
  1141. /*
  1142. * Need to make sure that buffer isn't trying to write out of bounds.
  1143. */
  1144. function checkOffset (offset, ext, length) {
  1145. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1146. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1147. }
  1148. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1149. offset = offset | 0
  1150. byteLength = byteLength | 0
  1151. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1152. var val = this[offset]
  1153. var mul = 1
  1154. var i = 0
  1155. while (++i < byteLength && (mul *= 0x100)) {
  1156. val += this[offset + i] * mul
  1157. }
  1158. return val
  1159. }
  1160. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1161. offset = offset | 0
  1162. byteLength = byteLength | 0
  1163. if (!noAssert) {
  1164. checkOffset(offset, byteLength, this.length)
  1165. }
  1166. var val = this[offset + --byteLength]
  1167. var mul = 1
  1168. while (byteLength > 0 && (mul *= 0x100)) {
  1169. val += this[offset + --byteLength] * mul
  1170. }
  1171. return val
  1172. }
  1173. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1174. if (!noAssert) checkOffset(offset, 1, this.length)
  1175. return this[offset]
  1176. }
  1177. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1178. if (!noAssert) checkOffset(offset, 2, this.length)
  1179. return this[offset] | (this[offset + 1] << 8)
  1180. }
  1181. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1182. if (!noAssert) checkOffset(offset, 2, this.length)
  1183. return (this[offset] << 8) | this[offset + 1]
  1184. }
  1185. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1186. if (!noAssert) checkOffset(offset, 4, this.length)
  1187. return ((this[offset]) |
  1188. (this[offset + 1] << 8) |
  1189. (this[offset + 2] << 16)) +
  1190. (this[offset + 3] * 0x1000000)
  1191. }
  1192. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1193. if (!noAssert) checkOffset(offset, 4, this.length)
  1194. return (this[offset] * 0x1000000) +
  1195. ((this[offset + 1] << 16) |
  1196. (this[offset + 2] << 8) |
  1197. this[offset + 3])
  1198. }
  1199. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1200. offset = offset | 0
  1201. byteLength = byteLength | 0
  1202. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1203. var val = this[offset]
  1204. var mul = 1
  1205. var i = 0
  1206. while (++i < byteLength && (mul *= 0x100)) {
  1207. val += this[offset + i] * mul
  1208. }
  1209. mul *= 0x80
  1210. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1211. return val
  1212. }
  1213. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1214. offset = offset | 0
  1215. byteLength = byteLength | 0
  1216. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1217. var i = byteLength
  1218. var mul = 1
  1219. var val = this[offset + --i]
  1220. while (i > 0 && (mul *= 0x100)) {
  1221. val += this[offset + --i] * mul
  1222. }
  1223. mul *= 0x80
  1224. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1225. return val
  1226. }
  1227. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1228. if (!noAssert) checkOffset(offset, 1, this.length)
  1229. if (!(this[offset] & 0x80)) return (this[offset])
  1230. return ((0xff - this[offset] + 1) * -1)
  1231. }
  1232. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1233. if (!noAssert) checkOffset(offset, 2, this.length)
  1234. var val = this[offset] | (this[offset + 1] << 8)
  1235. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1236. }
  1237. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1238. if (!noAssert) checkOffset(offset, 2, this.length)
  1239. var val = this[offset + 1] | (this[offset] << 8)
  1240. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1241. }
  1242. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1243. if (!noAssert) checkOffset(offset, 4, this.length)
  1244. return (this[offset]) |
  1245. (this[offset + 1] << 8) |
  1246. (this[offset + 2] << 16) |
  1247. (this[offset + 3] << 24)
  1248. }
  1249. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1250. if (!noAssert) checkOffset(offset, 4, this.length)
  1251. return (this[offset] << 24) |
  1252. (this[offset + 1] << 16) |
  1253. (this[offset + 2] << 8) |
  1254. (this[offset + 3])
  1255. }
  1256. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1257. if (!noAssert) checkOffset(offset, 4, this.length)
  1258. return ieee754.read(this, offset, true, 23, 4)
  1259. }
  1260. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1261. if (!noAssert) checkOffset(offset, 4, this.length)
  1262. return ieee754.read(this, offset, false, 23, 4)
  1263. }
  1264. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1265. if (!noAssert) checkOffset(offset, 8, this.length)
  1266. return ieee754.read(this, offset, true, 52, 8)
  1267. }
  1268. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1269. if (!noAssert) checkOffset(offset, 8, this.length)
  1270. return ieee754.read(this, offset, false, 52, 8)
  1271. }
  1272. function checkInt (buf, value, offset, ext, max, min) {
  1273. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1274. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1275. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1276. }
  1277. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1278. value = +value
  1279. offset = offset | 0
  1280. byteLength = byteLength | 0
  1281. if (!noAssert) {
  1282. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1283. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1284. }
  1285. var mul = 1
  1286. var i = 0
  1287. this[offset] = value & 0xFF
  1288. while (++i < byteLength && (mul *= 0x100)) {
  1289. this[offset + i] = (value / mul) & 0xFF
  1290. }
  1291. return offset + byteLength
  1292. }
  1293. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1294. value = +value
  1295. offset = offset | 0
  1296. byteLength = byteLength | 0
  1297. if (!noAssert) {
  1298. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1299. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1300. }
  1301. var i = byteLength - 1
  1302. var mul = 1
  1303. this[offset + i] = value & 0xFF
  1304. while (--i >= 0 && (mul *= 0x100)) {
  1305. this[offset + i] = (value / mul) & 0xFF
  1306. }
  1307. return offset + byteLength
  1308. }
  1309. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1310. value = +value
  1311. offset = offset | 0
  1312. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1313. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1314. this[offset] = (value & 0xff)
  1315. return offset + 1
  1316. }
  1317. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1318. if (value < 0) value = 0xffff + value + 1
  1319. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1320. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1321. (littleEndian ? i : 1 - i) * 8
  1322. }
  1323. }
  1324. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1325. value = +value
  1326. offset = offset | 0
  1327. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1328. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1329. this[offset] = (value & 0xff)
  1330. this[offset + 1] = (value >>> 8)
  1331. } else {
  1332. objectWriteUInt16(this, value, offset, true)
  1333. }
  1334. return offset + 2
  1335. }
  1336. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1337. value = +value
  1338. offset = offset | 0
  1339. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1340. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1341. this[offset] = (value >>> 8)
  1342. this[offset + 1] = (value & 0xff)
  1343. } else {
  1344. objectWriteUInt16(this, value, offset, false)
  1345. }
  1346. return offset + 2
  1347. }
  1348. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1349. if (value < 0) value = 0xffffffff + value + 1
  1350. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1351. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1352. }
  1353. }
  1354. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1355. value = +value
  1356. offset = offset | 0
  1357. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1358. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1359. this[offset + 3] = (value >>> 24)
  1360. this[offset + 2] = (value >>> 16)
  1361. this[offset + 1] = (value >>> 8)
  1362. this[offset] = (value & 0xff)
  1363. } else {
  1364. objectWriteUInt32(this, value, offset, true)
  1365. }
  1366. return offset + 4
  1367. }
  1368. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1369. value = +value
  1370. offset = offset | 0
  1371. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1372. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1373. this[offset] = (value >>> 24)
  1374. this[offset + 1] = (value >>> 16)
  1375. this[offset + 2] = (value >>> 8)
  1376. this[offset + 3] = (value & 0xff)
  1377. } else {
  1378. objectWriteUInt32(this, value, offset, false)
  1379. }
  1380. return offset + 4
  1381. }
  1382. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1383. value = +value
  1384. offset = offset | 0
  1385. if (!noAssert) {
  1386. var limit = Math.pow(2, 8 * byteLength - 1)
  1387. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1388. }
  1389. var i = 0
  1390. var mul = 1
  1391. var sub = 0
  1392. this[offset] = value & 0xFF
  1393. while (++i < byteLength && (mul *= 0x100)) {
  1394. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1395. sub = 1
  1396. }
  1397. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1398. }
  1399. return offset + byteLength
  1400. }
  1401. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1402. value = +value
  1403. offset = offset | 0
  1404. if (!noAssert) {
  1405. var limit = Math.pow(2, 8 * byteLength - 1)
  1406. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1407. }
  1408. var i = byteLength - 1
  1409. var mul = 1
  1410. var sub = 0
  1411. this[offset + i] = value & 0xFF
  1412. while (--i >= 0 && (mul *= 0x100)) {
  1413. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1414. sub = 1
  1415. }
  1416. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1417. }
  1418. return offset + byteLength
  1419. }
  1420. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1421. value = +value
  1422. offset = offset | 0
  1423. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1424. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1425. if (value < 0) value = 0xff + value + 1
  1426. this[offset] = (value & 0xff)
  1427. return offset + 1
  1428. }
  1429. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1430. value = +value
  1431. offset = offset | 0
  1432. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1433. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1434. this[offset] = (value & 0xff)
  1435. this[offset + 1] = (value >>> 8)
  1436. } else {
  1437. objectWriteUInt16(this, value, offset, true)
  1438. }
  1439. return offset + 2
  1440. }
  1441. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1442. value = +value
  1443. offset = offset | 0
  1444. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1445. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1446. this[offset] = (value >>> 8)
  1447. this[offset + 1] = (value & 0xff)
  1448. } else {
  1449. objectWriteUInt16(this, value, offset, false)
  1450. }
  1451. return offset + 2
  1452. }
  1453. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1454. value = +value
  1455. offset = offset | 0
  1456. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1457. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1458. this[offset] = (value & 0xff)
  1459. this[offset + 1] = (value >>> 8)
  1460. this[offset + 2] = (value >>> 16)
  1461. this[offset + 3] = (value >>> 24)
  1462. } else {
  1463. objectWriteUInt32(this, value, offset, true)
  1464. }
  1465. return offset + 4
  1466. }
  1467. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1468. value = +value
  1469. offset = offset | 0
  1470. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1471. if (value < 0) value = 0xffffffff + value + 1
  1472. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1473. this[offset] = (value >>> 24)
  1474. this[offset + 1] = (value >>> 16)
  1475. this[offset + 2] = (value >>> 8)
  1476. this[offset + 3] = (value & 0xff)
  1477. } else {
  1478. objectWriteUInt32(this, value, offset, false)
  1479. }
  1480. return offset + 4
  1481. }
  1482. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1483. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1484. if (offset < 0) throw new RangeError('Index out of range')
  1485. }
  1486. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1487. if (!noAssert) {
  1488. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1489. }
  1490. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1491. return offset + 4
  1492. }
  1493. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1494. return writeFloat(this, value, offset, true, noAssert)
  1495. }
  1496. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1497. return writeFloat(this, value, offset, false, noAssert)
  1498. }
  1499. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1500. if (!noAssert) {
  1501. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1502. }
  1503. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1504. return offset + 8
  1505. }
  1506. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1507. return writeDouble(this, value, offset, true, noAssert)
  1508. }
  1509. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1510. return writeDouble(this, value, offset, false, noAssert)
  1511. }
  1512. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1513. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1514. if (!start) start = 0
  1515. if (!end && end !== 0) end = this.length
  1516. if (targetStart >= target.length) targetStart = target.length
  1517. if (!targetStart) targetStart = 0
  1518. if (end > 0 && end < start) end = start
  1519. // Copy 0 bytes; we're done
  1520. if (end === start) return 0
  1521. if (target.length === 0 || this.length === 0) return 0
  1522. // Fatal error conditions
  1523. if (targetStart < 0) {
  1524. throw new RangeError('targetStart out of bounds')
  1525. }
  1526. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1527. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1528. // Are we oob?
  1529. if (end > this.length) end = this.length
  1530. if (target.length - targetStart < end - start) {
  1531. end = target.length - targetStart + start
  1532. }
  1533. var len = end - start
  1534. var i
  1535. if (this === target && start < targetStart && targetStart < end) {
  1536. // descending copy from end
  1537. for (i = len - 1; i >= 0; --i) {
  1538. target[i + targetStart] = this[i + start]
  1539. }
  1540. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1541. // ascending copy from start
  1542. for (i = 0; i < len; ++i) {
  1543. target[i + targetStart] = this[i + start]
  1544. }
  1545. } else {
  1546. Uint8Array.prototype.set.call(
  1547. target,
  1548. this.subarray(start, start + len),
  1549. targetStart
  1550. )
  1551. }
  1552. return len
  1553. }
  1554. // Usage:
  1555. // buffer.fill(number[, offset[, end]])
  1556. // buffer.fill(buffer[, offset[, end]])
  1557. // buffer.fill(string[, offset[, end]][, encoding])
  1558. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1559. // Handle string cases:
  1560. if (typeof val === 'string') {
  1561. if (typeof start === 'string') {
  1562. encoding = start
  1563. start = 0
  1564. end = this.length
  1565. } else if (typeof end === 'string') {
  1566. encoding = end
  1567. end = this.length
  1568. }
  1569. if (val.length === 1) {
  1570. var code = val.charCodeAt(0)
  1571. if (code < 256) {
  1572. val = code
  1573. }
  1574. }
  1575. if (encoding !== undefined && typeof encoding !== 'string') {
  1576. throw new TypeError('encoding must be a string')
  1577. }
  1578. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1579. throw new TypeError('Unknown encoding: ' + encoding)
  1580. }
  1581. } else if (typeof val === 'number') {
  1582. val = val & 255
  1583. }
  1584. // Invalid ranges are not set to a default, so can range check early.
  1585. if (start < 0 || this.length < start || this.length < end) {
  1586. throw new RangeError('Out of range index')
  1587. }
  1588. if (end <= start) {
  1589. return this
  1590. }
  1591. start = start >>> 0
  1592. end = end === undefined ? this.length : end >>> 0
  1593. if (!val) val = 0
  1594. var i
  1595. if (typeof val === 'number') {
  1596. for (i = start; i < end; ++i) {
  1597. this[i] = val
  1598. }
  1599. } else {
  1600. var bytes = Buffer.isBuffer(val)
  1601. ? val
  1602. : utf8ToBytes(new Buffer(val, encoding).toString())
  1603. var len = bytes.length
  1604. for (i = 0; i < end - start; ++i) {
  1605. this[i + start] = bytes[i % len]
  1606. }
  1607. }
  1608. return this
  1609. }
  1610. // HELPER FUNCTIONS
  1611. // ================
  1612. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1613. function base64clean (str) {
  1614. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1615. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1616. // Node converts strings with length < 2 to ''
  1617. if (str.length < 2) return ''
  1618. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1619. while (str.length % 4 !== 0) {
  1620. str = str + '='
  1621. }
  1622. return str
  1623. }
  1624. function stringtrim (str) {
  1625. if (str.trim) return str.trim()
  1626. return str.replace(/^\s+|\s+$/g, '')
  1627. }
  1628. function toHex (n) {
  1629. if (n < 16) return '0' + n.toString(16)
  1630. return n.toString(16)
  1631. }
  1632. function utf8ToBytes (string, units) {
  1633. units = units || Infinity
  1634. var codePoint
  1635. var length = string.length
  1636. var leadSurrogate = null
  1637. var bytes = []
  1638. for (var i = 0; i < length; ++i) {
  1639. codePoint = string.charCodeAt(i)
  1640. // is surrogate component
  1641. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1642. // last char was a lead
  1643. if (!leadSurrogate) {
  1644. // no lead yet
  1645. if (codePoint > 0xDBFF) {
  1646. // unexpected trail
  1647. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1648. continue
  1649. } else if (i + 1 === length) {
  1650. // unpaired lead
  1651. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1652. continue
  1653. }
  1654. // valid lead
  1655. leadSurrogate = codePoint
  1656. continue
  1657. }
  1658. // 2 leads in a row
  1659. if (codePoint < 0xDC00) {
  1660. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1661. leadSurrogate = codePoint
  1662. continue
  1663. }
  1664. // valid surrogate pair
  1665. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1666. } else if (leadSurrogate) {
  1667. // valid bmp char, but last char was a lead
  1668. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1669. }
  1670. leadSurrogate = null
  1671. // encode utf8
  1672. if (codePoint < 0x80) {
  1673. if ((units -= 1) < 0) break
  1674. bytes.push(codePoint)
  1675. } else if (codePoint < 0x800) {
  1676. if ((units -= 2) < 0) break
  1677. bytes.push(
  1678. codePoint >> 0x6 | 0xC0,
  1679. codePoint & 0x3F | 0x80
  1680. )
  1681. } else if (codePoint < 0x10000) {
  1682. if ((units -= 3) < 0) break
  1683. bytes.push(
  1684. codePoint >> 0xC | 0xE0,
  1685. codePoint >> 0x6 & 0x3F | 0x80,
  1686. codePoint & 0x3F | 0x80
  1687. )
  1688. } else if (codePoint < 0x110000) {
  1689. if ((units -= 4) < 0) break
  1690. bytes.push(
  1691. codePoint >> 0x12 | 0xF0,
  1692. codePoint >> 0xC & 0x3F | 0x80,
  1693. codePoint >> 0x6 & 0x3F | 0x80,
  1694. codePoint & 0x3F | 0x80
  1695. )
  1696. } else {
  1697. throw new Error('Invalid code point')
  1698. }
  1699. }
  1700. return bytes
  1701. }
  1702. function asciiToBytes (str) {
  1703. var byteArray = []
  1704. for (var i = 0; i < str.length; ++i) {
  1705. // Node's code seems to be doing this and not & 0x7F..
  1706. byteArray.push(str.charCodeAt(i) & 0xFF)
  1707. }
  1708. return byteArray
  1709. }
  1710. function utf16leToBytes (str, units) {
  1711. var c, hi, lo
  1712. var byteArray = []
  1713. for (var i = 0; i < str.length; ++i) {
  1714. if ((units -= 2) < 0) break
  1715. c = str.charCodeAt(i)
  1716. hi = c >> 8
  1717. lo = c % 256
  1718. byteArray.push(lo)
  1719. byteArray.push(hi)
  1720. }
  1721. return byteArray
  1722. }
  1723. function base64ToBytes (str) {
  1724. return base64.toByteArray(base64clean(str))
  1725. }
  1726. function blitBuffer (src, dst, offset, length) {
  1727. for (var i = 0; i < length; ++i) {
  1728. if ((i + offset >= dst.length) || (i >= src.length)) break
  1729. dst[i + offset] = src[i]
  1730. }
  1731. return i
  1732. }
  1733. function isnan (val) {
  1734. return val !== val // eslint-disable-line no-self-compare
  1735. }
  1736. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  1737. },{"base64-js":3,"buffer":6,"ieee754":29,"isarray":35}],7:[function(_dereq_,module,exports){
  1738. // Polyfill for creating CustomEvents on IE9/10/11
  1739. // code pulled from:
  1740. // https://github.com/d4tocchini/customevent-polyfill
  1741. // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
  1742. (function() {
  1743. if (typeof window === 'undefined') {
  1744. return;
  1745. }
  1746. try {
  1747. var ce = new window.CustomEvent('test', { cancelable: true });
  1748. ce.preventDefault();
  1749. if (ce.defaultPrevented !== true) {
  1750. // IE has problems with .preventDefault() on custom events
  1751. // http://stackoverflow.com/questions/23349191
  1752. throw new Error('Could not prevent default');
  1753. }
  1754. } catch (e) {
  1755. var CustomEvent = function(event, params) {
  1756. var evt, origPrevent;
  1757. params = params || {};
  1758. params.bubbles = !!params.bubbles;
  1759. params.cancelable = !!params.cancelable;
  1760. evt = document.createEvent('CustomEvent');
  1761. evt.initCustomEvent(
  1762. event,
  1763. params.bubbles,
  1764. params.cancelable,
  1765. params.detail
  1766. );
  1767. origPrevent = evt.preventDefault;
  1768. evt.preventDefault = function() {
  1769. origPrevent.call(this);
  1770. try {
  1771. Object.defineProperty(this, 'defaultPrevented', {
  1772. get: function() {
  1773. return true;
  1774. }
  1775. });
  1776. } catch (e) {
  1777. this.defaultPrevented = true;
  1778. }
  1779. };
  1780. return evt;
  1781. };
  1782. CustomEvent.prototype = window.Event.prototype;
  1783. window.CustomEvent = CustomEvent; // expose definition to window
  1784. }
  1785. })();
  1786. },{}],8:[function(_dereq_,module,exports){
  1787. /**
  1788. * This is the web browser implementation of `debug()`.
  1789. *
  1790. * Expose `debug()` as the module.
  1791. */
  1792. exports = module.exports = _dereq_('./debug');
  1793. exports.log = log;
  1794. exports.formatArgs = formatArgs;
  1795. exports.save = save;
  1796. exports.load = load;
  1797. exports.useColors = useColors;
  1798. exports.storage = 'undefined' != typeof chrome
  1799. && 'undefined' != typeof chrome.storage
  1800. ? chrome.storage.local
  1801. : localstorage();
  1802. /**
  1803. * Colors.
  1804. */
  1805. exports.colors = [
  1806. 'lightseagreen',
  1807. 'forestgreen',
  1808. 'goldenrod',
  1809. 'dodgerblue',
  1810. 'darkorchid',
  1811. 'crimson'
  1812. ];
  1813. /**
  1814. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1815. * and the Firebug extension (any Firefox version) are known
  1816. * to support "%c" CSS customizations.
  1817. *
  1818. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1819. */
  1820. function useColors() {
  1821. // is webkit? http://stackoverflow.com/a/16459606/376773
  1822. return ('WebkitAppearance' in document.documentElement.style) ||
  1823. // is firebug? http://stackoverflow.com/a/398120/376773
  1824. (window.console && (console.firebug || (console.exception && console.table))) ||
  1825. // is firefox >= v31?
  1826. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1827. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1828. }
  1829. /**
  1830. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1831. */
  1832. exports.formatters.j = function(v) {
  1833. return JSON.stringify(v);
  1834. };
  1835. /**
  1836. * Colorize log arguments if enabled.
  1837. *
  1838. * @api public
  1839. */
  1840. function formatArgs() {
  1841. var args = arguments;
  1842. var useColors = this.useColors;
  1843. args[0] = (useColors ? '%c' : '')
  1844. + this.namespace
  1845. + (useColors ? ' %c' : ' ')
  1846. + args[0]
  1847. + (useColors ? '%c ' : ' ');
  1848. if (!useColors) return args;
  1849. var c = 'color: ' + this.color;
  1850. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1851. // the final "%c" is somewhat tricky, because there could be other
  1852. // arguments passed either before or after the %c, so we need to
  1853. // figure out the correct index to insert the CSS into
  1854. var index = 0;
  1855. var lastC = 0;
  1856. args[0].replace(/%[a-z%]/g, function(match) {
  1857. if ('%%' === match) return;
  1858. index++;
  1859. if ('%c' === match) {
  1860. // we only are interested in the *last* %c
  1861. // (the user may have provided their own)
  1862. lastC = index;
  1863. }
  1864. });
  1865. args.splice(lastC, 0, c);
  1866. return args;
  1867. }
  1868. /**
  1869. * Invokes `console.log()` when available.
  1870. * No-op when `console.log` is not a "function".
  1871. *
  1872. * @api public
  1873. */
  1874. function log() {
  1875. // this hackery is required for IE8/9, where
  1876. // the `console.log` function doesn't have 'apply'
  1877. return 'object' === typeof console
  1878. && console.log
  1879. && Function.prototype.apply.call(console.log, console, arguments);
  1880. }
  1881. /**
  1882. * Save `namespaces`.
  1883. *
  1884. * @param {String} namespaces
  1885. * @api private
  1886. */
  1887. function save(namespaces) {
  1888. try {
  1889. if (null == namespaces) {
  1890. exports.storage.removeItem('debug');
  1891. } else {
  1892. exports.storage.debug = namespaces;
  1893. }
  1894. } catch(e) {}
  1895. }
  1896. /**
  1897. * Load `namespaces`.
  1898. *
  1899. * @return {String} returns the previously persisted debug modes
  1900. * @api private
  1901. */
  1902. function load() {
  1903. var r;
  1904. try {
  1905. r = exports.storage.debug;
  1906. } catch(e) {}
  1907. return r;
  1908. }
  1909. /**
  1910. * Enable namespaces listed in `localStorage.debug` initially.
  1911. */
  1912. exports.enable(load());
  1913. /**
  1914. * Localstorage attempts to return the localstorage.
  1915. *
  1916. * This is necessary because safari throws
  1917. * when a user disables cookies/localstorage
  1918. * and you attempt to access it.
  1919. *
  1920. * @return {LocalStorage}
  1921. * @api private
  1922. */
  1923. function localstorage(){
  1924. try {
  1925. return window.localStorage;
  1926. } catch (e) {}
  1927. }
  1928. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1929. /**
  1930. * This is the common logic for both the Node.js and web browser
  1931. * implementations of `debug()`.
  1932. *
  1933. * Expose `debug()` as the module.
  1934. */
  1935. exports = module.exports = debug;
  1936. exports.coerce = coerce;
  1937. exports.disable = disable;
  1938. exports.enable = enable;
  1939. exports.enabled = enabled;
  1940. /**
  1941. * The currently active debug mode names, and names to skip.
  1942. */
  1943. exports.names = [];
  1944. exports.skips = [];
  1945. /**
  1946. * Map of special "%n" handling functions, for the debug "format" argument.
  1947. *
  1948. * Valid key names are a single, lowercased letter, i.e. "n".
  1949. */
  1950. exports.formatters = {};
  1951. /**
  1952. * Previously assigned color.
  1953. */
  1954. var prevColor = 0;
  1955. /**
  1956. * Select a color.
  1957. *
  1958. * @return {Number}
  1959. * @api private
  1960. */
  1961. function selectColor() {
  1962. return exports.colors[prevColor++ % exports.colors.length];
  1963. }
  1964. /**
  1965. * Create a debugger with the given `namespace`.
  1966. *
  1967. * @param {String} namespace
  1968. * @return {Function}
  1969. * @api public
  1970. */
  1971. function debug(namespace) {
  1972. // define the `disabled` version
  1973. function disabled() {
  1974. }
  1975. disabled.enabled = false;
  1976. // define the `enabled` version
  1977. function enabled() {
  1978. var self = enabled;
  1979. // add the `color` if not set
  1980. if (null == self.useColors) self.useColors = exports.useColors();
  1981. if (null == self.color && self.useColors) self.color = selectColor();
  1982. var args = Array.prototype.slice.call(arguments);
  1983. args[0] = exports.coerce(args[0]);
  1984. if ('string' !== typeof args[0]) {
  1985. // anything else let's inspect with %o
  1986. args = ['%o'].concat(args);
  1987. }
  1988. // apply any `formatters` transformations
  1989. var index = 0;
  1990. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1991. // if we encounter an escaped % then don't increase the array index
  1992. if (match === '%%') return match;
  1993. index++;
  1994. var formatter = exports.formatters[format];
  1995. if ('function' === typeof formatter) {
  1996. var val = args[index];
  1997. match = formatter.call(self, val);
  1998. // now we need to remove `args[index]` since it's inlined in the `format`
  1999. args.splice(index, 1);
  2000. index--;
  2001. }
  2002. return match;
  2003. });
  2004. if ('function' === typeof exports.formatArgs) {
  2005. args = exports.formatArgs.apply(self, args);
  2006. }
  2007. var logFn = enabled.log || exports.log || console.log.bind(console);
  2008. logFn.apply(self, args);
  2009. }
  2010. enabled.enabled = true;
  2011. var fn = exports.enabled(namespace) ? enabled : disabled;
  2012. fn.namespace = namespace;
  2013. return fn;
  2014. }
  2015. /**
  2016. * Enables a debug mode by namespaces. This can include modes
  2017. * separated by a colon and wildcards.
  2018. *
  2019. * @param {String} namespaces
  2020. * @api public
  2021. */
  2022. function enable(namespaces) {
  2023. exports.save(namespaces);
  2024. var split = (namespaces || '').split(/[\s,]+/);
  2025. var len = split.length;
  2026. for (var i = 0; i < len; i++) {
  2027. if (!split[i]) continue; // ignore empty strings
  2028. namespaces = split[i].replace(/\*/g, '.*?');
  2029. if (namespaces[0] === '-') {
  2030. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2031. } else {
  2032. exports.names.push(new RegExp('^' + namespaces + '$'));
  2033. }
  2034. }
  2035. }
  2036. /**
  2037. * Disable debug output.
  2038. *
  2039. * @api public
  2040. */
  2041. function disable() {
  2042. exports.enable('');
  2043. }
  2044. /**
  2045. * Returns true if the given mode name is enabled, false otherwise.
  2046. *
  2047. * @param {String} name
  2048. * @return {Boolean}
  2049. * @api public
  2050. */
  2051. function enabled(name) {
  2052. var i, len;
  2053. for (i = 0, len = exports.skips.length; i < len; i++) {
  2054. if (exports.skips[i].test(name)) {
  2055. return false;
  2056. }
  2057. }
  2058. for (i = 0, len = exports.names.length; i < len; i++) {
  2059. if (exports.names[i].test(name)) {
  2060. return true;
  2061. }
  2062. }
  2063. return false;
  2064. }
  2065. /**
  2066. * Coerce `val`.
  2067. *
  2068. * @param {Mixed} val
  2069. * @return {Mixed}
  2070. * @api private
  2071. */
  2072. function coerce(val) {
  2073. if (val instanceof Error) return val.stack || val.message;
  2074. return val;
  2075. }
  2076. },{}],10:[function(_dereq_,module,exports){
  2077. 'use strict';
  2078. var isObj = _dereq_('is-obj');
  2079. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2080. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2081. function toObject(val) {
  2082. if (val === null || val === undefined) {
  2083. throw new TypeError('Sources cannot be null or undefined');
  2084. }
  2085. return Object(val);
  2086. }
  2087. function assignKey(to, from, key) {
  2088. var val = from[key];
  2089. if (val === undefined || val === null) {
  2090. return;
  2091. }
  2092. if (hasOwnProperty.call(to, key)) {
  2093. if (to[key] === undefined || to[key] === null) {
  2094. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2095. }
  2096. }
  2097. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2098. to[key] = val;
  2099. } else {
  2100. to[key] = assign(Object(to[key]), from[key]);
  2101. }
  2102. }
  2103. function assign(to, from) {
  2104. if (to === from) {
  2105. return to;
  2106. }
  2107. from = Object(from);
  2108. for (var key in from) {
  2109. if (hasOwnProperty.call(from, key)) {
  2110. assignKey(to, from, key);
  2111. }
  2112. }
  2113. if (Object.getOwnPropertySymbols) {
  2114. var symbols = Object.getOwnPropertySymbols(from);
  2115. for (var i = 0; i < symbols.length; i++) {
  2116. if (propIsEnumerable.call(from, symbols[i])) {
  2117. assignKey(to, from, symbols[i]);
  2118. }
  2119. }
  2120. }
  2121. return to;
  2122. }
  2123. module.exports = function deepAssign(target) {
  2124. target = toObject(target);
  2125. for (var s = 1; s < arguments.length; s++) {
  2126. assign(target, arguments[s]);
  2127. }
  2128. return target;
  2129. };
  2130. },{"is-obj":34}],11:[function(_dereq_,module,exports){
  2131. 'use strict';
  2132. var keys = _dereq_('object-keys');
  2133. var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
  2134. var toStr = Object.prototype.toString;
  2135. var concat = Array.prototype.concat;
  2136. var origDefineProperty = Object.defineProperty;
  2137. var isFunction = function (fn) {
  2138. return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
  2139. };
  2140. var arePropertyDescriptorsSupported = function () {
  2141. var obj = {};
  2142. try {
  2143. origDefineProperty(obj, 'x', { enumerable: false, value: obj });
  2144. // eslint-disable-next-line no-unused-vars, no-restricted-syntax
  2145. for (var _ in obj) { // jscs:ignore disallowUnusedVariables
  2146. return false;
  2147. }
  2148. return obj.x === obj;
  2149. } catch (e) { /* this is IE 8. */
  2150. return false;
  2151. }
  2152. };
  2153. var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
  2154. var defineProperty = function (object, name, value, predicate) {
  2155. if (name in object && (!isFunction(predicate) || !predicate())) {
  2156. return;
  2157. }
  2158. if (supportsDescriptors) {
  2159. origDefineProperty(object, name, {
  2160. configurable: true,
  2161. enumerable: false,
  2162. value: value,
  2163. writable: true
  2164. });
  2165. } else {
  2166. object[name] = value;
  2167. }
  2168. };
  2169. var defineProperties = function (object, map) {
  2170. var predicates = arguments.length > 2 ? arguments[2] : {};
  2171. var props = keys(map);
  2172. if (hasSymbols) {
  2173. props = concat.call(props, Object.getOwnPropertySymbols(map));
  2174. }
  2175. for (var i = 0; i < props.length; i += 1) {
  2176. defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
  2177. }
  2178. };
  2179. defineProperties.supportsDescriptors = !!supportsDescriptors;
  2180. module.exports = defineProperties;
  2181. },{"object-keys":41}],12:[function(_dereq_,module,exports){
  2182. /*! (C) WebReflection Mit Style License */
  2183. (function(t,n,r,i){"use strict";function st(e,t){for(var n=0,r=e.length;n<r;n++)gt(e[n],t)}function ot(e){for(var t=0,n=e.length,r;t<n;t++)r=e[t],it(r,w[at(r)])}function ut(e){return function(t){F(t)&&(gt(t,e),st(t.querySelectorAll(E),e))}}function at(e){var t=R.call(e,"is"),n=e.nodeName.toUpperCase(),r=x.call(b,t?m+t.toUpperCase():v+n);return t&&-1<r&&!ft(n,t)?-1:r}function ft(e,t){return-1<E.indexOf(e+'[is="'+t+'"]')}function lt(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,i=e.target;Y&&(!i||i===t)&&t.attributeChangedCallback&&r!=="style"&&e.prevValue!==e.newValue&&t.attributeChangedCallback(r,n===e[f]?null:e.prevValue,n===e[c]?null:e.newValue)}function ct(e){var t=ut(e);return function(e){$.push(t,e.target)}}function ht(e){G&&(G=!1,e.currentTarget.removeEventListener(p,ht)),st((e.target||n).querySelectorAll(E),e.detail===u?u:o),j&&vt()}function pt(e,t){var n=this;U.call(n,e,t),Z.call(n,{target:n})}function dt(e,t){P(e,t),nt?nt.observe(e,X):(Q&&(e.setAttribute=pt,e[s]=tt(e),e.addEventListener(d,Z)),e.addEventListener(h,lt)),e.createdCallback&&Y&&(e.created=!0,e.createdCallback(),e.created=!1)}function vt(){for(var e,t=0,n=I.length;t<n;t++)e=I[t],S.contains(e)||(n--,I.splice(t--,1),gt(e,u))}function mt(e){throw new Error("A "+e+" type is already registered")}function gt(e,t){var n,r=at(e);-1<r&&(rt(e,w[r]),r=0,t===o&&!e[o]?(e[u]=!1,e[o]=!0,r=1,j&&x.call(I,e)<0&&I.push(e)):t===u&&!e[u]&&(e[o]=!1,e[u]=!0,r=1),r&&(n=e[t+"Callback"])&&n.call(e))}if(i in n)return;var s="__"+i+(Math.random()*1e5>>0),o="attached",u="detached",a="extends",f="ADDITION",l="MODIFICATION",c="REMOVAL",h="DOMAttrModified",p="DOMContentLoaded",d="DOMSubtreeModified",v="<",m="=",g=/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/,y=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],b=[],w=[],E="",S=n.documentElement,x=b.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},T=r.prototype,N=T.hasOwnProperty,C=T.isPrototypeOf,k=r.defineProperty,L=r.getOwnPropertyDescriptor,A=r.getOwnPropertyNames,O=r.getPrototypeOf,M=r.setPrototypeOf,_=!!r.__proto__,D=r.create||function yt(e){return e?(yt.prototype=e,new yt):this},P=M||(_?function(e,t){return e.__proto__=t,e}:A&&L?function(){function e(e,t){for(var n,r=A(t),i=0,s=r.length;i<s;i++)n=r[i],N.call(e,n)||k(e,n,L(t,n))}return function(t,n){do e(t,n);while((n=O(n))&&!C.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),H=t.MutationObserver||t.WebKitMutationObserver,B=(t.HTMLElement||t.Element||t.Node).prototype,j=!C.call(B,S),F=j?function(e){return e.nodeType===1}:function(e){return C.call(B,e)},I=j&&[],q=B.cloneNode,R=B.getAttribute,U=B.setAttribute,z=B.removeAttribute,W=n.createElement,X=H&&{attributes:!0,characterData:!0,attributeOldValue:!0},V=H||function(e){Q=!1,S.removeEventListener(h,V)},$,J=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,10)},K=!1,Q=!0,G=!0,Y=!0,Z,et,tt,nt,rt,it;M||_?(rt=function(e,t){C.call(t,e)||dt(e,t)},it=dt):(rt=function(e,t){e[s]||(e[s]=r(!0),dt(e,t))},it=rt),j?(Q=!1,function(){var t=L(B,"addEventListener"),n=t.value,r=function(e){var t=new CustomEvent(h,{bubbles:!0});t.attrName=e,t.prevValue=R.call(this,e),t.newValue=null,t[c]=t.attrChange=2,z.call(this,e),this.dispatchEvent(t)},i=function(t,n){var r=this.hasAttribute(t),i=r&&R.call(this,t);e=new CustomEvent(h,{bubbles:!0}),U.call(this,t,n),e.attrName=t,e.prevValue=r?i:null,e.newValue=n,r?e[l]=e.attrChange=1:e[f]=e.attrChange=0,this.dispatchEvent(e)},o=function(e){var t=e.currentTarget,n=t[s],r=e.propertyName,i;n.hasOwnProperty(r)&&(n=n[r],i=new CustomEvent(h,{bubbles:!0}),i.attrName=n.name,i.prevValue=n.value||null,i.newValue=n.value=t[r]||null,i.prevValue==null?i[f]=i.attrChange=0:i[l]=i.attrChange=1,t.dispatchEvent(i))};t.value=function(e,t,u){e===h&&this.attributeChangedCallback&&this.setAttribute!==i&&(this[s]={className:{name:"class",value:this.className}},this.setAttribute=i,this.removeAttribute=r,n.call(this,"propertychange",o)),n.call(this,e,t,u)},k(B,"addEventListener",t)}()):H||(S.addEventListener(h,V),S.setAttribute(s,1),S.removeAttribute(s),Q&&(Z=function(e){var t=this,n,r,i;if(t===e.target){n=t[s],t[s]=r=tt(t);for(i in r){if(!(i in n))return et(0,t,i,n[i],r[i],f);if(r[i]!==n[i])return et(1,t,i,n[i],r[i],l)}for(i in n)if(!(i in r))return et(2,t,i,n[i],r[i],c)}},et=function(e,t,n,r,i,s){var o={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:i};o[s]=e,lt(o)},tt=function(e){for(var t,n,r={},i=e.attributes,s=0,o=i.length;s<o;s++)t=i[s],n=t.name,n!=="setAttribute"&&(r[n]=t.value);return r})),n[i]=function(t,r){c=t.toUpperCase(),K||(K=!0,H?(nt=function(e,t){function n(e,t){for(var n=0,r=e.length;n<r;t(e[n++]));}return new H(function(r){for(var i,s,o,u=0,a=r.length;u<a;u++)i=r[u],i.type==="childList"?(n(i.addedNodes,e),n(i.removedNodes,t)):(s=i.target,Y&&s.attributeChangedCallback&&i.attributeName!=="style"&&(o=R.call(s,i.attributeName),o!==i.oldValue&&s.attributeChangedCallback(i.attributeName,i.oldValue,o)))})}(ut(o),ut(u)),nt.observe(n,{childList:!0,subtree:!0})):($=[],J(function d(){while($.length)$.shift().call(null,$.shift());J(d)}),n.addEventListener("DOMNodeInserted",ct(o)),n.addEventListener("DOMNodeRemoved",ct(u))),n.addEventListener(p,ht),n.addEventListener("readystatechange",ht),n.createElement=function(e,t){var r=W.apply(n,arguments),i=""+e,s=x.call(b,(t?m:v)+(t||i).toUpperCase()),o=-1<s;return t&&(r.setAttribute("is",t=t.toLowerCase()),o&&(o=ft(i.toUpperCase(),t))),Y=!n.createElement.innerHTMLHelper,o&&it(r,w[s]),r},B.cloneNode=function(e){var t=q.call(this,!!e),n=at(t);return-1<n&&it(t,w[n]),e&&ot(t.querySelectorAll(E)),t}),-2<x.call(b,m+c)+x.call(b,v+c)&&mt(t);if(!g.test(c)||-1<x.call(y,c))throw new Error("The type "+t+" is invalid");var i=function(){return f?n.createElement(l,c):n.createElement(l)},s=r||T,f=N.call(s,a),l=f?r[a].toUpperCase():c,c,h;return f&&-1<x.call(b,v+l)&&mt(l),h=b.push((f?m:v)+c)-1,E=E.concat(E.length?",":"",f?l+'[is="'+t.toLowerCase()+'"]':l),i.prototype=w[h]=N.call(s,"prototype")?s.prototype:D(B),st(n.querySelectorAll(E),o),i}})(window,document,Object,"registerElement");
  2184. },{}],13:[function(_dereq_,module,exports){
  2185. module.exports = function(dtype) {
  2186. switch (dtype) {
  2187. case 'int8':
  2188. return Int8Array
  2189. case 'int16':
  2190. return Int16Array
  2191. case 'int32':
  2192. return Int32Array
  2193. case 'uint8':
  2194. return Uint8Array
  2195. case 'uint16':
  2196. return Uint16Array
  2197. case 'uint32':
  2198. return Uint32Array
  2199. case 'float32':
  2200. return Float32Array
  2201. case 'float64':
  2202. return Float64Array
  2203. case 'array':
  2204. return Array
  2205. case 'uint8_clamped':
  2206. return Uint8ClampedArray
  2207. }
  2208. }
  2209. },{}],14:[function(_dereq_,module,exports){
  2210. 'use strict';
  2211. /* globals
  2212. Set,
  2213. Map,
  2214. WeakSet,
  2215. WeakMap,
  2216. Promise,
  2217. Symbol,
  2218. Proxy,
  2219. Atomics,
  2220. SharedArrayBuffer,
  2221. ArrayBuffer,
  2222. DataView,
  2223. Uint8Array,
  2224. Float32Array,
  2225. Float64Array,
  2226. Int8Array,
  2227. Int16Array,
  2228. Int32Array,
  2229. Uint8ClampedArray,
  2230. Uint16Array,
  2231. Uint32Array,
  2232. */
  2233. var undefined; // eslint-disable-line no-shadow-restricted-names
  2234. var ThrowTypeError = Object.getOwnPropertyDescriptor
  2235. ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }())
  2236. : function () { throw new TypeError(); };
  2237. var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
  2238. var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
  2239. var generator; // = function * () {};
  2240. var generatorFunction = generator ? getProto(generator) : undefined;
  2241. var asyncFn; // async function() {};
  2242. var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
  2243. var asyncGen; // async function * () {};
  2244. var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
  2245. var asyncGenIterator = asyncGen ? asyncGen() : undefined;
  2246. var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
  2247. var INTRINSICS = {
  2248. '$ %Array%': Array,
  2249. '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
  2250. '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
  2251. '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
  2252. '$ %ArrayPrototype%': Array.prototype,
  2253. '$ %ArrayProto_entries%': Array.prototype.entries,
  2254. '$ %ArrayProto_forEach%': Array.prototype.forEach,
  2255. '$ %ArrayProto_keys%': Array.prototype.keys,
  2256. '$ %ArrayProto_values%': Array.prototype.values,
  2257. '$ %AsyncFromSyncIteratorPrototype%': undefined,
  2258. '$ %AsyncFunction%': asyncFunction,
  2259. '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
  2260. '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
  2261. '$ %AsyncGeneratorFunction%': asyncGenFunction,
  2262. '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
  2263. '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
  2264. '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
  2265. '$ %Boolean%': Boolean,
  2266. '$ %BooleanPrototype%': Boolean.prototype,
  2267. '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView,
  2268. '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,
  2269. '$ %Date%': Date,
  2270. '$ %DatePrototype%': Date.prototype,
  2271. '$ %decodeURI%': decodeURI,
  2272. '$ %decodeURIComponent%': decodeURIComponent,
  2273. '$ %encodeURI%': encodeURI,
  2274. '$ %encodeURIComponent%': encodeURIComponent,
  2275. '$ %Error%': Error,
  2276. '$ %ErrorPrototype%': Error.prototype,
  2277. '$ %eval%': eval, // eslint-disable-line no-eval
  2278. '$ %EvalError%': EvalError,
  2279. '$ %EvalErrorPrototype%': EvalError.prototype,
  2280. '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
  2281. '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
  2282. '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
  2283. '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
  2284. '$ %Function%': Function,
  2285. '$ %FunctionPrototype%': Function.prototype,
  2286. '$ %Generator%': generator ? getProto(generator()) : undefined,
  2287. '$ %GeneratorFunction%': generatorFunction,
  2288. '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
  2289. '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
  2290. '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
  2291. '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
  2292. '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
  2293. '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
  2294. '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
  2295. '$ %isFinite%': isFinite,
  2296. '$ %isNaN%': isNaN,
  2297. '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
  2298. '$ %JSON%': JSON,
  2299. '$ %JSONParse%': JSON.parse,
  2300. '$ %Map%': typeof Map === 'undefined' ? undefined : Map,
  2301. '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
  2302. '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,
  2303. '$ %Math%': Math,
  2304. '$ %Number%': Number,
  2305. '$ %NumberPrototype%': Number.prototype,
  2306. '$ %Object%': Object,
  2307. '$ %ObjectPrototype%': Object.prototype,
  2308. '$ %ObjProto_toString%': Object.prototype.toString,
  2309. '$ %ObjProto_valueOf%': Object.prototype.valueOf,
  2310. '$ %parseFloat%': parseFloat,
  2311. '$ %parseInt%': parseInt,
  2312. '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise,
  2313. '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
  2314. '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
  2315. '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
  2316. '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
  2317. '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
  2318. '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
  2319. '$ %RangeError%': RangeError,
  2320. '$ %RangeErrorPrototype%': RangeError.prototype,
  2321. '$ %ReferenceError%': ReferenceError,
  2322. '$ %ReferenceErrorPrototype%': ReferenceError.prototype,
  2323. '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
  2324. '$ %RegExp%': RegExp,
  2325. '$ %RegExpPrototype%': RegExp.prototype,
  2326. '$ %Set%': typeof Set === 'undefined' ? undefined : Set,
  2327. '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
  2328. '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
  2329. '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
  2330. '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
  2331. '$ %String%': String,
  2332. '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
  2333. '$ %StringPrototype%': String.prototype,
  2334. '$ %Symbol%': hasSymbols ? Symbol : undefined,
  2335. '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
  2336. '$ %SyntaxError%': SyntaxError,
  2337. '$ %SyntaxErrorPrototype%': SyntaxError.prototype,
  2338. '$ %ThrowTypeError%': ThrowTypeError,
  2339. '$ %TypedArray%': TypedArray,
  2340. '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
  2341. '$ %TypeError%': TypeError,
  2342. '$ %TypeErrorPrototype%': TypeError.prototype,
  2343. '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
  2344. '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
  2345. '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
  2346. '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
  2347. '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
  2348. '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
  2349. '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
  2350. '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
  2351. '$ %URIError%': URIError,
  2352. '$ %URIErrorPrototype%': URIError.prototype,
  2353. '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
  2354. '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
  2355. '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
  2356. '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
  2357. };
  2358. module.exports = function GetIntrinsic(name, allowMissing) {
  2359. if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
  2360. throw new TypeError('"allowMissing" argument must be a boolean');
  2361. }
  2362. var key = '$ ' + name;
  2363. if (!(key in INTRINSICS)) {
  2364. throw new SyntaxError('intrinsic ' + name + ' does not exist!');
  2365. }
  2366. // istanbul ignore if // hopefully this is impossible to test :-)
  2367. if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
  2368. throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
  2369. }
  2370. return INTRINSICS[key];
  2371. };
  2372. },{}],15:[function(_dereq_,module,exports){
  2373. 'use strict';
  2374. var GetIntrinsic = _dereq_('./GetIntrinsic');
  2375. var $Object = GetIntrinsic('%Object%');
  2376. var $TypeError = GetIntrinsic('%TypeError%');
  2377. var $String = GetIntrinsic('%String%');
  2378. var assertRecord = _dereq_('./helpers/assertRecord');
  2379. var $isNaN = _dereq_('./helpers/isNaN');
  2380. var $isFinite = _dereq_('./helpers/isFinite');
  2381. var sign = _dereq_('./helpers/sign');
  2382. var mod = _dereq_('./helpers/mod');
  2383. var IsCallable = _dereq_('is-callable');
  2384. var toPrimitive = _dereq_('es-to-primitive/es5');
  2385. var has = _dereq_('has');
  2386. // https://es5.github.io/#x9
  2387. var ES5 = {
  2388. ToPrimitive: toPrimitive,
  2389. ToBoolean: function ToBoolean(value) {
  2390. return !!value;
  2391. },
  2392. ToNumber: function ToNumber(value) {
  2393. return +value; // eslint-disable-line no-implicit-coercion
  2394. },
  2395. ToInteger: function ToInteger(value) {
  2396. var number = this.ToNumber(value);
  2397. if ($isNaN(number)) { return 0; }
  2398. if (number === 0 || !$isFinite(number)) { return number; }
  2399. return sign(number) * Math.floor(Math.abs(number));
  2400. },
  2401. ToInt32: function ToInt32(x) {
  2402. return this.ToNumber(x) >> 0;
  2403. },
  2404. ToUint32: function ToUint32(x) {
  2405. return this.ToNumber(x) >>> 0;
  2406. },
  2407. ToUint16: function ToUint16(value) {
  2408. var number = this.ToNumber(value);
  2409. if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
  2410. var posInt = sign(number) * Math.floor(Math.abs(number));
  2411. return mod(posInt, 0x10000);
  2412. },
  2413. ToString: function ToString(value) {
  2414. return $String(value);
  2415. },
  2416. ToObject: function ToObject(value) {
  2417. this.CheckObjectCoercible(value);
  2418. return $Object(value);
  2419. },
  2420. CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
  2421. /* jshint eqnull:true */
  2422. if (value == null) {
  2423. throw new $TypeError(optMessage || 'Cannot call method on ' + value);
  2424. }
  2425. return value;
  2426. },
  2427. IsCallable: IsCallable,
  2428. SameValue: function SameValue(x, y) {
  2429. if (x === y) { // 0 === -0, but they are not identical.
  2430. if (x === 0) { return 1 / x === 1 / y; }
  2431. return true;
  2432. }
  2433. return $isNaN(x) && $isNaN(y);
  2434. },
  2435. // https://www.ecma-international.org/ecma-262/5.1/#sec-8
  2436. Type: function Type(x) {
  2437. if (x === null) {
  2438. return 'Null';
  2439. }
  2440. if (typeof x === 'undefined') {
  2441. return 'Undefined';
  2442. }
  2443. if (typeof x === 'function' || typeof x === 'object') {
  2444. return 'Object';
  2445. }
  2446. if (typeof x === 'number') {
  2447. return 'Number';
  2448. }
  2449. if (typeof x === 'boolean') {
  2450. return 'Boolean';
  2451. }
  2452. if (typeof x === 'string') {
  2453. return 'String';
  2454. }
  2455. },
  2456. // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  2457. IsPropertyDescriptor: function IsPropertyDescriptor(Desc) {
  2458. if (this.Type(Desc) !== 'Object') {
  2459. return false;
  2460. }
  2461. var allowed = {
  2462. '[[Configurable]]': true,
  2463. '[[Enumerable]]': true,
  2464. '[[Get]]': true,
  2465. '[[Set]]': true,
  2466. '[[Value]]': true,
  2467. '[[Writable]]': true
  2468. };
  2469. for (var key in Desc) { // eslint-disable-line
  2470. if (has(Desc, key) && !allowed[key]) {
  2471. return false;
  2472. }
  2473. }
  2474. var isData = has(Desc, '[[Value]]');
  2475. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  2476. if (isData && IsAccessor) {
  2477. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  2478. }
  2479. return true;
  2480. },
  2481. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1
  2482. IsAccessorDescriptor: function IsAccessorDescriptor(Desc) {
  2483. if (typeof Desc === 'undefined') {
  2484. return false;
  2485. }
  2486. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2487. if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
  2488. return false;
  2489. }
  2490. return true;
  2491. },
  2492. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2
  2493. IsDataDescriptor: function IsDataDescriptor(Desc) {
  2494. if (typeof Desc === 'undefined') {
  2495. return false;
  2496. }
  2497. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2498. if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
  2499. return false;
  2500. }
  2501. return true;
  2502. },
  2503. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3
  2504. IsGenericDescriptor: function IsGenericDescriptor(Desc) {
  2505. if (typeof Desc === 'undefined') {
  2506. return false;
  2507. }
  2508. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2509. if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) {
  2510. return true;
  2511. }
  2512. return false;
  2513. },
  2514. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4
  2515. FromPropertyDescriptor: function FromPropertyDescriptor(Desc) {
  2516. if (typeof Desc === 'undefined') {
  2517. return Desc;
  2518. }
  2519. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2520. if (this.IsDataDescriptor(Desc)) {
  2521. return {
  2522. value: Desc['[[Value]]'],
  2523. writable: !!Desc['[[Writable]]'],
  2524. enumerable: !!Desc['[[Enumerable]]'],
  2525. configurable: !!Desc['[[Configurable]]']
  2526. };
  2527. } else if (this.IsAccessorDescriptor(Desc)) {
  2528. return {
  2529. get: Desc['[[Get]]'],
  2530. set: Desc['[[Set]]'],
  2531. enumerable: !!Desc['[[Enumerable]]'],
  2532. configurable: !!Desc['[[Configurable]]']
  2533. };
  2534. } else {
  2535. throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');
  2536. }
  2537. },
  2538. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5
  2539. ToPropertyDescriptor: function ToPropertyDescriptor(Obj) {
  2540. if (this.Type(Obj) !== 'Object') {
  2541. throw new $TypeError('ToPropertyDescriptor requires an object');
  2542. }
  2543. var desc = {};
  2544. if (has(Obj, 'enumerable')) {
  2545. desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable);
  2546. }
  2547. if (has(Obj, 'configurable')) {
  2548. desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable);
  2549. }
  2550. if (has(Obj, 'value')) {
  2551. desc['[[Value]]'] = Obj.value;
  2552. }
  2553. if (has(Obj, 'writable')) {
  2554. desc['[[Writable]]'] = this.ToBoolean(Obj.writable);
  2555. }
  2556. if (has(Obj, 'get')) {
  2557. var getter = Obj.get;
  2558. if (typeof getter !== 'undefined' && !this.IsCallable(getter)) {
  2559. throw new TypeError('getter must be a function');
  2560. }
  2561. desc['[[Get]]'] = getter;
  2562. }
  2563. if (has(Obj, 'set')) {
  2564. var setter = Obj.set;
  2565. if (typeof setter !== 'undefined' && !this.IsCallable(setter)) {
  2566. throw new $TypeError('setter must be a function');
  2567. }
  2568. desc['[[Set]]'] = setter;
  2569. }
  2570. if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
  2571. throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
  2572. }
  2573. return desc;
  2574. }
  2575. };
  2576. module.exports = ES5;
  2577. },{"./GetIntrinsic":14,"./helpers/assertRecord":16,"./helpers/isFinite":17,"./helpers/isNaN":18,"./helpers/mod":19,"./helpers/sign":20,"es-to-primitive/es5":21,"has":28,"is-callable":32}],16:[function(_dereq_,module,exports){
  2578. 'use strict';
  2579. var GetIntrinsic = _dereq_('../GetIntrinsic');
  2580. var $TypeError = GetIntrinsic('%TypeError%');
  2581. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  2582. var has = _dereq_('has');
  2583. var predicates = {
  2584. // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  2585. 'Property Descriptor': function isPropertyDescriptor(ES, Desc) {
  2586. if (ES.Type(Desc) !== 'Object') {
  2587. return false;
  2588. }
  2589. var allowed = {
  2590. '[[Configurable]]': true,
  2591. '[[Enumerable]]': true,
  2592. '[[Get]]': true,
  2593. '[[Set]]': true,
  2594. '[[Value]]': true,
  2595. '[[Writable]]': true
  2596. };
  2597. for (var key in Desc) { // eslint-disable-line
  2598. if (has(Desc, key) && !allowed[key]) {
  2599. return false;
  2600. }
  2601. }
  2602. var isData = has(Desc, '[[Value]]');
  2603. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  2604. if (isData && IsAccessor) {
  2605. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  2606. }
  2607. return true;
  2608. }
  2609. };
  2610. module.exports = function assertRecord(ES, recordType, argumentName, value) {
  2611. var predicate = predicates[recordType];
  2612. if (typeof predicate !== 'function') {
  2613. throw new $SyntaxError('unknown record type: ' + recordType);
  2614. }
  2615. if (!predicate(ES, value)) {
  2616. throw new $TypeError(argumentName + ' must be a ' + recordType);
  2617. }
  2618. console.log(predicate(ES, value), value);
  2619. };
  2620. },{"../GetIntrinsic":14,"has":28}],17:[function(_dereq_,module,exports){
  2621. var $isNaN = Number.isNaN || function (a) { return a !== a; };
  2622. module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
  2623. },{}],18:[function(_dereq_,module,exports){
  2624. module.exports = Number.isNaN || function isNaN(a) {
  2625. return a !== a;
  2626. };
  2627. },{}],19:[function(_dereq_,module,exports){
  2628. module.exports = function mod(number, modulo) {
  2629. var remain = number % modulo;
  2630. return Math.floor(remain >= 0 ? remain : remain + modulo);
  2631. };
  2632. },{}],20:[function(_dereq_,module,exports){
  2633. module.exports = function sign(number) {
  2634. return number >= 0 ? 1 : -1;
  2635. };
  2636. },{}],21:[function(_dereq_,module,exports){
  2637. 'use strict';
  2638. var toStr = Object.prototype.toString;
  2639. var isPrimitive = _dereq_('./helpers/isPrimitive');
  2640. var isCallable = _dereq_('is-callable');
  2641. // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
  2642. var ES5internalSlots = {
  2643. '[[DefaultValue]]': function (O) {
  2644. var actualHint;
  2645. if (arguments.length > 1) {
  2646. actualHint = arguments[1];
  2647. } else {
  2648. actualHint = toStr.call(O) === '[object Date]' ? String : Number;
  2649. }
  2650. if (actualHint === String || actualHint === Number) {
  2651. var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
  2652. var value, i;
  2653. for (i = 0; i < methods.length; ++i) {
  2654. if (isCallable(O[methods[i]])) {
  2655. value = O[methods[i]]();
  2656. if (isPrimitive(value)) {
  2657. return value;
  2658. }
  2659. }
  2660. }
  2661. throw new TypeError('No default value');
  2662. }
  2663. throw new TypeError('invalid [[DefaultValue]] hint supplied');
  2664. }
  2665. };
  2666. // http://ecma-international.org/ecma-262/5.1/#sec-9.1
  2667. module.exports = function ToPrimitive(input) {
  2668. if (isPrimitive(input)) {
  2669. return input;
  2670. }
  2671. if (arguments.length > 1) {
  2672. return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
  2673. }
  2674. return ES5internalSlots['[[DefaultValue]]'](input);
  2675. };
  2676. },{"./helpers/isPrimitive":22,"is-callable":32}],22:[function(_dereq_,module,exports){
  2677. module.exports = function isPrimitive(value) {
  2678. return value === null || (typeof value !== 'function' && typeof value !== 'object');
  2679. };
  2680. },{}],23:[function(_dereq_,module,exports){
  2681. /*eslint new-cap:0*/
  2682. var dtype = _dereq_('dtype')
  2683. module.exports = flattenVertexData
  2684. function flattenVertexData (data, output, offset) {
  2685. if (!data) throw new TypeError('must specify data as first parameter')
  2686. offset = +(offset || 0) | 0
  2687. if (Array.isArray(data) && (data[0] && typeof data[0][0] === 'number')) {
  2688. var dim = data[0].length
  2689. var length = data.length * dim
  2690. var i, j, k, l
  2691. // no output specified, create a new typed array
  2692. if (!output || typeof output === 'string') {
  2693. output = new (dtype(output || 'float32'))(length + offset)
  2694. }
  2695. var dstLength = output.length - offset
  2696. if (length !== dstLength) {
  2697. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2698. ' does not match destination length ' + dstLength)
  2699. }
  2700. for (i = 0, k = offset; i < data.length; i++) {
  2701. for (j = 0; j < dim; j++) {
  2702. output[k++] = data[i][j] === null ? NaN : data[i][j]
  2703. }
  2704. }
  2705. } else {
  2706. if (!output || typeof output === 'string') {
  2707. // no output, create a new one
  2708. var Ctor = dtype(output || 'float32')
  2709. // handle arrays separately due to possible nulls
  2710. if (Array.isArray(data) || output === 'array') {
  2711. output = new Ctor(data.length + offset)
  2712. for (i = 0, k = offset, l = output.length; k < l; k++, i++) {
  2713. output[k] = data[i] === null ? NaN : data[i]
  2714. }
  2715. } else {
  2716. if (offset === 0) {
  2717. output = new Ctor(data)
  2718. } else {
  2719. output = new Ctor(data.length + offset)
  2720. output.set(data, offset)
  2721. }
  2722. }
  2723. } else {
  2724. // store output in existing array
  2725. output.set(data, offset)
  2726. }
  2727. }
  2728. return output
  2729. }
  2730. },{"dtype":13}],24:[function(_dereq_,module,exports){
  2731. 'use strict';
  2732. var isCallable = _dereq_('is-callable');
  2733. var toStr = Object.prototype.toString;
  2734. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2735. var forEachArray = function forEachArray(array, iterator, receiver) {
  2736. for (var i = 0, len = array.length; i < len; i++) {
  2737. if (hasOwnProperty.call(array, i)) {
  2738. if (receiver == null) {
  2739. iterator(array[i], i, array);
  2740. } else {
  2741. iterator.call(receiver, array[i], i, array);
  2742. }
  2743. }
  2744. }
  2745. };
  2746. var forEachString = function forEachString(string, iterator, receiver) {
  2747. for (var i = 0, len = string.length; i < len; i++) {
  2748. // no such thing as a sparse string.
  2749. if (receiver == null) {
  2750. iterator(string.charAt(i), i, string);
  2751. } else {
  2752. iterator.call(receiver, string.charAt(i), i, string);
  2753. }
  2754. }
  2755. };
  2756. var forEachObject = function forEachObject(object, iterator, receiver) {
  2757. for (var k in object) {
  2758. if (hasOwnProperty.call(object, k)) {
  2759. if (receiver == null) {
  2760. iterator(object[k], k, object);
  2761. } else {
  2762. iterator.call(receiver, object[k], k, object);
  2763. }
  2764. }
  2765. }
  2766. };
  2767. var forEach = function forEach(list, iterator, thisArg) {
  2768. if (!isCallable(iterator)) {
  2769. throw new TypeError('iterator must be a function');
  2770. }
  2771. var receiver;
  2772. if (arguments.length >= 3) {
  2773. receiver = thisArg;
  2774. }
  2775. if (toStr.call(list) === '[object Array]') {
  2776. forEachArray(list, iterator, receiver);
  2777. } else if (typeof list === 'string') {
  2778. forEachString(list, iterator, receiver);
  2779. } else {
  2780. forEachObject(list, iterator, receiver);
  2781. }
  2782. };
  2783. module.exports = forEach;
  2784. },{"is-callable":32}],25:[function(_dereq_,module,exports){
  2785. 'use strict';
  2786. /* eslint no-invalid-this: 1 */
  2787. var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
  2788. var slice = Array.prototype.slice;
  2789. var toStr = Object.prototype.toString;
  2790. var funcType = '[object Function]';
  2791. module.exports = function bind(that) {
  2792. var target = this;
  2793. if (typeof target !== 'function' || toStr.call(target) !== funcType) {
  2794. throw new TypeError(ERROR_MESSAGE + target);
  2795. }
  2796. var args = slice.call(arguments, 1);
  2797. var bound;
  2798. var binder = function () {
  2799. if (this instanceof bound) {
  2800. var result = target.apply(
  2801. this,
  2802. args.concat(slice.call(arguments))
  2803. );
  2804. if (Object(result) === result) {
  2805. return result;
  2806. }
  2807. return this;
  2808. } else {
  2809. return target.apply(
  2810. that,
  2811. args.concat(slice.call(arguments))
  2812. );
  2813. }
  2814. };
  2815. var boundLength = Math.max(0, target.length - args.length);
  2816. var boundArgs = [];
  2817. for (var i = 0; i < boundLength; i++) {
  2818. boundArgs.push('$' + i);
  2819. }
  2820. bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
  2821. if (target.prototype) {
  2822. var Empty = function Empty() {};
  2823. Empty.prototype = target.prototype;
  2824. bound.prototype = new Empty();
  2825. Empty.prototype = null;
  2826. }
  2827. return bound;
  2828. };
  2829. },{}],26:[function(_dereq_,module,exports){
  2830. 'use strict';
  2831. var implementation = _dereq_('./implementation');
  2832. module.exports = Function.prototype.bind || implementation;
  2833. },{"./implementation":25}],27:[function(_dereq_,module,exports){
  2834. (function (global){
  2835. var win;
  2836. if (typeof window !== "undefined") {
  2837. win = window;
  2838. } else if (typeof global !== "undefined") {
  2839. win = global;
  2840. } else if (typeof self !== "undefined"){
  2841. win = self;
  2842. } else {
  2843. win = {};
  2844. }
  2845. module.exports = win;
  2846. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2847. },{}],28:[function(_dereq_,module,exports){
  2848. 'use strict';
  2849. var bind = _dereq_('function-bind');
  2850. module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
  2851. },{"function-bind":26}],29:[function(_dereq_,module,exports){
  2852. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2853. var e, m
  2854. var eLen = (nBytes * 8) - mLen - 1
  2855. var eMax = (1 << eLen) - 1
  2856. var eBias = eMax >> 1
  2857. var nBits = -7
  2858. var i = isLE ? (nBytes - 1) : 0
  2859. var d = isLE ? -1 : 1
  2860. var s = buffer[offset + i]
  2861. i += d
  2862. e = s & ((1 << (-nBits)) - 1)
  2863. s >>= (-nBits)
  2864. nBits += eLen
  2865. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2866. m = e & ((1 << (-nBits)) - 1)
  2867. e >>= (-nBits)
  2868. nBits += mLen
  2869. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2870. if (e === 0) {
  2871. e = 1 - eBias
  2872. } else if (e === eMax) {
  2873. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2874. } else {
  2875. m = m + Math.pow(2, mLen)
  2876. e = e - eBias
  2877. }
  2878. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2879. }
  2880. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2881. var e, m, c
  2882. var eLen = (nBytes * 8) - mLen - 1
  2883. var eMax = (1 << eLen) - 1
  2884. var eBias = eMax >> 1
  2885. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2886. var i = isLE ? 0 : (nBytes - 1)
  2887. var d = isLE ? 1 : -1
  2888. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2889. value = Math.abs(value)
  2890. if (isNaN(value) || value === Infinity) {
  2891. m = isNaN(value) ? 1 : 0
  2892. e = eMax
  2893. } else {
  2894. e = Math.floor(Math.log(value) / Math.LN2)
  2895. if (value * (c = Math.pow(2, -e)) < 1) {
  2896. e--
  2897. c *= 2
  2898. }
  2899. if (e + eBias >= 1) {
  2900. value += rt / c
  2901. } else {
  2902. value += rt * Math.pow(2, 1 - eBias)
  2903. }
  2904. if (value * c >= 2) {
  2905. e++
  2906. c /= 2
  2907. }
  2908. if (e + eBias >= eMax) {
  2909. m = 0
  2910. e = eMax
  2911. } else if (e + eBias >= 1) {
  2912. m = ((value * c) - 1) * Math.pow(2, mLen)
  2913. e = e + eBias
  2914. } else {
  2915. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2916. e = 0
  2917. }
  2918. }
  2919. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2920. e = (e << mLen) | m
  2921. eLen += mLen
  2922. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2923. buffer[offset + i - d] |= s * 128
  2924. }
  2925. },{}],30:[function(_dereq_,module,exports){
  2926. if (typeof Object.create === 'function') {
  2927. // implementation from standard node.js 'util' module
  2928. module.exports = function inherits(ctor, superCtor) {
  2929. if (superCtor) {
  2930. ctor.super_ = superCtor
  2931. ctor.prototype = Object.create(superCtor.prototype, {
  2932. constructor: {
  2933. value: ctor,
  2934. enumerable: false,
  2935. writable: true,
  2936. configurable: true
  2937. }
  2938. })
  2939. }
  2940. };
  2941. } else {
  2942. // old school shim for old browsers
  2943. module.exports = function inherits(ctor, superCtor) {
  2944. if (superCtor) {
  2945. ctor.super_ = superCtor
  2946. var TempCtor = function () {}
  2947. TempCtor.prototype = superCtor.prototype
  2948. ctor.prototype = new TempCtor()
  2949. ctor.prototype.constructor = ctor
  2950. }
  2951. }
  2952. }
  2953. },{}],31:[function(_dereq_,module,exports){
  2954. /*!
  2955. * Determine if an object is a Buffer
  2956. *
  2957. * @author Feross Aboukhadijeh <https://feross.org>
  2958. * @license MIT
  2959. */
  2960. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2961. // Object.prototype.constructor. Remove this eventually
  2962. module.exports = function (obj) {
  2963. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2964. }
  2965. function isBuffer (obj) {
  2966. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2967. }
  2968. // For Node v0.10 support. Remove this eventually.
  2969. function isSlowBuffer (obj) {
  2970. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2971. }
  2972. },{}],32:[function(_dereq_,module,exports){
  2973. 'use strict';
  2974. var fnToStr = Function.prototype.toString;
  2975. var constructorRegex = /^\s*class\b/;
  2976. var isES6ClassFn = function isES6ClassFunction(value) {
  2977. try {
  2978. var fnStr = fnToStr.call(value);
  2979. return constructorRegex.test(fnStr);
  2980. } catch (e) {
  2981. return false; // not a function
  2982. }
  2983. };
  2984. var tryFunctionObject = function tryFunctionToStr(value) {
  2985. try {
  2986. if (isES6ClassFn(value)) { return false; }
  2987. fnToStr.call(value);
  2988. return true;
  2989. } catch (e) {
  2990. return false;
  2991. }
  2992. };
  2993. var toStr = Object.prototype.toString;
  2994. var fnClass = '[object Function]';
  2995. var genClass = '[object GeneratorFunction]';
  2996. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  2997. module.exports = function isCallable(value) {
  2998. if (!value) { return false; }
  2999. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  3000. if (typeof value === 'function' && !value.prototype) { return true; }
  3001. if (hasToStringTag) { return tryFunctionObject(value); }
  3002. if (isES6ClassFn(value)) { return false; }
  3003. var strClass = toStr.call(value);
  3004. return strClass === fnClass || strClass === genClass;
  3005. };
  3006. },{}],33:[function(_dereq_,module,exports){
  3007. module.exports = isFunction
  3008. var toString = Object.prototype.toString
  3009. function isFunction (fn) {
  3010. var string = toString.call(fn)
  3011. return string === '[object Function]' ||
  3012. (typeof fn === 'function' && string !== '[object RegExp]') ||
  3013. (typeof window !== 'undefined' &&
  3014. // IE8 and below
  3015. (fn === window.setTimeout ||
  3016. fn === window.alert ||
  3017. fn === window.confirm ||
  3018. fn === window.prompt))
  3019. };
  3020. },{}],34:[function(_dereq_,module,exports){
  3021. 'use strict';
  3022. module.exports = function (x) {
  3023. var type = typeof x;
  3024. return x !== null && (type === 'object' || type === 'function');
  3025. };
  3026. },{}],35:[function(_dereq_,module,exports){
  3027. var toString = {}.toString;
  3028. module.exports = Array.isArray || function (arr) {
  3029. return toString.call(arr) == '[object Array]';
  3030. };
  3031. },{}],36:[function(_dereq_,module,exports){
  3032. var wordWrap = _dereq_('word-wrapper')
  3033. var xtend = _dereq_('xtend')
  3034. var number = _dereq_('as-number')
  3035. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  3036. var M_WIDTHS = ['m', 'w']
  3037. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  3038. var TAB_ID = '\t'.charCodeAt(0)
  3039. var SPACE_ID = ' '.charCodeAt(0)
  3040. var ALIGN_LEFT = 0,
  3041. ALIGN_CENTER = 1,
  3042. ALIGN_RIGHT = 2
  3043. module.exports = function createLayout(opt) {
  3044. return new TextLayout(opt)
  3045. }
  3046. function TextLayout(opt) {
  3047. this.glyphs = []
  3048. this._measure = this.computeMetrics.bind(this)
  3049. this.update(opt)
  3050. }
  3051. TextLayout.prototype.update = function(opt) {
  3052. opt = xtend({
  3053. measure: this._measure
  3054. }, opt)
  3055. this._opt = opt
  3056. this._opt.tabSize = number(this._opt.tabSize, 4)
  3057. if (!opt.font)
  3058. throw new Error('must provide a valid bitmap font')
  3059. var glyphs = this.glyphs
  3060. var text = opt.text||''
  3061. var font = opt.font
  3062. this._setupSpaceGlyphs(font)
  3063. var lines = wordWrap.lines(text, opt)
  3064. var minWidth = opt.width || 0
  3065. //clear glyphs
  3066. glyphs.length = 0
  3067. //get max line width
  3068. var maxLineWidth = lines.reduce(function(prev, line) {
  3069. return Math.max(prev, line.width, minWidth)
  3070. }, 0)
  3071. //the pen position
  3072. var x = 0
  3073. var y = 0
  3074. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  3075. var baseline = font.common.base
  3076. var descender = lineHeight-baseline
  3077. var letterSpacing = opt.letterSpacing || 0
  3078. var height = lineHeight * lines.length - descender
  3079. var align = getAlignType(this._opt.align)
  3080. //draw text along baseline
  3081. y -= height
  3082. //the metrics for this text layout
  3083. this._width = maxLineWidth
  3084. this._height = height
  3085. this._descender = lineHeight - baseline
  3086. this._baseline = baseline
  3087. this._xHeight = getXHeight(font)
  3088. this._capHeight = getCapHeight(font)
  3089. this._lineHeight = lineHeight
  3090. this._ascender = lineHeight - descender - this._xHeight
  3091. //layout each glyph
  3092. var self = this
  3093. lines.forEach(function(line, lineIndex) {
  3094. var start = line.start
  3095. var end = line.end
  3096. var lineWidth = line.width
  3097. var lastGlyph
  3098. //for each glyph in that line...
  3099. for (var i=start; i<end; i++) {
  3100. var id = text.charCodeAt(i)
  3101. var glyph = self.getGlyph(font, id)
  3102. if (glyph) {
  3103. if (lastGlyph)
  3104. x += getKerning(font, lastGlyph.id, glyph.id)
  3105. var tx = x
  3106. if (align === ALIGN_CENTER)
  3107. tx += (maxLineWidth-lineWidth)/2
  3108. else if (align === ALIGN_RIGHT)
  3109. tx += (maxLineWidth-lineWidth)
  3110. glyphs.push({
  3111. position: [tx, y],
  3112. data: glyph,
  3113. index: i,
  3114. line: lineIndex
  3115. })
  3116. //move pen forward
  3117. x += glyph.xadvance + letterSpacing
  3118. lastGlyph = glyph
  3119. }
  3120. }
  3121. //next line down
  3122. y += lineHeight
  3123. x = 0
  3124. })
  3125. this._linesTotal = lines.length;
  3126. }
  3127. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  3128. //These are fallbacks, when the font doesn't include
  3129. //' ' or '\t' glyphs
  3130. this._fallbackSpaceGlyph = null
  3131. this._fallbackTabGlyph = null
  3132. if (!font.chars || font.chars.length === 0)
  3133. return
  3134. //try to get space glyph
  3135. //then fall back to the 'm' or 'w' glyphs
  3136. //then fall back to the first glyph available
  3137. var space = getGlyphById(font, SPACE_ID)
  3138. || getMGlyph(font)
  3139. || font.chars[0]
  3140. //and create a fallback for tab
  3141. var tabWidth = this._opt.tabSize * space.xadvance
  3142. this._fallbackSpaceGlyph = space
  3143. this._fallbackTabGlyph = xtend(space, {
  3144. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  3145. xoffset: 0, yoffset: 0, width: 0, height: 0
  3146. })
  3147. }
  3148. TextLayout.prototype.getGlyph = function(font, id) {
  3149. var glyph = getGlyphById(font, id)
  3150. if (glyph)
  3151. return glyph
  3152. else if (id === TAB_ID)
  3153. return this._fallbackTabGlyph
  3154. else if (id === SPACE_ID)
  3155. return this._fallbackSpaceGlyph
  3156. return null
  3157. }
  3158. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3159. var letterSpacing = this._opt.letterSpacing || 0
  3160. var font = this._opt.font
  3161. var curPen = 0
  3162. var curWidth = 0
  3163. var count = 0
  3164. var glyph
  3165. var lastGlyph
  3166. if (!font.chars || font.chars.length === 0) {
  3167. return {
  3168. start: start,
  3169. end: start,
  3170. width: 0
  3171. }
  3172. }
  3173. end = Math.min(text.length, end)
  3174. for (var i=start; i < end; i++) {
  3175. var id = text.charCodeAt(i)
  3176. var glyph = this.getGlyph(font, id)
  3177. if (glyph) {
  3178. //move pen forward
  3179. var xoff = glyph.xoffset
  3180. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3181. curPen += kern
  3182. var nextPen = curPen + glyph.xadvance + letterSpacing
  3183. var nextWidth = curPen + glyph.width
  3184. //we've hit our limit; we can't move onto the next glyph
  3185. if (nextWidth >= width || nextPen >= width)
  3186. break
  3187. //otherwise continue along our line
  3188. curPen = nextPen
  3189. curWidth = nextWidth
  3190. lastGlyph = glyph
  3191. }
  3192. count++
  3193. }
  3194. //make sure rightmost edge lines up with rendered glyphs
  3195. if (lastGlyph)
  3196. curWidth += lastGlyph.xoffset
  3197. return {
  3198. start: start,
  3199. end: start + count,
  3200. width: curWidth
  3201. }
  3202. }
  3203. //getters for the private vars
  3204. ;['width', 'height',
  3205. 'descender', 'ascender',
  3206. 'xHeight', 'baseline',
  3207. 'capHeight',
  3208. 'lineHeight' ].forEach(addGetter)
  3209. function addGetter(name) {
  3210. Object.defineProperty(TextLayout.prototype, name, {
  3211. get: wrapper(name),
  3212. configurable: true
  3213. })
  3214. }
  3215. //create lookups for private vars
  3216. function wrapper(name) {
  3217. return (new Function([
  3218. 'return function '+name+'() {',
  3219. ' return this._'+name,
  3220. '}'
  3221. ].join('\n')))()
  3222. }
  3223. function getGlyphById(font, id) {
  3224. if (!font.chars || font.chars.length === 0)
  3225. return null
  3226. var glyphIdx = findChar(font.chars, id)
  3227. if (glyphIdx >= 0)
  3228. return font.chars[glyphIdx]
  3229. return null
  3230. }
  3231. function getXHeight(font) {
  3232. for (var i=0; i<X_HEIGHTS.length; i++) {
  3233. var id = X_HEIGHTS[i].charCodeAt(0)
  3234. var idx = findChar(font.chars, id)
  3235. if (idx >= 0)
  3236. return font.chars[idx].height
  3237. }
  3238. return 0
  3239. }
  3240. function getMGlyph(font) {
  3241. for (var i=0; i<M_WIDTHS.length; i++) {
  3242. var id = M_WIDTHS[i].charCodeAt(0)
  3243. var idx = findChar(font.chars, id)
  3244. if (idx >= 0)
  3245. return font.chars[idx]
  3246. }
  3247. return 0
  3248. }
  3249. function getCapHeight(font) {
  3250. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3251. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3252. var idx = findChar(font.chars, id)
  3253. if (idx >= 0)
  3254. return font.chars[idx].height
  3255. }
  3256. return 0
  3257. }
  3258. function getKerning(font, left, right) {
  3259. if (!font.kernings || font.kernings.length === 0)
  3260. return 0
  3261. var table = font.kernings
  3262. for (var i=0; i<table.length; i++) {
  3263. var kern = table[i]
  3264. if (kern.first === left && kern.second === right)
  3265. return kern.amount
  3266. }
  3267. return 0
  3268. }
  3269. function getAlignType(align) {
  3270. if (align === 'center')
  3271. return ALIGN_CENTER
  3272. else if (align === 'right')
  3273. return ALIGN_RIGHT
  3274. return ALIGN_LEFT
  3275. }
  3276. function findChar (array, value, start) {
  3277. start = start || 0
  3278. for (var i = start; i < array.length; i++) {
  3279. if (array[i].id === value) {
  3280. return i
  3281. }
  3282. }
  3283. return -1
  3284. }
  3285. },{"as-number":2,"word-wrapper":68,"xtend":71}],37:[function(_dereq_,module,exports){
  3286. (function (Buffer){
  3287. var xhr = _dereq_('xhr')
  3288. var noop = function(){}
  3289. var parseASCII = _dereq_('parse-bmfont-ascii')
  3290. var parseXML = _dereq_('parse-bmfont-xml')
  3291. var readBinary = _dereq_('parse-bmfont-binary')
  3292. var isBinaryFormat = _dereq_('./lib/is-binary')
  3293. var xtend = _dereq_('xtend')
  3294. var xml2 = (function hasXML2() {
  3295. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3296. })()
  3297. module.exports = function(opt, cb) {
  3298. cb = typeof cb === 'function' ? cb : noop
  3299. if (typeof opt === 'string')
  3300. opt = { uri: opt }
  3301. else if (!opt)
  3302. opt = {}
  3303. var expectBinary = opt.binary
  3304. if (expectBinary)
  3305. opt = getBinaryOpts(opt)
  3306. xhr(opt, function(err, res, body) {
  3307. if (err)
  3308. return cb(err)
  3309. if (!/^2/.test(res.statusCode))
  3310. return cb(new Error('http status code: '+res.statusCode))
  3311. if (!body)
  3312. return cb(new Error('no body result'))
  3313. var binary = false
  3314. //if the response type is an array buffer,
  3315. //we need to convert it into a regular Buffer object
  3316. if (isArrayBuffer(body)) {
  3317. var array = new Uint8Array(body)
  3318. body = new Buffer(array, 'binary')
  3319. }
  3320. //now check the string/Buffer response
  3321. //and see if it has a binary BMF header
  3322. if (isBinaryFormat(body)) {
  3323. binary = true
  3324. //if we have a string, turn it into a Buffer
  3325. if (typeof body === 'string')
  3326. body = new Buffer(body, 'binary')
  3327. }
  3328. //we are not parsing a binary format, just ASCII/XML/etc
  3329. if (!binary) {
  3330. //might still be a buffer if responseType is 'arraybuffer'
  3331. if (Buffer.isBuffer(body))
  3332. body = body.toString(opt.encoding)
  3333. body = body.trim()
  3334. }
  3335. var result
  3336. try {
  3337. var type = res.headers['content-type']
  3338. if (binary)
  3339. result = readBinary(body)
  3340. else if (/json/.test(type) || body.charAt(0) === '{')
  3341. result = JSON.parse(body)
  3342. else if (/xml/.test(type) || body.charAt(0) === '<')
  3343. result = parseXML(body)
  3344. else
  3345. result = parseASCII(body)
  3346. } catch (e) {
  3347. cb(new Error('error parsing font '+e.message))
  3348. cb = noop
  3349. }
  3350. cb(null, result)
  3351. })
  3352. }
  3353. function isArrayBuffer(arr) {
  3354. var str = Object.prototype.toString
  3355. return str.call(arr) === '[object ArrayBuffer]'
  3356. }
  3357. function getBinaryOpts(opt) {
  3358. //IE10+ and other modern browsers support array buffers
  3359. if (xml2)
  3360. return xtend(opt, { responseType: 'arraybuffer' })
  3361. if (typeof self.XMLHttpRequest === 'undefined')
  3362. throw new Error('your browser does not support XHR loading')
  3363. //IE9 and XML1 browsers could still use an override
  3364. var req = new self.XMLHttpRequest()
  3365. req.overrideMimeType('text/plain; charset=x-user-defined')
  3366. return xtend({
  3367. xhr: req
  3368. }, opt)
  3369. }
  3370. }).call(this,_dereq_("buffer").Buffer)
  3371. },{"./lib/is-binary":38,"buffer":6,"parse-bmfont-ascii":43,"parse-bmfont-binary":44,"parse-bmfont-xml":45,"xhr":69,"xtend":71}],38:[function(_dereq_,module,exports){
  3372. (function (Buffer){
  3373. var equal = _dereq_('buffer-equal')
  3374. var HEADER = new Buffer([66, 77, 70, 3])
  3375. module.exports = function(buf) {
  3376. if (typeof buf === 'string')
  3377. return buf.substring(0, 3) === 'BMF'
  3378. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3379. }
  3380. }).call(this,_dereq_("buffer").Buffer)
  3381. },{"buffer":6,"buffer-equal":5}],39:[function(_dereq_,module,exports){
  3382. /*
  3383. object-assign
  3384. (c) Sindre Sorhus
  3385. @license MIT
  3386. */
  3387. 'use strict';
  3388. /* eslint-disable no-unused-vars */
  3389. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  3390. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3391. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3392. function toObject(val) {
  3393. if (val === null || val === undefined) {
  3394. throw new TypeError('Object.assign cannot be called with null or undefined');
  3395. }
  3396. return Object(val);
  3397. }
  3398. function shouldUseNative() {
  3399. try {
  3400. if (!Object.assign) {
  3401. return false;
  3402. }
  3403. // Detect buggy property enumeration order in older V8 versions.
  3404. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3405. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  3406. test1[5] = 'de';
  3407. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3408. return false;
  3409. }
  3410. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3411. var test2 = {};
  3412. for (var i = 0; i < 10; i++) {
  3413. test2['_' + String.fromCharCode(i)] = i;
  3414. }
  3415. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3416. return test2[n];
  3417. });
  3418. if (order2.join('') !== '0123456789') {
  3419. return false;
  3420. }
  3421. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3422. var test3 = {};
  3423. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3424. test3[letter] = letter;
  3425. });
  3426. if (Object.keys(Object.assign({}, test3)).join('') !==
  3427. 'abcdefghijklmnopqrst') {
  3428. return false;
  3429. }
  3430. return true;
  3431. } catch (err) {
  3432. // We don't expect any of the above to throw, but better to be safe.
  3433. return false;
  3434. }
  3435. }
  3436. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3437. var from;
  3438. var to = toObject(target);
  3439. var symbols;
  3440. for (var s = 1; s < arguments.length; s++) {
  3441. from = Object(arguments[s]);
  3442. for (var key in from) {
  3443. if (hasOwnProperty.call(from, key)) {
  3444. to[key] = from[key];
  3445. }
  3446. }
  3447. if (getOwnPropertySymbols) {
  3448. symbols = getOwnPropertySymbols(from);
  3449. for (var i = 0; i < symbols.length; i++) {
  3450. if (propIsEnumerable.call(from, symbols[i])) {
  3451. to[symbols[i]] = from[symbols[i]];
  3452. }
  3453. }
  3454. }
  3455. }
  3456. return to;
  3457. };
  3458. },{}],40:[function(_dereq_,module,exports){
  3459. 'use strict';
  3460. var keysShim;
  3461. if (!Object.keys) {
  3462. // modified from https://github.com/es-shims/es5-shim
  3463. var has = Object.prototype.hasOwnProperty;
  3464. var toStr = Object.prototype.toString;
  3465. var isArgs = _dereq_('./isArguments'); // eslint-disable-line global-require
  3466. var isEnumerable = Object.prototype.propertyIsEnumerable;
  3467. var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
  3468. var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
  3469. var dontEnums = [
  3470. 'toString',
  3471. 'toLocaleString',
  3472. 'valueOf',
  3473. 'hasOwnProperty',
  3474. 'isPrototypeOf',
  3475. 'propertyIsEnumerable',
  3476. 'constructor'
  3477. ];
  3478. var equalsConstructorPrototype = function (o) {
  3479. var ctor = o.constructor;
  3480. return ctor && ctor.prototype === o;
  3481. };
  3482. var excludedKeys = {
  3483. $applicationCache: true,
  3484. $console: true,
  3485. $external: true,
  3486. $frame: true,
  3487. $frameElement: true,
  3488. $frames: true,
  3489. $innerHeight: true,
  3490. $innerWidth: true,
  3491. $onmozfullscreenchange: true,
  3492. $onmozfullscreenerror: true,
  3493. $outerHeight: true,
  3494. $outerWidth: true,
  3495. $pageXOffset: true,
  3496. $pageYOffset: true,
  3497. $parent: true,
  3498. $scrollLeft: true,
  3499. $scrollTop: true,
  3500. $scrollX: true,
  3501. $scrollY: true,
  3502. $self: true,
  3503. $webkitIndexedDB: true,
  3504. $webkitStorageInfo: true,
  3505. $window: true
  3506. };
  3507. var hasAutomationEqualityBug = (function () {
  3508. /* global window */
  3509. if (typeof window === 'undefined') { return false; }
  3510. for (var k in window) {
  3511. try {
  3512. if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
  3513. try {
  3514. equalsConstructorPrototype(window[k]);
  3515. } catch (e) {
  3516. return true;
  3517. }
  3518. }
  3519. } catch (e) {
  3520. return true;
  3521. }
  3522. }
  3523. return false;
  3524. }());
  3525. var equalsConstructorPrototypeIfNotBuggy = function (o) {
  3526. /* global window */
  3527. if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
  3528. return equalsConstructorPrototype(o);
  3529. }
  3530. try {
  3531. return equalsConstructorPrototype(o);
  3532. } catch (e) {
  3533. return false;
  3534. }
  3535. };
  3536. keysShim = function keys(object) {
  3537. var isObject = object !== null && typeof object === 'object';
  3538. var isFunction = toStr.call(object) === '[object Function]';
  3539. var isArguments = isArgs(object);
  3540. var isString = isObject && toStr.call(object) === '[object String]';
  3541. var theKeys = [];
  3542. if (!isObject && !isFunction && !isArguments) {
  3543. throw new TypeError('Object.keys called on a non-object');
  3544. }
  3545. var skipProto = hasProtoEnumBug && isFunction;
  3546. if (isString && object.length > 0 && !has.call(object, 0)) {
  3547. for (var i = 0; i < object.length; ++i) {
  3548. theKeys.push(String(i));
  3549. }
  3550. }
  3551. if (isArguments && object.length > 0) {
  3552. for (var j = 0; j < object.length; ++j) {
  3553. theKeys.push(String(j));
  3554. }
  3555. } else {
  3556. for (var name in object) {
  3557. if (!(skipProto && name === 'prototype') && has.call(object, name)) {
  3558. theKeys.push(String(name));
  3559. }
  3560. }
  3561. }
  3562. if (hasDontEnumBug) {
  3563. var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
  3564. for (var k = 0; k < dontEnums.length; ++k) {
  3565. if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
  3566. theKeys.push(dontEnums[k]);
  3567. }
  3568. }
  3569. }
  3570. return theKeys;
  3571. };
  3572. }
  3573. module.exports = keysShim;
  3574. },{"./isArguments":42}],41:[function(_dereq_,module,exports){
  3575. 'use strict';
  3576. var slice = Array.prototype.slice;
  3577. var isArgs = _dereq_('./isArguments');
  3578. var origKeys = Object.keys;
  3579. var keysShim = origKeys ? function keys(o) { return origKeys(o); } : _dereq_('./implementation');
  3580. var originalKeys = Object.keys;
  3581. keysShim.shim = function shimObjectKeys() {
  3582. if (Object.keys) {
  3583. var keysWorksWithArguments = (function () {
  3584. // Safari 5.0 bug
  3585. var args = Object.keys(arguments);
  3586. return args && args.length === arguments.length;
  3587. }(1, 2));
  3588. if (!keysWorksWithArguments) {
  3589. Object.keys = function keys(object) { // eslint-disable-line func-name-matching
  3590. if (isArgs(object)) {
  3591. return originalKeys(slice.call(object));
  3592. }
  3593. return originalKeys(object);
  3594. };
  3595. }
  3596. } else {
  3597. Object.keys = keysShim;
  3598. }
  3599. return Object.keys || keysShim;
  3600. };
  3601. module.exports = keysShim;
  3602. },{"./implementation":40,"./isArguments":42}],42:[function(_dereq_,module,exports){
  3603. 'use strict';
  3604. var toStr = Object.prototype.toString;
  3605. module.exports = function isArguments(value) {
  3606. var str = toStr.call(value);
  3607. var isArgs = str === '[object Arguments]';
  3608. if (!isArgs) {
  3609. isArgs = str !== '[object Array]' &&
  3610. value !== null &&
  3611. typeof value === 'object' &&
  3612. typeof value.length === 'number' &&
  3613. value.length >= 0 &&
  3614. toStr.call(value.callee) === '[object Function]';
  3615. }
  3616. return isArgs;
  3617. };
  3618. },{}],43:[function(_dereq_,module,exports){
  3619. module.exports = function parseBMFontAscii(data) {
  3620. if (!data)
  3621. throw new Error('no data provided')
  3622. data = data.toString().trim()
  3623. var output = {
  3624. pages: [],
  3625. chars: [],
  3626. kernings: []
  3627. }
  3628. var lines = data.split(/\r\n?|\n/g)
  3629. if (lines.length === 0)
  3630. throw new Error('no data in BMFont file')
  3631. for (var i = 0; i < lines.length; i++) {
  3632. var lineData = splitLine(lines[i], i)
  3633. if (!lineData) //skip empty lines
  3634. continue
  3635. if (lineData.key === 'page') {
  3636. if (typeof lineData.data.id !== 'number')
  3637. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3638. if (typeof lineData.data.file !== 'string')
  3639. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3640. output.pages[lineData.data.id] = lineData.data.file
  3641. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3642. //... do nothing for these two ...
  3643. } else if (lineData.key === 'char') {
  3644. output.chars.push(lineData.data)
  3645. } else if (lineData.key === 'kerning') {
  3646. output.kernings.push(lineData.data)
  3647. } else {
  3648. output[lineData.key] = lineData.data
  3649. }
  3650. }
  3651. return output
  3652. }
  3653. function splitLine(line, idx) {
  3654. line = line.replace(/\t+/g, ' ').trim()
  3655. if (!line)
  3656. return null
  3657. var space = line.indexOf(' ')
  3658. if (space === -1)
  3659. throw new Error("no named row at line " + idx)
  3660. var key = line.substring(0, space)
  3661. line = line.substring(space + 1)
  3662. //clear "letter" field as it is non-standard and
  3663. //requires additional complexity to parse " / = symbols
  3664. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3665. line = line.split("=")
  3666. line = line.map(function(str) {
  3667. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3668. })
  3669. var data = []
  3670. for (var i = 0; i < line.length; i++) {
  3671. var dt = line[i]
  3672. if (i === 0) {
  3673. data.push({
  3674. key: dt[0],
  3675. data: ""
  3676. })
  3677. } else if (i === line.length - 1) {
  3678. data[data.length - 1].data = parseData(dt[0])
  3679. } else {
  3680. data[data.length - 1].data = parseData(dt[0])
  3681. data.push({
  3682. key: dt[1],
  3683. data: ""
  3684. })
  3685. }
  3686. }
  3687. var out = {
  3688. key: key,
  3689. data: {}
  3690. }
  3691. data.forEach(function(v) {
  3692. out.data[v.key] = v.data;
  3693. })
  3694. return out
  3695. }
  3696. function parseData(data) {
  3697. if (!data || data.length === 0)
  3698. return ""
  3699. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3700. return data.substring(1, data.length - 1)
  3701. if (data.indexOf(',') !== -1)
  3702. return parseIntList(data)
  3703. return parseInt(data, 10)
  3704. }
  3705. function parseIntList(data) {
  3706. return data.split(',').map(function(val) {
  3707. return parseInt(val, 10)
  3708. })
  3709. }
  3710. },{}],44:[function(_dereq_,module,exports){
  3711. var HEADER = [66, 77, 70]
  3712. module.exports = function readBMFontBinary(buf) {
  3713. if (buf.length < 6)
  3714. throw new Error('invalid buffer length for BMFont')
  3715. var header = HEADER.every(function(byte, i) {
  3716. return buf.readUInt8(i) === byte
  3717. })
  3718. if (!header)
  3719. throw new Error('BMFont missing BMF byte header')
  3720. var i = 3
  3721. var vers = buf.readUInt8(i++)
  3722. if (vers > 3)
  3723. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3724. var target = { kernings: [], chars: [] }
  3725. for (var b=0; b<5; b++)
  3726. i += readBlock(target, buf, i)
  3727. return target
  3728. }
  3729. function readBlock(target, buf, i) {
  3730. if (i > buf.length-1)
  3731. return 0
  3732. var blockID = buf.readUInt8(i++)
  3733. var blockSize = buf.readInt32LE(i)
  3734. i += 4
  3735. switch(blockID) {
  3736. case 1:
  3737. target.info = readInfo(buf, i)
  3738. break
  3739. case 2:
  3740. target.common = readCommon(buf, i)
  3741. break
  3742. case 3:
  3743. target.pages = readPages(buf, i, blockSize)
  3744. break
  3745. case 4:
  3746. target.chars = readChars(buf, i, blockSize)
  3747. break
  3748. case 5:
  3749. target.kernings = readKernings(buf, i, blockSize)
  3750. break
  3751. }
  3752. return 5 + blockSize
  3753. }
  3754. function readInfo(buf, i) {
  3755. var info = {}
  3756. info.size = buf.readInt16LE(i)
  3757. var bitField = buf.readUInt8(i+2)
  3758. info.smooth = (bitField >> 7) & 1
  3759. info.unicode = (bitField >> 6) & 1
  3760. info.italic = (bitField >> 5) & 1
  3761. info.bold = (bitField >> 4) & 1
  3762. //fixedHeight is only mentioned in binary spec
  3763. if ((bitField >> 3) & 1)
  3764. info.fixedHeight = 1
  3765. info.charset = buf.readUInt8(i+3) || ''
  3766. info.stretchH = buf.readUInt16LE(i+4)
  3767. info.aa = buf.readUInt8(i+6)
  3768. info.padding = [
  3769. buf.readInt8(i+7),
  3770. buf.readInt8(i+8),
  3771. buf.readInt8(i+9),
  3772. buf.readInt8(i+10)
  3773. ]
  3774. info.spacing = [
  3775. buf.readInt8(i+11),
  3776. buf.readInt8(i+12)
  3777. ]
  3778. info.outline = buf.readUInt8(i+13)
  3779. info.face = readStringNT(buf, i+14)
  3780. return info
  3781. }
  3782. function readCommon(buf, i) {
  3783. var common = {}
  3784. common.lineHeight = buf.readUInt16LE(i)
  3785. common.base = buf.readUInt16LE(i+2)
  3786. common.scaleW = buf.readUInt16LE(i+4)
  3787. common.scaleH = buf.readUInt16LE(i+6)
  3788. common.pages = buf.readUInt16LE(i+8)
  3789. var bitField = buf.readUInt8(i+10)
  3790. common.packed = 0
  3791. common.alphaChnl = buf.readUInt8(i+11)
  3792. common.redChnl = buf.readUInt8(i+12)
  3793. common.greenChnl = buf.readUInt8(i+13)
  3794. common.blueChnl = buf.readUInt8(i+14)
  3795. return common
  3796. }
  3797. function readPages(buf, i, size) {
  3798. var pages = []
  3799. var text = readNameNT(buf, i)
  3800. var len = text.length+1
  3801. var count = size / len
  3802. for (var c=0; c<count; c++) {
  3803. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3804. i += len
  3805. }
  3806. return pages
  3807. }
  3808. function readChars(buf, i, blockSize) {
  3809. var chars = []
  3810. var count = blockSize / 20
  3811. for (var c=0; c<count; c++) {
  3812. var char = {}
  3813. var off = c*20
  3814. char.id = buf.readUInt32LE(i + 0 + off)
  3815. char.x = buf.readUInt16LE(i + 4 + off)
  3816. char.y = buf.readUInt16LE(i + 6 + off)
  3817. char.width = buf.readUInt16LE(i + 8 + off)
  3818. char.height = buf.readUInt16LE(i + 10 + off)
  3819. char.xoffset = buf.readInt16LE(i + 12 + off)
  3820. char.yoffset = buf.readInt16LE(i + 14 + off)
  3821. char.xadvance = buf.readInt16LE(i + 16 + off)
  3822. char.page = buf.readUInt8(i + 18 + off)
  3823. char.chnl = buf.readUInt8(i + 19 + off)
  3824. chars[c] = char
  3825. }
  3826. return chars
  3827. }
  3828. function readKernings(buf, i, blockSize) {
  3829. var kernings = []
  3830. var count = blockSize / 10
  3831. for (var c=0; c<count; c++) {
  3832. var kern = {}
  3833. var off = c*10
  3834. kern.first = buf.readUInt32LE(i + 0 + off)
  3835. kern.second = buf.readUInt32LE(i + 4 + off)
  3836. kern.amount = buf.readInt16LE(i + 8 + off)
  3837. kernings[c] = kern
  3838. }
  3839. return kernings
  3840. }
  3841. function readNameNT(buf, offset) {
  3842. var pos=offset
  3843. for (; pos<buf.length; pos++) {
  3844. if (buf[pos] === 0x00)
  3845. break
  3846. }
  3847. return buf.slice(offset, pos)
  3848. }
  3849. function readStringNT(buf, offset) {
  3850. return readNameNT(buf, offset).toString('utf8')
  3851. }
  3852. },{}],45:[function(_dereq_,module,exports){
  3853. var parseAttributes = _dereq_('./parse-attribs')
  3854. var parseFromString = _dereq_('xml-parse-from-string')
  3855. //In some cases element.attribute.nodeName can return
  3856. //all lowercase values.. so we need to map them to the correct
  3857. //case
  3858. var NAME_MAP = {
  3859. scaleh: 'scaleH',
  3860. scalew: 'scaleW',
  3861. stretchh: 'stretchH',
  3862. lineheight: 'lineHeight',
  3863. alphachnl: 'alphaChnl',
  3864. redchnl: 'redChnl',
  3865. greenchnl: 'greenChnl',
  3866. bluechnl: 'blueChnl'
  3867. }
  3868. module.exports = function parse(data) {
  3869. data = data.toString()
  3870. var xmlRoot = parseFromString(data)
  3871. var output = {
  3872. pages: [],
  3873. chars: [],
  3874. kernings: []
  3875. }
  3876. //get config settings
  3877. ;['info', 'common'].forEach(function(key) {
  3878. var element = xmlRoot.getElementsByTagName(key)[0]
  3879. if (element)
  3880. output[key] = parseAttributes(getAttribs(element))
  3881. })
  3882. //get page info
  3883. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3884. if (!pageRoot)
  3885. throw new Error('malformed file -- no <pages> element')
  3886. var pages = pageRoot.getElementsByTagName('page')
  3887. for (var i=0; i<pages.length; i++) {
  3888. var p = pages[i]
  3889. var id = parseInt(p.getAttribute('id'), 10)
  3890. var file = p.getAttribute('file')
  3891. if (isNaN(id))
  3892. throw new Error('malformed file -- page "id" attribute is NaN')
  3893. if (!file)
  3894. throw new Error('malformed file -- needs page "file" attribute')
  3895. output.pages[parseInt(id, 10)] = file
  3896. }
  3897. //get kernings / chars
  3898. ;['chars', 'kernings'].forEach(function(key) {
  3899. var element = xmlRoot.getElementsByTagName(key)[0]
  3900. if (!element)
  3901. return
  3902. var childTag = key.substring(0, key.length-1)
  3903. var children = element.getElementsByTagName(childTag)
  3904. for (var i=0; i<children.length; i++) {
  3905. var child = children[i]
  3906. output[key].push(parseAttributes(getAttribs(child)))
  3907. }
  3908. })
  3909. return output
  3910. }
  3911. function getAttribs(element) {
  3912. var attribs = getAttribList(element)
  3913. return attribs.reduce(function(dict, attrib) {
  3914. var key = mapName(attrib.nodeName)
  3915. dict[key] = attrib.nodeValue
  3916. return dict
  3917. }, {})
  3918. }
  3919. function getAttribList(element) {
  3920. //IE8+ and modern browsers
  3921. var attribs = []
  3922. for (var i=0; i<element.attributes.length; i++)
  3923. attribs.push(element.attributes[i])
  3924. return attribs
  3925. }
  3926. function mapName(nodeName) {
  3927. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3928. }
  3929. },{"./parse-attribs":46,"xml-parse-from-string":70}],46:[function(_dereq_,module,exports){
  3930. //Some versions of GlyphDesigner have a typo
  3931. //that causes some bugs with parsing.
  3932. //Need to confirm with recent version of the software
  3933. //to see whether this is still an issue or not.
  3934. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3935. module.exports = function parseAttributes(obj) {
  3936. if (GLYPH_DESIGNER_ERROR in obj) {
  3937. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3938. delete obj[GLYPH_DESIGNER_ERROR]
  3939. }
  3940. for (var k in obj) {
  3941. if (k === 'face' || k === 'charset')
  3942. continue
  3943. else if (k === 'padding' || k === 'spacing')
  3944. obj[k] = parseIntList(obj[k])
  3945. else
  3946. obj[k] = parseInt(obj[k], 10)
  3947. }
  3948. return obj
  3949. }
  3950. function parseIntList(data) {
  3951. return data.split(',').map(function(val) {
  3952. return parseInt(val, 10)
  3953. })
  3954. }
  3955. },{}],47:[function(_dereq_,module,exports){
  3956. var trim = _dereq_('string.prototype.trim')
  3957. , forEach = _dereq_('for-each')
  3958. , isArray = function(arg) {
  3959. return Object.prototype.toString.call(arg) === '[object Array]';
  3960. }
  3961. module.exports = function (headers) {
  3962. if (!headers)
  3963. return {}
  3964. var result = {}
  3965. forEach(
  3966. trim(headers).split('\n')
  3967. , function (row) {
  3968. var index = row.indexOf(':')
  3969. , key = trim(row.slice(0, index)).toLowerCase()
  3970. , value = trim(row.slice(index + 1))
  3971. if (typeof(result[key]) === 'undefined') {
  3972. result[key] = value
  3973. } else if (isArray(result[key])) {
  3974. result[key].push(value)
  3975. } else {
  3976. result[key] = [ result[key], value ]
  3977. }
  3978. }
  3979. )
  3980. return result
  3981. }
  3982. },{"for-each":24,"string.prototype.trim":53}],48:[function(_dereq_,module,exports){
  3983. (function (global){
  3984. var performance = global.performance || {};
  3985. var present = (function () {
  3986. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3987. while (names.length) {
  3988. var name = names.shift();
  3989. if (name in performance) {
  3990. return performance[name].bind(performance);
  3991. }
  3992. }
  3993. var dateNow = Date.now || function () { return new Date().getTime(); };
  3994. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3995. return function () {
  3996. return dateNow() - navigationStart;
  3997. };
  3998. }());
  3999. present.performanceNow = performance.now;
  4000. present.noConflict = function () {
  4001. performance.now = present.performanceNow;
  4002. };
  4003. present.conflict = function () {
  4004. performance.now = present;
  4005. };
  4006. present.conflict();
  4007. module.exports = present;
  4008. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4009. },{}],49:[function(_dereq_,module,exports){
  4010. // shim for using process in browser
  4011. var process = module.exports = {};
  4012. // cached from whatever global is present so that test runners that stub it
  4013. // don't break things. But we need to wrap it in a try catch in case it is
  4014. // wrapped in strict mode code which doesn't define any globals. It's inside a
  4015. // function because try/catches deoptimize in certain engines.
  4016. var cachedSetTimeout;
  4017. var cachedClearTimeout;
  4018. function defaultSetTimout() {
  4019. throw new Error('setTimeout has not been defined');
  4020. }
  4021. function defaultClearTimeout () {
  4022. throw new Error('clearTimeout has not been defined');
  4023. }
  4024. (function () {
  4025. try {
  4026. if (typeof setTimeout === 'function') {
  4027. cachedSetTimeout = setTimeout;
  4028. } else {
  4029. cachedSetTimeout = defaultSetTimout;
  4030. }
  4031. } catch (e) {
  4032. cachedSetTimeout = defaultSetTimout;
  4033. }
  4034. try {
  4035. if (typeof clearTimeout === 'function') {
  4036. cachedClearTimeout = clearTimeout;
  4037. } else {
  4038. cachedClearTimeout = defaultClearTimeout;
  4039. }
  4040. } catch (e) {
  4041. cachedClearTimeout = defaultClearTimeout;
  4042. }
  4043. } ())
  4044. function runTimeout(fun) {
  4045. if (cachedSetTimeout === setTimeout) {
  4046. //normal enviroments in sane situations
  4047. return setTimeout(fun, 0);
  4048. }
  4049. // if setTimeout wasn't available but was latter defined
  4050. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  4051. cachedSetTimeout = setTimeout;
  4052. return setTimeout(fun, 0);
  4053. }
  4054. try {
  4055. // when when somebody has screwed with setTimeout but no I.E. maddness
  4056. return cachedSetTimeout(fun, 0);
  4057. } catch(e){
  4058. try {
  4059. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4060. return cachedSetTimeout.call(null, fun, 0);
  4061. } catch(e){
  4062. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  4063. return cachedSetTimeout.call(this, fun, 0);
  4064. }
  4065. }
  4066. }
  4067. function runClearTimeout(marker) {
  4068. if (cachedClearTimeout === clearTimeout) {
  4069. //normal enviroments in sane situations
  4070. return clearTimeout(marker);
  4071. }
  4072. // if clearTimeout wasn't available but was latter defined
  4073. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  4074. cachedClearTimeout = clearTimeout;
  4075. return clearTimeout(marker);
  4076. }
  4077. try {
  4078. // when when somebody has screwed with setTimeout but no I.E. maddness
  4079. return cachedClearTimeout(marker);
  4080. } catch (e){
  4081. try {
  4082. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4083. return cachedClearTimeout.call(null, marker);
  4084. } catch (e){
  4085. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  4086. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  4087. return cachedClearTimeout.call(this, marker);
  4088. }
  4089. }
  4090. }
  4091. var queue = [];
  4092. var draining = false;
  4093. var currentQueue;
  4094. var queueIndex = -1;
  4095. function cleanUpNextTick() {
  4096. if (!draining || !currentQueue) {
  4097. return;
  4098. }
  4099. draining = false;
  4100. if (currentQueue.length) {
  4101. queue = currentQueue.concat(queue);
  4102. } else {
  4103. queueIndex = -1;
  4104. }
  4105. if (queue.length) {
  4106. drainQueue();
  4107. }
  4108. }
  4109. function drainQueue() {
  4110. if (draining) {
  4111. return;
  4112. }
  4113. var timeout = runTimeout(cleanUpNextTick);
  4114. draining = true;
  4115. var len = queue.length;
  4116. while(len) {
  4117. currentQueue = queue;
  4118. queue = [];
  4119. while (++queueIndex < len) {
  4120. if (currentQueue) {
  4121. currentQueue[queueIndex].run();
  4122. }
  4123. }
  4124. queueIndex = -1;
  4125. len = queue.length;
  4126. }
  4127. currentQueue = null;
  4128. draining = false;
  4129. runClearTimeout(timeout);
  4130. }
  4131. process.nextTick = function (fun) {
  4132. var args = new Array(arguments.length - 1);
  4133. if (arguments.length > 1) {
  4134. for (var i = 1; i < arguments.length; i++) {
  4135. args[i - 1] = arguments[i];
  4136. }
  4137. }
  4138. queue.push(new Item(fun, args));
  4139. if (queue.length === 1 && !draining) {
  4140. runTimeout(drainQueue);
  4141. }
  4142. };
  4143. // v8 likes predictible objects
  4144. function Item(fun, array) {
  4145. this.fun = fun;
  4146. this.array = array;
  4147. }
  4148. Item.prototype.run = function () {
  4149. this.fun.apply(null, this.array);
  4150. };
  4151. process.title = 'browser';
  4152. process.browser = true;
  4153. process.env = {};
  4154. process.argv = [];
  4155. process.version = ''; // empty string to avoid regexp issues
  4156. process.versions = {};
  4157. function noop() {}
  4158. process.on = noop;
  4159. process.addListener = noop;
  4160. process.once = noop;
  4161. process.off = noop;
  4162. process.removeListener = noop;
  4163. process.removeAllListeners = noop;
  4164. process.emit = noop;
  4165. process.prependListener = noop;
  4166. process.prependOnceListener = noop;
  4167. process.listeners = function (name) { return [] }
  4168. process.binding = function (name) {
  4169. throw new Error('process.binding is not supported');
  4170. };
  4171. process.cwd = function () { return '/' };
  4172. process.chdir = function (dir) {
  4173. throw new Error('process.chdir is not supported');
  4174. };
  4175. process.umask = function() { return 0; };
  4176. },{}],50:[function(_dereq_,module,exports){
  4177. (function (setImmediate){
  4178. (function(root) {
  4179. // Store setTimeout reference so promise-polyfill will be unaffected by
  4180. // other code modifying setTimeout (like sinon.useFakeTimers())
  4181. var setTimeoutFunc = setTimeout;
  4182. // Use polyfill for setImmediate for performance gains
  4183. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  4184. function(fn) { setTimeoutFunc(fn, 1); };
  4185. // Polyfill for Function.prototype.bind
  4186. function bind(fn, thisArg) {
  4187. return function() {
  4188. fn.apply(thisArg, arguments);
  4189. }
  4190. }
  4191. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  4192. function Promise(fn) {
  4193. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  4194. if (typeof fn !== 'function') throw new TypeError('not a function');
  4195. this._state = null;
  4196. this._value = null;
  4197. this._deferreds = []
  4198. doResolve(fn, bind(resolve, this), bind(reject, this))
  4199. }
  4200. function handle(deferred) {
  4201. var me = this;
  4202. if (this._state === null) {
  4203. this._deferreds.push(deferred);
  4204. return
  4205. }
  4206. asap(function() {
  4207. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  4208. if (cb === null) {
  4209. (me._state ? deferred.resolve : deferred.reject)(me._value);
  4210. return;
  4211. }
  4212. var ret;
  4213. try {
  4214. ret = cb(me._value);
  4215. }
  4216. catch (e) {
  4217. deferred.reject(e);
  4218. return;
  4219. }
  4220. deferred.resolve(ret);
  4221. })
  4222. }
  4223. function resolve(newValue) {
  4224. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  4225. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  4226. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  4227. var then = newValue.then;
  4228. if (typeof then === 'function') {
  4229. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  4230. return;
  4231. }
  4232. }
  4233. this._state = true;
  4234. this._value = newValue;
  4235. finale.call(this);
  4236. } catch (e) { reject.call(this, e); }
  4237. }
  4238. function reject(newValue) {
  4239. this._state = false;
  4240. this._value = newValue;
  4241. finale.call(this);
  4242. }
  4243. function finale() {
  4244. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  4245. handle.call(this, this._deferreds[i]);
  4246. }
  4247. this._deferreds = null;
  4248. }
  4249. function Handler(onFulfilled, onRejected, resolve, reject){
  4250. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  4251. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  4252. this.resolve = resolve;
  4253. this.reject = reject;
  4254. }
  4255. /**
  4256. * Take a potentially misbehaving resolver function and make sure
  4257. * onFulfilled and onRejected are only called once.
  4258. *
  4259. * Makes no guarantees about asynchrony.
  4260. */
  4261. function doResolve(fn, onFulfilled, onRejected) {
  4262. var done = false;
  4263. try {
  4264. fn(function (value) {
  4265. if (done) return;
  4266. done = true;
  4267. onFulfilled(value);
  4268. }, function (reason) {
  4269. if (done) return;
  4270. done = true;
  4271. onRejected(reason);
  4272. })
  4273. } catch (ex) {
  4274. if (done) return;
  4275. done = true;
  4276. onRejected(ex);
  4277. }
  4278. }
  4279. Promise.prototype['catch'] = function (onRejected) {
  4280. return this.then(null, onRejected);
  4281. };
  4282. Promise.prototype.then = function(onFulfilled, onRejected) {
  4283. var me = this;
  4284. return new Promise(function(resolve, reject) {
  4285. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  4286. })
  4287. };
  4288. Promise.all = function () {
  4289. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  4290. return new Promise(function (resolve, reject) {
  4291. if (args.length === 0) return resolve([]);
  4292. var remaining = args.length;
  4293. function res(i, val) {
  4294. try {
  4295. if (val && (typeof val === 'object' || typeof val === 'function')) {
  4296. var then = val.then;
  4297. if (typeof then === 'function') {
  4298. then.call(val, function (val) { res(i, val) }, reject);
  4299. return;
  4300. }
  4301. }
  4302. args[i] = val;
  4303. if (--remaining === 0) {
  4304. resolve(args);
  4305. }
  4306. } catch (ex) {
  4307. reject(ex);
  4308. }
  4309. }
  4310. for (var i = 0; i < args.length; i++) {
  4311. res(i, args[i]);
  4312. }
  4313. });
  4314. };
  4315. Promise.resolve = function (value) {
  4316. if (value && typeof value === 'object' && value.constructor === Promise) {
  4317. return value;
  4318. }
  4319. return new Promise(function (resolve) {
  4320. resolve(value);
  4321. });
  4322. };
  4323. Promise.reject = function (value) {
  4324. return new Promise(function (resolve, reject) {
  4325. reject(value);
  4326. });
  4327. };
  4328. Promise.race = function (values) {
  4329. return new Promise(function (resolve, reject) {
  4330. for(var i = 0, len = values.length; i < len; i++) {
  4331. values[i].then(resolve, reject);
  4332. }
  4333. });
  4334. };
  4335. /**
  4336. * Set the immediate function to execute callbacks
  4337. * @param fn {function} Function to execute
  4338. * @private
  4339. */
  4340. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4341. asap = fn;
  4342. };
  4343. if (typeof module !== 'undefined' && module.exports) {
  4344. module.exports = Promise;
  4345. } else if (!root.Promise) {
  4346. root.Promise = Promise;
  4347. }
  4348. })(this);
  4349. }).call(this,_dereq_("timers").setImmediate)
  4350. },{"timers":66}],51:[function(_dereq_,module,exports){
  4351. var dtype = _dereq_('dtype')
  4352. var anArray = _dereq_('an-array')
  4353. var isBuffer = _dereq_('is-buffer')
  4354. var CW = [0, 2, 3]
  4355. var CCW = [2, 1, 3]
  4356. module.exports = function createQuadElements(array, opt) {
  4357. //if user didn't specify an output array
  4358. if (!array || !(anArray(array) || isBuffer(array))) {
  4359. opt = array || {}
  4360. array = null
  4361. }
  4362. if (typeof opt === 'number') //backwards-compatible
  4363. opt = { count: opt }
  4364. else
  4365. opt = opt || {}
  4366. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4367. var count = typeof opt.count === 'number' ? opt.count : 1
  4368. var start = (opt.start || 0)
  4369. var dir = opt.clockwise !== false ? CW : CCW,
  4370. a = dir[0],
  4371. b = dir[1],
  4372. c = dir[2]
  4373. var numIndices = count * 6
  4374. var indices = array || new (dtype(type))(numIndices)
  4375. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4376. var x = i + start
  4377. indices[x + 0] = j + 0
  4378. indices[x + 1] = j + 1
  4379. indices[x + 2] = j + 2
  4380. indices[x + 3] = j + a
  4381. indices[x + 4] = j + b
  4382. indices[x + 5] = j + c
  4383. }
  4384. return indices
  4385. }
  4386. },{"an-array":1,"dtype":13,"is-buffer":31}],52:[function(_dereq_,module,exports){
  4387. 'use strict';
  4388. var bind = _dereq_('function-bind');
  4389. var ES = _dereq_('es-abstract/es5');
  4390. var replace = bind.call(Function.call, String.prototype.replace);
  4391. /* eslint-disable no-control-regex */
  4392. var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/;
  4393. var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/;
  4394. /* eslint-enable no-control-regex */
  4395. module.exports = function trim() {
  4396. var S = ES.ToString(ES.CheckObjectCoercible(this));
  4397. return replace(replace(S, leftWhitespace, ''), rightWhitespace, '');
  4398. };
  4399. },{"es-abstract/es5":15,"function-bind":26}],53:[function(_dereq_,module,exports){
  4400. 'use strict';
  4401. var bind = _dereq_('function-bind');
  4402. var define = _dereq_('define-properties');
  4403. var implementation = _dereq_('./implementation');
  4404. var getPolyfill = _dereq_('./polyfill');
  4405. var shim = _dereq_('./shim');
  4406. var boundTrim = bind.call(Function.call, getPolyfill());
  4407. define(boundTrim, {
  4408. getPolyfill: getPolyfill,
  4409. implementation: implementation,
  4410. shim: shim
  4411. });
  4412. module.exports = boundTrim;
  4413. },{"./implementation":52,"./polyfill":54,"./shim":55,"define-properties":11,"function-bind":26}],54:[function(_dereq_,module,exports){
  4414. 'use strict';
  4415. var implementation = _dereq_('./implementation');
  4416. var zeroWidthSpace = '\u200b';
  4417. module.exports = function getPolyfill() {
  4418. if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) {
  4419. return String.prototype.trim;
  4420. }
  4421. return implementation;
  4422. };
  4423. },{"./implementation":52}],55:[function(_dereq_,module,exports){
  4424. 'use strict';
  4425. var define = _dereq_('define-properties');
  4426. var getPolyfill = _dereq_('./polyfill');
  4427. module.exports = function shimStringTrim() {
  4428. var polyfill = getPolyfill();
  4429. define(String.prototype, { trim: polyfill }, {
  4430. trim: function testTrim() {
  4431. return String.prototype.trim !== polyfill;
  4432. }
  4433. });
  4434. return polyfill;
  4435. };
  4436. },{"./polyfill":54,"define-properties":11}],56:[function(_dereq_,module,exports){
  4437. /*
  4438. * anime.js v3.0.0
  4439. * (c) 2019 Julian Garnier
  4440. * Released under the MIT license
  4441. * animejs.com
  4442. */
  4443. 'use strict';
  4444. // Defaults
  4445. var defaultInstanceSettings = {
  4446. update: null,
  4447. begin: null,
  4448. loopBegin: null,
  4449. changeBegin: null,
  4450. change: null,
  4451. changeComplete: null,
  4452. loopComplete: null,
  4453. complete: null,
  4454. loop: 1,
  4455. direction: 'normal',
  4456. autoplay: true,
  4457. timelineOffset: 0
  4458. };
  4459. var defaultTweenSettings = {
  4460. duration: 1000,
  4461. delay: 0,
  4462. endDelay: 0,
  4463. easing: 'easeOutElastic(1, .5)',
  4464. round: 0
  4465. };
  4466. var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective'];
  4467. // Caching
  4468. var cache = {
  4469. CSS: {},
  4470. springs: {}
  4471. };
  4472. // Utils
  4473. function minMax(val, min, max) {
  4474. return Math.min(Math.max(val, min), max);
  4475. }
  4476. function stringContains(str, text) {
  4477. return str.indexOf(text) > -1;
  4478. }
  4479. function applyArguments(func, args) {
  4480. return func.apply(null, args);
  4481. }
  4482. var hexRegex = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;
  4483. var rgbPrefixRegex = /^rgb/;
  4484. var hslRegex = /^hsl/;
  4485. var is = {
  4486. arr: function (a) { return Array.isArray(a); },
  4487. obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); },
  4488. pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); },
  4489. svg: function (a) { return a instanceof SVGElement; },
  4490. inp: function (a) { return a instanceof HTMLInputElement; },
  4491. dom: function (a) { return a.nodeType || is.svg(a); },
  4492. str: function (a) { return typeof a === 'string'; },
  4493. fnc: function (a) { return typeof a === 'function'; },
  4494. und: function (a) { return typeof a === 'undefined'; },
  4495. hex: function (a) { return hexRegex.test(a); },
  4496. rgb: function (a) { return rgbPrefixRegex.test(a); },
  4497. hsl: function (a) { return hslRegex.test(a); },
  4498. col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); },
  4499. key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; }
  4500. };
  4501. // Easings
  4502. var easingFunctionRegex = /\(([^)]+)\)/;
  4503. function parseEasingParameters(string) {
  4504. var match = easingFunctionRegex.exec(string);
  4505. return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : [];
  4506. }
  4507. // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js
  4508. function spring(string, duration) {
  4509. var params = parseEasingParameters(string);
  4510. var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100);
  4511. var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100);
  4512. var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100);
  4513. var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100);
  4514. var w0 = Math.sqrt(stiffness / mass);
  4515. var zeta = damping / (2 * Math.sqrt(stiffness * mass));
  4516. var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
  4517. var a = 1;
  4518. var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
  4519. function solver(t) {
  4520. var progress = duration ? (duration * t) / 1000 : t;
  4521. if (zeta < 1) {
  4522. progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
  4523. } else {
  4524. progress = (a + b * progress) * Math.exp(-progress * w0);
  4525. }
  4526. if (t === 0 || t === 1) { return t; }
  4527. return 1 - progress;
  4528. }
  4529. function getDuration() {
  4530. var cached = cache.springs[string];
  4531. if (cached) { return cached; }
  4532. var frame = 1/6;
  4533. var elapsed = 0;
  4534. var rest = 0;
  4535. while(true) {
  4536. elapsed += frame;
  4537. if (solver(elapsed) === 1) {
  4538. rest++;
  4539. if (rest >= 16) { break; }
  4540. } else {
  4541. rest = 0;
  4542. }
  4543. }
  4544. var duration = elapsed * frame * 1000;
  4545. cache.springs[string] = duration;
  4546. return duration;
  4547. }
  4548. return duration ? solver : getDuration;
  4549. }
  4550. // Elastic easing adapted from jQueryUI http://api.jqueryui.com/easings/
  4551. function elastic(amplitude, period) {
  4552. if ( amplitude === void 0 ) amplitude = 1;
  4553. if ( period === void 0 ) period = .5;
  4554. var a = minMax(amplitude, 1, 10);
  4555. var p = minMax(period, .1, 2);
  4556. return function (t) {
  4557. return (t === 0 || t === 1) ? t :
  4558. -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);
  4559. }
  4560. }
  4561. // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
  4562. function steps(steps) {
  4563. if ( steps === void 0 ) steps = 10;
  4564. return function (t) { return Math.round(t * steps) * (1 / steps); };
  4565. }
  4566. // BezierEasing https://github.com/gre/bezier-easing
  4567. var bezier = (function () {
  4568. var kSplineTableSize = 11;
  4569. var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  4570. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 }
  4571. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 }
  4572. function C(aA1) { return 3.0 * aA1 }
  4573. function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT }
  4574. function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) }
  4575. function binarySubdivide(aX, aA, aB, mX1, mX2) {
  4576. var currentX, currentT, i = 0;
  4577. do {
  4578. currentT = aA + (aB - aA) / 2.0;
  4579. currentX = calcBezier(currentT, mX1, mX2) - aX;
  4580. if (currentX > 0.0) { aB = currentT; } else { aA = currentT; }
  4581. } while (Math.abs(currentX) > 0.0000001 && ++i < 10);
  4582. return currentT;
  4583. }
  4584. function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  4585. for (var i = 0; i < 4; ++i) {
  4586. var currentSlope = getSlope(aGuessT, mX1, mX2);
  4587. if (currentSlope === 0.0) { return aGuessT; }
  4588. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  4589. aGuessT -= currentX / currentSlope;
  4590. }
  4591. return aGuessT;
  4592. }
  4593. function bezier(mX1, mY1, mX2, mY2) {
  4594. if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; }
  4595. var sampleValues = new Float32Array(kSplineTableSize);
  4596. if (mX1 !== mY1 || mX2 !== mY2) {
  4597. for (var i = 0; i < kSplineTableSize; ++i) {
  4598. sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
  4599. }
  4600. }
  4601. function getTForX(aX) {
  4602. var intervalStart = 0;
  4603. var currentSample = 1;
  4604. var lastSample = kSplineTableSize - 1;
  4605. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  4606. intervalStart += kSampleStepSize;
  4607. }
  4608. --currentSample;
  4609. var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  4610. var guessForT = intervalStart + dist * kSampleStepSize;
  4611. var initialSlope = getSlope(guessForT, mX1, mX2);
  4612. if (initialSlope >= 0.001) {
  4613. return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
  4614. } else if (initialSlope === 0.0) {
  4615. return guessForT;
  4616. } else {
  4617. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
  4618. }
  4619. }
  4620. return function (x) {
  4621. if (mX1 === mY1 && mX2 === mY2) { return x; }
  4622. if (x === 0 || x === 1) { return x; }
  4623. return calcBezier(getTForX(x), mY1, mY2);
  4624. }
  4625. }
  4626. return bezier;
  4627. })();
  4628. var penner = (function () {
  4629. var names = ['Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Expo', 'Circ', 'Back', 'Elastic'];
  4630. // Approximated Penner equations http://matthewlein.com/ceaser/
  4631. var curves = {
  4632. In: [
  4633. [0.550, 0.085, 0.680, 0.530], /* inQuad */
  4634. [0.550, 0.055, 0.675, 0.190], /* inCubic */
  4635. [0.895, 0.030, 0.685, 0.220], /* inQuart */
  4636. [0.755, 0.050, 0.855, 0.060], /* inQuint */
  4637. [0.470, 0.000, 0.745, 0.715], /* inSine */
  4638. [0.950, 0.050, 0.795, 0.035], /* inExpo */
  4639. [0.600, 0.040, 0.980, 0.335], /* inCirc */
  4640. [0.600,-0.280, 0.735, 0.045], /* inBack */
  4641. elastic /* inElastic */
  4642. ],
  4643. Out: [
  4644. [0.250, 0.460, 0.450, 0.940], /* outQuad */
  4645. [0.215, 0.610, 0.355, 1.000], /* outCubic */
  4646. [0.165, 0.840, 0.440, 1.000], /* outQuart */
  4647. [0.230, 1.000, 0.320, 1.000], /* outQuint */
  4648. [0.390, 0.575, 0.565, 1.000], /* outSine */
  4649. [0.190, 1.000, 0.220, 1.000], /* outExpo */
  4650. [0.075, 0.820, 0.165, 1.000], /* outCirc */
  4651. [0.175, 0.885, 0.320, 1.275], /* outBack */
  4652. function (a, p) { return function (t) { return 1 - elastic(a, p)(1 - t); }; } /* outElastic */
  4653. ],
  4654. InOut: [
  4655. [0.455, 0.030, 0.515, 0.955], /* inOutQuad */
  4656. [0.645, 0.045, 0.355, 1.000], /* inOutCubic */
  4657. [0.770, 0.000, 0.175, 1.000], /* inOutQuart */
  4658. [0.860, 0.000, 0.070, 1.000], /* inOutQuint */
  4659. [0.445, 0.050, 0.550, 0.950], /* inOutSine */
  4660. [1.000, 0.000, 0.000, 1.000], /* inOutExpo */
  4661. [0.785, 0.135, 0.150, 0.860], /* inOutCirc */
  4662. [0.680,-0.550, 0.265, 1.550], /* inOutBack */
  4663. function (a, p) { return function (t) { return t < .5 ? elastic(a, p)(t * 2) / 2 : 1 - elastic(a, p)(t * -2 + 2) / 2; }; } /* inOutElastic */
  4664. ]
  4665. };
  4666. var eases = {
  4667. linear: [0.250, 0.250, 0.750, 0.750]
  4668. };
  4669. for (var coords in curves) {
  4670. for (var i = 0, len = curves[coords].length; i < len; i++) {
  4671. eases['ease'+coords+names[i]] = curves[coords][i];
  4672. }
  4673. }
  4674. return eases;
  4675. })();
  4676. function parseEasings(easing, duration) {
  4677. if (is.fnc(easing)) { return easing; }
  4678. var name = easing.split('(')[0];
  4679. var ease = penner[name];
  4680. var args = parseEasingParameters(easing);
  4681. switch (name) {
  4682. case 'spring' : return spring(easing, duration);
  4683. case 'cubicBezier' : return applyArguments(bezier, args);
  4684. case 'steps' : return applyArguments(steps, args);
  4685. default : return is.fnc(ease) ? applyArguments(ease, args) : applyArguments(bezier, ease);
  4686. }
  4687. }
  4688. // Strings
  4689. function selectString(str) {
  4690. try {
  4691. var nodes = document.querySelectorAll(str);
  4692. return nodes;
  4693. } catch(e) {
  4694. return;
  4695. }
  4696. }
  4697. // Arrays
  4698. var auxArrayFilter = [];
  4699. function filterArray(arr, callback) {
  4700. var result = auxArrayFilter;
  4701. var len = arr.length;
  4702. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  4703. for (var i = 0; i < len; i++) {
  4704. if (i in arr) {
  4705. var val = arr[i];
  4706. if (callback.call(thisArg, val, i, arr)) {
  4707. result.push(val);
  4708. }
  4709. }
  4710. }
  4711. // arr turns into the auxArray and we return the previously aux array.
  4712. auxArrayFilter = arr;
  4713. auxArrayFilter.length = 0;
  4714. return result;
  4715. }
  4716. function flattenArray (arr, result) {
  4717. if (!result) { result = []; }
  4718. for (var i = 0, length = arr.length; i < length; i++) {
  4719. var value = arr[i];
  4720. if (Array.isArray(value)) {
  4721. flattenArray(value, result);
  4722. } else {
  4723. result.push(value);
  4724. }
  4725. }
  4726. return result;
  4727. }
  4728. function toArray(o) {
  4729. if (is.arr(o)) { return o; }
  4730. if (is.str(o)) { o = selectString(o) || o; }
  4731. if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); }
  4732. return [o];
  4733. }
  4734. function arrayContains(arr, val) {
  4735. return arr.some(function (a) { return a === val; });
  4736. }
  4737. // Objects
  4738. function cloneObject(o) {
  4739. var clone = {};
  4740. for (var p in o) { clone[p] = o[p]; }
  4741. return clone;
  4742. }
  4743. function replaceObjectProps(o1, o2) {
  4744. var o = cloneObject(o1);
  4745. for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; }
  4746. return o;
  4747. }
  4748. function mergeObjects(o1, o2) {
  4749. var o = cloneObject(o1);
  4750. for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; }
  4751. return o;
  4752. }
  4753. // Colors
  4754. var rgbRegex = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g;
  4755. function rgbToRgba(rgbValue) {
  4756. var rgb = rgbRegex.exec(rgbValue);
  4757. return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue;
  4758. }
  4759. var hexToRgbaHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  4760. var hexToRgbaRgbRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  4761. function hexToRgba(hexValue) {
  4762. var hex = hexValue.replace(hexToRgbaHexRegex, function (m, r, g, b) { return r + r + g + g + b + b; } );
  4763. var rgb = hexToRgbaRgbRegex.exec(hex);
  4764. var r = parseInt(rgb[1], 16);
  4765. var g = parseInt(rgb[2], 16);
  4766. var b = parseInt(rgb[3], 16);
  4767. return ("rgba(" + r + "," + g + "," + b + ",1)");
  4768. }
  4769. var hslToRgbaHsl1Regex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g;
  4770. var hslToRgbaHsl2Regex = /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g;
  4771. function hslToRgba(hslValue) {
  4772. var hsl = hslToRgbaHsl1Regex.exec(hslValue) || hslToRgbaHsl2Regex.exec(hslValue);
  4773. var h = parseInt(hsl[1], 10) / 360;
  4774. var s = parseInt(hsl[2], 10) / 100;
  4775. var l = parseInt(hsl[3], 10) / 100;
  4776. var a = hsl[4] || 1;
  4777. function hue2rgb(p, q, t) {
  4778. if (t < 0) { t += 1; }
  4779. if (t > 1) { t -= 1; }
  4780. if (t < 1/6) { return p + (q - p) * 6 * t; }
  4781. if (t < 1/2) { return q; }
  4782. if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
  4783. return p;
  4784. }
  4785. var r, g, b;
  4786. if (s == 0) {
  4787. r = g = b = l;
  4788. } else {
  4789. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  4790. var p = 2 * l - q;
  4791. r = hue2rgb(p, q, h + 1/3);
  4792. g = hue2rgb(p, q, h);
  4793. b = hue2rgb(p, q, h - 1/3);
  4794. }
  4795. return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")");
  4796. }
  4797. function colorToRgb(val) {
  4798. if (is.rgb(val)) { return rgbToRgba(val); }
  4799. if (is.hex(val)) { return hexToRgba(val); }
  4800. if (is.hsl(val)) { return hslToRgba(val); }
  4801. }
  4802. // Units
  4803. var unitRegex = /([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  4804. function getUnit(val) {
  4805. var split = unitRegex.exec(val);
  4806. if (split) { return split[2]; }
  4807. }
  4808. function getTransformUnit(propName) {
  4809. if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; }
  4810. if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; }
  4811. }
  4812. // Values
  4813. function getFunctionValue(val, animatable) {
  4814. if (!is.fnc(val)) { return val; }
  4815. return val(animatable.target, animatable.id, animatable.total);
  4816. }
  4817. function getAttribute(el, prop) {
  4818. return el.getAttribute(prop);
  4819. }
  4820. function convertPxToUnit(el, value, unit) {
  4821. var valueUnit = getUnit(value);
  4822. if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; }
  4823. var cached = cache.CSS[value + unit];
  4824. if (!is.und(cached)) { return cached; }
  4825. var baseline = 100;
  4826. var tempEl = document.createElement(el.tagName);
  4827. var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body;
  4828. parentEl.appendChild(tempEl);
  4829. tempEl.style.position = 'absolute';
  4830. tempEl.style.width = baseline + unit;
  4831. var factor = baseline / tempEl.offsetWidth;
  4832. parentEl.removeChild(tempEl);
  4833. var convertedUnit = factor * parseFloat(value);
  4834. cache.CSS[value + unit] = convertedUnit;
  4835. return convertedUnit;
  4836. }
  4837. function getCSSValue(el, prop, unit) {
  4838. if (prop in el.style) {
  4839. var uppercasePropName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  4840. var value = el.style[prop] || getComputedStyle(el).getPropertyValue(uppercasePropName) || '0';
  4841. return unit ? convertPxToUnit(el, value, unit) : value;
  4842. }
  4843. }
  4844. function getAnimationType(el, prop) {
  4845. if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; }
  4846. if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; }
  4847. if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; }
  4848. if (el[prop] != null) { return 'object'; }
  4849. }
  4850. var transformRegex = /(\w+)\(([^)]*)\)/g;
  4851. function getElementTransforms(el) {
  4852. if (!is.dom(el)) { return; }
  4853. var str = el.style.transform || '';
  4854. var transforms = new Map();
  4855. var m; while (m = transformRegex.exec(str)) { transforms.set(m[1], m[2]); }
  4856. return transforms;
  4857. }
  4858. function getTransformValue(el, propName, animatable, unit) {
  4859. var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName);
  4860. var value = getElementTransforms(el).get(propName) || defaultVal;
  4861. if (animatable) {
  4862. animatable.transforms.list.set(propName, value);
  4863. animatable.transforms['last'] = propName;
  4864. }
  4865. return unit ? convertPxToUnit(el, value, unit) : value;
  4866. }
  4867. function getOriginalTargetValue(target, propName, unit, animatable) {
  4868. switch (getAnimationType(target, propName)) {
  4869. case 'transform': return getTransformValue(target, propName, animatable, unit);
  4870. case 'css': return getCSSValue(target, propName, unit);
  4871. case 'attribute': return getAttribute(target, propName);
  4872. default: return target[propName] || 0;
  4873. }
  4874. }
  4875. var operatorRegex = /^(\*=|\+=|-=)/;
  4876. function getRelativeValue(to, from) {
  4877. var operator = operatorRegex.exec(to);
  4878. if (!operator) { return to; }
  4879. var u = getUnit(to) || 0;
  4880. var x = parseFloat(from);
  4881. var y = parseFloat(to.replace(operator[0], ''));
  4882. switch (operator[0][0]) {
  4883. case '+': return x + y + u;
  4884. case '-': return x - y + u;
  4885. case '*': return x * y + u;
  4886. }
  4887. }
  4888. var whitespaceRegex = /\s/g;
  4889. function validateValue(val, unit) {
  4890. if (is.col(val)) { return colorToRgb(val); }
  4891. var originalUnit = getUnit(val);
  4892. var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val;
  4893. return unit && !whitespaceRegex.test(val) ? unitLess + unit : unitLess;
  4894. }
  4895. // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes
  4896. // adapted from https://gist.github.com/SebLambla/3e0550c496c236709744
  4897. function getDistance(p1, p2) {
  4898. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  4899. }
  4900. function getCircleLength(el) {
  4901. return Math.PI * 2 * getAttribute(el, 'r');
  4902. }
  4903. function getRectLength(el) {
  4904. return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2);
  4905. }
  4906. function getLineLength(el) {
  4907. return getDistance(
  4908. {x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')},
  4909. {x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')}
  4910. );
  4911. }
  4912. function getPolylineLength(el) {
  4913. var points = el.points;
  4914. var totalLength = 0;
  4915. var previousPos;
  4916. for (var i = 0 ; i < points.numberOfItems; i++) {
  4917. var currentPos = points.getItem(i);
  4918. if (i > 0) { totalLength += getDistance(previousPos, currentPos); }
  4919. previousPos = currentPos;
  4920. }
  4921. return totalLength;
  4922. }
  4923. function getPolygonLength(el) {
  4924. var points = el.points;
  4925. return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
  4926. }
  4927. // Path animation
  4928. function getTotalLength(el) {
  4929. if (el.getTotalLength) { return el.getTotalLength(); }
  4930. switch(el.tagName.toLowerCase()) {
  4931. case 'circle': return getCircleLength(el);
  4932. case 'rect': return getRectLength(el);
  4933. case 'line': return getLineLength(el);
  4934. case 'polyline': return getPolylineLength(el);
  4935. case 'polygon': return getPolygonLength(el);
  4936. }
  4937. }
  4938. function setDashoffset(el) {
  4939. var pathLength = getTotalLength(el);
  4940. el.setAttribute('stroke-dasharray', pathLength);
  4941. return pathLength;
  4942. }
  4943. // Motion path
  4944. function getParentSvgEl(el) {
  4945. var parentEl = el.parentNode;
  4946. while (is.svg(parentEl)) {
  4947. parentEl = parentEl.parentNode;
  4948. if (!is.svg(parentEl.parentNode)) { break; }
  4949. }
  4950. return parentEl;
  4951. }
  4952. function getParentSvg(pathEl, svgData) {
  4953. var svg = svgData || {};
  4954. var parentSvgEl = svg.el || getParentSvgEl(pathEl);
  4955. var rect = parentSvgEl.getBoundingClientRect();
  4956. var viewBoxAttr = getAttribute(parentSvgEl, 'viewBox');
  4957. var width = rect.width;
  4958. var height = rect.height;
  4959. var viewBox = svg.viewBox || (viewBoxAttr ? viewBoxAttr.split(' ') : [0, 0, width, height]);
  4960. return {
  4961. el: parentSvgEl,
  4962. viewBox: viewBox,
  4963. x: viewBox[0] / 1,
  4964. y: viewBox[1] / 1,
  4965. w: width / viewBox[2],
  4966. h: height / viewBox[3]
  4967. }
  4968. }
  4969. function getPath(path, percent) {
  4970. var pathEl = is.str(path) ? selectString(path)[0] : path;
  4971. var p = percent || 100;
  4972. return function(property) {
  4973. return {
  4974. property: property,
  4975. el: pathEl,
  4976. svg: getParentSvg(pathEl),
  4977. totalLength: getTotalLength(pathEl) * (p / 100)
  4978. }
  4979. }
  4980. }
  4981. function getPathProgress(path, progress) {
  4982. function point(offset) {
  4983. if ( offset === void 0 ) offset = 0;
  4984. var l = progress + offset >= 1 ? progress + offset : 0;
  4985. return path.el.getPointAtLength(l);
  4986. }
  4987. var svg = getParentSvg(path.el, path.svg);
  4988. var p = point();
  4989. var p0 = point(-1);
  4990. var p1 = point(+1);
  4991. switch (path.property) {
  4992. case 'x': return (p.x - svg.x) * svg.w;
  4993. case 'y': return (p.y - svg.y) * svg.h;
  4994. case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
  4995. }
  4996. }
  4997. // Decompose value
  4998. var valueRegex = /-?\d*\.?\d+/g;
  4999. function decomposeValue(val, unit) {
  5000. var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + '';
  5001. return {
  5002. original: value,
  5003. numbers: value.match(valueRegex) ? value.match(valueRegex).map(Number) : [0],
  5004. strings: (is.str(val) || unit) ? value.split(valueRegex) : []
  5005. }
  5006. }
  5007. // Animatables
  5008. function parseTargets(targets) {
  5009. var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : [];
  5010. return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; });
  5011. }
  5012. function getAnimatables(targets) {
  5013. var parsed = parseTargets(targets);
  5014. return parsed.map(function (t, i) {
  5015. return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } };
  5016. });
  5017. }
  5018. // Properties
  5019. var springRegex = /^spring/;
  5020. function normalizePropertyTweens(prop, tweenSettings) {
  5021. var settings = cloneObject(tweenSettings);
  5022. // Override duration if easing is a spring
  5023. if (springRegex.test(settings.easing)) { settings.duration = spring(settings.easing); }
  5024. if (is.arr(prop)) {
  5025. var l = prop.length;
  5026. var isFromTo = (l === 2 && !is.obj(prop[0]));
  5027. if (!isFromTo) {
  5028. // Duration divided by the number of tweens
  5029. if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; }
  5030. } else {
  5031. // Transform [from, to] values shorthand to a valid tween value
  5032. prop = {value: prop};
  5033. }
  5034. }
  5035. var propArray = is.arr(prop) ? prop : [prop];
  5036. return propArray.map(function (v, i) {
  5037. var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v};
  5038. // Default delay value should only be applied to the first tween
  5039. if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; }
  5040. // Default endDelay value should only be applied to the last tween
  5041. if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; }
  5042. return obj;
  5043. }).map(function (k) { return mergeObjects(k, settings); });
  5044. }
  5045. function flattenKeyframes(keyframes) {
  5046. var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); })
  5047. .reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []);
  5048. var properties = {};
  5049. var loop = function ( i ) {
  5050. var propName = propertyNames[i];
  5051. properties[propName] = keyframes.map(function (key) {
  5052. var newKey = {};
  5053. for (var p in key) {
  5054. if (is.key(p)) {
  5055. if (p == propName) { newKey.value = key[p]; }
  5056. } else {
  5057. newKey[p] = key[p];
  5058. }
  5059. }
  5060. return newKey;
  5061. });
  5062. };
  5063. for (var i = 0; i < propertyNames.length; i++) loop( i );
  5064. return properties;
  5065. }
  5066. function getProperties(tweenSettings, params) {
  5067. var properties = [];
  5068. var keyframes = params.keyframes;
  5069. if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); }
  5070. for (var p in params) {
  5071. if (is.key(p)) {
  5072. properties.push({
  5073. name: p,
  5074. tweens: normalizePropertyTweens(params[p], tweenSettings)
  5075. });
  5076. }
  5077. }
  5078. return properties;
  5079. }
  5080. // Tweens
  5081. function normalizeTweenValues(tween, animatable) {
  5082. var t = {};
  5083. for (var p in tween) {
  5084. var value = getFunctionValue(tween[p], animatable);
  5085. if (is.arr(value)) {
  5086. value = value.map(function (v) { return getFunctionValue(v, animatable); });
  5087. if (value.length === 1) { value = value[0]; }
  5088. }
  5089. t[p] = value;
  5090. }
  5091. t.duration = parseFloat(t.duration);
  5092. t.delay = parseFloat(t.delay);
  5093. return t;
  5094. }
  5095. function normalizeTweens(prop, animatable) {
  5096. var previousTween;
  5097. return prop.tweens.map(function (t) {
  5098. var tween = normalizeTweenValues(t, animatable);
  5099. var tweenValue = tween.value;
  5100. var to = is.arr(tweenValue) ? tweenValue[1] : tweenValue;
  5101. var toUnit = getUnit(to);
  5102. var originalValue = getOriginalTargetValue(animatable.target, prop.name, toUnit, animatable);
  5103. var previousValue = previousTween ? previousTween.to.original : originalValue;
  5104. var from = is.arr(tweenValue) ? tweenValue[0] : previousValue;
  5105. var fromUnit = getUnit(from) || getUnit(originalValue);
  5106. var unit = toUnit || fromUnit;
  5107. if (is.und(to)) { to = previousValue; }
  5108. tween.from = decomposeValue(from, unit);
  5109. tween.to = decomposeValue(getRelativeValue(to, from), unit);
  5110. tween.start = previousTween ? previousTween.end : 0;
  5111. tween.end = tween.start + tween.delay + tween.duration + tween.endDelay;
  5112. tween.easing = parseEasings(tween.easing, tween.duration);
  5113. tween.isPath = is.pth(tweenValue);
  5114. tween.isColor = is.col(tween.from.original);
  5115. if (tween.isColor) { tween.round = 1; }
  5116. previousTween = tween;
  5117. return tween;
  5118. });
  5119. }
  5120. // Tween progress
  5121. var setProgressValue = {
  5122. css: function (t, p, v) { return t.style[p] = v; },
  5123. attribute: function (t, p, v) { return t.setAttribute(p, v); },
  5124. object: function (t, p, v) { return t[p] = v; },
  5125. transform: function (t, p, v, transforms, manual) {
  5126. transforms.list.set(p, v);
  5127. if (p === transforms.last || manual) {
  5128. var str = '';
  5129. transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; });
  5130. t.style.transform = str;
  5131. }
  5132. }
  5133. };
  5134. // Set Value helper
  5135. function setTargetsValue(targets, properties) {
  5136. var animatables = getAnimatables(targets);
  5137. for (var i = 0, len = animatables.length; i < len; i++) {
  5138. var animatable = animatables[i];
  5139. for (var property in properties) {
  5140. var value = getFunctionValue(properties[property], animatable);
  5141. var target = animatable.target;
  5142. var valueUnit = getUnit(value);
  5143. var originalValue = getOriginalTargetValue(target, property, valueUnit, animatable);
  5144. var unit = valueUnit || getUnit(originalValue);
  5145. var to = getRelativeValue(validateValue(value, unit), originalValue);
  5146. var animType = getAnimationType(target, property);
  5147. setProgressValue[animType](target, property, to, animatable.transforms, true);
  5148. }
  5149. }
  5150. }
  5151. // Animations
  5152. function createAnimation(animatable, prop) {
  5153. var animType = getAnimationType(animatable.target, prop.name);
  5154. if (animType) {
  5155. var tweens = normalizeTweens(prop, animatable);
  5156. var lastTween = tweens[tweens.length - 1];
  5157. return {
  5158. type: animType,
  5159. property: prop.name,
  5160. animatable: animatable,
  5161. tweens: tweens,
  5162. duration: lastTween.end,
  5163. delay: tweens[0].delay,
  5164. endDelay: lastTween.endDelay
  5165. }
  5166. }
  5167. }
  5168. function getAnimations(animatables, properties) {
  5169. return filterArray(flattenArray(animatables.map(function (animatable) {
  5170. return properties.map(function (prop) {
  5171. return createAnimation(animatable, prop);
  5172. });
  5173. })), function (a) { return !is.und(a); });
  5174. }
  5175. // Create Instance
  5176. function getInstanceTimings(animations, tweenSettings) {
  5177. var animLength = animations.length;
  5178. var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; };
  5179. var timings = {};
  5180. timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration;
  5181. timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay;
  5182. timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay;
  5183. return timings;
  5184. }
  5185. var instanceID = 0;
  5186. function createNewInstance(params) {
  5187. var instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
  5188. var tweenSettings = replaceObjectProps(defaultTweenSettings, params);
  5189. var properties = getProperties(tweenSettings, params);
  5190. var animatables = getAnimatables(params.targets);
  5191. var animations = getAnimations(animatables, properties);
  5192. var timings = getInstanceTimings(animations, tweenSettings);
  5193. var id = instanceID;
  5194. instanceID++;
  5195. return mergeObjects(instanceSettings, {
  5196. id: id,
  5197. children: [],
  5198. animatables: animatables,
  5199. animations: animations,
  5200. duration: timings.duration,
  5201. delay: timings.delay,
  5202. endDelay: timings.endDelay
  5203. });
  5204. }
  5205. // Core
  5206. var activeInstances = [];
  5207. var pausedInstances = [];
  5208. var raf;
  5209. var engine = (function () {
  5210. function play() {
  5211. raf = requestAnimationFrame(step);
  5212. }
  5213. function step(t) {
  5214. var activeInstancesLength = activeInstances.length;
  5215. if (activeInstancesLength) {
  5216. var i = 0;
  5217. while (i < activeInstancesLength) {
  5218. var activeInstance = activeInstances[i];
  5219. if (!activeInstance.paused) {
  5220. activeInstance.tick(t);
  5221. } else {
  5222. var instanceIndex = activeInstances.indexOf(activeInstance);
  5223. if (instanceIndex > -1) {
  5224. activeInstances.splice(instanceIndex, 1);
  5225. activeInstancesLength = activeInstances.length;
  5226. }
  5227. }
  5228. i++;
  5229. }
  5230. play();
  5231. } else {
  5232. raf = cancelAnimationFrame(raf);
  5233. }
  5234. }
  5235. return play;
  5236. })();
  5237. function handleVisibilityChange() {
  5238. if (document.hidden) {
  5239. for (var i = 0, len = activeInstances.length; i < len; i++) {
  5240. activeInstance[i].pause();
  5241. }
  5242. pausedInstances = activeInstances.slice(0);
  5243. activeInstances = [];
  5244. } else {
  5245. for (var i$1 = 0, len$1 = pausedInstances.length; i$1 < len$1; i$1++) {
  5246. pausedInstances[i$1].play();
  5247. }
  5248. }
  5249. }
  5250. document.addEventListener('visibilitychange', handleVisibilityChange);
  5251. // Public Instance
  5252. function anime(params) {
  5253. if ( params === void 0 ) params = {};
  5254. var startTime = 0, lastTime = 0, now = 0;
  5255. var children, childrenLength = 0;
  5256. var resolve = null;
  5257. function makePromise() {
  5258. return window.Promise && new Promise(function (_resolve) { return resolve = _resolve; });
  5259. }
  5260. var promise = makePromise();
  5261. var instance = createNewInstance(params);
  5262. function toggleInstanceDirection() {
  5263. instance.reversed = !instance.reversed;
  5264. for (var i = 0, len = children.length; i < len; i++) {
  5265. children[i].reversed = instance.reversed;
  5266. }
  5267. }
  5268. function adjustTime(time) {
  5269. return instance.reversed ? instance.duration - time : time;
  5270. }
  5271. function resetTime() {
  5272. startTime = 0;
  5273. lastTime = adjustTime(instance.currentTime) * (1 / anime.speed);
  5274. }
  5275. function seekCild(time, child) {
  5276. if (child) { child.seek(time - child.timelineOffset); }
  5277. }
  5278. function syncInstanceChildren(time) {
  5279. if (!instance.reversePlayback) {
  5280. for (var i = 0; i < childrenLength; i++) { seekCild(time, children[i]); }
  5281. } else {
  5282. for (var i$1 = childrenLength; i$1--;) { seekCild(time, children[i$1]); }
  5283. }
  5284. }
  5285. function setAnimationsProgress(insTime) {
  5286. var i = 0;
  5287. var animations = instance.animations;
  5288. var animationsLength = animations.length;
  5289. while (i < animationsLength) {
  5290. var anim = animations[i];
  5291. var animatable = anim.animatable;
  5292. var tweens = anim.tweens;
  5293. var tweenLength = tweens.length - 1;
  5294. var tween = tweens[tweenLength];
  5295. // Only check for keyframes if there is more than one tween
  5296. if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; }
  5297. var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration;
  5298. var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed);
  5299. var strings = tween.to.strings;
  5300. var round = tween.round;
  5301. var numbers = [];
  5302. var toNumbersLength = tween.to.numbers.length;
  5303. var progress = (void 0);
  5304. for (var n = 0; n < toNumbersLength; n++) {
  5305. var value = (void 0);
  5306. var toNumber = tween.to.numbers[n];
  5307. var fromNumber = tween.from.numbers[n] || 0;
  5308. if (!tween.isPath) {
  5309. value = fromNumber + (eased * (toNumber - fromNumber));
  5310. } else {
  5311. value = getPathProgress(tween.value, eased * toNumber);
  5312. }
  5313. if (round) {
  5314. if (!(tween.isColor && n > 2)) {
  5315. value = Math.round(value * round) / round;
  5316. }
  5317. }
  5318. numbers.push(value);
  5319. }
  5320. // Manual Array.reduce for better performances
  5321. var stringsLength = strings.length;
  5322. if (!stringsLength) {
  5323. progress = numbers[0];
  5324. } else {
  5325. progress = strings[0];
  5326. for (var s = 0; s < stringsLength; s++) {
  5327. var a = strings[s];
  5328. var b = strings[s + 1];
  5329. var n$1 = numbers[s];
  5330. if (!isNaN(n$1)) {
  5331. if (!b) {
  5332. progress += n$1 + ' ';
  5333. } else {
  5334. progress += n$1 + b;
  5335. }
  5336. }
  5337. }
  5338. }
  5339. setProgressValue[anim.type](animatable.target, anim.property, progress, animatable.transforms);
  5340. anim.currentValue = progress;
  5341. i++;
  5342. }
  5343. }
  5344. function setCallback(cb) {
  5345. if (instance[cb] && !instance.passThrough) { instance[cb](instance); }
  5346. }
  5347. function countIteration() {
  5348. if (instance.remaining && instance.remaining !== true) {
  5349. instance.remaining--;
  5350. }
  5351. }
  5352. function setInstanceProgress(engineTime) {
  5353. var insDuration = instance.duration;
  5354. var insDelay = instance.delay;
  5355. var insEndDelay = insDuration - instance.endDelay;
  5356. var insTime = adjustTime(engineTime);
  5357. instance.progress = minMax((insTime / insDuration) * 100, 0, 100);
  5358. instance.reversePlayback = insTime < instance.currentTime;
  5359. if (children) { syncInstanceChildren(insTime); }
  5360. if (!instance.began && instance.currentTime > 0) {
  5361. instance.began = true;
  5362. setCallback('begin');
  5363. setCallback('loopBegin');
  5364. }
  5365. if (insTime <= insDelay && instance.currentTime !== 0) {
  5366. setAnimationsProgress(0);
  5367. }
  5368. if ((insTime >= insEndDelay && instance.currentTime !== insDuration) || !insDuration) {
  5369. setAnimationsProgress(insDuration);
  5370. }
  5371. if (insTime > insDelay && insTime < insEndDelay) {
  5372. if (!instance.changeBegan) {
  5373. instance.changeBegan = true;
  5374. instance.changeCompleted = false;
  5375. setCallback('changeBegin');
  5376. }
  5377. setCallback('change');
  5378. setAnimationsProgress(insTime);
  5379. } else {
  5380. if (instance.changeBegan) {
  5381. instance.changeCompleted = true;
  5382. instance.changeBegan = false;
  5383. setCallback('changeComplete');
  5384. }
  5385. }
  5386. instance.currentTime = minMax(insTime, 0, insDuration);
  5387. if (instance.began) { setCallback('update'); }
  5388. if (engineTime >= insDuration) {
  5389. lastTime = 0;
  5390. countIteration();
  5391. if (instance.remaining) {
  5392. startTime = now;
  5393. setCallback('loopComplete');
  5394. setCallback('loopBegin');
  5395. if (instance.direction === 'alternate') { toggleInstanceDirection(); }
  5396. } else {
  5397. instance.paused = true;
  5398. if (!instance.completed) {
  5399. instance.completed = true;
  5400. setCallback('loopComplete');
  5401. setCallback('complete');
  5402. if ('Promise' in window) {
  5403. resolve();
  5404. promise = makePromise();
  5405. }
  5406. }
  5407. }
  5408. }
  5409. }
  5410. instance.reset = function() {
  5411. var direction = instance.direction;
  5412. instance.passThrough = false;
  5413. instance.currentTime = 0;
  5414. instance.progress = 0;
  5415. instance.paused = true;
  5416. instance.began = false;
  5417. instance.changeBegan = false;
  5418. instance.completed = false;
  5419. instance.changeCompleted = false;
  5420. instance.reversePlayback = false;
  5421. instance.reversed = direction === 'reverse';
  5422. instance.remaining = instance.loop;
  5423. children = instance.children;
  5424. childrenLength = children.length;
  5425. for (var i = childrenLength; i--;) { instance.children[i].reset(); }
  5426. if (instance.reversed && instance.loop !== true || (direction === 'alternate' && instance.loop === 1)) { instance.remaining++; }
  5427. setAnimationsProgress(0);
  5428. };
  5429. // Set Value helper
  5430. instance.set = function(targets, properties) {
  5431. setTargetsValue(targets, properties);
  5432. return instance;
  5433. };
  5434. instance.tick = function(t) {
  5435. now = t;
  5436. if (!startTime) { startTime = now; }
  5437. setInstanceProgress((now + (lastTime - startTime)) * anime.speed);
  5438. };
  5439. instance.seek = function(time) {
  5440. setInstanceProgress(adjustTime(time));
  5441. };
  5442. instance.pause = function() {
  5443. instance.paused = true;
  5444. resetTime();
  5445. };
  5446. instance.play = function() {
  5447. if (!instance.paused) { return; }
  5448. instance.paused = false;
  5449. activeInstances.push(instance);
  5450. resetTime();
  5451. if (!raf) { engine(); }
  5452. };
  5453. instance.reverse = function() {
  5454. toggleInstanceDirection();
  5455. resetTime();
  5456. };
  5457. instance.restart = function() {
  5458. instance.reset();
  5459. instance.play();
  5460. };
  5461. instance.finished = promise;
  5462. instance.reset();
  5463. if (instance.autoplay) { instance.play(); }
  5464. return instance;
  5465. }
  5466. // Remove targets from animation
  5467. function removeTargetsFromAnimations(targetsArray, animations) {
  5468. for (var a = animations.length; a--;) {
  5469. if (arrayContains(targetsArray, animations[a].animatable.target)) {
  5470. animations.splice(a, 1);
  5471. }
  5472. }
  5473. }
  5474. function removeTargets(targets) {
  5475. var targetsArray = parseTargets(targets);
  5476. for (var i = activeInstances.length; i--;) {
  5477. var instance = activeInstances[i];
  5478. var animations = instance.animations;
  5479. var children = instance.children;
  5480. removeTargetsFromAnimations(targetsArray, animations);
  5481. for (var c = children.length; c--;) {
  5482. var child = children[c];
  5483. var childAnimations = child.animations;
  5484. removeTargetsFromAnimations(targetsArray, childAnimations);
  5485. if (!childAnimations.length && !child.children.length) { children.splice(c, 1); }
  5486. }
  5487. if (!animations.length && !children.length) { instance.pause(); }
  5488. }
  5489. }
  5490. // Stagger helpers
  5491. function stagger(val, params) {
  5492. if ( params === void 0 ) params = {};
  5493. var direction = params.direction || 'normal';
  5494. var easing = params.easing ? parseEasings(params.easing) : null;
  5495. var grid = params.grid;
  5496. var axis = params.axis;
  5497. var fromIndex = params.from || 0;
  5498. var fromFirst = fromIndex === 'first';
  5499. var fromCenter = fromIndex === 'center';
  5500. var fromLast = fromIndex === 'last';
  5501. var isRange = is.arr(val);
  5502. var val1 = isRange ? parseFloat(val[0]) : parseFloat(val);
  5503. var val2 = isRange ? parseFloat(val[1]) : 0;
  5504. var unit = getUnit(isRange ? val[1] : val) || 0;
  5505. var start = params.start || 0 + (isRange ? val1 : 0);
  5506. var values = [];
  5507. var maxValue = 0;
  5508. return function (el, i, t) {
  5509. if (fromFirst) { fromIndex = 0; }
  5510. if (fromCenter) { fromIndex = (t - 1) / 2; }
  5511. if (fromLast) { fromIndex = t - 1; }
  5512. if (!values.length) {
  5513. for (var index = 0; index < t; index++) {
  5514. if (!grid) {
  5515. values.push(Math.abs(fromIndex - index));
  5516. } else {
  5517. var fromX = !fromCenter ? fromIndex%grid[0] : (grid[0]-1)/2;
  5518. var fromY = !fromCenter ? Math.floor(fromIndex/grid[0]) : (grid[1]-1)/2;
  5519. var toX = index%grid[0];
  5520. var toY = Math.floor(index/grid[0]);
  5521. var distanceX = fromX - toX;
  5522. var distanceY = fromY - toY;
  5523. var value = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
  5524. if (axis === 'x') { value = -distanceX; }
  5525. if (axis === 'y') { value = -distanceY; }
  5526. values.push(value);
  5527. }
  5528. maxValue = Math.max.apply(Math, values);
  5529. }
  5530. if (easing) { values = values.map(function (val) { return easing(val / maxValue) * maxValue; }); }
  5531. if (direction === 'reverse') { values = values.map(function (val) { return axis ? (val < 0) ? val * -1 : -val : Math.abs(maxValue - val); }); }
  5532. }
  5533. var spacing = isRange ? (val2 - val1) / maxValue : val1;
  5534. return start + (spacing * (Math.round(values[i] * 100) / 100)) + unit;
  5535. }
  5536. }
  5537. // Timeline
  5538. function timeline(params) {
  5539. if ( params === void 0 ) params = {};
  5540. var tl = anime(params);
  5541. tl.duration = 0;
  5542. tl.add = function(instanceParams, timelineOffset) {
  5543. var tlIndex = activeInstances.indexOf(tl);
  5544. var children = tl.children;
  5545. if (tlIndex > -1) { activeInstances.splice(tlIndex, 1); }
  5546. function passThrough(ins) { ins.passThrough = true; }
  5547. for (var i = 0; i < children.length; i++) { passThrough(children[i]); }
  5548. var insParams = mergeObjects(instanceParams, replaceObjectProps(defaultTweenSettings, params));
  5549. insParams.targets = insParams.targets || params.targets;
  5550. var tlDuration = tl.duration;
  5551. insParams.autoplay = false;
  5552. insParams.direction = tl.direction;
  5553. insParams.timelineOffset = is.und(timelineOffset) ? tlDuration : getRelativeValue(timelineOffset, tlDuration);
  5554. passThrough(tl);
  5555. tl.seek(insParams.timelineOffset);
  5556. var ins = anime(insParams);
  5557. passThrough(ins);
  5558. children.push(ins);
  5559. var timings = getInstanceTimings(children, params);
  5560. tl.delay = timings.delay;
  5561. tl.endDelay = timings.endDelay;
  5562. tl.duration = timings.duration;
  5563. tl.seek(0);
  5564. tl.reset();
  5565. if (tl.autoplay) { tl.play(); }
  5566. return tl;
  5567. };
  5568. return tl;
  5569. }
  5570. anime.version = '3.0.0';
  5571. anime.speed = 1;
  5572. anime.running = activeInstances;
  5573. anime.remove = removeTargets;
  5574. anime.get = getOriginalTargetValue;
  5575. anime.set = setTargetsValue;
  5576. anime.convertPx = convertPxToUnit;
  5577. anime.path = getPath;
  5578. anime.setDashoffset = setDashoffset;
  5579. anime.stagger = stagger;
  5580. anime.timeline = timeline;
  5581. anime.easing = parseEasings;
  5582. anime.penner = penner;
  5583. anime.random = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; };
  5584. module.exports = anime;
  5585. },{}],57:[function(_dereq_,module,exports){
  5586. // threejs.org/license
  5587. (function (global, factory) {
  5588. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5589. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5590. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  5591. }(this, (function (exports) { 'use strict';
  5592. var REVISION = '123';
  5593. var MOUSE = {
  5594. LEFT: 0,
  5595. MIDDLE: 1,
  5596. RIGHT: 2,
  5597. ROTATE: 0,
  5598. DOLLY: 1,
  5599. PAN: 2
  5600. };
  5601. var TOUCH = {
  5602. ROTATE: 0,
  5603. PAN: 1,
  5604. DOLLY_PAN: 2,
  5605. DOLLY_ROTATE: 3
  5606. };
  5607. var CullFaceNone = 0;
  5608. var CullFaceBack = 1;
  5609. var CullFaceFront = 2;
  5610. var CullFaceFrontBack = 3;
  5611. var BasicShadowMap = 0;
  5612. var PCFShadowMap = 1;
  5613. var PCFSoftShadowMap = 2;
  5614. var VSMShadowMap = 3;
  5615. var FrontSide = 0;
  5616. var BackSide = 1;
  5617. var DoubleSide = 2;
  5618. var FlatShading = 1;
  5619. var SmoothShading = 2;
  5620. var NoBlending = 0;
  5621. var NormalBlending = 1;
  5622. var AdditiveBlending = 2;
  5623. var SubtractiveBlending = 3;
  5624. var MultiplyBlending = 4;
  5625. var CustomBlending = 5;
  5626. var AddEquation = 100;
  5627. var SubtractEquation = 101;
  5628. var ReverseSubtractEquation = 102;
  5629. var MinEquation = 103;
  5630. var MaxEquation = 104;
  5631. var ZeroFactor = 200;
  5632. var OneFactor = 201;
  5633. var SrcColorFactor = 202;
  5634. var OneMinusSrcColorFactor = 203;
  5635. var SrcAlphaFactor = 204;
  5636. var OneMinusSrcAlphaFactor = 205;
  5637. var DstAlphaFactor = 206;
  5638. var OneMinusDstAlphaFactor = 207;
  5639. var DstColorFactor = 208;
  5640. var OneMinusDstColorFactor = 209;
  5641. var SrcAlphaSaturateFactor = 210;
  5642. var NeverDepth = 0;
  5643. var AlwaysDepth = 1;
  5644. var LessDepth = 2;
  5645. var LessEqualDepth = 3;
  5646. var EqualDepth = 4;
  5647. var GreaterEqualDepth = 5;
  5648. var GreaterDepth = 6;
  5649. var NotEqualDepth = 7;
  5650. var MultiplyOperation = 0;
  5651. var MixOperation = 1;
  5652. var AddOperation = 2;
  5653. var NoToneMapping = 0;
  5654. var LinearToneMapping = 1;
  5655. var ReinhardToneMapping = 2;
  5656. var CineonToneMapping = 3;
  5657. var ACESFilmicToneMapping = 4;
  5658. var CustomToneMapping = 5;
  5659. var UVMapping = 300;
  5660. var CubeReflectionMapping = 301;
  5661. var CubeRefractionMapping = 302;
  5662. var EquirectangularReflectionMapping = 303;
  5663. var EquirectangularRefractionMapping = 304;
  5664. var CubeUVReflectionMapping = 306;
  5665. var CubeUVRefractionMapping = 307;
  5666. var RepeatWrapping = 1000;
  5667. var ClampToEdgeWrapping = 1001;
  5668. var MirroredRepeatWrapping = 1002;
  5669. var NearestFilter = 1003;
  5670. var NearestMipmapNearestFilter = 1004;
  5671. var NearestMipMapNearestFilter = 1004;
  5672. var NearestMipmapLinearFilter = 1005;
  5673. var NearestMipMapLinearFilter = 1005;
  5674. var LinearFilter = 1006;
  5675. var LinearMipmapNearestFilter = 1007;
  5676. var LinearMipMapNearestFilter = 1007;
  5677. var LinearMipmapLinearFilter = 1008;
  5678. var LinearMipMapLinearFilter = 1008;
  5679. var UnsignedByteType = 1009;
  5680. var ByteType = 1010;
  5681. var ShortType = 1011;
  5682. var UnsignedShortType = 1012;
  5683. var IntType = 1013;
  5684. var UnsignedIntType = 1014;
  5685. var FloatType = 1015;
  5686. var HalfFloatType = 1016;
  5687. var UnsignedShort4444Type = 1017;
  5688. var UnsignedShort5551Type = 1018;
  5689. var UnsignedShort565Type = 1019;
  5690. var UnsignedInt248Type = 1020;
  5691. var AlphaFormat = 1021;
  5692. var RGBFormat = 1022;
  5693. var RGBAFormat = 1023;
  5694. var LuminanceFormat = 1024;
  5695. var LuminanceAlphaFormat = 1025;
  5696. var RGBEFormat = RGBAFormat;
  5697. var DepthFormat = 1026;
  5698. var DepthStencilFormat = 1027;
  5699. var RedFormat = 1028;
  5700. var RedIntegerFormat = 1029;
  5701. var RGFormat = 1030;
  5702. var RGIntegerFormat = 1031;
  5703. var RGBIntegerFormat = 1032;
  5704. var RGBAIntegerFormat = 1033;
  5705. var RGB_S3TC_DXT1_Format = 33776;
  5706. var RGBA_S3TC_DXT1_Format = 33777;
  5707. var RGBA_S3TC_DXT3_Format = 33778;
  5708. var RGBA_S3TC_DXT5_Format = 33779;
  5709. var RGB_PVRTC_4BPPV1_Format = 35840;
  5710. var RGB_PVRTC_2BPPV1_Format = 35841;
  5711. var RGBA_PVRTC_4BPPV1_Format = 35842;
  5712. var RGBA_PVRTC_2BPPV1_Format = 35843;
  5713. var RGB_ETC1_Format = 36196;
  5714. var RGB_ETC2_Format = 37492;
  5715. var RGBA_ETC2_EAC_Format = 37496;
  5716. var RGBA_ASTC_4x4_Format = 37808;
  5717. var RGBA_ASTC_5x4_Format = 37809;
  5718. var RGBA_ASTC_5x5_Format = 37810;
  5719. var RGBA_ASTC_6x5_Format = 37811;
  5720. var RGBA_ASTC_6x6_Format = 37812;
  5721. var RGBA_ASTC_8x5_Format = 37813;
  5722. var RGBA_ASTC_8x6_Format = 37814;
  5723. var RGBA_ASTC_8x8_Format = 37815;
  5724. var RGBA_ASTC_10x5_Format = 37816;
  5725. var RGBA_ASTC_10x6_Format = 37817;
  5726. var RGBA_ASTC_10x8_Format = 37818;
  5727. var RGBA_ASTC_10x10_Format = 37819;
  5728. var RGBA_ASTC_12x10_Format = 37820;
  5729. var RGBA_ASTC_12x12_Format = 37821;
  5730. var RGBA_BPTC_Format = 36492;
  5731. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  5732. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  5733. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  5734. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  5735. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  5736. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  5737. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  5738. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  5739. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  5740. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  5741. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  5742. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  5743. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  5744. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  5745. var LoopOnce = 2200;
  5746. var LoopRepeat = 2201;
  5747. var LoopPingPong = 2202;
  5748. var InterpolateDiscrete = 2300;
  5749. var InterpolateLinear = 2301;
  5750. var InterpolateSmooth = 2302;
  5751. var ZeroCurvatureEnding = 2400;
  5752. var ZeroSlopeEnding = 2401;
  5753. var WrapAroundEnding = 2402;
  5754. var NormalAnimationBlendMode = 2500;
  5755. var AdditiveAnimationBlendMode = 2501;
  5756. var TrianglesDrawMode = 0;
  5757. var TriangleStripDrawMode = 1;
  5758. var TriangleFanDrawMode = 2;
  5759. var LinearEncoding = 3000;
  5760. var sRGBEncoding = 3001;
  5761. var GammaEncoding = 3007;
  5762. var RGBEEncoding = 3002;
  5763. var LogLuvEncoding = 3003;
  5764. var RGBM7Encoding = 3004;
  5765. var RGBM16Encoding = 3005;
  5766. var RGBDEncoding = 3006;
  5767. var BasicDepthPacking = 3200;
  5768. var RGBADepthPacking = 3201;
  5769. var TangentSpaceNormalMap = 0;
  5770. var ObjectSpaceNormalMap = 1;
  5771. var ZeroStencilOp = 0;
  5772. var KeepStencilOp = 7680;
  5773. var ReplaceStencilOp = 7681;
  5774. var IncrementStencilOp = 7682;
  5775. var DecrementStencilOp = 7683;
  5776. var IncrementWrapStencilOp = 34055;
  5777. var DecrementWrapStencilOp = 34056;
  5778. var InvertStencilOp = 5386;
  5779. var NeverStencilFunc = 512;
  5780. var LessStencilFunc = 513;
  5781. var EqualStencilFunc = 514;
  5782. var LessEqualStencilFunc = 515;
  5783. var GreaterStencilFunc = 516;
  5784. var NotEqualStencilFunc = 517;
  5785. var GreaterEqualStencilFunc = 518;
  5786. var AlwaysStencilFunc = 519;
  5787. var StaticDrawUsage = 35044;
  5788. var DynamicDrawUsage = 35048;
  5789. var StreamDrawUsage = 35040;
  5790. var StaticReadUsage = 35045;
  5791. var DynamicReadUsage = 35049;
  5792. var StreamReadUsage = 35041;
  5793. var StaticCopyUsage = 35046;
  5794. var DynamicCopyUsage = 35050;
  5795. var StreamCopyUsage = 35042;
  5796. var GLSL1 = "100";
  5797. var GLSL3 = "300 es";
  5798. /**
  5799. * https://github.com/mrdoob/eventdispatcher.js/
  5800. */
  5801. function EventDispatcher() {}
  5802. Object.assign(EventDispatcher.prototype, {
  5803. addEventListener: function addEventListener(type, listener) {
  5804. if (this._listeners === undefined) this._listeners = {};
  5805. var listeners = this._listeners;
  5806. if (listeners[type] === undefined) {
  5807. listeners[type] = [];
  5808. }
  5809. if (listeners[type].indexOf(listener) === -1) {
  5810. listeners[type].push(listener);
  5811. }
  5812. },
  5813. hasEventListener: function hasEventListener(type, listener) {
  5814. if (this._listeners === undefined) return false;
  5815. var listeners = this._listeners;
  5816. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  5817. },
  5818. removeEventListener: function removeEventListener(type, listener) {
  5819. if (this._listeners === undefined) return;
  5820. var listeners = this._listeners;
  5821. var listenerArray = listeners[type];
  5822. if (listenerArray !== undefined) {
  5823. var index = listenerArray.indexOf(listener);
  5824. if (index !== -1) {
  5825. listenerArray.splice(index, 1);
  5826. }
  5827. }
  5828. },
  5829. dispatchEvent: function dispatchEvent(event) {
  5830. if (this._listeners === undefined) return;
  5831. var listeners = this._listeners;
  5832. var listenerArray = listeners[event.type];
  5833. if (listenerArray !== undefined) {
  5834. event.target = this; // Make a copy, in case listeners are removed while iterating.
  5835. var array = listenerArray.slice(0);
  5836. for (var i = 0, l = array.length; i < l; i++) {
  5837. array[i].call(this, event);
  5838. }
  5839. }
  5840. }
  5841. });
  5842. var _lut = [];
  5843. for (var i = 0; i < 256; i++) {
  5844. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  5845. }
  5846. var _seed = 1234567;
  5847. var MathUtils = {
  5848. DEG2RAD: Math.PI / 180,
  5849. RAD2DEG: 180 / Math.PI,
  5850. generateUUID: function generateUUID() {
  5851. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  5852. var d0 = Math.random() * 0xffffffff | 0;
  5853. var d1 = Math.random() * 0xffffffff | 0;
  5854. var d2 = Math.random() * 0xffffffff | 0;
  5855. var d3 = Math.random() * 0xffffffff | 0;
  5856. var uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  5857. return uuid.toUpperCase();
  5858. },
  5859. clamp: function clamp(value, min, max) {
  5860. return Math.max(min, Math.min(max, value));
  5861. },
  5862. // compute euclidian modulo of m % n
  5863. // https://en.wikipedia.org/wiki/Modulo_operation
  5864. euclideanModulo: function euclideanModulo(n, m) {
  5865. return (n % m + m) % m;
  5866. },
  5867. // Linear mapping from range <a1, a2> to range <b1, b2>
  5868. mapLinear: function mapLinear(x, a1, a2, b1, b2) {
  5869. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  5870. },
  5871. // https://en.wikipedia.org/wiki/Linear_interpolation
  5872. lerp: function lerp(x, y, t) {
  5873. return (1 - t) * x + t * y;
  5874. },
  5875. // http://en.wikipedia.org/wiki/Smoothstep
  5876. smoothstep: function smoothstep(x, min, max) {
  5877. if (x <= min) return 0;
  5878. if (x >= max) return 1;
  5879. x = (x - min) / (max - min);
  5880. return x * x * (3 - 2 * x);
  5881. },
  5882. smootherstep: function smootherstep(x, min, max) {
  5883. if (x <= min) return 0;
  5884. if (x >= max) return 1;
  5885. x = (x - min) / (max - min);
  5886. return x * x * x * (x * (x * 6 - 15) + 10);
  5887. },
  5888. // Random integer from <low, high> interval
  5889. randInt: function randInt(low, high) {
  5890. return low + Math.floor(Math.random() * (high - low + 1));
  5891. },
  5892. // Random float from <low, high> interval
  5893. randFloat: function randFloat(low, high) {
  5894. return low + Math.random() * (high - low);
  5895. },
  5896. // Random float from <-range/2, range/2> interval
  5897. randFloatSpread: function randFloatSpread(range) {
  5898. return range * (0.5 - Math.random());
  5899. },
  5900. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  5901. seededRandom: function seededRandom(s) {
  5902. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  5903. _seed = _seed * 16807 % 2147483647;
  5904. return (_seed - 1) / 2147483646;
  5905. },
  5906. degToRad: function degToRad(degrees) {
  5907. return degrees * MathUtils.DEG2RAD;
  5908. },
  5909. radToDeg: function radToDeg(radians) {
  5910. return radians * MathUtils.RAD2DEG;
  5911. },
  5912. isPowerOfTwo: function isPowerOfTwo(value) {
  5913. return (value & value - 1) === 0 && value !== 0;
  5914. },
  5915. ceilPowerOfTwo: function ceilPowerOfTwo(value) {
  5916. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  5917. },
  5918. floorPowerOfTwo: function floorPowerOfTwo(value) {
  5919. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  5920. },
  5921. setQuaternionFromProperEuler: function setQuaternionFromProperEuler(q, a, b, c, order) {
  5922. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  5923. // rotations are applied to the axes in the order specified by 'order'
  5924. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  5925. // angles are in radians
  5926. var cos = Math.cos;
  5927. var sin = Math.sin;
  5928. var c2 = cos(b / 2);
  5929. var s2 = sin(b / 2);
  5930. var c13 = cos((a + c) / 2);
  5931. var s13 = sin((a + c) / 2);
  5932. var c1_3 = cos((a - c) / 2);
  5933. var s1_3 = sin((a - c) / 2);
  5934. var c3_1 = cos((c - a) / 2);
  5935. var s3_1 = sin((c - a) / 2);
  5936. switch (order) {
  5937. case 'XYX':
  5938. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  5939. break;
  5940. case 'YZY':
  5941. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  5942. break;
  5943. case 'ZXZ':
  5944. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  5945. break;
  5946. case 'XZX':
  5947. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  5948. break;
  5949. case 'YXY':
  5950. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  5951. break;
  5952. case 'ZYZ':
  5953. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  5954. break;
  5955. default:
  5956. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  5957. }
  5958. }
  5959. };
  5960. function _defineProperties(target, props) {
  5961. for (var i = 0; i < props.length; i++) {
  5962. var descriptor = props[i];
  5963. descriptor.enumerable = descriptor.enumerable || false;
  5964. descriptor.configurable = true;
  5965. if ("value" in descriptor) descriptor.writable = true;
  5966. Object.defineProperty(target, descriptor.key, descriptor);
  5967. }
  5968. }
  5969. function _createClass(Constructor, protoProps, staticProps) {
  5970. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  5971. if (staticProps) _defineProperties(Constructor, staticProps);
  5972. return Constructor;
  5973. }
  5974. function _inheritsLoose(subClass, superClass) {
  5975. subClass.prototype = Object.create(superClass.prototype);
  5976. subClass.prototype.constructor = subClass;
  5977. subClass.__proto__ = superClass;
  5978. }
  5979. function _assertThisInitialized(self) {
  5980. if (self === void 0) {
  5981. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  5982. }
  5983. return self;
  5984. }
  5985. var Vector2 = /*#__PURE__*/function () {
  5986. function Vector2(x, y) {
  5987. if (x === void 0) {
  5988. x = 0;
  5989. }
  5990. if (y === void 0) {
  5991. y = 0;
  5992. }
  5993. Object.defineProperty(this, 'isVector2', {
  5994. value: true
  5995. });
  5996. this.x = x;
  5997. this.y = y;
  5998. }
  5999. var _proto = Vector2.prototype;
  6000. _proto.set = function set(x, y) {
  6001. this.x = x;
  6002. this.y = y;
  6003. return this;
  6004. };
  6005. _proto.setScalar = function setScalar(scalar) {
  6006. this.x = scalar;
  6007. this.y = scalar;
  6008. return this;
  6009. };
  6010. _proto.setX = function setX(x) {
  6011. this.x = x;
  6012. return this;
  6013. };
  6014. _proto.setY = function setY(y) {
  6015. this.y = y;
  6016. return this;
  6017. };
  6018. _proto.setComponent = function setComponent(index, value) {
  6019. switch (index) {
  6020. case 0:
  6021. this.x = value;
  6022. break;
  6023. case 1:
  6024. this.y = value;
  6025. break;
  6026. default:
  6027. throw new Error('index is out of range: ' + index);
  6028. }
  6029. return this;
  6030. };
  6031. _proto.getComponent = function getComponent(index) {
  6032. switch (index) {
  6033. case 0:
  6034. return this.x;
  6035. case 1:
  6036. return this.y;
  6037. default:
  6038. throw new Error('index is out of range: ' + index);
  6039. }
  6040. };
  6041. _proto.clone = function clone() {
  6042. return new this.constructor(this.x, this.y);
  6043. };
  6044. _proto.copy = function copy(v) {
  6045. this.x = v.x;
  6046. this.y = v.y;
  6047. return this;
  6048. };
  6049. _proto.add = function add(v, w) {
  6050. if (w !== undefined) {
  6051. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  6052. return this.addVectors(v, w);
  6053. }
  6054. this.x += v.x;
  6055. this.y += v.y;
  6056. return this;
  6057. };
  6058. _proto.addScalar = function addScalar(s) {
  6059. this.x += s;
  6060. this.y += s;
  6061. return this;
  6062. };
  6063. _proto.addVectors = function addVectors(a, b) {
  6064. this.x = a.x + b.x;
  6065. this.y = a.y + b.y;
  6066. return this;
  6067. };
  6068. _proto.addScaledVector = function addScaledVector(v, s) {
  6069. this.x += v.x * s;
  6070. this.y += v.y * s;
  6071. return this;
  6072. };
  6073. _proto.sub = function sub(v, w) {
  6074. if (w !== undefined) {
  6075. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  6076. return this.subVectors(v, w);
  6077. }
  6078. this.x -= v.x;
  6079. this.y -= v.y;
  6080. return this;
  6081. };
  6082. _proto.subScalar = function subScalar(s) {
  6083. this.x -= s;
  6084. this.y -= s;
  6085. return this;
  6086. };
  6087. _proto.subVectors = function subVectors(a, b) {
  6088. this.x = a.x - b.x;
  6089. this.y = a.y - b.y;
  6090. return this;
  6091. };
  6092. _proto.multiply = function multiply(v) {
  6093. this.x *= v.x;
  6094. this.y *= v.y;
  6095. return this;
  6096. };
  6097. _proto.multiplyScalar = function multiplyScalar(scalar) {
  6098. this.x *= scalar;
  6099. this.y *= scalar;
  6100. return this;
  6101. };
  6102. _proto.divide = function divide(v) {
  6103. this.x /= v.x;
  6104. this.y /= v.y;
  6105. return this;
  6106. };
  6107. _proto.divideScalar = function divideScalar(scalar) {
  6108. return this.multiplyScalar(1 / scalar);
  6109. };
  6110. _proto.applyMatrix3 = function applyMatrix3(m) {
  6111. var x = this.x,
  6112. y = this.y;
  6113. var e = m.elements;
  6114. this.x = e[0] * x + e[3] * y + e[6];
  6115. this.y = e[1] * x + e[4] * y + e[7];
  6116. return this;
  6117. };
  6118. _proto.min = function min(v) {
  6119. this.x = Math.min(this.x, v.x);
  6120. this.y = Math.min(this.y, v.y);
  6121. return this;
  6122. };
  6123. _proto.max = function max(v) {
  6124. this.x = Math.max(this.x, v.x);
  6125. this.y = Math.max(this.y, v.y);
  6126. return this;
  6127. };
  6128. _proto.clamp = function clamp(min, max) {
  6129. // assumes min < max, componentwise
  6130. this.x = Math.max(min.x, Math.min(max.x, this.x));
  6131. this.y = Math.max(min.y, Math.min(max.y, this.y));
  6132. return this;
  6133. };
  6134. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  6135. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  6136. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  6137. return this;
  6138. };
  6139. _proto.clampLength = function clampLength(min, max) {
  6140. var length = this.length();
  6141. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  6142. };
  6143. _proto.floor = function floor() {
  6144. this.x = Math.floor(this.x);
  6145. this.y = Math.floor(this.y);
  6146. return this;
  6147. };
  6148. _proto.ceil = function ceil() {
  6149. this.x = Math.ceil(this.x);
  6150. this.y = Math.ceil(this.y);
  6151. return this;
  6152. };
  6153. _proto.round = function round() {
  6154. this.x = Math.round(this.x);
  6155. this.y = Math.round(this.y);
  6156. return this;
  6157. };
  6158. _proto.roundToZero = function roundToZero() {
  6159. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  6160. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  6161. return this;
  6162. };
  6163. _proto.negate = function negate() {
  6164. this.x = -this.x;
  6165. this.y = -this.y;
  6166. return this;
  6167. };
  6168. _proto.dot = function dot(v) {
  6169. return this.x * v.x + this.y * v.y;
  6170. };
  6171. _proto.cross = function cross(v) {
  6172. return this.x * v.y - this.y * v.x;
  6173. };
  6174. _proto.lengthSq = function lengthSq() {
  6175. return this.x * this.x + this.y * this.y;
  6176. };
  6177. _proto.length = function length() {
  6178. return Math.sqrt(this.x * this.x + this.y * this.y);
  6179. };
  6180. _proto.manhattanLength = function manhattanLength() {
  6181. return Math.abs(this.x) + Math.abs(this.y);
  6182. };
  6183. _proto.normalize = function normalize() {
  6184. return this.divideScalar(this.length() || 1);
  6185. };
  6186. _proto.angle = function angle() {
  6187. // computes the angle in radians with respect to the positive x-axis
  6188. var angle = Math.atan2(-this.y, -this.x) + Math.PI;
  6189. return angle;
  6190. };
  6191. _proto.distanceTo = function distanceTo(v) {
  6192. return Math.sqrt(this.distanceToSquared(v));
  6193. };
  6194. _proto.distanceToSquared = function distanceToSquared(v) {
  6195. var dx = this.x - v.x,
  6196. dy = this.y - v.y;
  6197. return dx * dx + dy * dy;
  6198. };
  6199. _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
  6200. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  6201. };
  6202. _proto.setLength = function setLength(length) {
  6203. return this.normalize().multiplyScalar(length);
  6204. };
  6205. _proto.lerp = function lerp(v, alpha) {
  6206. this.x += (v.x - this.x) * alpha;
  6207. this.y += (v.y - this.y) * alpha;
  6208. return this;
  6209. };
  6210. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  6211. this.x = v1.x + (v2.x - v1.x) * alpha;
  6212. this.y = v1.y + (v2.y - v1.y) * alpha;
  6213. return this;
  6214. };
  6215. _proto.equals = function equals(v) {
  6216. return v.x === this.x && v.y === this.y;
  6217. };
  6218. _proto.fromArray = function fromArray(array, offset) {
  6219. if (offset === void 0) {
  6220. offset = 0;
  6221. }
  6222. this.x = array[offset];
  6223. this.y = array[offset + 1];
  6224. return this;
  6225. };
  6226. _proto.toArray = function toArray(array, offset) {
  6227. if (array === void 0) {
  6228. array = [];
  6229. }
  6230. if (offset === void 0) {
  6231. offset = 0;
  6232. }
  6233. array[offset] = this.x;
  6234. array[offset + 1] = this.y;
  6235. return array;
  6236. };
  6237. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  6238. if (offset !== undefined) {
  6239. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  6240. }
  6241. this.x = attribute.getX(index);
  6242. this.y = attribute.getY(index);
  6243. return this;
  6244. };
  6245. _proto.rotateAround = function rotateAround(center, angle) {
  6246. var c = Math.cos(angle),
  6247. s = Math.sin(angle);
  6248. var x = this.x - center.x;
  6249. var y = this.y - center.y;
  6250. this.x = x * c - y * s + center.x;
  6251. this.y = x * s + y * c + center.y;
  6252. return this;
  6253. };
  6254. _proto.random = function random() {
  6255. this.x = Math.random();
  6256. this.y = Math.random();
  6257. return this;
  6258. };
  6259. _createClass(Vector2, [{
  6260. key: "width",
  6261. get: function get() {
  6262. return this.x;
  6263. },
  6264. set: function set(value) {
  6265. this.x = value;
  6266. }
  6267. }, {
  6268. key: "height",
  6269. get: function get() {
  6270. return this.y;
  6271. },
  6272. set: function set(value) {
  6273. this.y = value;
  6274. }
  6275. }]);
  6276. return Vector2;
  6277. }();
  6278. var Matrix3 = /*#__PURE__*/function () {
  6279. function Matrix3() {
  6280. Object.defineProperty(this, 'isMatrix3', {
  6281. value: true
  6282. });
  6283. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  6284. if (arguments.length > 0) {
  6285. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  6286. }
  6287. }
  6288. var _proto = Matrix3.prototype;
  6289. _proto.set = function set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  6290. var te = this.elements;
  6291. te[0] = n11;
  6292. te[1] = n21;
  6293. te[2] = n31;
  6294. te[3] = n12;
  6295. te[4] = n22;
  6296. te[5] = n32;
  6297. te[6] = n13;
  6298. te[7] = n23;
  6299. te[8] = n33;
  6300. return this;
  6301. };
  6302. _proto.identity = function identity() {
  6303. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  6304. return this;
  6305. };
  6306. _proto.clone = function clone() {
  6307. return new this.constructor().fromArray(this.elements);
  6308. };
  6309. _proto.copy = function copy(m) {
  6310. var te = this.elements;
  6311. var me = m.elements;
  6312. te[0] = me[0];
  6313. te[1] = me[1];
  6314. te[2] = me[2];
  6315. te[3] = me[3];
  6316. te[4] = me[4];
  6317. te[5] = me[5];
  6318. te[6] = me[6];
  6319. te[7] = me[7];
  6320. te[8] = me[8];
  6321. return this;
  6322. };
  6323. _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
  6324. xAxis.setFromMatrix3Column(this, 0);
  6325. yAxis.setFromMatrix3Column(this, 1);
  6326. zAxis.setFromMatrix3Column(this, 2);
  6327. return this;
  6328. };
  6329. _proto.setFromMatrix4 = function setFromMatrix4(m) {
  6330. var me = m.elements;
  6331. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  6332. return this;
  6333. };
  6334. _proto.multiply = function multiply(m) {
  6335. return this.multiplyMatrices(this, m);
  6336. };
  6337. _proto.premultiply = function premultiply(m) {
  6338. return this.multiplyMatrices(m, this);
  6339. };
  6340. _proto.multiplyMatrices = function multiplyMatrices(a, b) {
  6341. var ae = a.elements;
  6342. var be = b.elements;
  6343. var te = this.elements;
  6344. var a11 = ae[0],
  6345. a12 = ae[3],
  6346. a13 = ae[6];
  6347. var a21 = ae[1],
  6348. a22 = ae[4],
  6349. a23 = ae[7];
  6350. var a31 = ae[2],
  6351. a32 = ae[5],
  6352. a33 = ae[8];
  6353. var b11 = be[0],
  6354. b12 = be[3],
  6355. b13 = be[6];
  6356. var b21 = be[1],
  6357. b22 = be[4],
  6358. b23 = be[7];
  6359. var b31 = be[2],
  6360. b32 = be[5],
  6361. b33 = be[8];
  6362. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  6363. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  6364. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  6365. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  6366. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  6367. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  6368. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  6369. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  6370. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  6371. return this;
  6372. };
  6373. _proto.multiplyScalar = function multiplyScalar(s) {
  6374. var te = this.elements;
  6375. te[0] *= s;
  6376. te[3] *= s;
  6377. te[6] *= s;
  6378. te[1] *= s;
  6379. te[4] *= s;
  6380. te[7] *= s;
  6381. te[2] *= s;
  6382. te[5] *= s;
  6383. te[8] *= s;
  6384. return this;
  6385. };
  6386. _proto.determinant = function determinant() {
  6387. var te = this.elements;
  6388. var a = te[0],
  6389. b = te[1],
  6390. c = te[2],
  6391. d = te[3],
  6392. e = te[4],
  6393. f = te[5],
  6394. g = te[6],
  6395. h = te[7],
  6396. i = te[8];
  6397. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6398. };
  6399. _proto.invert = function invert() {
  6400. var te = this.elements,
  6401. n11 = te[0],
  6402. n21 = te[1],
  6403. n31 = te[2],
  6404. n12 = te[3],
  6405. n22 = te[4],
  6406. n32 = te[5],
  6407. n13 = te[6],
  6408. n23 = te[7],
  6409. n33 = te[8],
  6410. t11 = n33 * n22 - n32 * n23,
  6411. t12 = n32 * n13 - n33 * n12,
  6412. t13 = n23 * n12 - n22 * n13,
  6413. det = n11 * t11 + n21 * t12 + n31 * t13;
  6414. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  6415. var detInv = 1 / det;
  6416. te[0] = t11 * detInv;
  6417. te[1] = (n31 * n23 - n33 * n21) * detInv;
  6418. te[2] = (n32 * n21 - n31 * n22) * detInv;
  6419. te[3] = t12 * detInv;
  6420. te[4] = (n33 * n11 - n31 * n13) * detInv;
  6421. te[5] = (n31 * n12 - n32 * n11) * detInv;
  6422. te[6] = t13 * detInv;
  6423. te[7] = (n21 * n13 - n23 * n11) * detInv;
  6424. te[8] = (n22 * n11 - n21 * n12) * detInv;
  6425. return this;
  6426. };
  6427. _proto.transpose = function transpose() {
  6428. var tmp;
  6429. var m = this.elements;
  6430. tmp = m[1];
  6431. m[1] = m[3];
  6432. m[3] = tmp;
  6433. tmp = m[2];
  6434. m[2] = m[6];
  6435. m[6] = tmp;
  6436. tmp = m[5];
  6437. m[5] = m[7];
  6438. m[7] = tmp;
  6439. return this;
  6440. };
  6441. _proto.getNormalMatrix = function getNormalMatrix(matrix4) {
  6442. return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
  6443. };
  6444. _proto.transposeIntoArray = function transposeIntoArray(r) {
  6445. var m = this.elements;
  6446. r[0] = m[0];
  6447. r[1] = m[3];
  6448. r[2] = m[6];
  6449. r[3] = m[1];
  6450. r[4] = m[4];
  6451. r[5] = m[7];
  6452. r[6] = m[2];
  6453. r[7] = m[5];
  6454. r[8] = m[8];
  6455. return this;
  6456. };
  6457. _proto.setUvTransform = function setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  6458. var c = Math.cos(rotation);
  6459. var s = Math.sin(rotation);
  6460. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  6461. };
  6462. _proto.scale = function scale(sx, sy) {
  6463. var te = this.elements;
  6464. te[0] *= sx;
  6465. te[3] *= sx;
  6466. te[6] *= sx;
  6467. te[1] *= sy;
  6468. te[4] *= sy;
  6469. te[7] *= sy;
  6470. return this;
  6471. };
  6472. _proto.rotate = function rotate(theta) {
  6473. var c = Math.cos(theta);
  6474. var s = Math.sin(theta);
  6475. var te = this.elements;
  6476. var a11 = te[0],
  6477. a12 = te[3],
  6478. a13 = te[6];
  6479. var a21 = te[1],
  6480. a22 = te[4],
  6481. a23 = te[7];
  6482. te[0] = c * a11 + s * a21;
  6483. te[3] = c * a12 + s * a22;
  6484. te[6] = c * a13 + s * a23;
  6485. te[1] = -s * a11 + c * a21;
  6486. te[4] = -s * a12 + c * a22;
  6487. te[7] = -s * a13 + c * a23;
  6488. return this;
  6489. };
  6490. _proto.translate = function translate(tx, ty) {
  6491. var te = this.elements;
  6492. te[0] += tx * te[2];
  6493. te[3] += tx * te[5];
  6494. te[6] += tx * te[8];
  6495. te[1] += ty * te[2];
  6496. te[4] += ty * te[5];
  6497. te[7] += ty * te[8];
  6498. return this;
  6499. };
  6500. _proto.equals = function equals(matrix) {
  6501. var te = this.elements;
  6502. var me = matrix.elements;
  6503. for (var i = 0; i < 9; i++) {
  6504. if (te[i] !== me[i]) return false;
  6505. }
  6506. return true;
  6507. };
  6508. _proto.fromArray = function fromArray(array, offset) {
  6509. if (offset === void 0) {
  6510. offset = 0;
  6511. }
  6512. for (var i = 0; i < 9; i++) {
  6513. this.elements[i] = array[i + offset];
  6514. }
  6515. return this;
  6516. };
  6517. _proto.toArray = function toArray(array, offset) {
  6518. if (array === void 0) {
  6519. array = [];
  6520. }
  6521. if (offset === void 0) {
  6522. offset = 0;
  6523. }
  6524. var te = this.elements;
  6525. array[offset] = te[0];
  6526. array[offset + 1] = te[1];
  6527. array[offset + 2] = te[2];
  6528. array[offset + 3] = te[3];
  6529. array[offset + 4] = te[4];
  6530. array[offset + 5] = te[5];
  6531. array[offset + 6] = te[6];
  6532. array[offset + 7] = te[7];
  6533. array[offset + 8] = te[8];
  6534. return array;
  6535. };
  6536. return Matrix3;
  6537. }();
  6538. var _canvas;
  6539. var ImageUtils = {
  6540. getDataURL: function getDataURL(image) {
  6541. if (/^data:/i.test(image.src)) {
  6542. return image.src;
  6543. }
  6544. if (typeof HTMLCanvasElement == 'undefined') {
  6545. return image.src;
  6546. }
  6547. var canvas;
  6548. if (image instanceof HTMLCanvasElement) {
  6549. canvas = image;
  6550. } else {
  6551. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  6552. _canvas.width = image.width;
  6553. _canvas.height = image.height;
  6554. var context = _canvas.getContext('2d');
  6555. if (image instanceof ImageData) {
  6556. context.putImageData(image, 0, 0);
  6557. } else {
  6558. context.drawImage(image, 0, 0, image.width, image.height);
  6559. }
  6560. canvas = _canvas;
  6561. }
  6562. if (canvas.width > 2048 || canvas.height > 2048) {
  6563. return canvas.toDataURL('image/jpeg', 0.6);
  6564. } else {
  6565. return canvas.toDataURL('image/png');
  6566. }
  6567. }
  6568. };
  6569. var textureId = 0;
  6570. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  6571. if (image === void 0) {
  6572. image = Texture.DEFAULT_IMAGE;
  6573. }
  6574. if (mapping === void 0) {
  6575. mapping = Texture.DEFAULT_MAPPING;
  6576. }
  6577. if (wrapS === void 0) {
  6578. wrapS = ClampToEdgeWrapping;
  6579. }
  6580. if (wrapT === void 0) {
  6581. wrapT = ClampToEdgeWrapping;
  6582. }
  6583. if (magFilter === void 0) {
  6584. magFilter = LinearFilter;
  6585. }
  6586. if (minFilter === void 0) {
  6587. minFilter = LinearMipmapLinearFilter;
  6588. }
  6589. if (format === void 0) {
  6590. format = RGBAFormat;
  6591. }
  6592. if (type === void 0) {
  6593. type = UnsignedByteType;
  6594. }
  6595. if (anisotropy === void 0) {
  6596. anisotropy = 1;
  6597. }
  6598. if (encoding === void 0) {
  6599. encoding = LinearEncoding;
  6600. }
  6601. Object.defineProperty(this, 'id', {
  6602. value: textureId++
  6603. });
  6604. this.uuid = MathUtils.generateUUID();
  6605. this.name = '';
  6606. this.image = image;
  6607. this.mipmaps = [];
  6608. this.mapping = mapping;
  6609. this.wrapS = wrapS;
  6610. this.wrapT = wrapT;
  6611. this.magFilter = magFilter;
  6612. this.minFilter = minFilter;
  6613. this.anisotropy = anisotropy;
  6614. this.format = format;
  6615. this.internalFormat = null;
  6616. this.type = type;
  6617. this.offset = new Vector2(0, 0);
  6618. this.repeat = new Vector2(1, 1);
  6619. this.center = new Vector2(0, 0);
  6620. this.rotation = 0;
  6621. this.matrixAutoUpdate = true;
  6622. this.matrix = new Matrix3();
  6623. this.generateMipmaps = true;
  6624. this.premultiplyAlpha = false;
  6625. this.flipY = true;
  6626. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6627. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6628. //
  6629. // Also changing the encoding after already used by a Material will not automatically make the Material
  6630. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6631. this.encoding = encoding;
  6632. this.version = 0;
  6633. this.onUpdate = null;
  6634. }
  6635. Texture.DEFAULT_IMAGE = undefined;
  6636. Texture.DEFAULT_MAPPING = UVMapping;
  6637. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6638. constructor: Texture,
  6639. isTexture: true,
  6640. updateMatrix: function updateMatrix() {
  6641. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  6642. },
  6643. clone: function clone() {
  6644. return new this.constructor().copy(this);
  6645. },
  6646. copy: function copy(source) {
  6647. this.name = source.name;
  6648. this.image = source.image;
  6649. this.mipmaps = source.mipmaps.slice(0);
  6650. this.mapping = source.mapping;
  6651. this.wrapS = source.wrapS;
  6652. this.wrapT = source.wrapT;
  6653. this.magFilter = source.magFilter;
  6654. this.minFilter = source.minFilter;
  6655. this.anisotropy = source.anisotropy;
  6656. this.format = source.format;
  6657. this.internalFormat = source.internalFormat;
  6658. this.type = source.type;
  6659. this.offset.copy(source.offset);
  6660. this.repeat.copy(source.repeat);
  6661. this.center.copy(source.center);
  6662. this.rotation = source.rotation;
  6663. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6664. this.matrix.copy(source.matrix);
  6665. this.generateMipmaps = source.generateMipmaps;
  6666. this.premultiplyAlpha = source.premultiplyAlpha;
  6667. this.flipY = source.flipY;
  6668. this.unpackAlignment = source.unpackAlignment;
  6669. this.encoding = source.encoding;
  6670. return this;
  6671. },
  6672. toJSON: function toJSON(meta) {
  6673. var isRootObject = meta === undefined || typeof meta === 'string';
  6674. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  6675. return meta.textures[this.uuid];
  6676. }
  6677. var output = {
  6678. metadata: {
  6679. version: 4.5,
  6680. type: 'Texture',
  6681. generator: 'Texture.toJSON'
  6682. },
  6683. uuid: this.uuid,
  6684. name: this.name,
  6685. mapping: this.mapping,
  6686. repeat: [this.repeat.x, this.repeat.y],
  6687. offset: [this.offset.x, this.offset.y],
  6688. center: [this.center.x, this.center.y],
  6689. rotation: this.rotation,
  6690. wrap: [this.wrapS, this.wrapT],
  6691. format: this.format,
  6692. type: this.type,
  6693. encoding: this.encoding,
  6694. minFilter: this.minFilter,
  6695. magFilter: this.magFilter,
  6696. anisotropy: this.anisotropy,
  6697. flipY: this.flipY,
  6698. premultiplyAlpha: this.premultiplyAlpha,
  6699. unpackAlignment: this.unpackAlignment
  6700. };
  6701. if (this.image !== undefined) {
  6702. // TODO: Move to THREE.Image
  6703. var image = this.image;
  6704. if (image.uuid === undefined) {
  6705. image.uuid = MathUtils.generateUUID(); // UGH
  6706. }
  6707. if (!isRootObject && meta.images[image.uuid] === undefined) {
  6708. var url;
  6709. if (Array.isArray(image)) {
  6710. // process array of images e.g. CubeTexture
  6711. url = [];
  6712. for (var i = 0, l = image.length; i < l; i++) {
  6713. // check cube texture with data textures
  6714. if (image[i].isDataTexture) {
  6715. url.push(serializeImage(image[i].image));
  6716. } else {
  6717. url.push(serializeImage(image[i]));
  6718. }
  6719. }
  6720. } else {
  6721. // process single image
  6722. url = serializeImage(image);
  6723. }
  6724. meta.images[image.uuid] = {
  6725. uuid: image.uuid,
  6726. url: url
  6727. };
  6728. }
  6729. output.image = image.uuid;
  6730. }
  6731. if (!isRootObject) {
  6732. meta.textures[this.uuid] = output;
  6733. }
  6734. return output;
  6735. },
  6736. dispose: function dispose() {
  6737. this.dispatchEvent({
  6738. type: 'dispose'
  6739. });
  6740. },
  6741. transformUv: function transformUv(uv) {
  6742. if (this.mapping !== UVMapping) return uv;
  6743. uv.applyMatrix3(this.matrix);
  6744. if (uv.x < 0 || uv.x > 1) {
  6745. switch (this.wrapS) {
  6746. case RepeatWrapping:
  6747. uv.x = uv.x - Math.floor(uv.x);
  6748. break;
  6749. case ClampToEdgeWrapping:
  6750. uv.x = uv.x < 0 ? 0 : 1;
  6751. break;
  6752. case MirroredRepeatWrapping:
  6753. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  6754. uv.x = Math.ceil(uv.x) - uv.x;
  6755. } else {
  6756. uv.x = uv.x - Math.floor(uv.x);
  6757. }
  6758. break;
  6759. }
  6760. }
  6761. if (uv.y < 0 || uv.y > 1) {
  6762. switch (this.wrapT) {
  6763. case RepeatWrapping:
  6764. uv.y = uv.y - Math.floor(uv.y);
  6765. break;
  6766. case ClampToEdgeWrapping:
  6767. uv.y = uv.y < 0 ? 0 : 1;
  6768. break;
  6769. case MirroredRepeatWrapping:
  6770. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  6771. uv.y = Math.ceil(uv.y) - uv.y;
  6772. } else {
  6773. uv.y = uv.y - Math.floor(uv.y);
  6774. }
  6775. break;
  6776. }
  6777. }
  6778. if (this.flipY) {
  6779. uv.y = 1 - uv.y;
  6780. }
  6781. return uv;
  6782. }
  6783. });
  6784. Object.defineProperty(Texture.prototype, "needsUpdate", {
  6785. set: function set(value) {
  6786. if (value === true) this.version++;
  6787. }
  6788. });
  6789. function serializeImage(image) {
  6790. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  6791. // default images
  6792. return ImageUtils.getDataURL(image);
  6793. } else {
  6794. if (image.data) {
  6795. // images of DataTexture
  6796. return {
  6797. data: Array.prototype.slice.call(image.data),
  6798. width: image.width,
  6799. height: image.height,
  6800. type: image.data.constructor.name
  6801. };
  6802. } else {
  6803. console.warn('THREE.Texture: Unable to serialize Texture.');
  6804. return {};
  6805. }
  6806. }
  6807. }
  6808. var Vector4 = /*#__PURE__*/function () {
  6809. function Vector4(x, y, z, w) {
  6810. if (x === void 0) {
  6811. x = 0;
  6812. }
  6813. if (y === void 0) {
  6814. y = 0;
  6815. }
  6816. if (z === void 0) {
  6817. z = 0;
  6818. }
  6819. if (w === void 0) {
  6820. w = 1;
  6821. }
  6822. Object.defineProperty(this, 'isVector4', {
  6823. value: true
  6824. });
  6825. this.x = x;
  6826. this.y = y;
  6827. this.z = z;
  6828. this.w = w;
  6829. }
  6830. var _proto = Vector4.prototype;
  6831. _proto.set = function set(x, y, z, w) {
  6832. this.x = x;
  6833. this.y = y;
  6834. this.z = z;
  6835. this.w = w;
  6836. return this;
  6837. };
  6838. _proto.setScalar = function setScalar(scalar) {
  6839. this.x = scalar;
  6840. this.y = scalar;
  6841. this.z = scalar;
  6842. this.w = scalar;
  6843. return this;
  6844. };
  6845. _proto.setX = function setX(x) {
  6846. this.x = x;
  6847. return this;
  6848. };
  6849. _proto.setY = function setY(y) {
  6850. this.y = y;
  6851. return this;
  6852. };
  6853. _proto.setZ = function setZ(z) {
  6854. this.z = z;
  6855. return this;
  6856. };
  6857. _proto.setW = function setW(w) {
  6858. this.w = w;
  6859. return this;
  6860. };
  6861. _proto.setComponent = function setComponent(index, value) {
  6862. switch (index) {
  6863. case 0:
  6864. this.x = value;
  6865. break;
  6866. case 1:
  6867. this.y = value;
  6868. break;
  6869. case 2:
  6870. this.z = value;
  6871. break;
  6872. case 3:
  6873. this.w = value;
  6874. break;
  6875. default:
  6876. throw new Error('index is out of range: ' + index);
  6877. }
  6878. return this;
  6879. };
  6880. _proto.getComponent = function getComponent(index) {
  6881. switch (index) {
  6882. case 0:
  6883. return this.x;
  6884. case 1:
  6885. return this.y;
  6886. case 2:
  6887. return this.z;
  6888. case 3:
  6889. return this.w;
  6890. default:
  6891. throw new Error('index is out of range: ' + index);
  6892. }
  6893. };
  6894. _proto.clone = function clone() {
  6895. return new this.constructor(this.x, this.y, this.z, this.w);
  6896. };
  6897. _proto.copy = function copy(v) {
  6898. this.x = v.x;
  6899. this.y = v.y;
  6900. this.z = v.z;
  6901. this.w = v.w !== undefined ? v.w : 1;
  6902. return this;
  6903. };
  6904. _proto.add = function add(v, w) {
  6905. if (w !== undefined) {
  6906. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  6907. return this.addVectors(v, w);
  6908. }
  6909. this.x += v.x;
  6910. this.y += v.y;
  6911. this.z += v.z;
  6912. this.w += v.w;
  6913. return this;
  6914. };
  6915. _proto.addScalar = function addScalar(s) {
  6916. this.x += s;
  6917. this.y += s;
  6918. this.z += s;
  6919. this.w += s;
  6920. return this;
  6921. };
  6922. _proto.addVectors = function addVectors(a, b) {
  6923. this.x = a.x + b.x;
  6924. this.y = a.y + b.y;
  6925. this.z = a.z + b.z;
  6926. this.w = a.w + b.w;
  6927. return this;
  6928. };
  6929. _proto.addScaledVector = function addScaledVector(v, s) {
  6930. this.x += v.x * s;
  6931. this.y += v.y * s;
  6932. this.z += v.z * s;
  6933. this.w += v.w * s;
  6934. return this;
  6935. };
  6936. _proto.sub = function sub(v, w) {
  6937. if (w !== undefined) {
  6938. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  6939. return this.subVectors(v, w);
  6940. }
  6941. this.x -= v.x;
  6942. this.y -= v.y;
  6943. this.z -= v.z;
  6944. this.w -= v.w;
  6945. return this;
  6946. };
  6947. _proto.subScalar = function subScalar(s) {
  6948. this.x -= s;
  6949. this.y -= s;
  6950. this.z -= s;
  6951. this.w -= s;
  6952. return this;
  6953. };
  6954. _proto.subVectors = function subVectors(a, b) {
  6955. this.x = a.x - b.x;
  6956. this.y = a.y - b.y;
  6957. this.z = a.z - b.z;
  6958. this.w = a.w - b.w;
  6959. return this;
  6960. };
  6961. _proto.multiplyScalar = function multiplyScalar(scalar) {
  6962. this.x *= scalar;
  6963. this.y *= scalar;
  6964. this.z *= scalar;
  6965. this.w *= scalar;
  6966. return this;
  6967. };
  6968. _proto.applyMatrix4 = function applyMatrix4(m) {
  6969. var x = this.x,
  6970. y = this.y,
  6971. z = this.z,
  6972. w = this.w;
  6973. var e = m.elements;
  6974. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  6975. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  6976. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  6977. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  6978. return this;
  6979. };
  6980. _proto.divideScalar = function divideScalar(scalar) {
  6981. return this.multiplyScalar(1 / scalar);
  6982. };
  6983. _proto.setAxisAngleFromQuaternion = function setAxisAngleFromQuaternion(q) {
  6984. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6985. // q is assumed to be normalized
  6986. this.w = 2 * Math.acos(q.w);
  6987. var s = Math.sqrt(1 - q.w * q.w);
  6988. if (s < 0.0001) {
  6989. this.x = 1;
  6990. this.y = 0;
  6991. this.z = 0;
  6992. } else {
  6993. this.x = q.x / s;
  6994. this.y = q.y / s;
  6995. this.z = q.z / s;
  6996. }
  6997. return this;
  6998. };
  6999. _proto.setAxisAngleFromRotationMatrix = function setAxisAngleFromRotationMatrix(m) {
  7000. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7001. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7002. var angle, x, y, z; // variables for result
  7003. var epsilon = 0.01,
  7004. // margin to allow for rounding errors
  7005. epsilon2 = 0.1,
  7006. // margin to distinguish between 0 and 180 degrees
  7007. te = m.elements,
  7008. m11 = te[0],
  7009. m12 = te[4],
  7010. m13 = te[8],
  7011. m21 = te[1],
  7012. m22 = te[5],
  7013. m23 = te[9],
  7014. m31 = te[2],
  7015. m32 = te[6],
  7016. m33 = te[10];
  7017. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  7018. // singularity found
  7019. // first check for identity matrix which must have +1 for all terms
  7020. // in leading diagonal and zero in other terms
  7021. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  7022. // this singularity is identity matrix so angle = 0
  7023. this.set(1, 0, 0, 0);
  7024. return this; // zero angle, arbitrary axis
  7025. } // otherwise this singularity is angle = 180
  7026. angle = Math.PI;
  7027. var xx = (m11 + 1) / 2;
  7028. var yy = (m22 + 1) / 2;
  7029. var zz = (m33 + 1) / 2;
  7030. var xy = (m12 + m21) / 4;
  7031. var xz = (m13 + m31) / 4;
  7032. var yz = (m23 + m32) / 4;
  7033. if (xx > yy && xx > zz) {
  7034. // m11 is the largest diagonal term
  7035. if (xx < epsilon) {
  7036. x = 0;
  7037. y = 0.707106781;
  7038. z = 0.707106781;
  7039. } else {
  7040. x = Math.sqrt(xx);
  7041. y = xy / x;
  7042. z = xz / x;
  7043. }
  7044. } else if (yy > zz) {
  7045. // m22 is the largest diagonal term
  7046. if (yy < epsilon) {
  7047. x = 0.707106781;
  7048. y = 0;
  7049. z = 0.707106781;
  7050. } else {
  7051. y = Math.sqrt(yy);
  7052. x = xy / y;
  7053. z = yz / y;
  7054. }
  7055. } else {
  7056. // m33 is the largest diagonal term so base result on this
  7057. if (zz < epsilon) {
  7058. x = 0.707106781;
  7059. y = 0.707106781;
  7060. z = 0;
  7061. } else {
  7062. z = Math.sqrt(zz);
  7063. x = xz / z;
  7064. y = yz / z;
  7065. }
  7066. }
  7067. this.set(x, y, z, angle);
  7068. return this; // return 180 deg rotation
  7069. } // as we have reached here there are no singularities so we can handle normally
  7070. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  7071. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7072. // caught by singularity test above, but I've left it in just in case
  7073. this.x = (m32 - m23) / s;
  7074. this.y = (m13 - m31) / s;
  7075. this.z = (m21 - m12) / s;
  7076. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  7077. return this;
  7078. };
  7079. _proto.min = function min(v) {
  7080. this.x = Math.min(this.x, v.x);
  7081. this.y = Math.min(this.y, v.y);
  7082. this.z = Math.min(this.z, v.z);
  7083. this.w = Math.min(this.w, v.w);
  7084. return this;
  7085. };
  7086. _proto.max = function max(v) {
  7087. this.x = Math.max(this.x, v.x);
  7088. this.y = Math.max(this.y, v.y);
  7089. this.z = Math.max(this.z, v.z);
  7090. this.w = Math.max(this.w, v.w);
  7091. return this;
  7092. };
  7093. _proto.clamp = function clamp(min, max) {
  7094. // assumes min < max, componentwise
  7095. this.x = Math.max(min.x, Math.min(max.x, this.x));
  7096. this.y = Math.max(min.y, Math.min(max.y, this.y));
  7097. this.z = Math.max(min.z, Math.min(max.z, this.z));
  7098. this.w = Math.max(min.w, Math.min(max.w, this.w));
  7099. return this;
  7100. };
  7101. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  7102. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  7103. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  7104. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  7105. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  7106. return this;
  7107. };
  7108. _proto.clampLength = function clampLength(min, max) {
  7109. var length = this.length();
  7110. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  7111. };
  7112. _proto.floor = function floor() {
  7113. this.x = Math.floor(this.x);
  7114. this.y = Math.floor(this.y);
  7115. this.z = Math.floor(this.z);
  7116. this.w = Math.floor(this.w);
  7117. return this;
  7118. };
  7119. _proto.ceil = function ceil() {
  7120. this.x = Math.ceil(this.x);
  7121. this.y = Math.ceil(this.y);
  7122. this.z = Math.ceil(this.z);
  7123. this.w = Math.ceil(this.w);
  7124. return this;
  7125. };
  7126. _proto.round = function round() {
  7127. this.x = Math.round(this.x);
  7128. this.y = Math.round(this.y);
  7129. this.z = Math.round(this.z);
  7130. this.w = Math.round(this.w);
  7131. return this;
  7132. };
  7133. _proto.roundToZero = function roundToZero() {
  7134. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  7135. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  7136. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  7137. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  7138. return this;
  7139. };
  7140. _proto.negate = function negate() {
  7141. this.x = -this.x;
  7142. this.y = -this.y;
  7143. this.z = -this.z;
  7144. this.w = -this.w;
  7145. return this;
  7146. };
  7147. _proto.dot = function dot(v) {
  7148. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7149. };
  7150. _proto.lengthSq = function lengthSq() {
  7151. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7152. };
  7153. _proto.length = function length() {
  7154. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  7155. };
  7156. _proto.manhattanLength = function manhattanLength() {
  7157. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  7158. };
  7159. _proto.normalize = function normalize() {
  7160. return this.divideScalar(this.length() || 1);
  7161. };
  7162. _proto.setLength = function setLength(length) {
  7163. return this.normalize().multiplyScalar(length);
  7164. };
  7165. _proto.lerp = function lerp(v, alpha) {
  7166. this.x += (v.x - this.x) * alpha;
  7167. this.y += (v.y - this.y) * alpha;
  7168. this.z += (v.z - this.z) * alpha;
  7169. this.w += (v.w - this.w) * alpha;
  7170. return this;
  7171. };
  7172. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  7173. this.x = v1.x + (v2.x - v1.x) * alpha;
  7174. this.y = v1.y + (v2.y - v1.y) * alpha;
  7175. this.z = v1.z + (v2.z - v1.z) * alpha;
  7176. this.w = v1.w + (v2.w - v1.w) * alpha;
  7177. return this;
  7178. };
  7179. _proto.equals = function equals(v) {
  7180. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  7181. };
  7182. _proto.fromArray = function fromArray(array, offset) {
  7183. if (offset === void 0) {
  7184. offset = 0;
  7185. }
  7186. this.x = array[offset];
  7187. this.y = array[offset + 1];
  7188. this.z = array[offset + 2];
  7189. this.w = array[offset + 3];
  7190. return this;
  7191. };
  7192. _proto.toArray = function toArray(array, offset) {
  7193. if (array === void 0) {
  7194. array = [];
  7195. }
  7196. if (offset === void 0) {
  7197. offset = 0;
  7198. }
  7199. array[offset] = this.x;
  7200. array[offset + 1] = this.y;
  7201. array[offset + 2] = this.z;
  7202. array[offset + 3] = this.w;
  7203. return array;
  7204. };
  7205. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  7206. if (offset !== undefined) {
  7207. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  7208. }
  7209. this.x = attribute.getX(index);
  7210. this.y = attribute.getY(index);
  7211. this.z = attribute.getZ(index);
  7212. this.w = attribute.getW(index);
  7213. return this;
  7214. };
  7215. _proto.random = function random() {
  7216. this.x = Math.random();
  7217. this.y = Math.random();
  7218. this.z = Math.random();
  7219. this.w = Math.random();
  7220. return this;
  7221. };
  7222. _createClass(Vector4, [{
  7223. key: "width",
  7224. get: function get() {
  7225. return this.z;
  7226. },
  7227. set: function set(value) {
  7228. this.z = value;
  7229. }
  7230. }, {
  7231. key: "height",
  7232. get: function get() {
  7233. return this.w;
  7234. },
  7235. set: function set(value) {
  7236. this.w = value;
  7237. }
  7238. }]);
  7239. return Vector4;
  7240. }();
  7241. /*
  7242. In options, we can specify:
  7243. * Texture parameters for an auto-generated target texture
  7244. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7245. */
  7246. function WebGLRenderTarget(width, height, options) {
  7247. this.width = width;
  7248. this.height = height;
  7249. this.scissor = new Vector4(0, 0, width, height);
  7250. this.scissorTest = false;
  7251. this.viewport = new Vector4(0, 0, width, height);
  7252. options = options || {};
  7253. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7254. this.texture.image = {};
  7255. this.texture.image.width = width;
  7256. this.texture.image.height = height;
  7257. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7258. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7259. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7260. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  7261. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7262. }
  7263. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7264. constructor: WebGLRenderTarget,
  7265. isWebGLRenderTarget: true,
  7266. setSize: function setSize(width, height) {
  7267. if (this.width !== width || this.height !== height) {
  7268. this.width = width;
  7269. this.height = height;
  7270. this.texture.image.width = width;
  7271. this.texture.image.height = height;
  7272. this.dispose();
  7273. }
  7274. this.viewport.set(0, 0, width, height);
  7275. this.scissor.set(0, 0, width, height);
  7276. },
  7277. clone: function clone() {
  7278. return new this.constructor().copy(this);
  7279. },
  7280. copy: function copy(source) {
  7281. this.width = source.width;
  7282. this.height = source.height;
  7283. this.viewport.copy(source.viewport);
  7284. this.texture = source.texture.clone();
  7285. this.depthBuffer = source.depthBuffer;
  7286. this.stencilBuffer = source.stencilBuffer;
  7287. this.depthTexture = source.depthTexture;
  7288. return this;
  7289. },
  7290. dispose: function dispose() {
  7291. this.dispatchEvent({
  7292. type: 'dispose'
  7293. });
  7294. }
  7295. });
  7296. function WebGLMultisampleRenderTarget(width, height, options) {
  7297. WebGLRenderTarget.call(this, width, height, options);
  7298. this.samples = 4;
  7299. }
  7300. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  7301. constructor: WebGLMultisampleRenderTarget,
  7302. isWebGLMultisampleRenderTarget: true,
  7303. copy: function copy(source) {
  7304. WebGLRenderTarget.prototype.copy.call(this, source);
  7305. this.samples = source.samples;
  7306. return this;
  7307. }
  7308. });
  7309. var Quaternion = /*#__PURE__*/function () {
  7310. function Quaternion(x, y, z, w) {
  7311. if (x === void 0) {
  7312. x = 0;
  7313. }
  7314. if (y === void 0) {
  7315. y = 0;
  7316. }
  7317. if (z === void 0) {
  7318. z = 0;
  7319. }
  7320. if (w === void 0) {
  7321. w = 1;
  7322. }
  7323. Object.defineProperty(this, 'isQuaternion', {
  7324. value: true
  7325. });
  7326. this._x = x;
  7327. this._y = y;
  7328. this._z = z;
  7329. this._w = w;
  7330. }
  7331. Quaternion.slerp = function slerp(qa, qb, qm, t) {
  7332. return qm.copy(qa).slerp(qb, t);
  7333. };
  7334. Quaternion.slerpFlat = function slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  7335. // fuzz-free, array-based Quaternion SLERP operation
  7336. var x0 = src0[srcOffset0 + 0],
  7337. y0 = src0[srcOffset0 + 1],
  7338. z0 = src0[srcOffset0 + 2],
  7339. w0 = src0[srcOffset0 + 3];
  7340. var x1 = src1[srcOffset1 + 0],
  7341. y1 = src1[srcOffset1 + 1],
  7342. z1 = src1[srcOffset1 + 2],
  7343. w1 = src1[srcOffset1 + 3];
  7344. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  7345. var s = 1 - t;
  7346. var cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  7347. dir = cos >= 0 ? 1 : -1,
  7348. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  7349. if (sqrSin > Number.EPSILON) {
  7350. var sin = Math.sqrt(sqrSin),
  7351. len = Math.atan2(sin, cos * dir);
  7352. s = Math.sin(s * len) / sin;
  7353. t = Math.sin(t * len) / sin;
  7354. }
  7355. var tDir = t * dir;
  7356. x0 = x0 * s + x1 * tDir;
  7357. y0 = y0 * s + y1 * tDir;
  7358. z0 = z0 * s + z1 * tDir;
  7359. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  7360. if (s === 1 - t) {
  7361. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  7362. x0 *= f;
  7363. y0 *= f;
  7364. z0 *= f;
  7365. w0 *= f;
  7366. }
  7367. }
  7368. dst[dstOffset] = x0;
  7369. dst[dstOffset + 1] = y0;
  7370. dst[dstOffset + 2] = z0;
  7371. dst[dstOffset + 3] = w0;
  7372. };
  7373. Quaternion.multiplyQuaternionsFlat = function multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  7374. var x0 = src0[srcOffset0];
  7375. var y0 = src0[srcOffset0 + 1];
  7376. var z0 = src0[srcOffset0 + 2];
  7377. var w0 = src0[srcOffset0 + 3];
  7378. var x1 = src1[srcOffset1];
  7379. var y1 = src1[srcOffset1 + 1];
  7380. var z1 = src1[srcOffset1 + 2];
  7381. var w1 = src1[srcOffset1 + 3];
  7382. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  7383. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  7384. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  7385. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  7386. return dst;
  7387. };
  7388. var _proto = Quaternion.prototype;
  7389. _proto.set = function set(x, y, z, w) {
  7390. this._x = x;
  7391. this._y = y;
  7392. this._z = z;
  7393. this._w = w;
  7394. this._onChangeCallback();
  7395. return this;
  7396. };
  7397. _proto.clone = function clone() {
  7398. return new this.constructor(this._x, this._y, this._z, this._w);
  7399. };
  7400. _proto.copy = function copy(quaternion) {
  7401. this._x = quaternion.x;
  7402. this._y = quaternion.y;
  7403. this._z = quaternion.z;
  7404. this._w = quaternion.w;
  7405. this._onChangeCallback();
  7406. return this;
  7407. };
  7408. _proto.setFromEuler = function setFromEuler(euler, update) {
  7409. if (!(euler && euler.isEuler)) {
  7410. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  7411. }
  7412. var x = euler._x,
  7413. y = euler._y,
  7414. z = euler._z,
  7415. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  7416. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  7417. // content/SpinCalc.m
  7418. var cos = Math.cos;
  7419. var sin = Math.sin;
  7420. var c1 = cos(x / 2);
  7421. var c2 = cos(y / 2);
  7422. var c3 = cos(z / 2);
  7423. var s1 = sin(x / 2);
  7424. var s2 = sin(y / 2);
  7425. var s3 = sin(z / 2);
  7426. switch (order) {
  7427. case 'XYZ':
  7428. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7429. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7430. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7431. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7432. break;
  7433. case 'YXZ':
  7434. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7435. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7436. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7437. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7438. break;
  7439. case 'ZXY':
  7440. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7441. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7442. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7443. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7444. break;
  7445. case 'ZYX':
  7446. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7447. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7448. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7449. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7450. break;
  7451. case 'YZX':
  7452. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7453. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7454. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7455. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7456. break;
  7457. case 'XZY':
  7458. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7459. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7460. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7461. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7462. break;
  7463. default:
  7464. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  7465. }
  7466. if (update !== false) this._onChangeCallback();
  7467. return this;
  7468. };
  7469. _proto.setFromAxisAngle = function setFromAxisAngle(axis, angle) {
  7470. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  7471. // assumes axis is normalized
  7472. var halfAngle = angle / 2,
  7473. s = Math.sin(halfAngle);
  7474. this._x = axis.x * s;
  7475. this._y = axis.y * s;
  7476. this._z = axis.z * s;
  7477. this._w = Math.cos(halfAngle);
  7478. this._onChangeCallback();
  7479. return this;
  7480. };
  7481. _proto.setFromRotationMatrix = function setFromRotationMatrix(m) {
  7482. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  7483. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7484. var te = m.elements,
  7485. m11 = te[0],
  7486. m12 = te[4],
  7487. m13 = te[8],
  7488. m21 = te[1],
  7489. m22 = te[5],
  7490. m23 = te[9],
  7491. m31 = te[2],
  7492. m32 = te[6],
  7493. m33 = te[10],
  7494. trace = m11 + m22 + m33;
  7495. if (trace > 0) {
  7496. var s = 0.5 / Math.sqrt(trace + 1.0);
  7497. this._w = 0.25 / s;
  7498. this._x = (m32 - m23) * s;
  7499. this._y = (m13 - m31) * s;
  7500. this._z = (m21 - m12) * s;
  7501. } else if (m11 > m22 && m11 > m33) {
  7502. var _s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7503. this._w = (m32 - m23) / _s;
  7504. this._x = 0.25 * _s;
  7505. this._y = (m12 + m21) / _s;
  7506. this._z = (m13 + m31) / _s;
  7507. } else if (m22 > m33) {
  7508. var _s2 = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7509. this._w = (m13 - m31) / _s2;
  7510. this._x = (m12 + m21) / _s2;
  7511. this._y = 0.25 * _s2;
  7512. this._z = (m23 + m32) / _s2;
  7513. } else {
  7514. var _s3 = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7515. this._w = (m21 - m12) / _s3;
  7516. this._x = (m13 + m31) / _s3;
  7517. this._y = (m23 + m32) / _s3;
  7518. this._z = 0.25 * _s3;
  7519. }
  7520. this._onChangeCallback();
  7521. return this;
  7522. };
  7523. _proto.setFromUnitVectors = function setFromUnitVectors(vFrom, vTo) {
  7524. // assumes direction vectors vFrom and vTo are normalized
  7525. var EPS = 0.000001;
  7526. var r = vFrom.dot(vTo) + 1;
  7527. if (r < EPS) {
  7528. r = 0;
  7529. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  7530. this._x = -vFrom.y;
  7531. this._y = vFrom.x;
  7532. this._z = 0;
  7533. this._w = r;
  7534. } else {
  7535. this._x = 0;
  7536. this._y = -vFrom.z;
  7537. this._z = vFrom.y;
  7538. this._w = r;
  7539. }
  7540. } else {
  7541. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  7542. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  7543. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  7544. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  7545. this._w = r;
  7546. }
  7547. return this.normalize();
  7548. };
  7549. _proto.angleTo = function angleTo(q) {
  7550. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  7551. };
  7552. _proto.rotateTowards = function rotateTowards(q, step) {
  7553. var angle = this.angleTo(q);
  7554. if (angle === 0) return this;
  7555. var t = Math.min(1, step / angle);
  7556. this.slerp(q, t);
  7557. return this;
  7558. };
  7559. _proto.identity = function identity() {
  7560. return this.set(0, 0, 0, 1);
  7561. };
  7562. _proto.invert = function invert() {
  7563. // quaternion is assumed to have unit length
  7564. return this.conjugate();
  7565. };
  7566. _proto.conjugate = function conjugate() {
  7567. this._x *= -1;
  7568. this._y *= -1;
  7569. this._z *= -1;
  7570. this._onChangeCallback();
  7571. return this;
  7572. };
  7573. _proto.dot = function dot(v) {
  7574. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  7575. };
  7576. _proto.lengthSq = function lengthSq() {
  7577. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  7578. };
  7579. _proto.length = function length() {
  7580. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  7581. };
  7582. _proto.normalize = function normalize() {
  7583. var l = this.length();
  7584. if (l === 0) {
  7585. this._x = 0;
  7586. this._y = 0;
  7587. this._z = 0;
  7588. this._w = 1;
  7589. } else {
  7590. l = 1 / l;
  7591. this._x = this._x * l;
  7592. this._y = this._y * l;
  7593. this._z = this._z * l;
  7594. this._w = this._w * l;
  7595. }
  7596. this._onChangeCallback();
  7597. return this;
  7598. };
  7599. _proto.multiply = function multiply(q, p) {
  7600. if (p !== undefined) {
  7601. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  7602. return this.multiplyQuaternions(q, p);
  7603. }
  7604. return this.multiplyQuaternions(this, q);
  7605. };
  7606. _proto.premultiply = function premultiply(q) {
  7607. return this.multiplyQuaternions(q, this);
  7608. };
  7609. _proto.multiplyQuaternions = function multiplyQuaternions(a, b) {
  7610. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  7611. var qax = a._x,
  7612. qay = a._y,
  7613. qaz = a._z,
  7614. qaw = a._w;
  7615. var qbx = b._x,
  7616. qby = b._y,
  7617. qbz = b._z,
  7618. qbw = b._w;
  7619. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  7620. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  7621. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  7622. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  7623. this._onChangeCallback();
  7624. return this;
  7625. };
  7626. _proto.slerp = function slerp(qb, t) {
  7627. if (t === 0) return this;
  7628. if (t === 1) return this.copy(qb);
  7629. var x = this._x,
  7630. y = this._y,
  7631. z = this._z,
  7632. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  7633. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  7634. if (cosHalfTheta < 0) {
  7635. this._w = -qb._w;
  7636. this._x = -qb._x;
  7637. this._y = -qb._y;
  7638. this._z = -qb._z;
  7639. cosHalfTheta = -cosHalfTheta;
  7640. } else {
  7641. this.copy(qb);
  7642. }
  7643. if (cosHalfTheta >= 1.0) {
  7644. this._w = w;
  7645. this._x = x;
  7646. this._y = y;
  7647. this._z = z;
  7648. return this;
  7649. }
  7650. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  7651. if (sqrSinHalfTheta <= Number.EPSILON) {
  7652. var s = 1 - t;
  7653. this._w = s * w + t * this._w;
  7654. this._x = s * x + t * this._x;
  7655. this._y = s * y + t * this._y;
  7656. this._z = s * z + t * this._z;
  7657. this.normalize();
  7658. this._onChangeCallback();
  7659. return this;
  7660. }
  7661. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  7662. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  7663. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  7664. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  7665. this._w = w * ratioA + this._w * ratioB;
  7666. this._x = x * ratioA + this._x * ratioB;
  7667. this._y = y * ratioA + this._y * ratioB;
  7668. this._z = z * ratioA + this._z * ratioB;
  7669. this._onChangeCallback();
  7670. return this;
  7671. };
  7672. _proto.equals = function equals(quaternion) {
  7673. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  7674. };
  7675. _proto.fromArray = function fromArray(array, offset) {
  7676. if (offset === void 0) {
  7677. offset = 0;
  7678. }
  7679. this._x = array[offset];
  7680. this._y = array[offset + 1];
  7681. this._z = array[offset + 2];
  7682. this._w = array[offset + 3];
  7683. this._onChangeCallback();
  7684. return this;
  7685. };
  7686. _proto.toArray = function toArray(array, offset) {
  7687. if (array === void 0) {
  7688. array = [];
  7689. }
  7690. if (offset === void 0) {
  7691. offset = 0;
  7692. }
  7693. array[offset] = this._x;
  7694. array[offset + 1] = this._y;
  7695. array[offset + 2] = this._z;
  7696. array[offset + 3] = this._w;
  7697. return array;
  7698. };
  7699. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
  7700. this._x = attribute.getX(index);
  7701. this._y = attribute.getY(index);
  7702. this._z = attribute.getZ(index);
  7703. this._w = attribute.getW(index);
  7704. return this;
  7705. };
  7706. _proto._onChange = function _onChange(callback) {
  7707. this._onChangeCallback = callback;
  7708. return this;
  7709. };
  7710. _proto._onChangeCallback = function _onChangeCallback() {};
  7711. _createClass(Quaternion, [{
  7712. key: "x",
  7713. get: function get() {
  7714. return this._x;
  7715. },
  7716. set: function set(value) {
  7717. this._x = value;
  7718. this._onChangeCallback();
  7719. }
  7720. }, {
  7721. key: "y",
  7722. get: function get() {
  7723. return this._y;
  7724. },
  7725. set: function set(value) {
  7726. this._y = value;
  7727. this._onChangeCallback();
  7728. }
  7729. }, {
  7730. key: "z",
  7731. get: function get() {
  7732. return this._z;
  7733. },
  7734. set: function set(value) {
  7735. this._z = value;
  7736. this._onChangeCallback();
  7737. }
  7738. }, {
  7739. key: "w",
  7740. get: function get() {
  7741. return this._w;
  7742. },
  7743. set: function set(value) {
  7744. this._w = value;
  7745. this._onChangeCallback();
  7746. }
  7747. }]);
  7748. return Quaternion;
  7749. }();
  7750. var Vector3 = /*#__PURE__*/function () {
  7751. function Vector3(x, y, z) {
  7752. if (x === void 0) {
  7753. x = 0;
  7754. }
  7755. if (y === void 0) {
  7756. y = 0;
  7757. }
  7758. if (z === void 0) {
  7759. z = 0;
  7760. }
  7761. Object.defineProperty(this, 'isVector3', {
  7762. value: true
  7763. });
  7764. this.x = x;
  7765. this.y = y;
  7766. this.z = z;
  7767. }
  7768. var _proto = Vector3.prototype;
  7769. _proto.set = function set(x, y, z) {
  7770. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  7771. this.x = x;
  7772. this.y = y;
  7773. this.z = z;
  7774. return this;
  7775. };
  7776. _proto.setScalar = function setScalar(scalar) {
  7777. this.x = scalar;
  7778. this.y = scalar;
  7779. this.z = scalar;
  7780. return this;
  7781. };
  7782. _proto.setX = function setX(x) {
  7783. this.x = x;
  7784. return this;
  7785. };
  7786. _proto.setY = function setY(y) {
  7787. this.y = y;
  7788. return this;
  7789. };
  7790. _proto.setZ = function setZ(z) {
  7791. this.z = z;
  7792. return this;
  7793. };
  7794. _proto.setComponent = function setComponent(index, value) {
  7795. switch (index) {
  7796. case 0:
  7797. this.x = value;
  7798. break;
  7799. case 1:
  7800. this.y = value;
  7801. break;
  7802. case 2:
  7803. this.z = value;
  7804. break;
  7805. default:
  7806. throw new Error('index is out of range: ' + index);
  7807. }
  7808. return this;
  7809. };
  7810. _proto.getComponent = function getComponent(index) {
  7811. switch (index) {
  7812. case 0:
  7813. return this.x;
  7814. case 1:
  7815. return this.y;
  7816. case 2:
  7817. return this.z;
  7818. default:
  7819. throw new Error('index is out of range: ' + index);
  7820. }
  7821. };
  7822. _proto.clone = function clone() {
  7823. return new this.constructor(this.x, this.y, this.z);
  7824. };
  7825. _proto.copy = function copy(v) {
  7826. this.x = v.x;
  7827. this.y = v.y;
  7828. this.z = v.z;
  7829. return this;
  7830. };
  7831. _proto.add = function add(v, w) {
  7832. if (w !== undefined) {
  7833. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  7834. return this.addVectors(v, w);
  7835. }
  7836. this.x += v.x;
  7837. this.y += v.y;
  7838. this.z += v.z;
  7839. return this;
  7840. };
  7841. _proto.addScalar = function addScalar(s) {
  7842. this.x += s;
  7843. this.y += s;
  7844. this.z += s;
  7845. return this;
  7846. };
  7847. _proto.addVectors = function addVectors(a, b) {
  7848. this.x = a.x + b.x;
  7849. this.y = a.y + b.y;
  7850. this.z = a.z + b.z;
  7851. return this;
  7852. };
  7853. _proto.addScaledVector = function addScaledVector(v, s) {
  7854. this.x += v.x * s;
  7855. this.y += v.y * s;
  7856. this.z += v.z * s;
  7857. return this;
  7858. };
  7859. _proto.sub = function sub(v, w) {
  7860. if (w !== undefined) {
  7861. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  7862. return this.subVectors(v, w);
  7863. }
  7864. this.x -= v.x;
  7865. this.y -= v.y;
  7866. this.z -= v.z;
  7867. return this;
  7868. };
  7869. _proto.subScalar = function subScalar(s) {
  7870. this.x -= s;
  7871. this.y -= s;
  7872. this.z -= s;
  7873. return this;
  7874. };
  7875. _proto.subVectors = function subVectors(a, b) {
  7876. this.x = a.x - b.x;
  7877. this.y = a.y - b.y;
  7878. this.z = a.z - b.z;
  7879. return this;
  7880. };
  7881. _proto.multiply = function multiply(v, w) {
  7882. if (w !== undefined) {
  7883. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  7884. return this.multiplyVectors(v, w);
  7885. }
  7886. this.x *= v.x;
  7887. this.y *= v.y;
  7888. this.z *= v.z;
  7889. return this;
  7890. };
  7891. _proto.multiplyScalar = function multiplyScalar(scalar) {
  7892. this.x *= scalar;
  7893. this.y *= scalar;
  7894. this.z *= scalar;
  7895. return this;
  7896. };
  7897. _proto.multiplyVectors = function multiplyVectors(a, b) {
  7898. this.x = a.x * b.x;
  7899. this.y = a.y * b.y;
  7900. this.z = a.z * b.z;
  7901. return this;
  7902. };
  7903. _proto.applyEuler = function applyEuler(euler) {
  7904. if (!(euler && euler.isEuler)) {
  7905. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  7906. }
  7907. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  7908. };
  7909. _proto.applyAxisAngle = function applyAxisAngle(axis, angle) {
  7910. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  7911. };
  7912. _proto.applyMatrix3 = function applyMatrix3(m) {
  7913. var x = this.x,
  7914. y = this.y,
  7915. z = this.z;
  7916. var e = m.elements;
  7917. this.x = e[0] * x + e[3] * y + e[6] * z;
  7918. this.y = e[1] * x + e[4] * y + e[7] * z;
  7919. this.z = e[2] * x + e[5] * y + e[8] * z;
  7920. return this;
  7921. };
  7922. _proto.applyNormalMatrix = function applyNormalMatrix(m) {
  7923. return this.applyMatrix3(m).normalize();
  7924. };
  7925. _proto.applyMatrix4 = function applyMatrix4(m) {
  7926. var x = this.x,
  7927. y = this.y,
  7928. z = this.z;
  7929. var e = m.elements;
  7930. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  7931. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  7932. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  7933. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  7934. return this;
  7935. };
  7936. _proto.applyQuaternion = function applyQuaternion(q) {
  7937. var x = this.x,
  7938. y = this.y,
  7939. z = this.z;
  7940. var qx = q.x,
  7941. qy = q.y,
  7942. qz = q.z,
  7943. qw = q.w; // calculate quat * vector
  7944. var ix = qw * x + qy * z - qz * y;
  7945. var iy = qw * y + qz * x - qx * z;
  7946. var iz = qw * z + qx * y - qy * x;
  7947. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  7948. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  7949. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  7950. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  7951. return this;
  7952. };
  7953. _proto.project = function project(camera) {
  7954. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  7955. };
  7956. _proto.unproject = function unproject(camera) {
  7957. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  7958. };
  7959. _proto.transformDirection = function transformDirection(m) {
  7960. // input: THREE.Matrix4 affine matrix
  7961. // vector interpreted as a direction
  7962. var x = this.x,
  7963. y = this.y,
  7964. z = this.z;
  7965. var e = m.elements;
  7966. this.x = e[0] * x + e[4] * y + e[8] * z;
  7967. this.y = e[1] * x + e[5] * y + e[9] * z;
  7968. this.z = e[2] * x + e[6] * y + e[10] * z;
  7969. return this.normalize();
  7970. };
  7971. _proto.divide = function divide(v) {
  7972. this.x /= v.x;
  7973. this.y /= v.y;
  7974. this.z /= v.z;
  7975. return this;
  7976. };
  7977. _proto.divideScalar = function divideScalar(scalar) {
  7978. return this.multiplyScalar(1 / scalar);
  7979. };
  7980. _proto.min = function min(v) {
  7981. this.x = Math.min(this.x, v.x);
  7982. this.y = Math.min(this.y, v.y);
  7983. this.z = Math.min(this.z, v.z);
  7984. return this;
  7985. };
  7986. _proto.max = function max(v) {
  7987. this.x = Math.max(this.x, v.x);
  7988. this.y = Math.max(this.y, v.y);
  7989. this.z = Math.max(this.z, v.z);
  7990. return this;
  7991. };
  7992. _proto.clamp = function clamp(min, max) {
  7993. // assumes min < max, componentwise
  7994. this.x = Math.max(min.x, Math.min(max.x, this.x));
  7995. this.y = Math.max(min.y, Math.min(max.y, this.y));
  7996. this.z = Math.max(min.z, Math.min(max.z, this.z));
  7997. return this;
  7998. };
  7999. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  8000. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  8001. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  8002. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  8003. return this;
  8004. };
  8005. _proto.clampLength = function clampLength(min, max) {
  8006. var length = this.length();
  8007. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  8008. };
  8009. _proto.floor = function floor() {
  8010. this.x = Math.floor(this.x);
  8011. this.y = Math.floor(this.y);
  8012. this.z = Math.floor(this.z);
  8013. return this;
  8014. };
  8015. _proto.ceil = function ceil() {
  8016. this.x = Math.ceil(this.x);
  8017. this.y = Math.ceil(this.y);
  8018. this.z = Math.ceil(this.z);
  8019. return this;
  8020. };
  8021. _proto.round = function round() {
  8022. this.x = Math.round(this.x);
  8023. this.y = Math.round(this.y);
  8024. this.z = Math.round(this.z);
  8025. return this;
  8026. };
  8027. _proto.roundToZero = function roundToZero() {
  8028. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  8029. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  8030. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  8031. return this;
  8032. };
  8033. _proto.negate = function negate() {
  8034. this.x = -this.x;
  8035. this.y = -this.y;
  8036. this.z = -this.z;
  8037. return this;
  8038. };
  8039. _proto.dot = function dot(v) {
  8040. return this.x * v.x + this.y * v.y + this.z * v.z;
  8041. } // TODO lengthSquared?
  8042. ;
  8043. _proto.lengthSq = function lengthSq() {
  8044. return this.x * this.x + this.y * this.y + this.z * this.z;
  8045. };
  8046. _proto.length = function length() {
  8047. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  8048. };
  8049. _proto.manhattanLength = function manhattanLength() {
  8050. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  8051. };
  8052. _proto.normalize = function normalize() {
  8053. return this.divideScalar(this.length() || 1);
  8054. };
  8055. _proto.setLength = function setLength(length) {
  8056. return this.normalize().multiplyScalar(length);
  8057. };
  8058. _proto.lerp = function lerp(v, alpha) {
  8059. this.x += (v.x - this.x) * alpha;
  8060. this.y += (v.y - this.y) * alpha;
  8061. this.z += (v.z - this.z) * alpha;
  8062. return this;
  8063. };
  8064. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  8065. this.x = v1.x + (v2.x - v1.x) * alpha;
  8066. this.y = v1.y + (v2.y - v1.y) * alpha;
  8067. this.z = v1.z + (v2.z - v1.z) * alpha;
  8068. return this;
  8069. };
  8070. _proto.cross = function cross(v, w) {
  8071. if (w !== undefined) {
  8072. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  8073. return this.crossVectors(v, w);
  8074. }
  8075. return this.crossVectors(this, v);
  8076. };
  8077. _proto.crossVectors = function crossVectors(a, b) {
  8078. var ax = a.x,
  8079. ay = a.y,
  8080. az = a.z;
  8081. var bx = b.x,
  8082. by = b.y,
  8083. bz = b.z;
  8084. this.x = ay * bz - az * by;
  8085. this.y = az * bx - ax * bz;
  8086. this.z = ax * by - ay * bx;
  8087. return this;
  8088. };
  8089. _proto.projectOnVector = function projectOnVector(v) {
  8090. var denominator = v.lengthSq();
  8091. if (denominator === 0) return this.set(0, 0, 0);
  8092. var scalar = v.dot(this) / denominator;
  8093. return this.copy(v).multiplyScalar(scalar);
  8094. };
  8095. _proto.projectOnPlane = function projectOnPlane(planeNormal) {
  8096. _vector.copy(this).projectOnVector(planeNormal);
  8097. return this.sub(_vector);
  8098. };
  8099. _proto.reflect = function reflect(normal) {
  8100. // reflect incident vector off plane orthogonal to normal
  8101. // normal is assumed to have unit length
  8102. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  8103. };
  8104. _proto.angleTo = function angleTo(v) {
  8105. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  8106. if (denominator === 0) return Math.PI / 2;
  8107. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  8108. return Math.acos(MathUtils.clamp(theta, -1, 1));
  8109. };
  8110. _proto.distanceTo = function distanceTo(v) {
  8111. return Math.sqrt(this.distanceToSquared(v));
  8112. };
  8113. _proto.distanceToSquared = function distanceToSquared(v) {
  8114. var dx = this.x - v.x,
  8115. dy = this.y - v.y,
  8116. dz = this.z - v.z;
  8117. return dx * dx + dy * dy + dz * dz;
  8118. };
  8119. _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
  8120. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  8121. };
  8122. _proto.setFromSpherical = function setFromSpherical(s) {
  8123. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  8124. };
  8125. _proto.setFromSphericalCoords = function setFromSphericalCoords(radius, phi, theta) {
  8126. var sinPhiRadius = Math.sin(phi) * radius;
  8127. this.x = sinPhiRadius * Math.sin(theta);
  8128. this.y = Math.cos(phi) * radius;
  8129. this.z = sinPhiRadius * Math.cos(theta);
  8130. return this;
  8131. };
  8132. _proto.setFromCylindrical = function setFromCylindrical(c) {
  8133. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  8134. };
  8135. _proto.setFromCylindricalCoords = function setFromCylindricalCoords(radius, theta, y) {
  8136. this.x = radius * Math.sin(theta);
  8137. this.y = y;
  8138. this.z = radius * Math.cos(theta);
  8139. return this;
  8140. };
  8141. _proto.setFromMatrixPosition = function setFromMatrixPosition(m) {
  8142. var e = m.elements;
  8143. this.x = e[12];
  8144. this.y = e[13];
  8145. this.z = e[14];
  8146. return this;
  8147. };
  8148. _proto.setFromMatrixScale = function setFromMatrixScale(m) {
  8149. var sx = this.setFromMatrixColumn(m, 0).length();
  8150. var sy = this.setFromMatrixColumn(m, 1).length();
  8151. var sz = this.setFromMatrixColumn(m, 2).length();
  8152. this.x = sx;
  8153. this.y = sy;
  8154. this.z = sz;
  8155. return this;
  8156. };
  8157. _proto.setFromMatrixColumn = function setFromMatrixColumn(m, index) {
  8158. return this.fromArray(m.elements, index * 4);
  8159. };
  8160. _proto.setFromMatrix3Column = function setFromMatrix3Column(m, index) {
  8161. return this.fromArray(m.elements, index * 3);
  8162. };
  8163. _proto.equals = function equals(v) {
  8164. return v.x === this.x && v.y === this.y && v.z === this.z;
  8165. };
  8166. _proto.fromArray = function fromArray(array, offset) {
  8167. if (offset === void 0) {
  8168. offset = 0;
  8169. }
  8170. this.x = array[offset];
  8171. this.y = array[offset + 1];
  8172. this.z = array[offset + 2];
  8173. return this;
  8174. };
  8175. _proto.toArray = function toArray(array, offset) {
  8176. if (array === void 0) {
  8177. array = [];
  8178. }
  8179. if (offset === void 0) {
  8180. offset = 0;
  8181. }
  8182. array[offset] = this.x;
  8183. array[offset + 1] = this.y;
  8184. array[offset + 2] = this.z;
  8185. return array;
  8186. };
  8187. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  8188. if (offset !== undefined) {
  8189. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  8190. }
  8191. this.x = attribute.getX(index);
  8192. this.y = attribute.getY(index);
  8193. this.z = attribute.getZ(index);
  8194. return this;
  8195. };
  8196. _proto.random = function random() {
  8197. this.x = Math.random();
  8198. this.y = Math.random();
  8199. this.z = Math.random();
  8200. return this;
  8201. };
  8202. return Vector3;
  8203. }();
  8204. var _vector = /*@__PURE__*/new Vector3();
  8205. var _quaternion = /*@__PURE__*/new Quaternion();
  8206. var Box3 = /*#__PURE__*/function () {
  8207. function Box3(min, max) {
  8208. Object.defineProperty(this, 'isBox3', {
  8209. value: true
  8210. });
  8211. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  8212. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  8213. }
  8214. var _proto = Box3.prototype;
  8215. _proto.set = function set(min, max) {
  8216. this.min.copy(min);
  8217. this.max.copy(max);
  8218. return this;
  8219. };
  8220. _proto.setFromArray = function setFromArray(array) {
  8221. var minX = +Infinity;
  8222. var minY = +Infinity;
  8223. var minZ = +Infinity;
  8224. var maxX = -Infinity;
  8225. var maxY = -Infinity;
  8226. var maxZ = -Infinity;
  8227. for (var i = 0, l = array.length; i < l; i += 3) {
  8228. var x = array[i];
  8229. var y = array[i + 1];
  8230. var z = array[i + 2];
  8231. if (x < minX) minX = x;
  8232. if (y < minY) minY = y;
  8233. if (z < minZ) minZ = z;
  8234. if (x > maxX) maxX = x;
  8235. if (y > maxY) maxY = y;
  8236. if (z > maxZ) maxZ = z;
  8237. }
  8238. this.min.set(minX, minY, minZ);
  8239. this.max.set(maxX, maxY, maxZ);
  8240. return this;
  8241. };
  8242. _proto.setFromBufferAttribute = function setFromBufferAttribute(attribute) {
  8243. var minX = +Infinity;
  8244. var minY = +Infinity;
  8245. var minZ = +Infinity;
  8246. var maxX = -Infinity;
  8247. var maxY = -Infinity;
  8248. var maxZ = -Infinity;
  8249. for (var i = 0, l = attribute.count; i < l; i++) {
  8250. var x = attribute.getX(i);
  8251. var y = attribute.getY(i);
  8252. var z = attribute.getZ(i);
  8253. if (x < minX) minX = x;
  8254. if (y < minY) minY = y;
  8255. if (z < minZ) minZ = z;
  8256. if (x > maxX) maxX = x;
  8257. if (y > maxY) maxY = y;
  8258. if (z > maxZ) maxZ = z;
  8259. }
  8260. this.min.set(minX, minY, minZ);
  8261. this.max.set(maxX, maxY, maxZ);
  8262. return this;
  8263. };
  8264. _proto.setFromPoints = function setFromPoints(points) {
  8265. this.makeEmpty();
  8266. for (var i = 0, il = points.length; i < il; i++) {
  8267. this.expandByPoint(points[i]);
  8268. }
  8269. return this;
  8270. };
  8271. _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
  8272. var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  8273. this.min.copy(center).sub(halfSize);
  8274. this.max.copy(center).add(halfSize);
  8275. return this;
  8276. };
  8277. _proto.setFromObject = function setFromObject(object) {
  8278. this.makeEmpty();
  8279. return this.expandByObject(object);
  8280. };
  8281. _proto.clone = function clone() {
  8282. return new this.constructor().copy(this);
  8283. };
  8284. _proto.copy = function copy(box) {
  8285. this.min.copy(box.min);
  8286. this.max.copy(box.max);
  8287. return this;
  8288. };
  8289. _proto.makeEmpty = function makeEmpty() {
  8290. this.min.x = this.min.y = this.min.z = +Infinity;
  8291. this.max.x = this.max.y = this.max.z = -Infinity;
  8292. return this;
  8293. };
  8294. _proto.isEmpty = function isEmpty() {
  8295. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8296. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  8297. };
  8298. _proto.getCenter = function getCenter(target) {
  8299. if (target === undefined) {
  8300. console.warn('THREE.Box3: .getCenter() target is now required');
  8301. target = new Vector3();
  8302. }
  8303. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  8304. };
  8305. _proto.getSize = function getSize(target) {
  8306. if (target === undefined) {
  8307. console.warn('THREE.Box3: .getSize() target is now required');
  8308. target = new Vector3();
  8309. }
  8310. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  8311. };
  8312. _proto.expandByPoint = function expandByPoint(point) {
  8313. this.min.min(point);
  8314. this.max.max(point);
  8315. return this;
  8316. };
  8317. _proto.expandByVector = function expandByVector(vector) {
  8318. this.min.sub(vector);
  8319. this.max.add(vector);
  8320. return this;
  8321. };
  8322. _proto.expandByScalar = function expandByScalar(scalar) {
  8323. this.min.addScalar(-scalar);
  8324. this.max.addScalar(scalar);
  8325. return this;
  8326. };
  8327. _proto.expandByObject = function expandByObject(object) {
  8328. // Computes the world-axis-aligned bounding box of an object (including its children),
  8329. // accounting for both the object's, and children's, world transforms
  8330. object.updateWorldMatrix(false, false);
  8331. var geometry = object.geometry;
  8332. if (geometry !== undefined) {
  8333. if (geometry.boundingBox === null) {
  8334. geometry.computeBoundingBox();
  8335. }
  8336. _box.copy(geometry.boundingBox);
  8337. _box.applyMatrix4(object.matrixWorld);
  8338. this.union(_box);
  8339. }
  8340. var children = object.children;
  8341. for (var i = 0, l = children.length; i < l; i++) {
  8342. this.expandByObject(children[i]);
  8343. }
  8344. return this;
  8345. };
  8346. _proto.containsPoint = function containsPoint(point) {
  8347. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  8348. };
  8349. _proto.containsBox = function containsBox(box) {
  8350. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  8351. };
  8352. _proto.getParameter = function getParameter(point, target) {
  8353. // This can potentially have a divide by zero if the box
  8354. // has a size dimension of 0.
  8355. if (target === undefined) {
  8356. console.warn('THREE.Box3: .getParameter() target is now required');
  8357. target = new Vector3();
  8358. }
  8359. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  8360. };
  8361. _proto.intersectsBox = function intersectsBox(box) {
  8362. // using 6 splitting planes to rule out intersections.
  8363. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  8364. };
  8365. _proto.intersectsSphere = function intersectsSphere(sphere) {
  8366. // Find the point on the AABB closest to the sphere center.
  8367. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  8368. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  8369. };
  8370. _proto.intersectsPlane = function intersectsPlane(plane) {
  8371. // We compute the minimum and maximum dot product values. If those values
  8372. // are on the same side (back or front) of the plane, then there is no intersection.
  8373. var min, max;
  8374. if (plane.normal.x > 0) {
  8375. min = plane.normal.x * this.min.x;
  8376. max = plane.normal.x * this.max.x;
  8377. } else {
  8378. min = plane.normal.x * this.max.x;
  8379. max = plane.normal.x * this.min.x;
  8380. }
  8381. if (plane.normal.y > 0) {
  8382. min += plane.normal.y * this.min.y;
  8383. max += plane.normal.y * this.max.y;
  8384. } else {
  8385. min += plane.normal.y * this.max.y;
  8386. max += plane.normal.y * this.min.y;
  8387. }
  8388. if (plane.normal.z > 0) {
  8389. min += plane.normal.z * this.min.z;
  8390. max += plane.normal.z * this.max.z;
  8391. } else {
  8392. min += plane.normal.z * this.max.z;
  8393. max += plane.normal.z * this.min.z;
  8394. }
  8395. return min <= -plane.constant && max >= -plane.constant;
  8396. };
  8397. _proto.intersectsTriangle = function intersectsTriangle(triangle) {
  8398. if (this.isEmpty()) {
  8399. return false;
  8400. } // compute box center and extents
  8401. this.getCenter(_center);
  8402. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  8403. _v0.subVectors(triangle.a, _center);
  8404. _v1.subVectors(triangle.b, _center);
  8405. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  8406. _f0.subVectors(_v1, _v0);
  8407. _f1.subVectors(_v2, _v1);
  8408. _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  8409. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  8410. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  8411. var axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  8412. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  8413. return false;
  8414. } // test 3 face normals from the aabb
  8415. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  8416. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  8417. return false;
  8418. } // finally testing the face normal of the triangle
  8419. // use already existing triangle edge vectors here
  8420. _triangleNormal.crossVectors(_f0, _f1);
  8421. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  8422. return satForAxes(axes, _v0, _v1, _v2, _extents);
  8423. };
  8424. _proto.clampPoint = function clampPoint(point, target) {
  8425. if (target === undefined) {
  8426. console.warn('THREE.Box3: .clampPoint() target is now required');
  8427. target = new Vector3();
  8428. }
  8429. return target.copy(point).clamp(this.min, this.max);
  8430. };
  8431. _proto.distanceToPoint = function distanceToPoint(point) {
  8432. var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  8433. return clampedPoint.sub(point).length();
  8434. };
  8435. _proto.getBoundingSphere = function getBoundingSphere(target) {
  8436. if (target === undefined) {
  8437. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  8438. }
  8439. this.getCenter(target.center);
  8440. target.radius = this.getSize(_vector$1).length() * 0.5;
  8441. return target;
  8442. };
  8443. _proto.intersect = function intersect(box) {
  8444. this.min.max(box.min);
  8445. this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  8446. if (this.isEmpty()) this.makeEmpty();
  8447. return this;
  8448. };
  8449. _proto.union = function union(box) {
  8450. this.min.min(box.min);
  8451. this.max.max(box.max);
  8452. return this;
  8453. };
  8454. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  8455. // transform of empty box is an empty box.
  8456. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8457. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  8458. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  8459. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  8460. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  8461. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  8462. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  8463. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  8464. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  8465. this.setFromPoints(_points);
  8466. return this;
  8467. };
  8468. _proto.translate = function translate(offset) {
  8469. this.min.add(offset);
  8470. this.max.add(offset);
  8471. return this;
  8472. };
  8473. _proto.equals = function equals(box) {
  8474. return box.min.equals(this.min) && box.max.equals(this.max);
  8475. };
  8476. return Box3;
  8477. }();
  8478. function satForAxes(axes, v0, v1, v2, extents) {
  8479. for (var i = 0, j = axes.length - 3; i <= j; i += 3) {
  8480. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  8481. var r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  8482. var p0 = v0.dot(_testAxis);
  8483. var p1 = v1.dot(_testAxis);
  8484. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  8485. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  8486. // points of the projected triangle are outside the projected half-length of the aabb
  8487. // the axis is seperating and we can exit
  8488. return false;
  8489. }
  8490. }
  8491. return true;
  8492. }
  8493. var _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  8494. var _vector$1 = /*@__PURE__*/new Vector3();
  8495. var _box = /*@__PURE__*/new Box3(); // triangle centered vertices
  8496. var _v0 = /*@__PURE__*/new Vector3();
  8497. var _v1 = /*@__PURE__*/new Vector3();
  8498. var _v2 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  8499. var _f0 = /*@__PURE__*/new Vector3();
  8500. var _f1 = /*@__PURE__*/new Vector3();
  8501. var _f2 = /*@__PURE__*/new Vector3();
  8502. var _center = /*@__PURE__*/new Vector3();
  8503. var _extents = /*@__PURE__*/new Vector3();
  8504. var _triangleNormal = /*@__PURE__*/new Vector3();
  8505. var _testAxis = /*@__PURE__*/new Vector3();
  8506. var _box$1 = /*@__PURE__*/new Box3();
  8507. var Sphere = /*#__PURE__*/function () {
  8508. function Sphere(center, radius) {
  8509. this.center = center !== undefined ? center : new Vector3();
  8510. this.radius = radius !== undefined ? radius : -1;
  8511. }
  8512. var _proto = Sphere.prototype;
  8513. _proto.set = function set(center, radius) {
  8514. this.center.copy(center);
  8515. this.radius = radius;
  8516. return this;
  8517. };
  8518. _proto.setFromPoints = function setFromPoints(points, optionalCenter) {
  8519. var center = this.center;
  8520. if (optionalCenter !== undefined) {
  8521. center.copy(optionalCenter);
  8522. } else {
  8523. _box$1.setFromPoints(points).getCenter(center);
  8524. }
  8525. var maxRadiusSq = 0;
  8526. for (var i = 0, il = points.length; i < il; i++) {
  8527. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  8528. }
  8529. this.radius = Math.sqrt(maxRadiusSq);
  8530. return this;
  8531. };
  8532. _proto.clone = function clone() {
  8533. return new this.constructor().copy(this);
  8534. };
  8535. _proto.copy = function copy(sphere) {
  8536. this.center.copy(sphere.center);
  8537. this.radius = sphere.radius;
  8538. return this;
  8539. };
  8540. _proto.isEmpty = function isEmpty() {
  8541. return this.radius < 0;
  8542. };
  8543. _proto.makeEmpty = function makeEmpty() {
  8544. this.center.set(0, 0, 0);
  8545. this.radius = -1;
  8546. return this;
  8547. };
  8548. _proto.containsPoint = function containsPoint(point) {
  8549. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  8550. };
  8551. _proto.distanceToPoint = function distanceToPoint(point) {
  8552. return point.distanceTo(this.center) - this.radius;
  8553. };
  8554. _proto.intersectsSphere = function intersectsSphere(sphere) {
  8555. var radiusSum = this.radius + sphere.radius;
  8556. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  8557. };
  8558. _proto.intersectsBox = function intersectsBox(box) {
  8559. return box.intersectsSphere(this);
  8560. };
  8561. _proto.intersectsPlane = function intersectsPlane(plane) {
  8562. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  8563. };
  8564. _proto.clampPoint = function clampPoint(point, target) {
  8565. var deltaLengthSq = this.center.distanceToSquared(point);
  8566. if (target === undefined) {
  8567. console.warn('THREE.Sphere: .clampPoint() target is now required');
  8568. target = new Vector3();
  8569. }
  8570. target.copy(point);
  8571. if (deltaLengthSq > this.radius * this.radius) {
  8572. target.sub(this.center).normalize();
  8573. target.multiplyScalar(this.radius).add(this.center);
  8574. }
  8575. return target;
  8576. };
  8577. _proto.getBoundingBox = function getBoundingBox(target) {
  8578. if (target === undefined) {
  8579. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  8580. target = new Box3();
  8581. }
  8582. if (this.isEmpty()) {
  8583. // Empty sphere produces empty bounding box
  8584. target.makeEmpty();
  8585. return target;
  8586. }
  8587. target.set(this.center, this.center);
  8588. target.expandByScalar(this.radius);
  8589. return target;
  8590. };
  8591. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  8592. this.center.applyMatrix4(matrix);
  8593. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8594. return this;
  8595. };
  8596. _proto.translate = function translate(offset) {
  8597. this.center.add(offset);
  8598. return this;
  8599. };
  8600. _proto.equals = function equals(sphere) {
  8601. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  8602. };
  8603. return Sphere;
  8604. }();
  8605. var _vector$2 = /*@__PURE__*/new Vector3();
  8606. var _segCenter = /*@__PURE__*/new Vector3();
  8607. var _segDir = /*@__PURE__*/new Vector3();
  8608. var _diff = /*@__PURE__*/new Vector3();
  8609. var _edge1 = /*@__PURE__*/new Vector3();
  8610. var _edge2 = /*@__PURE__*/new Vector3();
  8611. var _normal = /*@__PURE__*/new Vector3();
  8612. var Ray = /*#__PURE__*/function () {
  8613. function Ray(origin, direction) {
  8614. this.origin = origin !== undefined ? origin : new Vector3();
  8615. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  8616. }
  8617. var _proto = Ray.prototype;
  8618. _proto.set = function set(origin, direction) {
  8619. this.origin.copy(origin);
  8620. this.direction.copy(direction);
  8621. return this;
  8622. };
  8623. _proto.clone = function clone() {
  8624. return new this.constructor().copy(this);
  8625. };
  8626. _proto.copy = function copy(ray) {
  8627. this.origin.copy(ray.origin);
  8628. this.direction.copy(ray.direction);
  8629. return this;
  8630. };
  8631. _proto.at = function at(t, target) {
  8632. if (target === undefined) {
  8633. console.warn('THREE.Ray: .at() target is now required');
  8634. target = new Vector3();
  8635. }
  8636. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  8637. };
  8638. _proto.lookAt = function lookAt(v) {
  8639. this.direction.copy(v).sub(this.origin).normalize();
  8640. return this;
  8641. };
  8642. _proto.recast = function recast(t) {
  8643. this.origin.copy(this.at(t, _vector$2));
  8644. return this;
  8645. };
  8646. _proto.closestPointToPoint = function closestPointToPoint(point, target) {
  8647. if (target === undefined) {
  8648. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  8649. target = new Vector3();
  8650. }
  8651. target.subVectors(point, this.origin);
  8652. var directionDistance = target.dot(this.direction);
  8653. if (directionDistance < 0) {
  8654. return target.copy(this.origin);
  8655. }
  8656. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  8657. };
  8658. _proto.distanceToPoint = function distanceToPoint(point) {
  8659. return Math.sqrt(this.distanceSqToPoint(point));
  8660. };
  8661. _proto.distanceSqToPoint = function distanceSqToPoint(point) {
  8662. var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  8663. if (directionDistance < 0) {
  8664. return this.origin.distanceToSquared(point);
  8665. }
  8666. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  8667. return _vector$2.distanceToSquared(point);
  8668. };
  8669. _proto.distanceSqToSegment = function distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  8670. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8671. // It returns the min distance between the ray and the segment
  8672. // defined by v0 and v1
  8673. // It can also set two optional targets :
  8674. // - The closest point on the ray
  8675. // - The closest point on the segment
  8676. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  8677. _segDir.copy(v1).sub(v0).normalize();
  8678. _diff.copy(this.origin).sub(_segCenter);
  8679. var segExtent = v0.distanceTo(v1) * 0.5;
  8680. var a01 = -this.direction.dot(_segDir);
  8681. var b0 = _diff.dot(this.direction);
  8682. var b1 = -_diff.dot(_segDir);
  8683. var c = _diff.lengthSq();
  8684. var det = Math.abs(1 - a01 * a01);
  8685. var s0, s1, sqrDist, extDet;
  8686. if (det > 0) {
  8687. // The ray and segment are not parallel.
  8688. s0 = a01 * b1 - b0;
  8689. s1 = a01 * b0 - b1;
  8690. extDet = segExtent * det;
  8691. if (s0 >= 0) {
  8692. if (s1 >= -extDet) {
  8693. if (s1 <= extDet) {
  8694. // region 0
  8695. // Minimum at interior points of ray and segment.
  8696. var invDet = 1 / det;
  8697. s0 *= invDet;
  8698. s1 *= invDet;
  8699. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  8700. } else {
  8701. // region 1
  8702. s1 = segExtent;
  8703. s0 = Math.max(0, -(a01 * s1 + b0));
  8704. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8705. }
  8706. } else {
  8707. // region 5
  8708. s1 = -segExtent;
  8709. s0 = Math.max(0, -(a01 * s1 + b0));
  8710. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8711. }
  8712. } else {
  8713. if (s1 <= -extDet) {
  8714. // region 4
  8715. s0 = Math.max(0, -(-a01 * segExtent + b0));
  8716. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  8717. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8718. } else if (s1 <= extDet) {
  8719. // region 3
  8720. s0 = 0;
  8721. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  8722. sqrDist = s1 * (s1 + 2 * b1) + c;
  8723. } else {
  8724. // region 2
  8725. s0 = Math.max(0, -(a01 * segExtent + b0));
  8726. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  8727. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8728. }
  8729. }
  8730. } else {
  8731. // Ray and segment are parallel.
  8732. s1 = a01 > 0 ? -segExtent : segExtent;
  8733. s0 = Math.max(0, -(a01 * s1 + b0));
  8734. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8735. }
  8736. if (optionalPointOnRay) {
  8737. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  8738. }
  8739. if (optionalPointOnSegment) {
  8740. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  8741. }
  8742. return sqrDist;
  8743. };
  8744. _proto.intersectSphere = function intersectSphere(sphere, target) {
  8745. _vector$2.subVectors(sphere.center, this.origin);
  8746. var tca = _vector$2.dot(this.direction);
  8747. var d2 = _vector$2.dot(_vector$2) - tca * tca;
  8748. var radius2 = sphere.radius * sphere.radius;
  8749. if (d2 > radius2) return null;
  8750. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  8751. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  8752. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  8753. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  8754. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8755. // in order to always return an intersect point that is in front of the ray.
  8756. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  8757. return this.at(t0, target);
  8758. };
  8759. _proto.intersectsSphere = function intersectsSphere(sphere) {
  8760. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  8761. };
  8762. _proto.distanceToPlane = function distanceToPlane(plane) {
  8763. var denominator = plane.normal.dot(this.direction);
  8764. if (denominator === 0) {
  8765. // line is coplanar, return origin
  8766. if (plane.distanceToPoint(this.origin) === 0) {
  8767. return 0;
  8768. } // Null is preferable to undefined since undefined means.... it is undefined
  8769. return null;
  8770. }
  8771. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  8772. return t >= 0 ? t : null;
  8773. };
  8774. _proto.intersectPlane = function intersectPlane(plane, target) {
  8775. var t = this.distanceToPlane(plane);
  8776. if (t === null) {
  8777. return null;
  8778. }
  8779. return this.at(t, target);
  8780. };
  8781. _proto.intersectsPlane = function intersectsPlane(plane) {
  8782. // check if the ray lies on the plane first
  8783. var distToPoint = plane.distanceToPoint(this.origin);
  8784. if (distToPoint === 0) {
  8785. return true;
  8786. }
  8787. var denominator = plane.normal.dot(this.direction);
  8788. if (denominator * distToPoint < 0) {
  8789. return true;
  8790. } // ray origin is behind the plane (and is pointing behind it)
  8791. return false;
  8792. };
  8793. _proto.intersectBox = function intersectBox(box, target) {
  8794. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  8795. var invdirx = 1 / this.direction.x,
  8796. invdiry = 1 / this.direction.y,
  8797. invdirz = 1 / this.direction.z;
  8798. var origin = this.origin;
  8799. if (invdirx >= 0) {
  8800. tmin = (box.min.x - origin.x) * invdirx;
  8801. tmax = (box.max.x - origin.x) * invdirx;
  8802. } else {
  8803. tmin = (box.max.x - origin.x) * invdirx;
  8804. tmax = (box.min.x - origin.x) * invdirx;
  8805. }
  8806. if (invdiry >= 0) {
  8807. tymin = (box.min.y - origin.y) * invdiry;
  8808. tymax = (box.max.y - origin.y) * invdiry;
  8809. } else {
  8810. tymin = (box.max.y - origin.y) * invdiry;
  8811. tymax = (box.min.y - origin.y) * invdiry;
  8812. }
  8813. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  8814. // (result of 0 * Infinity). x !== x returns true if x is NaN
  8815. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  8816. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  8817. if (invdirz >= 0) {
  8818. tzmin = (box.min.z - origin.z) * invdirz;
  8819. tzmax = (box.max.z - origin.z) * invdirz;
  8820. } else {
  8821. tzmin = (box.max.z - origin.z) * invdirz;
  8822. tzmax = (box.min.z - origin.z) * invdirz;
  8823. }
  8824. if (tmin > tzmax || tzmin > tmax) return null;
  8825. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  8826. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  8827. if (tmax < 0) return null;
  8828. return this.at(tmin >= 0 ? tmin : tmax, target);
  8829. };
  8830. _proto.intersectsBox = function intersectsBox(box) {
  8831. return this.intersectBox(box, _vector$2) !== null;
  8832. };
  8833. _proto.intersectTriangle = function intersectTriangle(a, b, c, backfaceCulling, target) {
  8834. // Compute the offset origin, edges, and normal.
  8835. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8836. _edge1.subVectors(b, a);
  8837. _edge2.subVectors(c, a);
  8838. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8839. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8840. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8841. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8842. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8843. var DdN = this.direction.dot(_normal);
  8844. var sign;
  8845. if (DdN > 0) {
  8846. if (backfaceCulling) return null;
  8847. sign = 1;
  8848. } else if (DdN < 0) {
  8849. sign = -1;
  8850. DdN = -DdN;
  8851. } else {
  8852. return null;
  8853. }
  8854. _diff.subVectors(this.origin, a);
  8855. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  8856. if (DdQxE2 < 0) {
  8857. return null;
  8858. }
  8859. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  8860. if (DdE1xQ < 0) {
  8861. return null;
  8862. } // b1+b2 > 1, no intersection
  8863. if (DdQxE2 + DdE1xQ > DdN) {
  8864. return null;
  8865. } // Line intersects triangle, check if ray does.
  8866. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  8867. if (QdN < 0) {
  8868. return null;
  8869. } // Ray intersects triangle.
  8870. return this.at(QdN / DdN, target);
  8871. };
  8872. _proto.applyMatrix4 = function applyMatrix4(matrix4) {
  8873. this.origin.applyMatrix4(matrix4);
  8874. this.direction.transformDirection(matrix4);
  8875. return this;
  8876. };
  8877. _proto.equals = function equals(ray) {
  8878. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  8879. };
  8880. return Ray;
  8881. }();
  8882. var Matrix4 = /*#__PURE__*/function () {
  8883. function Matrix4() {
  8884. Object.defineProperty(this, 'isMatrix4', {
  8885. value: true
  8886. });
  8887. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  8888. if (arguments.length > 0) {
  8889. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  8890. }
  8891. }
  8892. var _proto = Matrix4.prototype;
  8893. _proto.set = function set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  8894. var te = this.elements;
  8895. te[0] = n11;
  8896. te[4] = n12;
  8897. te[8] = n13;
  8898. te[12] = n14;
  8899. te[1] = n21;
  8900. te[5] = n22;
  8901. te[9] = n23;
  8902. te[13] = n24;
  8903. te[2] = n31;
  8904. te[6] = n32;
  8905. te[10] = n33;
  8906. te[14] = n34;
  8907. te[3] = n41;
  8908. te[7] = n42;
  8909. te[11] = n43;
  8910. te[15] = n44;
  8911. return this;
  8912. };
  8913. _proto.identity = function identity() {
  8914. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  8915. return this;
  8916. };
  8917. _proto.clone = function clone() {
  8918. return new Matrix4().fromArray(this.elements);
  8919. };
  8920. _proto.copy = function copy(m) {
  8921. var te = this.elements;
  8922. var me = m.elements;
  8923. te[0] = me[0];
  8924. te[1] = me[1];
  8925. te[2] = me[2];
  8926. te[3] = me[3];
  8927. te[4] = me[4];
  8928. te[5] = me[5];
  8929. te[6] = me[6];
  8930. te[7] = me[7];
  8931. te[8] = me[8];
  8932. te[9] = me[9];
  8933. te[10] = me[10];
  8934. te[11] = me[11];
  8935. te[12] = me[12];
  8936. te[13] = me[13];
  8937. te[14] = me[14];
  8938. te[15] = me[15];
  8939. return this;
  8940. };
  8941. _proto.copyPosition = function copyPosition(m) {
  8942. var te = this.elements,
  8943. me = m.elements;
  8944. te[12] = me[12];
  8945. te[13] = me[13];
  8946. te[14] = me[14];
  8947. return this;
  8948. };
  8949. _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
  8950. xAxis.setFromMatrixColumn(this, 0);
  8951. yAxis.setFromMatrixColumn(this, 1);
  8952. zAxis.setFromMatrixColumn(this, 2);
  8953. return this;
  8954. };
  8955. _proto.makeBasis = function makeBasis(xAxis, yAxis, zAxis) {
  8956. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  8957. return this;
  8958. };
  8959. _proto.extractRotation = function extractRotation(m) {
  8960. // this method does not support reflection matrices
  8961. var te = this.elements;
  8962. var me = m.elements;
  8963. var scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
  8964. var scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
  8965. var scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
  8966. te[0] = me[0] * scaleX;
  8967. te[1] = me[1] * scaleX;
  8968. te[2] = me[2] * scaleX;
  8969. te[3] = 0;
  8970. te[4] = me[4] * scaleY;
  8971. te[5] = me[5] * scaleY;
  8972. te[6] = me[6] * scaleY;
  8973. te[7] = 0;
  8974. te[8] = me[8] * scaleZ;
  8975. te[9] = me[9] * scaleZ;
  8976. te[10] = me[10] * scaleZ;
  8977. te[11] = 0;
  8978. te[12] = 0;
  8979. te[13] = 0;
  8980. te[14] = 0;
  8981. te[15] = 1;
  8982. return this;
  8983. };
  8984. _proto.makeRotationFromEuler = function makeRotationFromEuler(euler) {
  8985. if (!(euler && euler.isEuler)) {
  8986. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  8987. }
  8988. var te = this.elements;
  8989. var x = euler.x,
  8990. y = euler.y,
  8991. z = euler.z;
  8992. var a = Math.cos(x),
  8993. b = Math.sin(x);
  8994. var c = Math.cos(y),
  8995. d = Math.sin(y);
  8996. var e = Math.cos(z),
  8997. f = Math.sin(z);
  8998. if (euler.order === 'XYZ') {
  8999. var ae = a * e,
  9000. af = a * f,
  9001. be = b * e,
  9002. bf = b * f;
  9003. te[0] = c * e;
  9004. te[4] = -c * f;
  9005. te[8] = d;
  9006. te[1] = af + be * d;
  9007. te[5] = ae - bf * d;
  9008. te[9] = -b * c;
  9009. te[2] = bf - ae * d;
  9010. te[6] = be + af * d;
  9011. te[10] = a * c;
  9012. } else if (euler.order === 'YXZ') {
  9013. var ce = c * e,
  9014. cf = c * f,
  9015. de = d * e,
  9016. df = d * f;
  9017. te[0] = ce + df * b;
  9018. te[4] = de * b - cf;
  9019. te[8] = a * d;
  9020. te[1] = a * f;
  9021. te[5] = a * e;
  9022. te[9] = -b;
  9023. te[2] = cf * b - de;
  9024. te[6] = df + ce * b;
  9025. te[10] = a * c;
  9026. } else if (euler.order === 'ZXY') {
  9027. var _ce = c * e,
  9028. _cf = c * f,
  9029. _de = d * e,
  9030. _df = d * f;
  9031. te[0] = _ce - _df * b;
  9032. te[4] = -a * f;
  9033. te[8] = _de + _cf * b;
  9034. te[1] = _cf + _de * b;
  9035. te[5] = a * e;
  9036. te[9] = _df - _ce * b;
  9037. te[2] = -a * d;
  9038. te[6] = b;
  9039. te[10] = a * c;
  9040. } else if (euler.order === 'ZYX') {
  9041. var _ae = a * e,
  9042. _af = a * f,
  9043. _be = b * e,
  9044. _bf = b * f;
  9045. te[0] = c * e;
  9046. te[4] = _be * d - _af;
  9047. te[8] = _ae * d + _bf;
  9048. te[1] = c * f;
  9049. te[5] = _bf * d + _ae;
  9050. te[9] = _af * d - _be;
  9051. te[2] = -d;
  9052. te[6] = b * c;
  9053. te[10] = a * c;
  9054. } else if (euler.order === 'YZX') {
  9055. var ac = a * c,
  9056. ad = a * d,
  9057. bc = b * c,
  9058. bd = b * d;
  9059. te[0] = c * e;
  9060. te[4] = bd - ac * f;
  9061. te[8] = bc * f + ad;
  9062. te[1] = f;
  9063. te[5] = a * e;
  9064. te[9] = -b * e;
  9065. te[2] = -d * e;
  9066. te[6] = ad * f + bc;
  9067. te[10] = ac - bd * f;
  9068. } else if (euler.order === 'XZY') {
  9069. var _ac = a * c,
  9070. _ad = a * d,
  9071. _bc = b * c,
  9072. _bd = b * d;
  9073. te[0] = c * e;
  9074. te[4] = -f;
  9075. te[8] = d * e;
  9076. te[1] = _ac * f + _bd;
  9077. te[5] = a * e;
  9078. te[9] = _ad * f - _bc;
  9079. te[2] = _bc * f - _ad;
  9080. te[6] = b * e;
  9081. te[10] = _bd * f + _ac;
  9082. } // bottom row
  9083. te[3] = 0;
  9084. te[7] = 0;
  9085. te[11] = 0; // last column
  9086. te[12] = 0;
  9087. te[13] = 0;
  9088. te[14] = 0;
  9089. te[15] = 1;
  9090. return this;
  9091. };
  9092. _proto.makeRotationFromQuaternion = function makeRotationFromQuaternion(q) {
  9093. return this.compose(_zero, q, _one);
  9094. };
  9095. _proto.lookAt = function lookAt(eye, target, up) {
  9096. var te = this.elements;
  9097. _z.subVectors(eye, target);
  9098. if (_z.lengthSq() === 0) {
  9099. // eye and target are in the same position
  9100. _z.z = 1;
  9101. }
  9102. _z.normalize();
  9103. _x.crossVectors(up, _z);
  9104. if (_x.lengthSq() === 0) {
  9105. // up and z are parallel
  9106. if (Math.abs(up.z) === 1) {
  9107. _z.x += 0.0001;
  9108. } else {
  9109. _z.z += 0.0001;
  9110. }
  9111. _z.normalize();
  9112. _x.crossVectors(up, _z);
  9113. }
  9114. _x.normalize();
  9115. _y.crossVectors(_z, _x);
  9116. te[0] = _x.x;
  9117. te[4] = _y.x;
  9118. te[8] = _z.x;
  9119. te[1] = _x.y;
  9120. te[5] = _y.y;
  9121. te[9] = _z.y;
  9122. te[2] = _x.z;
  9123. te[6] = _y.z;
  9124. te[10] = _z.z;
  9125. return this;
  9126. };
  9127. _proto.multiply = function multiply(m, n) {
  9128. if (n !== undefined) {
  9129. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  9130. return this.multiplyMatrices(m, n);
  9131. }
  9132. return this.multiplyMatrices(this, m);
  9133. };
  9134. _proto.premultiply = function premultiply(m) {
  9135. return this.multiplyMatrices(m, this);
  9136. };
  9137. _proto.multiplyMatrices = function multiplyMatrices(a, b) {
  9138. var ae = a.elements;
  9139. var be = b.elements;
  9140. var te = this.elements;
  9141. var a11 = ae[0],
  9142. a12 = ae[4],
  9143. a13 = ae[8],
  9144. a14 = ae[12];
  9145. var a21 = ae[1],
  9146. a22 = ae[5],
  9147. a23 = ae[9],
  9148. a24 = ae[13];
  9149. var a31 = ae[2],
  9150. a32 = ae[6],
  9151. a33 = ae[10],
  9152. a34 = ae[14];
  9153. var a41 = ae[3],
  9154. a42 = ae[7],
  9155. a43 = ae[11],
  9156. a44 = ae[15];
  9157. var b11 = be[0],
  9158. b12 = be[4],
  9159. b13 = be[8],
  9160. b14 = be[12];
  9161. var b21 = be[1],
  9162. b22 = be[5],
  9163. b23 = be[9],
  9164. b24 = be[13];
  9165. var b31 = be[2],
  9166. b32 = be[6],
  9167. b33 = be[10],
  9168. b34 = be[14];
  9169. var b41 = be[3],
  9170. b42 = be[7],
  9171. b43 = be[11],
  9172. b44 = be[15];
  9173. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9174. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9175. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9176. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9177. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9178. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9179. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9180. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9181. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9182. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9183. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9184. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9185. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9186. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9187. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9188. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9189. return this;
  9190. };
  9191. _proto.multiplyScalar = function multiplyScalar(s) {
  9192. var te = this.elements;
  9193. te[0] *= s;
  9194. te[4] *= s;
  9195. te[8] *= s;
  9196. te[12] *= s;
  9197. te[1] *= s;
  9198. te[5] *= s;
  9199. te[9] *= s;
  9200. te[13] *= s;
  9201. te[2] *= s;
  9202. te[6] *= s;
  9203. te[10] *= s;
  9204. te[14] *= s;
  9205. te[3] *= s;
  9206. te[7] *= s;
  9207. te[11] *= s;
  9208. te[15] *= s;
  9209. return this;
  9210. };
  9211. _proto.determinant = function determinant() {
  9212. var te = this.elements;
  9213. var n11 = te[0],
  9214. n12 = te[4],
  9215. n13 = te[8],
  9216. n14 = te[12];
  9217. var n21 = te[1],
  9218. n22 = te[5],
  9219. n23 = te[9],
  9220. n24 = te[13];
  9221. var n31 = te[2],
  9222. n32 = te[6],
  9223. n33 = te[10],
  9224. n34 = te[14];
  9225. var n41 = te[3],
  9226. n42 = te[7],
  9227. n43 = te[11],
  9228. n44 = te[15]; //TODO: make this more efficient
  9229. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  9230. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  9231. };
  9232. _proto.transpose = function transpose() {
  9233. var te = this.elements;
  9234. var tmp;
  9235. tmp = te[1];
  9236. te[1] = te[4];
  9237. te[4] = tmp;
  9238. tmp = te[2];
  9239. te[2] = te[8];
  9240. te[8] = tmp;
  9241. tmp = te[6];
  9242. te[6] = te[9];
  9243. te[9] = tmp;
  9244. tmp = te[3];
  9245. te[3] = te[12];
  9246. te[12] = tmp;
  9247. tmp = te[7];
  9248. te[7] = te[13];
  9249. te[13] = tmp;
  9250. tmp = te[11];
  9251. te[11] = te[14];
  9252. te[14] = tmp;
  9253. return this;
  9254. };
  9255. _proto.setPosition = function setPosition(x, y, z) {
  9256. var te = this.elements;
  9257. if (x.isVector3) {
  9258. te[12] = x.x;
  9259. te[13] = x.y;
  9260. te[14] = x.z;
  9261. } else {
  9262. te[12] = x;
  9263. te[13] = y;
  9264. te[14] = z;
  9265. }
  9266. return this;
  9267. };
  9268. _proto.invert = function invert() {
  9269. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9270. var te = this.elements,
  9271. n11 = te[0],
  9272. n21 = te[1],
  9273. n31 = te[2],
  9274. n41 = te[3],
  9275. n12 = te[4],
  9276. n22 = te[5],
  9277. n32 = te[6],
  9278. n42 = te[7],
  9279. n13 = te[8],
  9280. n23 = te[9],
  9281. n33 = te[10],
  9282. n43 = te[11],
  9283. n14 = te[12],
  9284. n24 = te[13],
  9285. n34 = te[14],
  9286. n44 = te[15],
  9287. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9288. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9289. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9290. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9291. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9292. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  9293. var detInv = 1 / det;
  9294. te[0] = t11 * detInv;
  9295. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  9296. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  9297. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  9298. te[4] = t12 * detInv;
  9299. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  9300. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  9301. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  9302. te[8] = t13 * detInv;
  9303. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  9304. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  9305. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  9306. te[12] = t14 * detInv;
  9307. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  9308. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  9309. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  9310. return this;
  9311. };
  9312. _proto.scale = function scale(v) {
  9313. var te = this.elements;
  9314. var x = v.x,
  9315. y = v.y,
  9316. z = v.z;
  9317. te[0] *= x;
  9318. te[4] *= y;
  9319. te[8] *= z;
  9320. te[1] *= x;
  9321. te[5] *= y;
  9322. te[9] *= z;
  9323. te[2] *= x;
  9324. te[6] *= y;
  9325. te[10] *= z;
  9326. te[3] *= x;
  9327. te[7] *= y;
  9328. te[11] *= z;
  9329. return this;
  9330. };
  9331. _proto.getMaxScaleOnAxis = function getMaxScaleOnAxis() {
  9332. var te = this.elements;
  9333. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  9334. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  9335. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  9336. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  9337. };
  9338. _proto.makeTranslation = function makeTranslation(x, y, z) {
  9339. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  9340. return this;
  9341. };
  9342. _proto.makeRotationX = function makeRotationX(theta) {
  9343. var c = Math.cos(theta),
  9344. s = Math.sin(theta);
  9345. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  9346. return this;
  9347. };
  9348. _proto.makeRotationY = function makeRotationY(theta) {
  9349. var c = Math.cos(theta),
  9350. s = Math.sin(theta);
  9351. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  9352. return this;
  9353. };
  9354. _proto.makeRotationZ = function makeRotationZ(theta) {
  9355. var c = Math.cos(theta),
  9356. s = Math.sin(theta);
  9357. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  9358. return this;
  9359. };
  9360. _proto.makeRotationAxis = function makeRotationAxis(axis, angle) {
  9361. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9362. var c = Math.cos(angle);
  9363. var s = Math.sin(angle);
  9364. var t = 1 - c;
  9365. var x = axis.x,
  9366. y = axis.y,
  9367. z = axis.z;
  9368. var tx = t * x,
  9369. ty = t * y;
  9370. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  9371. return this;
  9372. };
  9373. _proto.makeScale = function makeScale(x, y, z) {
  9374. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  9375. return this;
  9376. };
  9377. _proto.makeShear = function makeShear(x, y, z) {
  9378. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  9379. return this;
  9380. };
  9381. _proto.compose = function compose(position, quaternion, scale) {
  9382. var te = this.elements;
  9383. var x = quaternion._x,
  9384. y = quaternion._y,
  9385. z = quaternion._z,
  9386. w = quaternion._w;
  9387. var x2 = x + x,
  9388. y2 = y + y,
  9389. z2 = z + z;
  9390. var xx = x * x2,
  9391. xy = x * y2,
  9392. xz = x * z2;
  9393. var yy = y * y2,
  9394. yz = y * z2,
  9395. zz = z * z2;
  9396. var wx = w * x2,
  9397. wy = w * y2,
  9398. wz = w * z2;
  9399. var sx = scale.x,
  9400. sy = scale.y,
  9401. sz = scale.z;
  9402. te[0] = (1 - (yy + zz)) * sx;
  9403. te[1] = (xy + wz) * sx;
  9404. te[2] = (xz - wy) * sx;
  9405. te[3] = 0;
  9406. te[4] = (xy - wz) * sy;
  9407. te[5] = (1 - (xx + zz)) * sy;
  9408. te[6] = (yz + wx) * sy;
  9409. te[7] = 0;
  9410. te[8] = (xz + wy) * sz;
  9411. te[9] = (yz - wx) * sz;
  9412. te[10] = (1 - (xx + yy)) * sz;
  9413. te[11] = 0;
  9414. te[12] = position.x;
  9415. te[13] = position.y;
  9416. te[14] = position.z;
  9417. te[15] = 1;
  9418. return this;
  9419. };
  9420. _proto.decompose = function decompose(position, quaternion, scale) {
  9421. var te = this.elements;
  9422. var sx = _v1$1.set(te[0], te[1], te[2]).length();
  9423. var sy = _v1$1.set(te[4], te[5], te[6]).length();
  9424. var sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  9425. var det = this.determinant();
  9426. if (det < 0) sx = -sx;
  9427. position.x = te[12];
  9428. position.y = te[13];
  9429. position.z = te[14]; // scale the rotation part
  9430. _m1.copy(this);
  9431. var invSX = 1 / sx;
  9432. var invSY = 1 / sy;
  9433. var invSZ = 1 / sz;
  9434. _m1.elements[0] *= invSX;
  9435. _m1.elements[1] *= invSX;
  9436. _m1.elements[2] *= invSX;
  9437. _m1.elements[4] *= invSY;
  9438. _m1.elements[5] *= invSY;
  9439. _m1.elements[6] *= invSY;
  9440. _m1.elements[8] *= invSZ;
  9441. _m1.elements[9] *= invSZ;
  9442. _m1.elements[10] *= invSZ;
  9443. quaternion.setFromRotationMatrix(_m1);
  9444. scale.x = sx;
  9445. scale.y = sy;
  9446. scale.z = sz;
  9447. return this;
  9448. };
  9449. _proto.makePerspective = function makePerspective(left, right, top, bottom, near, far) {
  9450. if (far === undefined) {
  9451. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  9452. }
  9453. var te = this.elements;
  9454. var x = 2 * near / (right - left);
  9455. var y = 2 * near / (top - bottom);
  9456. var a = (right + left) / (right - left);
  9457. var b = (top + bottom) / (top - bottom);
  9458. var c = -(far + near) / (far - near);
  9459. var d = -2 * far * near / (far - near);
  9460. te[0] = x;
  9461. te[4] = 0;
  9462. te[8] = a;
  9463. te[12] = 0;
  9464. te[1] = 0;
  9465. te[5] = y;
  9466. te[9] = b;
  9467. te[13] = 0;
  9468. te[2] = 0;
  9469. te[6] = 0;
  9470. te[10] = c;
  9471. te[14] = d;
  9472. te[3] = 0;
  9473. te[7] = 0;
  9474. te[11] = -1;
  9475. te[15] = 0;
  9476. return this;
  9477. };
  9478. _proto.makeOrthographic = function makeOrthographic(left, right, top, bottom, near, far) {
  9479. var te = this.elements;
  9480. var w = 1.0 / (right - left);
  9481. var h = 1.0 / (top - bottom);
  9482. var p = 1.0 / (far - near);
  9483. var x = (right + left) * w;
  9484. var y = (top + bottom) * h;
  9485. var z = (far + near) * p;
  9486. te[0] = 2 * w;
  9487. te[4] = 0;
  9488. te[8] = 0;
  9489. te[12] = -x;
  9490. te[1] = 0;
  9491. te[5] = 2 * h;
  9492. te[9] = 0;
  9493. te[13] = -y;
  9494. te[2] = 0;
  9495. te[6] = 0;
  9496. te[10] = -2 * p;
  9497. te[14] = -z;
  9498. te[3] = 0;
  9499. te[7] = 0;
  9500. te[11] = 0;
  9501. te[15] = 1;
  9502. return this;
  9503. };
  9504. _proto.equals = function equals(matrix) {
  9505. var te = this.elements;
  9506. var me = matrix.elements;
  9507. for (var i = 0; i < 16; i++) {
  9508. if (te[i] !== me[i]) return false;
  9509. }
  9510. return true;
  9511. };
  9512. _proto.fromArray = function fromArray(array, offset) {
  9513. if (offset === void 0) {
  9514. offset = 0;
  9515. }
  9516. for (var i = 0; i < 16; i++) {
  9517. this.elements[i] = array[i + offset];
  9518. }
  9519. return this;
  9520. };
  9521. _proto.toArray = function toArray(array, offset) {
  9522. if (array === void 0) {
  9523. array = [];
  9524. }
  9525. if (offset === void 0) {
  9526. offset = 0;
  9527. }
  9528. var te = this.elements;
  9529. array[offset] = te[0];
  9530. array[offset + 1] = te[1];
  9531. array[offset + 2] = te[2];
  9532. array[offset + 3] = te[3];
  9533. array[offset + 4] = te[4];
  9534. array[offset + 5] = te[5];
  9535. array[offset + 6] = te[6];
  9536. array[offset + 7] = te[7];
  9537. array[offset + 8] = te[8];
  9538. array[offset + 9] = te[9];
  9539. array[offset + 10] = te[10];
  9540. array[offset + 11] = te[11];
  9541. array[offset + 12] = te[12];
  9542. array[offset + 13] = te[13];
  9543. array[offset + 14] = te[14];
  9544. array[offset + 15] = te[15];
  9545. return array;
  9546. };
  9547. return Matrix4;
  9548. }();
  9549. var _v1$1 = /*@__PURE__*/new Vector3();
  9550. var _m1 = /*@__PURE__*/new Matrix4();
  9551. var _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  9552. var _one = /*@__PURE__*/new Vector3(1, 1, 1);
  9553. var _x = /*@__PURE__*/new Vector3();
  9554. var _y = /*@__PURE__*/new Vector3();
  9555. var _z = /*@__PURE__*/new Vector3();
  9556. var Euler = /*#__PURE__*/function () {
  9557. function Euler(x, y, z, order) {
  9558. if (x === void 0) {
  9559. x = 0;
  9560. }
  9561. if (y === void 0) {
  9562. y = 0;
  9563. }
  9564. if (z === void 0) {
  9565. z = 0;
  9566. }
  9567. if (order === void 0) {
  9568. order = Euler.DefaultOrder;
  9569. }
  9570. Object.defineProperty(this, 'isEuler', {
  9571. value: true
  9572. });
  9573. this._x = x;
  9574. this._y = y;
  9575. this._z = z;
  9576. this._order = order;
  9577. }
  9578. var _proto = Euler.prototype;
  9579. _proto.set = function set(x, y, z, order) {
  9580. this._x = x;
  9581. this._y = y;
  9582. this._z = z;
  9583. this._order = order || this._order;
  9584. this._onChangeCallback();
  9585. return this;
  9586. };
  9587. _proto.clone = function clone() {
  9588. return new this.constructor(this._x, this._y, this._z, this._order);
  9589. };
  9590. _proto.copy = function copy(euler) {
  9591. this._x = euler._x;
  9592. this._y = euler._y;
  9593. this._z = euler._z;
  9594. this._order = euler._order;
  9595. this._onChangeCallback();
  9596. return this;
  9597. };
  9598. _proto.setFromRotationMatrix = function setFromRotationMatrix(m, order, update) {
  9599. var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9600. var te = m.elements;
  9601. var m11 = te[0],
  9602. m12 = te[4],
  9603. m13 = te[8];
  9604. var m21 = te[1],
  9605. m22 = te[5],
  9606. m23 = te[9];
  9607. var m31 = te[2],
  9608. m32 = te[6],
  9609. m33 = te[10];
  9610. order = order || this._order;
  9611. switch (order) {
  9612. case 'XYZ':
  9613. this._y = Math.asin(clamp(m13, -1, 1));
  9614. if (Math.abs(m13) < 0.9999999) {
  9615. this._x = Math.atan2(-m23, m33);
  9616. this._z = Math.atan2(-m12, m11);
  9617. } else {
  9618. this._x = Math.atan2(m32, m22);
  9619. this._z = 0;
  9620. }
  9621. break;
  9622. case 'YXZ':
  9623. this._x = Math.asin(-clamp(m23, -1, 1));
  9624. if (Math.abs(m23) < 0.9999999) {
  9625. this._y = Math.atan2(m13, m33);
  9626. this._z = Math.atan2(m21, m22);
  9627. } else {
  9628. this._y = Math.atan2(-m31, m11);
  9629. this._z = 0;
  9630. }
  9631. break;
  9632. case 'ZXY':
  9633. this._x = Math.asin(clamp(m32, -1, 1));
  9634. if (Math.abs(m32) < 0.9999999) {
  9635. this._y = Math.atan2(-m31, m33);
  9636. this._z = Math.atan2(-m12, m22);
  9637. } else {
  9638. this._y = 0;
  9639. this._z = Math.atan2(m21, m11);
  9640. }
  9641. break;
  9642. case 'ZYX':
  9643. this._y = Math.asin(-clamp(m31, -1, 1));
  9644. if (Math.abs(m31) < 0.9999999) {
  9645. this._x = Math.atan2(m32, m33);
  9646. this._z = Math.atan2(m21, m11);
  9647. } else {
  9648. this._x = 0;
  9649. this._z = Math.atan2(-m12, m22);
  9650. }
  9651. break;
  9652. case 'YZX':
  9653. this._z = Math.asin(clamp(m21, -1, 1));
  9654. if (Math.abs(m21) < 0.9999999) {
  9655. this._x = Math.atan2(-m23, m22);
  9656. this._y = Math.atan2(-m31, m11);
  9657. } else {
  9658. this._x = 0;
  9659. this._y = Math.atan2(m13, m33);
  9660. }
  9661. break;
  9662. case 'XZY':
  9663. this._z = Math.asin(-clamp(m12, -1, 1));
  9664. if (Math.abs(m12) < 0.9999999) {
  9665. this._x = Math.atan2(m32, m22);
  9666. this._y = Math.atan2(m13, m11);
  9667. } else {
  9668. this._x = Math.atan2(-m23, m33);
  9669. this._y = 0;
  9670. }
  9671. break;
  9672. default:
  9673. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  9674. }
  9675. this._order = order;
  9676. if (update !== false) this._onChangeCallback();
  9677. return this;
  9678. };
  9679. _proto.setFromQuaternion = function setFromQuaternion(q, order, update) {
  9680. _matrix.makeRotationFromQuaternion(q);
  9681. return this.setFromRotationMatrix(_matrix, order, update);
  9682. };
  9683. _proto.setFromVector3 = function setFromVector3(v, order) {
  9684. return this.set(v.x, v.y, v.z, order || this._order);
  9685. };
  9686. _proto.reorder = function reorder(newOrder) {
  9687. // WARNING: this discards revolution information -bhouston
  9688. _quaternion$1.setFromEuler(this);
  9689. return this.setFromQuaternion(_quaternion$1, newOrder);
  9690. };
  9691. _proto.equals = function equals(euler) {
  9692. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  9693. };
  9694. _proto.fromArray = function fromArray(array) {
  9695. this._x = array[0];
  9696. this._y = array[1];
  9697. this._z = array[2];
  9698. if (array[3] !== undefined) this._order = array[3];
  9699. this._onChangeCallback();
  9700. return this;
  9701. };
  9702. _proto.toArray = function toArray(array, offset) {
  9703. if (array === void 0) {
  9704. array = [];
  9705. }
  9706. if (offset === void 0) {
  9707. offset = 0;
  9708. }
  9709. array[offset] = this._x;
  9710. array[offset + 1] = this._y;
  9711. array[offset + 2] = this._z;
  9712. array[offset + 3] = this._order;
  9713. return array;
  9714. };
  9715. _proto.toVector3 = function toVector3(optionalResult) {
  9716. if (optionalResult) {
  9717. return optionalResult.set(this._x, this._y, this._z);
  9718. } else {
  9719. return new Vector3(this._x, this._y, this._z);
  9720. }
  9721. };
  9722. _proto._onChange = function _onChange(callback) {
  9723. this._onChangeCallback = callback;
  9724. return this;
  9725. };
  9726. _proto._onChangeCallback = function _onChangeCallback() {};
  9727. _createClass(Euler, [{
  9728. key: "x",
  9729. get: function get() {
  9730. return this._x;
  9731. },
  9732. set: function set(value) {
  9733. this._x = value;
  9734. this._onChangeCallback();
  9735. }
  9736. }, {
  9737. key: "y",
  9738. get: function get() {
  9739. return this._y;
  9740. },
  9741. set: function set(value) {
  9742. this._y = value;
  9743. this._onChangeCallback();
  9744. }
  9745. }, {
  9746. key: "z",
  9747. get: function get() {
  9748. return this._z;
  9749. },
  9750. set: function set(value) {
  9751. this._z = value;
  9752. this._onChangeCallback();
  9753. }
  9754. }, {
  9755. key: "order",
  9756. get: function get() {
  9757. return this._order;
  9758. },
  9759. set: function set(value) {
  9760. this._order = value;
  9761. this._onChangeCallback();
  9762. }
  9763. }]);
  9764. return Euler;
  9765. }();
  9766. Euler.DefaultOrder = 'XYZ';
  9767. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  9768. var _matrix = /*@__PURE__*/new Matrix4();
  9769. var _quaternion$1 = /*@__PURE__*/new Quaternion();
  9770. var Layers = /*#__PURE__*/function () {
  9771. function Layers() {
  9772. this.mask = 1 | 0;
  9773. }
  9774. var _proto = Layers.prototype;
  9775. _proto.set = function set(channel) {
  9776. this.mask = 1 << channel | 0;
  9777. };
  9778. _proto.enable = function enable(channel) {
  9779. this.mask |= 1 << channel | 0;
  9780. };
  9781. _proto.enableAll = function enableAll() {
  9782. this.mask = 0xffffffff | 0;
  9783. };
  9784. _proto.toggle = function toggle(channel) {
  9785. this.mask ^= 1 << channel | 0;
  9786. };
  9787. _proto.disable = function disable(channel) {
  9788. this.mask &= ~(1 << channel | 0);
  9789. };
  9790. _proto.disableAll = function disableAll() {
  9791. this.mask = 0;
  9792. };
  9793. _proto.test = function test(layers) {
  9794. return (this.mask & layers.mask) !== 0;
  9795. };
  9796. return Layers;
  9797. }();
  9798. var _object3DId = 0;
  9799. var _v1$2 = new Vector3();
  9800. var _q1 = new Quaternion();
  9801. var _m1$1 = new Matrix4();
  9802. var _target = new Vector3();
  9803. var _position = new Vector3();
  9804. var _scale = new Vector3();
  9805. var _quaternion$2 = new Quaternion();
  9806. var _xAxis = new Vector3(1, 0, 0);
  9807. var _yAxis = new Vector3(0, 1, 0);
  9808. var _zAxis = new Vector3(0, 0, 1);
  9809. var _addedEvent = {
  9810. type: 'added'
  9811. };
  9812. var _removedEvent = {
  9813. type: 'removed'
  9814. };
  9815. function Object3D() {
  9816. Object.defineProperty(this, 'id', {
  9817. value: _object3DId++
  9818. });
  9819. this.uuid = MathUtils.generateUUID();
  9820. this.name = '';
  9821. this.type = 'Object3D';
  9822. this.parent = null;
  9823. this.children = [];
  9824. this.up = Object3D.DefaultUp.clone();
  9825. var position = new Vector3();
  9826. var rotation = new Euler();
  9827. var quaternion = new Quaternion();
  9828. var scale = new Vector3(1, 1, 1);
  9829. function onRotationChange() {
  9830. quaternion.setFromEuler(rotation, false);
  9831. }
  9832. function onQuaternionChange() {
  9833. rotation.setFromQuaternion(quaternion, undefined, false);
  9834. }
  9835. rotation._onChange(onRotationChange);
  9836. quaternion._onChange(onQuaternionChange);
  9837. Object.defineProperties(this, {
  9838. position: {
  9839. configurable: true,
  9840. enumerable: true,
  9841. value: position
  9842. },
  9843. rotation: {
  9844. configurable: true,
  9845. enumerable: true,
  9846. value: rotation
  9847. },
  9848. quaternion: {
  9849. configurable: true,
  9850. enumerable: true,
  9851. value: quaternion
  9852. },
  9853. scale: {
  9854. configurable: true,
  9855. enumerable: true,
  9856. value: scale
  9857. },
  9858. modelViewMatrix: {
  9859. value: new Matrix4()
  9860. },
  9861. normalMatrix: {
  9862. value: new Matrix3()
  9863. }
  9864. });
  9865. this.matrix = new Matrix4();
  9866. this.matrixWorld = new Matrix4();
  9867. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  9868. this.matrixWorldNeedsUpdate = false;
  9869. this.layers = new Layers();
  9870. this.visible = true;
  9871. this.castShadow = false;
  9872. this.receiveShadow = false;
  9873. this.frustumCulled = true;
  9874. this.renderOrder = 0;
  9875. this.animations = [];
  9876. this.userData = {};
  9877. }
  9878. Object3D.DefaultUp = new Vector3(0, 1, 0);
  9879. Object3D.DefaultMatrixAutoUpdate = true;
  9880. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  9881. constructor: Object3D,
  9882. isObject3D: true,
  9883. onBeforeRender: function onBeforeRender() {},
  9884. onAfterRender: function onAfterRender() {},
  9885. applyMatrix4: function applyMatrix4(matrix) {
  9886. if (this.matrixAutoUpdate) this.updateMatrix();
  9887. this.matrix.premultiply(matrix);
  9888. this.matrix.decompose(this.position, this.quaternion, this.scale);
  9889. },
  9890. applyQuaternion: function applyQuaternion(q) {
  9891. this.quaternion.premultiply(q);
  9892. return this;
  9893. },
  9894. setRotationFromAxisAngle: function setRotationFromAxisAngle(axis, angle) {
  9895. // assumes axis is normalized
  9896. this.quaternion.setFromAxisAngle(axis, angle);
  9897. },
  9898. setRotationFromEuler: function setRotationFromEuler(euler) {
  9899. this.quaternion.setFromEuler(euler, true);
  9900. },
  9901. setRotationFromMatrix: function setRotationFromMatrix(m) {
  9902. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9903. this.quaternion.setFromRotationMatrix(m);
  9904. },
  9905. setRotationFromQuaternion: function setRotationFromQuaternion(q) {
  9906. // assumes q is normalized
  9907. this.quaternion.copy(q);
  9908. },
  9909. rotateOnAxis: function rotateOnAxis(axis, angle) {
  9910. // rotate object on axis in object space
  9911. // axis is assumed to be normalized
  9912. _q1.setFromAxisAngle(axis, angle);
  9913. this.quaternion.multiply(_q1);
  9914. return this;
  9915. },
  9916. rotateOnWorldAxis: function rotateOnWorldAxis(axis, angle) {
  9917. // rotate object on axis in world space
  9918. // axis is assumed to be normalized
  9919. // method assumes no rotated parent
  9920. _q1.setFromAxisAngle(axis, angle);
  9921. this.quaternion.premultiply(_q1);
  9922. return this;
  9923. },
  9924. rotateX: function rotateX(angle) {
  9925. return this.rotateOnAxis(_xAxis, angle);
  9926. },
  9927. rotateY: function rotateY(angle) {
  9928. return this.rotateOnAxis(_yAxis, angle);
  9929. },
  9930. rotateZ: function rotateZ(angle) {
  9931. return this.rotateOnAxis(_zAxis, angle);
  9932. },
  9933. translateOnAxis: function translateOnAxis(axis, distance) {
  9934. // translate object by distance along axis in object space
  9935. // axis is assumed to be normalized
  9936. _v1$2.copy(axis).applyQuaternion(this.quaternion);
  9937. this.position.add(_v1$2.multiplyScalar(distance));
  9938. return this;
  9939. },
  9940. translateX: function translateX(distance) {
  9941. return this.translateOnAxis(_xAxis, distance);
  9942. },
  9943. translateY: function translateY(distance) {
  9944. return this.translateOnAxis(_yAxis, distance);
  9945. },
  9946. translateZ: function translateZ(distance) {
  9947. return this.translateOnAxis(_zAxis, distance);
  9948. },
  9949. localToWorld: function localToWorld(vector) {
  9950. return vector.applyMatrix4(this.matrixWorld);
  9951. },
  9952. worldToLocal: function worldToLocal(vector) {
  9953. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  9954. },
  9955. lookAt: function lookAt(x, y, z) {
  9956. // This method does not support objects having non-uniformly-scaled parent(s)
  9957. if (x.isVector3) {
  9958. _target.copy(x);
  9959. } else {
  9960. _target.set(x, y, z);
  9961. }
  9962. var parent = this.parent;
  9963. this.updateWorldMatrix(true, false);
  9964. _position.setFromMatrixPosition(this.matrixWorld);
  9965. if (this.isCamera || this.isLight) {
  9966. _m1$1.lookAt(_position, _target, this.up);
  9967. } else {
  9968. _m1$1.lookAt(_target, _position, this.up);
  9969. }
  9970. this.quaternion.setFromRotationMatrix(_m1$1);
  9971. if (parent) {
  9972. _m1$1.extractRotation(parent.matrixWorld);
  9973. _q1.setFromRotationMatrix(_m1$1);
  9974. this.quaternion.premultiply(_q1.invert());
  9975. }
  9976. },
  9977. add: function add(object) {
  9978. if (arguments.length > 1) {
  9979. for (var i = 0; i < arguments.length; i++) {
  9980. this.add(arguments[i]);
  9981. }
  9982. return this;
  9983. }
  9984. if (object === this) {
  9985. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  9986. return this;
  9987. }
  9988. if (object && object.isObject3D) {
  9989. if (object.parent !== null) {
  9990. object.parent.remove(object);
  9991. }
  9992. object.parent = this;
  9993. this.children.push(object);
  9994. object.dispatchEvent(_addedEvent);
  9995. } else {
  9996. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  9997. }
  9998. return this;
  9999. },
  10000. remove: function remove(object) {
  10001. if (arguments.length > 1) {
  10002. for (var i = 0; i < arguments.length; i++) {
  10003. this.remove(arguments[i]);
  10004. }
  10005. return this;
  10006. }
  10007. var index = this.children.indexOf(object);
  10008. if (index !== -1) {
  10009. object.parent = null;
  10010. this.children.splice(index, 1);
  10011. object.dispatchEvent(_removedEvent);
  10012. }
  10013. return this;
  10014. },
  10015. clear: function clear() {
  10016. for (var i = 0; i < this.children.length; i++) {
  10017. var object = this.children[i];
  10018. object.parent = null;
  10019. object.dispatchEvent(_removedEvent);
  10020. }
  10021. this.children.length = 0;
  10022. return this;
  10023. },
  10024. attach: function attach(object) {
  10025. // adds object as a child of this, while maintaining the object's world transform
  10026. this.updateWorldMatrix(true, false);
  10027. _m1$1.copy(this.matrixWorld).invert();
  10028. if (object.parent !== null) {
  10029. object.parent.updateWorldMatrix(true, false);
  10030. _m1$1.multiply(object.parent.matrixWorld);
  10031. }
  10032. object.applyMatrix4(_m1$1);
  10033. object.updateWorldMatrix(false, false);
  10034. this.add(object);
  10035. return this;
  10036. },
  10037. getObjectById: function getObjectById(id) {
  10038. return this.getObjectByProperty('id', id);
  10039. },
  10040. getObjectByName: function getObjectByName(name) {
  10041. return this.getObjectByProperty('name', name);
  10042. },
  10043. getObjectByProperty: function getObjectByProperty(name, value) {
  10044. if (this[name] === value) return this;
  10045. for (var i = 0, l = this.children.length; i < l; i++) {
  10046. var child = this.children[i];
  10047. var object = child.getObjectByProperty(name, value);
  10048. if (object !== undefined) {
  10049. return object;
  10050. }
  10051. }
  10052. return undefined;
  10053. },
  10054. getWorldPosition: function getWorldPosition(target) {
  10055. if (target === undefined) {
  10056. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  10057. target = new Vector3();
  10058. }
  10059. this.updateWorldMatrix(true, false);
  10060. return target.setFromMatrixPosition(this.matrixWorld);
  10061. },
  10062. getWorldQuaternion: function getWorldQuaternion(target) {
  10063. if (target === undefined) {
  10064. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  10065. target = new Quaternion();
  10066. }
  10067. this.updateWorldMatrix(true, false);
  10068. this.matrixWorld.decompose(_position, target, _scale);
  10069. return target;
  10070. },
  10071. getWorldScale: function getWorldScale(target) {
  10072. if (target === undefined) {
  10073. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  10074. target = new Vector3();
  10075. }
  10076. this.updateWorldMatrix(true, false);
  10077. this.matrixWorld.decompose(_position, _quaternion$2, target);
  10078. return target;
  10079. },
  10080. getWorldDirection: function getWorldDirection(target) {
  10081. if (target === undefined) {
  10082. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  10083. target = new Vector3();
  10084. }
  10085. this.updateWorldMatrix(true, false);
  10086. var e = this.matrixWorld.elements;
  10087. return target.set(e[8], e[9], e[10]).normalize();
  10088. },
  10089. raycast: function raycast() {},
  10090. traverse: function traverse(callback) {
  10091. callback(this);
  10092. var children = this.children;
  10093. for (var i = 0, l = children.length; i < l; i++) {
  10094. children[i].traverse(callback);
  10095. }
  10096. },
  10097. traverseVisible: function traverseVisible(callback) {
  10098. if (this.visible === false) return;
  10099. callback(this);
  10100. var children = this.children;
  10101. for (var i = 0, l = children.length; i < l; i++) {
  10102. children[i].traverseVisible(callback);
  10103. }
  10104. },
  10105. traverseAncestors: function traverseAncestors(callback) {
  10106. var parent = this.parent;
  10107. if (parent !== null) {
  10108. callback(parent);
  10109. parent.traverseAncestors(callback);
  10110. }
  10111. },
  10112. updateMatrix: function updateMatrix() {
  10113. this.matrix.compose(this.position, this.quaternion, this.scale);
  10114. this.matrixWorldNeedsUpdate = true;
  10115. },
  10116. updateMatrixWorld: function updateMatrixWorld(force) {
  10117. if (this.matrixAutoUpdate) this.updateMatrix();
  10118. if (this.matrixWorldNeedsUpdate || force) {
  10119. if (this.parent === null) {
  10120. this.matrixWorld.copy(this.matrix);
  10121. } else {
  10122. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10123. }
  10124. this.matrixWorldNeedsUpdate = false;
  10125. force = true;
  10126. } // update children
  10127. var children = this.children;
  10128. for (var i = 0, l = children.length; i < l; i++) {
  10129. children[i].updateMatrixWorld(force);
  10130. }
  10131. },
  10132. updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
  10133. var parent = this.parent;
  10134. if (updateParents === true && parent !== null) {
  10135. parent.updateWorldMatrix(true, false);
  10136. }
  10137. if (this.matrixAutoUpdate) this.updateMatrix();
  10138. if (this.parent === null) {
  10139. this.matrixWorld.copy(this.matrix);
  10140. } else {
  10141. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10142. } // update children
  10143. if (updateChildren === true) {
  10144. var children = this.children;
  10145. for (var i = 0, l = children.length; i < l; i++) {
  10146. children[i].updateWorldMatrix(false, true);
  10147. }
  10148. }
  10149. },
  10150. toJSON: function toJSON(meta) {
  10151. // meta is a string when called from JSON.stringify
  10152. var isRootObject = meta === undefined || typeof meta === 'string';
  10153. var output = {}; // meta is a hash used to collect geometries, materials.
  10154. // not providing it implies that this is the root object
  10155. // being serialized.
  10156. if (isRootObject) {
  10157. // initialize meta obj
  10158. meta = {
  10159. geometries: {},
  10160. materials: {},
  10161. textures: {},
  10162. images: {},
  10163. shapes: {},
  10164. skeletons: {},
  10165. animations: {}
  10166. };
  10167. output.metadata = {
  10168. version: 4.5,
  10169. type: 'Object',
  10170. generator: 'Object3D.toJSON'
  10171. };
  10172. } // standard Object3D serialization
  10173. var object = {};
  10174. object.uuid = this.uuid;
  10175. object.type = this.type;
  10176. if (this.name !== '') object.name = this.name;
  10177. if (this.castShadow === true) object.castShadow = true;
  10178. if (this.receiveShadow === true) object.receiveShadow = true;
  10179. if (this.visible === false) object.visible = false;
  10180. if (this.frustumCulled === false) object.frustumCulled = false;
  10181. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  10182. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  10183. object.layers = this.layers.mask;
  10184. object.matrix = this.matrix.toArray();
  10185. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  10186. if (this.isInstancedMesh) {
  10187. object.type = 'InstancedMesh';
  10188. object.count = this.count;
  10189. object.instanceMatrix = this.instanceMatrix.toJSON();
  10190. } //
  10191. function serialize(library, element) {
  10192. if (library[element.uuid] === undefined) {
  10193. library[element.uuid] = element.toJSON(meta);
  10194. }
  10195. return element.uuid;
  10196. }
  10197. if (this.isMesh || this.isLine || this.isPoints) {
  10198. object.geometry = serialize(meta.geometries, this.geometry);
  10199. var parameters = this.geometry.parameters;
  10200. if (parameters !== undefined && parameters.shapes !== undefined) {
  10201. var shapes = parameters.shapes;
  10202. if (Array.isArray(shapes)) {
  10203. for (var i = 0, l = shapes.length; i < l; i++) {
  10204. var shape = shapes[i];
  10205. serialize(meta.shapes, shape);
  10206. }
  10207. } else {
  10208. serialize(meta.shapes, shapes);
  10209. }
  10210. }
  10211. }
  10212. if (this.isSkinnedMesh) {
  10213. object.bindMode = this.bindMode;
  10214. object.bindMatrix = this.bindMatrix.toArray();
  10215. if (this.skeleton !== undefined) {
  10216. serialize(meta.skeletons, this.skeleton);
  10217. object.skeleton = this.skeleton.uuid;
  10218. }
  10219. }
  10220. if (this.material !== undefined) {
  10221. if (Array.isArray(this.material)) {
  10222. var uuids = [];
  10223. for (var _i = 0, _l = this.material.length; _i < _l; _i++) {
  10224. uuids.push(serialize(meta.materials, this.material[_i]));
  10225. }
  10226. object.material = uuids;
  10227. } else {
  10228. object.material = serialize(meta.materials, this.material);
  10229. }
  10230. } //
  10231. if (this.children.length > 0) {
  10232. object.children = [];
  10233. for (var _i2 = 0; _i2 < this.children.length; _i2++) {
  10234. object.children.push(this.children[_i2].toJSON(meta).object);
  10235. }
  10236. } //
  10237. if (this.animations.length > 0) {
  10238. object.animations = [];
  10239. for (var _i3 = 0; _i3 < this.animations.length; _i3++) {
  10240. var animation = this.animations[_i3];
  10241. object.animations.push(serialize(meta.animations, animation));
  10242. }
  10243. }
  10244. if (isRootObject) {
  10245. var geometries = extractFromCache(meta.geometries);
  10246. var materials = extractFromCache(meta.materials);
  10247. var textures = extractFromCache(meta.textures);
  10248. var images = extractFromCache(meta.images);
  10249. var _shapes = extractFromCache(meta.shapes);
  10250. var skeletons = extractFromCache(meta.skeletons);
  10251. var animations = extractFromCache(meta.animations);
  10252. if (geometries.length > 0) output.geometries = geometries;
  10253. if (materials.length > 0) output.materials = materials;
  10254. if (textures.length > 0) output.textures = textures;
  10255. if (images.length > 0) output.images = images;
  10256. if (_shapes.length > 0) output.shapes = _shapes;
  10257. if (skeletons.length > 0) output.skeletons = skeletons;
  10258. if (animations.length > 0) output.animations = animations;
  10259. }
  10260. output.object = object;
  10261. return output; // extract data from the cache hash
  10262. // remove metadata on each item
  10263. // and return as array
  10264. function extractFromCache(cache) {
  10265. var values = [];
  10266. for (var key in cache) {
  10267. var data = cache[key];
  10268. delete data.metadata;
  10269. values.push(data);
  10270. }
  10271. return values;
  10272. }
  10273. },
  10274. clone: function clone(recursive) {
  10275. return new this.constructor().copy(this, recursive);
  10276. },
  10277. copy: function copy(source, recursive) {
  10278. if (recursive === void 0) {
  10279. recursive = true;
  10280. }
  10281. this.name = source.name;
  10282. this.up.copy(source.up);
  10283. this.position.copy(source.position);
  10284. this.rotation.order = source.rotation.order;
  10285. this.quaternion.copy(source.quaternion);
  10286. this.scale.copy(source.scale);
  10287. this.matrix.copy(source.matrix);
  10288. this.matrixWorld.copy(source.matrixWorld);
  10289. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10290. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10291. this.layers.mask = source.layers.mask;
  10292. this.visible = source.visible;
  10293. this.castShadow = source.castShadow;
  10294. this.receiveShadow = source.receiveShadow;
  10295. this.frustumCulled = source.frustumCulled;
  10296. this.renderOrder = source.renderOrder;
  10297. this.userData = JSON.parse(JSON.stringify(source.userData));
  10298. if (recursive === true) {
  10299. for (var i = 0; i < source.children.length; i++) {
  10300. var child = source.children[i];
  10301. this.add(child.clone());
  10302. }
  10303. }
  10304. return this;
  10305. }
  10306. });
  10307. var _vector1 = /*@__PURE__*/new Vector3();
  10308. var _vector2 = /*@__PURE__*/new Vector3();
  10309. var _normalMatrix = /*@__PURE__*/new Matrix3();
  10310. var Plane = /*#__PURE__*/function () {
  10311. function Plane(normal, constant) {
  10312. Object.defineProperty(this, 'isPlane', {
  10313. value: true
  10314. }); // normal is assumed to be normalized
  10315. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  10316. this.constant = constant !== undefined ? constant : 0;
  10317. }
  10318. var _proto = Plane.prototype;
  10319. _proto.set = function set(normal, constant) {
  10320. this.normal.copy(normal);
  10321. this.constant = constant;
  10322. return this;
  10323. };
  10324. _proto.setComponents = function setComponents(x, y, z, w) {
  10325. this.normal.set(x, y, z);
  10326. this.constant = w;
  10327. return this;
  10328. };
  10329. _proto.setFromNormalAndCoplanarPoint = function setFromNormalAndCoplanarPoint(normal, point) {
  10330. this.normal.copy(normal);
  10331. this.constant = -point.dot(this.normal);
  10332. return this;
  10333. };
  10334. _proto.setFromCoplanarPoints = function setFromCoplanarPoints(a, b, c) {
  10335. var normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  10336. this.setFromNormalAndCoplanarPoint(normal, a);
  10337. return this;
  10338. };
  10339. _proto.clone = function clone() {
  10340. return new this.constructor().copy(this);
  10341. };
  10342. _proto.copy = function copy(plane) {
  10343. this.normal.copy(plane.normal);
  10344. this.constant = plane.constant;
  10345. return this;
  10346. };
  10347. _proto.normalize = function normalize() {
  10348. // Note: will lead to a divide by zero if the plane is invalid.
  10349. var inverseNormalLength = 1.0 / this.normal.length();
  10350. this.normal.multiplyScalar(inverseNormalLength);
  10351. this.constant *= inverseNormalLength;
  10352. return this;
  10353. };
  10354. _proto.negate = function negate() {
  10355. this.constant *= -1;
  10356. this.normal.negate();
  10357. return this;
  10358. };
  10359. _proto.distanceToPoint = function distanceToPoint(point) {
  10360. return this.normal.dot(point) + this.constant;
  10361. };
  10362. _proto.distanceToSphere = function distanceToSphere(sphere) {
  10363. return this.distanceToPoint(sphere.center) - sphere.radius;
  10364. };
  10365. _proto.projectPoint = function projectPoint(point, target) {
  10366. if (target === undefined) {
  10367. console.warn('THREE.Plane: .projectPoint() target is now required');
  10368. target = new Vector3();
  10369. }
  10370. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  10371. };
  10372. _proto.intersectLine = function intersectLine(line, target) {
  10373. if (target === undefined) {
  10374. console.warn('THREE.Plane: .intersectLine() target is now required');
  10375. target = new Vector3();
  10376. }
  10377. var direction = line.delta(_vector1);
  10378. var denominator = this.normal.dot(direction);
  10379. if (denominator === 0) {
  10380. // line is coplanar, return origin
  10381. if (this.distanceToPoint(line.start) === 0) {
  10382. return target.copy(line.start);
  10383. } // Unsure if this is the correct method to handle this case.
  10384. return undefined;
  10385. }
  10386. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  10387. if (t < 0 || t > 1) {
  10388. return undefined;
  10389. }
  10390. return target.copy(direction).multiplyScalar(t).add(line.start);
  10391. };
  10392. _proto.intersectsLine = function intersectsLine(line) {
  10393. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10394. var startSign = this.distanceToPoint(line.start);
  10395. var endSign = this.distanceToPoint(line.end);
  10396. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  10397. };
  10398. _proto.intersectsBox = function intersectsBox(box) {
  10399. return box.intersectsPlane(this);
  10400. };
  10401. _proto.intersectsSphere = function intersectsSphere(sphere) {
  10402. return sphere.intersectsPlane(this);
  10403. };
  10404. _proto.coplanarPoint = function coplanarPoint(target) {
  10405. if (target === undefined) {
  10406. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  10407. target = new Vector3();
  10408. }
  10409. return target.copy(this.normal).multiplyScalar(-this.constant);
  10410. };
  10411. _proto.applyMatrix4 = function applyMatrix4(matrix, optionalNormalMatrix) {
  10412. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  10413. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  10414. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  10415. this.constant = -referencePoint.dot(normal);
  10416. return this;
  10417. };
  10418. _proto.translate = function translate(offset) {
  10419. this.constant -= offset.dot(this.normal);
  10420. return this;
  10421. };
  10422. _proto.equals = function equals(plane) {
  10423. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  10424. };
  10425. return Plane;
  10426. }();
  10427. var _v0$1 = /*@__PURE__*/new Vector3();
  10428. var _v1$3 = /*@__PURE__*/new Vector3();
  10429. var _v2$1 = /*@__PURE__*/new Vector3();
  10430. var _v3 = /*@__PURE__*/new Vector3();
  10431. var _vab = /*@__PURE__*/new Vector3();
  10432. var _vac = /*@__PURE__*/new Vector3();
  10433. var _vbc = /*@__PURE__*/new Vector3();
  10434. var _vap = /*@__PURE__*/new Vector3();
  10435. var _vbp = /*@__PURE__*/new Vector3();
  10436. var _vcp = /*@__PURE__*/new Vector3();
  10437. var Triangle = /*#__PURE__*/function () {
  10438. function Triangle(a, b, c) {
  10439. this.a = a !== undefined ? a : new Vector3();
  10440. this.b = b !== undefined ? b : new Vector3();
  10441. this.c = c !== undefined ? c : new Vector3();
  10442. }
  10443. Triangle.getNormal = function getNormal(a, b, c, target) {
  10444. if (target === undefined) {
  10445. console.warn('THREE.Triangle: .getNormal() target is now required');
  10446. target = new Vector3();
  10447. }
  10448. target.subVectors(c, b);
  10449. _v0$1.subVectors(a, b);
  10450. target.cross(_v0$1);
  10451. var targetLengthSq = target.lengthSq();
  10452. if (targetLengthSq > 0) {
  10453. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  10454. }
  10455. return target.set(0, 0, 0);
  10456. } // static/instance method to calculate barycentric coordinates
  10457. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10458. ;
  10459. Triangle.getBarycoord = function getBarycoord(point, a, b, c, target) {
  10460. _v0$1.subVectors(c, a);
  10461. _v1$3.subVectors(b, a);
  10462. _v2$1.subVectors(point, a);
  10463. var dot00 = _v0$1.dot(_v0$1);
  10464. var dot01 = _v0$1.dot(_v1$3);
  10465. var dot02 = _v0$1.dot(_v2$1);
  10466. var dot11 = _v1$3.dot(_v1$3);
  10467. var dot12 = _v1$3.dot(_v2$1);
  10468. var denom = dot00 * dot11 - dot01 * dot01;
  10469. if (target === undefined) {
  10470. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  10471. target = new Vector3();
  10472. } // collinear or singular triangle
  10473. if (denom === 0) {
  10474. // arbitrary location outside of triangle?
  10475. // not sure if this is the best idea, maybe should be returning undefined
  10476. return target.set(-2, -1, -1);
  10477. }
  10478. var invDenom = 1 / denom;
  10479. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  10480. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  10481. return target.set(1 - u - v, v, u);
  10482. };
  10483. Triangle.containsPoint = function containsPoint(point, a, b, c) {
  10484. this.getBarycoord(point, a, b, c, _v3);
  10485. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  10486. };
  10487. Triangle.getUV = function getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  10488. this.getBarycoord(point, p1, p2, p3, _v3);
  10489. target.set(0, 0);
  10490. target.addScaledVector(uv1, _v3.x);
  10491. target.addScaledVector(uv2, _v3.y);
  10492. target.addScaledVector(uv3, _v3.z);
  10493. return target;
  10494. };
  10495. Triangle.isFrontFacing = function isFrontFacing(a, b, c, direction) {
  10496. _v0$1.subVectors(c, b);
  10497. _v1$3.subVectors(a, b); // strictly front facing
  10498. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  10499. };
  10500. var _proto = Triangle.prototype;
  10501. _proto.set = function set(a, b, c) {
  10502. this.a.copy(a);
  10503. this.b.copy(b);
  10504. this.c.copy(c);
  10505. return this;
  10506. };
  10507. _proto.setFromPointsAndIndices = function setFromPointsAndIndices(points, i0, i1, i2) {
  10508. this.a.copy(points[i0]);
  10509. this.b.copy(points[i1]);
  10510. this.c.copy(points[i2]);
  10511. return this;
  10512. };
  10513. _proto.clone = function clone() {
  10514. return new this.constructor().copy(this);
  10515. };
  10516. _proto.copy = function copy(triangle) {
  10517. this.a.copy(triangle.a);
  10518. this.b.copy(triangle.b);
  10519. this.c.copy(triangle.c);
  10520. return this;
  10521. };
  10522. _proto.getArea = function getArea() {
  10523. _v0$1.subVectors(this.c, this.b);
  10524. _v1$3.subVectors(this.a, this.b);
  10525. return _v0$1.cross(_v1$3).length() * 0.5;
  10526. };
  10527. _proto.getMidpoint = function getMidpoint(target) {
  10528. if (target === undefined) {
  10529. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  10530. target = new Vector3();
  10531. }
  10532. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  10533. };
  10534. _proto.getNormal = function getNormal(target) {
  10535. return Triangle.getNormal(this.a, this.b, this.c, target);
  10536. };
  10537. _proto.getPlane = function getPlane(target) {
  10538. if (target === undefined) {
  10539. console.warn('THREE.Triangle: .getPlane() target is now required');
  10540. target = new Plane();
  10541. }
  10542. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  10543. };
  10544. _proto.getBarycoord = function getBarycoord(point, target) {
  10545. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  10546. };
  10547. _proto.getUV = function getUV(point, uv1, uv2, uv3, target) {
  10548. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  10549. };
  10550. _proto.containsPoint = function containsPoint(point) {
  10551. return Triangle.containsPoint(point, this.a, this.b, this.c);
  10552. };
  10553. _proto.isFrontFacing = function isFrontFacing(direction) {
  10554. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  10555. };
  10556. _proto.intersectsBox = function intersectsBox(box) {
  10557. return box.intersectsTriangle(this);
  10558. };
  10559. _proto.closestPointToPoint = function closestPointToPoint(p, target) {
  10560. if (target === undefined) {
  10561. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  10562. target = new Vector3();
  10563. }
  10564. var a = this.a,
  10565. b = this.b,
  10566. c = this.c;
  10567. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  10568. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  10569. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  10570. // basically, we're distinguishing which of the voronoi regions of the triangle
  10571. // the point lies in with the minimum amount of redundant computation.
  10572. _vab.subVectors(b, a);
  10573. _vac.subVectors(c, a);
  10574. _vap.subVectors(p, a);
  10575. var d1 = _vab.dot(_vap);
  10576. var d2 = _vac.dot(_vap);
  10577. if (d1 <= 0 && d2 <= 0) {
  10578. // vertex region of A; barycentric coords (1, 0, 0)
  10579. return target.copy(a);
  10580. }
  10581. _vbp.subVectors(p, b);
  10582. var d3 = _vab.dot(_vbp);
  10583. var d4 = _vac.dot(_vbp);
  10584. if (d3 >= 0 && d4 <= d3) {
  10585. // vertex region of B; barycentric coords (0, 1, 0)
  10586. return target.copy(b);
  10587. }
  10588. var vc = d1 * d4 - d3 * d2;
  10589. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  10590. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  10591. return target.copy(a).addScaledVector(_vab, v);
  10592. }
  10593. _vcp.subVectors(p, c);
  10594. var d5 = _vab.dot(_vcp);
  10595. var d6 = _vac.dot(_vcp);
  10596. if (d6 >= 0 && d5 <= d6) {
  10597. // vertex region of C; barycentric coords (0, 0, 1)
  10598. return target.copy(c);
  10599. }
  10600. var vb = d5 * d2 - d1 * d6;
  10601. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  10602. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  10603. return target.copy(a).addScaledVector(_vac, w);
  10604. }
  10605. var va = d3 * d6 - d5 * d4;
  10606. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  10607. _vbc.subVectors(c, b);
  10608. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  10609. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  10610. } // face region
  10611. var denom = 1 / (va + vb + vc); // u = va * denom
  10612. v = vb * denom;
  10613. w = vc * denom;
  10614. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  10615. };
  10616. _proto.equals = function equals(triangle) {
  10617. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  10618. };
  10619. return Triangle;
  10620. }();
  10621. var _colorKeywords = {
  10622. 'aliceblue': 0xF0F8FF,
  10623. 'antiquewhite': 0xFAEBD7,
  10624. 'aqua': 0x00FFFF,
  10625. 'aquamarine': 0x7FFFD4,
  10626. 'azure': 0xF0FFFF,
  10627. 'beige': 0xF5F5DC,
  10628. 'bisque': 0xFFE4C4,
  10629. 'black': 0x000000,
  10630. 'blanchedalmond': 0xFFEBCD,
  10631. 'blue': 0x0000FF,
  10632. 'blueviolet': 0x8A2BE2,
  10633. 'brown': 0xA52A2A,
  10634. 'burlywood': 0xDEB887,
  10635. 'cadetblue': 0x5F9EA0,
  10636. 'chartreuse': 0x7FFF00,
  10637. 'chocolate': 0xD2691E,
  10638. 'coral': 0xFF7F50,
  10639. 'cornflowerblue': 0x6495ED,
  10640. 'cornsilk': 0xFFF8DC,
  10641. 'crimson': 0xDC143C,
  10642. 'cyan': 0x00FFFF,
  10643. 'darkblue': 0x00008B,
  10644. 'darkcyan': 0x008B8B,
  10645. 'darkgoldenrod': 0xB8860B,
  10646. 'darkgray': 0xA9A9A9,
  10647. 'darkgreen': 0x006400,
  10648. 'darkgrey': 0xA9A9A9,
  10649. 'darkkhaki': 0xBDB76B,
  10650. 'darkmagenta': 0x8B008B,
  10651. 'darkolivegreen': 0x556B2F,
  10652. 'darkorange': 0xFF8C00,
  10653. 'darkorchid': 0x9932CC,
  10654. 'darkred': 0x8B0000,
  10655. 'darksalmon': 0xE9967A,
  10656. 'darkseagreen': 0x8FBC8F,
  10657. 'darkslateblue': 0x483D8B,
  10658. 'darkslategray': 0x2F4F4F,
  10659. 'darkslategrey': 0x2F4F4F,
  10660. 'darkturquoise': 0x00CED1,
  10661. 'darkviolet': 0x9400D3,
  10662. 'deeppink': 0xFF1493,
  10663. 'deepskyblue': 0x00BFFF,
  10664. 'dimgray': 0x696969,
  10665. 'dimgrey': 0x696969,
  10666. 'dodgerblue': 0x1E90FF,
  10667. 'firebrick': 0xB22222,
  10668. 'floralwhite': 0xFFFAF0,
  10669. 'forestgreen': 0x228B22,
  10670. 'fuchsia': 0xFF00FF,
  10671. 'gainsboro': 0xDCDCDC,
  10672. 'ghostwhite': 0xF8F8FF,
  10673. 'gold': 0xFFD700,
  10674. 'goldenrod': 0xDAA520,
  10675. 'gray': 0x808080,
  10676. 'green': 0x008000,
  10677. 'greenyellow': 0xADFF2F,
  10678. 'grey': 0x808080,
  10679. 'honeydew': 0xF0FFF0,
  10680. 'hotpink': 0xFF69B4,
  10681. 'indianred': 0xCD5C5C,
  10682. 'indigo': 0x4B0082,
  10683. 'ivory': 0xFFFFF0,
  10684. 'khaki': 0xF0E68C,
  10685. 'lavender': 0xE6E6FA,
  10686. 'lavenderblush': 0xFFF0F5,
  10687. 'lawngreen': 0x7CFC00,
  10688. 'lemonchiffon': 0xFFFACD,
  10689. 'lightblue': 0xADD8E6,
  10690. 'lightcoral': 0xF08080,
  10691. 'lightcyan': 0xE0FFFF,
  10692. 'lightgoldenrodyellow': 0xFAFAD2,
  10693. 'lightgray': 0xD3D3D3,
  10694. 'lightgreen': 0x90EE90,
  10695. 'lightgrey': 0xD3D3D3,
  10696. 'lightpink': 0xFFB6C1,
  10697. 'lightsalmon': 0xFFA07A,
  10698. 'lightseagreen': 0x20B2AA,
  10699. 'lightskyblue': 0x87CEFA,
  10700. 'lightslategray': 0x778899,
  10701. 'lightslategrey': 0x778899,
  10702. 'lightsteelblue': 0xB0C4DE,
  10703. 'lightyellow': 0xFFFFE0,
  10704. 'lime': 0x00FF00,
  10705. 'limegreen': 0x32CD32,
  10706. 'linen': 0xFAF0E6,
  10707. 'magenta': 0xFF00FF,
  10708. 'maroon': 0x800000,
  10709. 'mediumaquamarine': 0x66CDAA,
  10710. 'mediumblue': 0x0000CD,
  10711. 'mediumorchid': 0xBA55D3,
  10712. 'mediumpurple': 0x9370DB,
  10713. 'mediumseagreen': 0x3CB371,
  10714. 'mediumslateblue': 0x7B68EE,
  10715. 'mediumspringgreen': 0x00FA9A,
  10716. 'mediumturquoise': 0x48D1CC,
  10717. 'mediumvioletred': 0xC71585,
  10718. 'midnightblue': 0x191970,
  10719. 'mintcream': 0xF5FFFA,
  10720. 'mistyrose': 0xFFE4E1,
  10721. 'moccasin': 0xFFE4B5,
  10722. 'navajowhite': 0xFFDEAD,
  10723. 'navy': 0x000080,
  10724. 'oldlace': 0xFDF5E6,
  10725. 'olive': 0x808000,
  10726. 'olivedrab': 0x6B8E23,
  10727. 'orange': 0xFFA500,
  10728. 'orangered': 0xFF4500,
  10729. 'orchid': 0xDA70D6,
  10730. 'palegoldenrod': 0xEEE8AA,
  10731. 'palegreen': 0x98FB98,
  10732. 'paleturquoise': 0xAFEEEE,
  10733. 'palevioletred': 0xDB7093,
  10734. 'papayawhip': 0xFFEFD5,
  10735. 'peachpuff': 0xFFDAB9,
  10736. 'peru': 0xCD853F,
  10737. 'pink': 0xFFC0CB,
  10738. 'plum': 0xDDA0DD,
  10739. 'powderblue': 0xB0E0E6,
  10740. 'purple': 0x800080,
  10741. 'rebeccapurple': 0x663399,
  10742. 'red': 0xFF0000,
  10743. 'rosybrown': 0xBC8F8F,
  10744. 'royalblue': 0x4169E1,
  10745. 'saddlebrown': 0x8B4513,
  10746. 'salmon': 0xFA8072,
  10747. 'sandybrown': 0xF4A460,
  10748. 'seagreen': 0x2E8B57,
  10749. 'seashell': 0xFFF5EE,
  10750. 'sienna': 0xA0522D,
  10751. 'silver': 0xC0C0C0,
  10752. 'skyblue': 0x87CEEB,
  10753. 'slateblue': 0x6A5ACD,
  10754. 'slategray': 0x708090,
  10755. 'slategrey': 0x708090,
  10756. 'snow': 0xFFFAFA,
  10757. 'springgreen': 0x00FF7F,
  10758. 'steelblue': 0x4682B4,
  10759. 'tan': 0xD2B48C,
  10760. 'teal': 0x008080,
  10761. 'thistle': 0xD8BFD8,
  10762. 'tomato': 0xFF6347,
  10763. 'turquoise': 0x40E0D0,
  10764. 'violet': 0xEE82EE,
  10765. 'wheat': 0xF5DEB3,
  10766. 'white': 0xFFFFFF,
  10767. 'whitesmoke': 0xF5F5F5,
  10768. 'yellow': 0xFFFF00,
  10769. 'yellowgreen': 0x9ACD32
  10770. };
  10771. var _hslA = {
  10772. h: 0,
  10773. s: 0,
  10774. l: 0
  10775. };
  10776. var _hslB = {
  10777. h: 0,
  10778. s: 0,
  10779. l: 0
  10780. };
  10781. function hue2rgb(p, q, t) {
  10782. if (t < 0) t += 1;
  10783. if (t > 1) t -= 1;
  10784. if (t < 1 / 6) return p + (q - p) * 6 * t;
  10785. if (t < 1 / 2) return q;
  10786. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  10787. return p;
  10788. }
  10789. function SRGBToLinear(c) {
  10790. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  10791. }
  10792. function LinearToSRGB(c) {
  10793. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  10794. }
  10795. var Color = /*#__PURE__*/function () {
  10796. function Color(r, g, b) {
  10797. Object.defineProperty(this, 'isColor', {
  10798. value: true
  10799. });
  10800. if (g === undefined && b === undefined) {
  10801. // r is THREE.Color, hex or string
  10802. return this.set(r);
  10803. }
  10804. return this.setRGB(r, g, b);
  10805. }
  10806. var _proto = Color.prototype;
  10807. _proto.set = function set(value) {
  10808. if (value && value.isColor) {
  10809. this.copy(value);
  10810. } else if (typeof value === 'number') {
  10811. this.setHex(value);
  10812. } else if (typeof value === 'string') {
  10813. this.setStyle(value);
  10814. }
  10815. return this;
  10816. };
  10817. _proto.setScalar = function setScalar(scalar) {
  10818. this.r = scalar;
  10819. this.g = scalar;
  10820. this.b = scalar;
  10821. return this;
  10822. };
  10823. _proto.setHex = function setHex(hex) {
  10824. hex = Math.floor(hex);
  10825. this.r = (hex >> 16 & 255) / 255;
  10826. this.g = (hex >> 8 & 255) / 255;
  10827. this.b = (hex & 255) / 255;
  10828. return this;
  10829. };
  10830. _proto.setRGB = function setRGB(r, g, b) {
  10831. this.r = r;
  10832. this.g = g;
  10833. this.b = b;
  10834. return this;
  10835. };
  10836. _proto.setHSL = function setHSL(h, s, l) {
  10837. // h,s,l ranges are in 0.0 - 1.0
  10838. h = MathUtils.euclideanModulo(h, 1);
  10839. s = MathUtils.clamp(s, 0, 1);
  10840. l = MathUtils.clamp(l, 0, 1);
  10841. if (s === 0) {
  10842. this.r = this.g = this.b = l;
  10843. } else {
  10844. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  10845. var q = 2 * l - p;
  10846. this.r = hue2rgb(q, p, h + 1 / 3);
  10847. this.g = hue2rgb(q, p, h);
  10848. this.b = hue2rgb(q, p, h - 1 / 3);
  10849. }
  10850. return this;
  10851. };
  10852. _proto.setStyle = function setStyle(style) {
  10853. function handleAlpha(string) {
  10854. if (string === undefined) return;
  10855. if (parseFloat(string) < 1) {
  10856. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  10857. }
  10858. }
  10859. var m;
  10860. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  10861. // rgb / hsl
  10862. var color;
  10863. var name = m[1];
  10864. var components = m[2];
  10865. switch (name) {
  10866. case 'rgb':
  10867. case 'rgba':
  10868. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  10869. // rgb(255,0,0) rgba(255,0,0,0.5)
  10870. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  10871. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  10872. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  10873. handleAlpha(color[5]);
  10874. return this;
  10875. }
  10876. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  10877. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10878. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  10879. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  10880. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  10881. handleAlpha(color[5]);
  10882. return this;
  10883. }
  10884. break;
  10885. case 'hsl':
  10886. case 'hsla':
  10887. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  10888. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10889. var h = parseFloat(color[1]) / 360;
  10890. var s = parseInt(color[2], 10) / 100;
  10891. var l = parseInt(color[3], 10) / 100;
  10892. handleAlpha(color[5]);
  10893. return this.setHSL(h, s, l);
  10894. }
  10895. break;
  10896. }
  10897. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  10898. // hex color
  10899. var hex = m[1];
  10900. var size = hex.length;
  10901. if (size === 3) {
  10902. // #ff0
  10903. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  10904. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  10905. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  10906. return this;
  10907. } else if (size === 6) {
  10908. // #ff0000
  10909. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  10910. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  10911. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  10912. return this;
  10913. }
  10914. }
  10915. if (style && style.length > 0) {
  10916. return this.setColorName(style);
  10917. }
  10918. return this;
  10919. };
  10920. _proto.setColorName = function setColorName(style) {
  10921. // color keywords
  10922. var hex = _colorKeywords[style];
  10923. if (hex !== undefined) {
  10924. // red
  10925. this.setHex(hex);
  10926. } else {
  10927. // unknown color
  10928. console.warn('THREE.Color: Unknown color ' + style);
  10929. }
  10930. return this;
  10931. };
  10932. _proto.clone = function clone() {
  10933. return new this.constructor(this.r, this.g, this.b);
  10934. };
  10935. _proto.copy = function copy(color) {
  10936. this.r = color.r;
  10937. this.g = color.g;
  10938. this.b = color.b;
  10939. return this;
  10940. };
  10941. _proto.copyGammaToLinear = function copyGammaToLinear(color, gammaFactor) {
  10942. if (gammaFactor === void 0) {
  10943. gammaFactor = 2.0;
  10944. }
  10945. this.r = Math.pow(color.r, gammaFactor);
  10946. this.g = Math.pow(color.g, gammaFactor);
  10947. this.b = Math.pow(color.b, gammaFactor);
  10948. return this;
  10949. };
  10950. _proto.copyLinearToGamma = function copyLinearToGamma(color, gammaFactor) {
  10951. if (gammaFactor === void 0) {
  10952. gammaFactor = 2.0;
  10953. }
  10954. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  10955. this.r = Math.pow(color.r, safeInverse);
  10956. this.g = Math.pow(color.g, safeInverse);
  10957. this.b = Math.pow(color.b, safeInverse);
  10958. return this;
  10959. };
  10960. _proto.convertGammaToLinear = function convertGammaToLinear(gammaFactor) {
  10961. this.copyGammaToLinear(this, gammaFactor);
  10962. return this;
  10963. };
  10964. _proto.convertLinearToGamma = function convertLinearToGamma(gammaFactor) {
  10965. this.copyLinearToGamma(this, gammaFactor);
  10966. return this;
  10967. };
  10968. _proto.copySRGBToLinear = function copySRGBToLinear(color) {
  10969. this.r = SRGBToLinear(color.r);
  10970. this.g = SRGBToLinear(color.g);
  10971. this.b = SRGBToLinear(color.b);
  10972. return this;
  10973. };
  10974. _proto.copyLinearToSRGB = function copyLinearToSRGB(color) {
  10975. this.r = LinearToSRGB(color.r);
  10976. this.g = LinearToSRGB(color.g);
  10977. this.b = LinearToSRGB(color.b);
  10978. return this;
  10979. };
  10980. _proto.convertSRGBToLinear = function convertSRGBToLinear() {
  10981. this.copySRGBToLinear(this);
  10982. return this;
  10983. };
  10984. _proto.convertLinearToSRGB = function convertLinearToSRGB() {
  10985. this.copyLinearToSRGB(this);
  10986. return this;
  10987. };
  10988. _proto.getHex = function getHex() {
  10989. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  10990. };
  10991. _proto.getHexString = function getHexString() {
  10992. return ('000000' + this.getHex().toString(16)).slice(-6);
  10993. };
  10994. _proto.getHSL = function getHSL(target) {
  10995. // h,s,l ranges are in 0.0 - 1.0
  10996. if (target === undefined) {
  10997. console.warn('THREE.Color: .getHSL() target is now required');
  10998. target = {
  10999. h: 0,
  11000. s: 0,
  11001. l: 0
  11002. };
  11003. }
  11004. var r = this.r,
  11005. g = this.g,
  11006. b = this.b;
  11007. var max = Math.max(r, g, b);
  11008. var min = Math.min(r, g, b);
  11009. var hue, saturation;
  11010. var lightness = (min + max) / 2.0;
  11011. if (min === max) {
  11012. hue = 0;
  11013. saturation = 0;
  11014. } else {
  11015. var delta = max - min;
  11016. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  11017. switch (max) {
  11018. case r:
  11019. hue = (g - b) / delta + (g < b ? 6 : 0);
  11020. break;
  11021. case g:
  11022. hue = (b - r) / delta + 2;
  11023. break;
  11024. case b:
  11025. hue = (r - g) / delta + 4;
  11026. break;
  11027. }
  11028. hue /= 6;
  11029. }
  11030. target.h = hue;
  11031. target.s = saturation;
  11032. target.l = lightness;
  11033. return target;
  11034. };
  11035. _proto.getStyle = function getStyle() {
  11036. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  11037. };
  11038. _proto.offsetHSL = function offsetHSL(h, s, l) {
  11039. this.getHSL(_hslA);
  11040. _hslA.h += h;
  11041. _hslA.s += s;
  11042. _hslA.l += l;
  11043. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  11044. return this;
  11045. };
  11046. _proto.add = function add(color) {
  11047. this.r += color.r;
  11048. this.g += color.g;
  11049. this.b += color.b;
  11050. return this;
  11051. };
  11052. _proto.addColors = function addColors(color1, color2) {
  11053. this.r = color1.r + color2.r;
  11054. this.g = color1.g + color2.g;
  11055. this.b = color1.b + color2.b;
  11056. return this;
  11057. };
  11058. _proto.addScalar = function addScalar(s) {
  11059. this.r += s;
  11060. this.g += s;
  11061. this.b += s;
  11062. return this;
  11063. };
  11064. _proto.sub = function sub(color) {
  11065. this.r = Math.max(0, this.r - color.r);
  11066. this.g = Math.max(0, this.g - color.g);
  11067. this.b = Math.max(0, this.b - color.b);
  11068. return this;
  11069. };
  11070. _proto.multiply = function multiply(color) {
  11071. this.r *= color.r;
  11072. this.g *= color.g;
  11073. this.b *= color.b;
  11074. return this;
  11075. };
  11076. _proto.multiplyScalar = function multiplyScalar(s) {
  11077. this.r *= s;
  11078. this.g *= s;
  11079. this.b *= s;
  11080. return this;
  11081. };
  11082. _proto.lerp = function lerp(color, alpha) {
  11083. this.r += (color.r - this.r) * alpha;
  11084. this.g += (color.g - this.g) * alpha;
  11085. this.b += (color.b - this.b) * alpha;
  11086. return this;
  11087. };
  11088. _proto.lerpHSL = function lerpHSL(color, alpha) {
  11089. this.getHSL(_hslA);
  11090. color.getHSL(_hslB);
  11091. var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  11092. var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  11093. var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  11094. this.setHSL(h, s, l);
  11095. return this;
  11096. };
  11097. _proto.equals = function equals(c) {
  11098. return c.r === this.r && c.g === this.g && c.b === this.b;
  11099. };
  11100. _proto.fromArray = function fromArray(array, offset) {
  11101. if (offset === void 0) {
  11102. offset = 0;
  11103. }
  11104. this.r = array[offset];
  11105. this.g = array[offset + 1];
  11106. this.b = array[offset + 2];
  11107. return this;
  11108. };
  11109. _proto.toArray = function toArray(array, offset) {
  11110. if (array === void 0) {
  11111. array = [];
  11112. }
  11113. if (offset === void 0) {
  11114. offset = 0;
  11115. }
  11116. array[offset] = this.r;
  11117. array[offset + 1] = this.g;
  11118. array[offset + 2] = this.b;
  11119. return array;
  11120. };
  11121. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
  11122. this.r = attribute.getX(index);
  11123. this.g = attribute.getY(index);
  11124. this.b = attribute.getZ(index);
  11125. if (attribute.normalized === true) {
  11126. // assuming Uint8Array
  11127. this.r /= 255;
  11128. this.g /= 255;
  11129. this.b /= 255;
  11130. }
  11131. return this;
  11132. };
  11133. _proto.toJSON = function toJSON() {
  11134. return this.getHex();
  11135. };
  11136. return Color;
  11137. }();
  11138. Color.NAMES = _colorKeywords;
  11139. Color.prototype.r = 1;
  11140. Color.prototype.g = 1;
  11141. Color.prototype.b = 1;
  11142. var Face3 = /*#__PURE__*/function () {
  11143. function Face3(a, b, c, normal, color, materialIndex) {
  11144. if (materialIndex === void 0) {
  11145. materialIndex = 0;
  11146. }
  11147. this.a = a;
  11148. this.b = b;
  11149. this.c = c;
  11150. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  11151. this.vertexNormals = Array.isArray(normal) ? normal : [];
  11152. this.color = color && color.isColor ? color : new Color();
  11153. this.vertexColors = Array.isArray(color) ? color : [];
  11154. this.materialIndex = materialIndex;
  11155. }
  11156. var _proto = Face3.prototype;
  11157. _proto.clone = function clone() {
  11158. return new this.constructor().copy(this);
  11159. };
  11160. _proto.copy = function copy(source) {
  11161. this.a = source.a;
  11162. this.b = source.b;
  11163. this.c = source.c;
  11164. this.normal.copy(source.normal);
  11165. this.color.copy(source.color);
  11166. this.materialIndex = source.materialIndex;
  11167. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  11168. this.vertexNormals[i] = source.vertexNormals[i].clone();
  11169. }
  11170. for (var _i = 0, _il = source.vertexColors.length; _i < _il; _i++) {
  11171. this.vertexColors[_i] = source.vertexColors[_i].clone();
  11172. }
  11173. return this;
  11174. };
  11175. return Face3;
  11176. }();
  11177. var materialId = 0;
  11178. function Material() {
  11179. Object.defineProperty(this, 'id', {
  11180. value: materialId++
  11181. });
  11182. this.uuid = MathUtils.generateUUID();
  11183. this.name = '';
  11184. this.type = 'Material';
  11185. this.fog = true;
  11186. this.blending = NormalBlending;
  11187. this.side = FrontSide;
  11188. this.flatShading = false;
  11189. this.vertexColors = false;
  11190. this.opacity = 1;
  11191. this.transparent = false;
  11192. this.blendSrc = SrcAlphaFactor;
  11193. this.blendDst = OneMinusSrcAlphaFactor;
  11194. this.blendEquation = AddEquation;
  11195. this.blendSrcAlpha = null;
  11196. this.blendDstAlpha = null;
  11197. this.blendEquationAlpha = null;
  11198. this.depthFunc = LessEqualDepth;
  11199. this.depthTest = true;
  11200. this.depthWrite = true;
  11201. this.stencilWriteMask = 0xff;
  11202. this.stencilFunc = AlwaysStencilFunc;
  11203. this.stencilRef = 0;
  11204. this.stencilFuncMask = 0xff;
  11205. this.stencilFail = KeepStencilOp;
  11206. this.stencilZFail = KeepStencilOp;
  11207. this.stencilZPass = KeepStencilOp;
  11208. this.stencilWrite = false;
  11209. this.clippingPlanes = null;
  11210. this.clipIntersection = false;
  11211. this.clipShadows = false;
  11212. this.shadowSide = null;
  11213. this.colorWrite = true;
  11214. this.precision = null; // override the renderer's default precision for this material
  11215. this.polygonOffset = false;
  11216. this.polygonOffsetFactor = 0;
  11217. this.polygonOffsetUnits = 0;
  11218. this.dithering = false;
  11219. this.alphaTest = 0;
  11220. this.premultipliedAlpha = false;
  11221. this.visible = true;
  11222. this.toneMapped = true;
  11223. this.userData = {};
  11224. this.version = 0;
  11225. }
  11226. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  11227. constructor: Material,
  11228. isMaterial: true,
  11229. onBeforeCompile: function onBeforeCompile()
  11230. /* shaderobject, renderer */
  11231. {},
  11232. customProgramCacheKey: function customProgramCacheKey() {
  11233. return this.onBeforeCompile.toString();
  11234. },
  11235. setValues: function setValues(values) {
  11236. if (values === undefined) return;
  11237. for (var key in values) {
  11238. var newValue = values[key];
  11239. if (newValue === undefined) {
  11240. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  11241. continue;
  11242. } // for backward compatability if shading is set in the constructor
  11243. if (key === 'shading') {
  11244. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  11245. this.flatShading = newValue === FlatShading ? true : false;
  11246. continue;
  11247. }
  11248. var currentValue = this[key];
  11249. if (currentValue === undefined) {
  11250. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  11251. continue;
  11252. }
  11253. if (currentValue && currentValue.isColor) {
  11254. currentValue.set(newValue);
  11255. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  11256. currentValue.copy(newValue);
  11257. } else {
  11258. this[key] = newValue;
  11259. }
  11260. }
  11261. },
  11262. toJSON: function toJSON(meta) {
  11263. var isRoot = meta === undefined || typeof meta === 'string';
  11264. if (isRoot) {
  11265. meta = {
  11266. textures: {},
  11267. images: {}
  11268. };
  11269. }
  11270. var data = {
  11271. metadata: {
  11272. version: 4.5,
  11273. type: 'Material',
  11274. generator: 'Material.toJSON'
  11275. }
  11276. }; // standard Material serialization
  11277. data.uuid = this.uuid;
  11278. data.type = this.type;
  11279. if (this.name !== '') data.name = this.name;
  11280. if (this.color && this.color.isColor) data.color = this.color.getHex();
  11281. if (this.roughness !== undefined) data.roughness = this.roughness;
  11282. if (this.metalness !== undefined) data.metalness = this.metalness;
  11283. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  11284. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  11285. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  11286. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  11287. if (this.shininess !== undefined) data.shininess = this.shininess;
  11288. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  11289. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  11290. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  11291. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  11292. }
  11293. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  11294. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  11295. }
  11296. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  11297. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  11298. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  11299. }
  11300. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  11301. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  11302. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  11303. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  11304. if (this.aoMap && this.aoMap.isTexture) {
  11305. data.aoMap = this.aoMap.toJSON(meta).uuid;
  11306. data.aoMapIntensity = this.aoMapIntensity;
  11307. }
  11308. if (this.bumpMap && this.bumpMap.isTexture) {
  11309. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  11310. data.bumpScale = this.bumpScale;
  11311. }
  11312. if (this.normalMap && this.normalMap.isTexture) {
  11313. data.normalMap = this.normalMap.toJSON(meta).uuid;
  11314. data.normalMapType = this.normalMapType;
  11315. data.normalScale = this.normalScale.toArray();
  11316. }
  11317. if (this.displacementMap && this.displacementMap.isTexture) {
  11318. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  11319. data.displacementScale = this.displacementScale;
  11320. data.displacementBias = this.displacementBias;
  11321. }
  11322. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  11323. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  11324. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  11325. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  11326. if (this.envMap && this.envMap.isTexture) {
  11327. data.envMap = this.envMap.toJSON(meta).uuid;
  11328. data.reflectivity = this.reflectivity; // Scale behind envMap
  11329. data.refractionRatio = this.refractionRatio;
  11330. if (this.combine !== undefined) data.combine = this.combine;
  11331. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  11332. }
  11333. if (this.gradientMap && this.gradientMap.isTexture) {
  11334. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  11335. }
  11336. if (this.size !== undefined) data.size = this.size;
  11337. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  11338. if (this.blending !== NormalBlending) data.blending = this.blending;
  11339. if (this.flatShading === true) data.flatShading = this.flatShading;
  11340. if (this.side !== FrontSide) data.side = this.side;
  11341. if (this.vertexColors) data.vertexColors = true;
  11342. if (this.opacity < 1) data.opacity = this.opacity;
  11343. if (this.transparent === true) data.transparent = this.transparent;
  11344. data.depthFunc = this.depthFunc;
  11345. data.depthTest = this.depthTest;
  11346. data.depthWrite = this.depthWrite;
  11347. data.stencilWrite = this.stencilWrite;
  11348. data.stencilWriteMask = this.stencilWriteMask;
  11349. data.stencilFunc = this.stencilFunc;
  11350. data.stencilRef = this.stencilRef;
  11351. data.stencilFuncMask = this.stencilFuncMask;
  11352. data.stencilFail = this.stencilFail;
  11353. data.stencilZFail = this.stencilZFail;
  11354. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  11355. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  11356. if (this.polygonOffset === true) data.polygonOffset = true;
  11357. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  11358. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  11359. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  11360. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  11361. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  11362. if (this.scale !== undefined) data.scale = this.scale;
  11363. if (this.dithering === true) data.dithering = true;
  11364. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  11365. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  11366. if (this.wireframe === true) data.wireframe = this.wireframe;
  11367. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  11368. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  11369. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  11370. if (this.morphTargets === true) data.morphTargets = true;
  11371. if (this.morphNormals === true) data.morphNormals = true;
  11372. if (this.skinning === true) data.skinning = true;
  11373. if (this.visible === false) data.visible = false;
  11374. if (this.toneMapped === false) data.toneMapped = false;
  11375. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  11376. function extractFromCache(cache) {
  11377. var values = [];
  11378. for (var key in cache) {
  11379. var _data = cache[key];
  11380. delete _data.metadata;
  11381. values.push(_data);
  11382. }
  11383. return values;
  11384. }
  11385. if (isRoot) {
  11386. var textures = extractFromCache(meta.textures);
  11387. var images = extractFromCache(meta.images);
  11388. if (textures.length > 0) data.textures = textures;
  11389. if (images.length > 0) data.images = images;
  11390. }
  11391. return data;
  11392. },
  11393. clone: function clone() {
  11394. return new this.constructor().copy(this);
  11395. },
  11396. copy: function copy(source) {
  11397. this.name = source.name;
  11398. this.fog = source.fog;
  11399. this.blending = source.blending;
  11400. this.side = source.side;
  11401. this.flatShading = source.flatShading;
  11402. this.vertexColors = source.vertexColors;
  11403. this.opacity = source.opacity;
  11404. this.transparent = source.transparent;
  11405. this.blendSrc = source.blendSrc;
  11406. this.blendDst = source.blendDst;
  11407. this.blendEquation = source.blendEquation;
  11408. this.blendSrcAlpha = source.blendSrcAlpha;
  11409. this.blendDstAlpha = source.blendDstAlpha;
  11410. this.blendEquationAlpha = source.blendEquationAlpha;
  11411. this.depthFunc = source.depthFunc;
  11412. this.depthTest = source.depthTest;
  11413. this.depthWrite = source.depthWrite;
  11414. this.stencilWriteMask = source.stencilWriteMask;
  11415. this.stencilFunc = source.stencilFunc;
  11416. this.stencilRef = source.stencilRef;
  11417. this.stencilFuncMask = source.stencilFuncMask;
  11418. this.stencilFail = source.stencilFail;
  11419. this.stencilZFail = source.stencilZFail;
  11420. this.stencilZPass = source.stencilZPass;
  11421. this.stencilWrite = source.stencilWrite;
  11422. var srcPlanes = source.clippingPlanes;
  11423. var dstPlanes = null;
  11424. if (srcPlanes !== null) {
  11425. var n = srcPlanes.length;
  11426. dstPlanes = new Array(n);
  11427. for (var i = 0; i !== n; ++i) {
  11428. dstPlanes[i] = srcPlanes[i].clone();
  11429. }
  11430. }
  11431. this.clippingPlanes = dstPlanes;
  11432. this.clipIntersection = source.clipIntersection;
  11433. this.clipShadows = source.clipShadows;
  11434. this.shadowSide = source.shadowSide;
  11435. this.colorWrite = source.colorWrite;
  11436. this.precision = source.precision;
  11437. this.polygonOffset = source.polygonOffset;
  11438. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11439. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11440. this.dithering = source.dithering;
  11441. this.alphaTest = source.alphaTest;
  11442. this.premultipliedAlpha = source.premultipliedAlpha;
  11443. this.visible = source.visible;
  11444. this.toneMapped = source.toneMapped;
  11445. this.userData = JSON.parse(JSON.stringify(source.userData));
  11446. return this;
  11447. },
  11448. dispose: function dispose() {
  11449. this.dispatchEvent({
  11450. type: 'dispose'
  11451. });
  11452. }
  11453. });
  11454. Object.defineProperty(Material.prototype, 'needsUpdate', {
  11455. set: function set(value) {
  11456. if (value === true) this.version++;
  11457. }
  11458. });
  11459. /**
  11460. * parameters = {
  11461. * color: <hex>,
  11462. * opacity: <float>,
  11463. * map: new THREE.Texture( <Image> ),
  11464. *
  11465. * lightMap: new THREE.Texture( <Image> ),
  11466. * lightMapIntensity: <float>
  11467. *
  11468. * aoMap: new THREE.Texture( <Image> ),
  11469. * aoMapIntensity: <float>
  11470. *
  11471. * specularMap: new THREE.Texture( <Image> ),
  11472. *
  11473. * alphaMap: new THREE.Texture( <Image> ),
  11474. *
  11475. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  11476. * combine: THREE.Multiply,
  11477. * reflectivity: <float>,
  11478. * refractionRatio: <float>,
  11479. *
  11480. * depthTest: <bool>,
  11481. * depthWrite: <bool>,
  11482. *
  11483. * wireframe: <boolean>,
  11484. * wireframeLinewidth: <float>,
  11485. *
  11486. * skinning: <bool>,
  11487. * morphTargets: <bool>
  11488. * }
  11489. */
  11490. function MeshBasicMaterial(parameters) {
  11491. Material.call(this);
  11492. this.type = 'MeshBasicMaterial';
  11493. this.color = new Color(0xffffff); // emissive
  11494. this.map = null;
  11495. this.lightMap = null;
  11496. this.lightMapIntensity = 1.0;
  11497. this.aoMap = null;
  11498. this.aoMapIntensity = 1.0;
  11499. this.specularMap = null;
  11500. this.alphaMap = null;
  11501. this.envMap = null;
  11502. this.combine = MultiplyOperation;
  11503. this.reflectivity = 1;
  11504. this.refractionRatio = 0.98;
  11505. this.wireframe = false;
  11506. this.wireframeLinewidth = 1;
  11507. this.wireframeLinecap = 'round';
  11508. this.wireframeLinejoin = 'round';
  11509. this.skinning = false;
  11510. this.morphTargets = false;
  11511. this.setValues(parameters);
  11512. }
  11513. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  11514. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11515. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11516. MeshBasicMaterial.prototype.copy = function (source) {
  11517. Material.prototype.copy.call(this, source);
  11518. this.color.copy(source.color);
  11519. this.map = source.map;
  11520. this.lightMap = source.lightMap;
  11521. this.lightMapIntensity = source.lightMapIntensity;
  11522. this.aoMap = source.aoMap;
  11523. this.aoMapIntensity = source.aoMapIntensity;
  11524. this.specularMap = source.specularMap;
  11525. this.alphaMap = source.alphaMap;
  11526. this.envMap = source.envMap;
  11527. this.combine = source.combine;
  11528. this.reflectivity = source.reflectivity;
  11529. this.refractionRatio = source.refractionRatio;
  11530. this.wireframe = source.wireframe;
  11531. this.wireframeLinewidth = source.wireframeLinewidth;
  11532. this.wireframeLinecap = source.wireframeLinecap;
  11533. this.wireframeLinejoin = source.wireframeLinejoin;
  11534. this.skinning = source.skinning;
  11535. this.morphTargets = source.morphTargets;
  11536. return this;
  11537. };
  11538. var _vector$3 = new Vector3();
  11539. var _vector2$1 = new Vector2();
  11540. function BufferAttribute(array, itemSize, normalized) {
  11541. if (Array.isArray(array)) {
  11542. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  11543. }
  11544. this.name = '';
  11545. this.array = array;
  11546. this.itemSize = itemSize;
  11547. this.count = array !== undefined ? array.length / itemSize : 0;
  11548. this.normalized = normalized === true;
  11549. this.usage = StaticDrawUsage;
  11550. this.updateRange = {
  11551. offset: 0,
  11552. count: -1
  11553. };
  11554. this.version = 0;
  11555. }
  11556. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  11557. set: function set(value) {
  11558. if (value === true) this.version++;
  11559. }
  11560. });
  11561. Object.assign(BufferAttribute.prototype, {
  11562. isBufferAttribute: true,
  11563. onUploadCallback: function onUploadCallback() {},
  11564. setUsage: function setUsage(value) {
  11565. this.usage = value;
  11566. return this;
  11567. },
  11568. copy: function copy(source) {
  11569. this.name = source.name;
  11570. this.array = new source.array.constructor(source.array);
  11571. this.itemSize = source.itemSize;
  11572. this.count = source.count;
  11573. this.normalized = source.normalized;
  11574. this.usage = source.usage;
  11575. return this;
  11576. },
  11577. copyAt: function copyAt(index1, attribute, index2) {
  11578. index1 *= this.itemSize;
  11579. index2 *= attribute.itemSize;
  11580. for (var i = 0, l = this.itemSize; i < l; i++) {
  11581. this.array[index1 + i] = attribute.array[index2 + i];
  11582. }
  11583. return this;
  11584. },
  11585. copyArray: function copyArray(array) {
  11586. this.array.set(array);
  11587. return this;
  11588. },
  11589. copyColorsArray: function copyColorsArray(colors) {
  11590. var array = this.array;
  11591. var offset = 0;
  11592. for (var i = 0, l = colors.length; i < l; i++) {
  11593. var color = colors[i];
  11594. if (color === undefined) {
  11595. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  11596. color = new Color();
  11597. }
  11598. array[offset++] = color.r;
  11599. array[offset++] = color.g;
  11600. array[offset++] = color.b;
  11601. }
  11602. return this;
  11603. },
  11604. copyVector2sArray: function copyVector2sArray(vectors) {
  11605. var array = this.array;
  11606. var offset = 0;
  11607. for (var i = 0, l = vectors.length; i < l; i++) {
  11608. var vector = vectors[i];
  11609. if (vector === undefined) {
  11610. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  11611. vector = new Vector2();
  11612. }
  11613. array[offset++] = vector.x;
  11614. array[offset++] = vector.y;
  11615. }
  11616. return this;
  11617. },
  11618. copyVector3sArray: function copyVector3sArray(vectors) {
  11619. var array = this.array;
  11620. var offset = 0;
  11621. for (var i = 0, l = vectors.length; i < l; i++) {
  11622. var vector = vectors[i];
  11623. if (vector === undefined) {
  11624. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  11625. vector = new Vector3();
  11626. }
  11627. array[offset++] = vector.x;
  11628. array[offset++] = vector.y;
  11629. array[offset++] = vector.z;
  11630. }
  11631. return this;
  11632. },
  11633. copyVector4sArray: function copyVector4sArray(vectors) {
  11634. var array = this.array;
  11635. var offset = 0;
  11636. for (var i = 0, l = vectors.length; i < l; i++) {
  11637. var vector = vectors[i];
  11638. if (vector === undefined) {
  11639. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  11640. vector = new Vector4();
  11641. }
  11642. array[offset++] = vector.x;
  11643. array[offset++] = vector.y;
  11644. array[offset++] = vector.z;
  11645. array[offset++] = vector.w;
  11646. }
  11647. return this;
  11648. },
  11649. applyMatrix3: function applyMatrix3(m) {
  11650. if (this.itemSize === 2) {
  11651. for (var i = 0, l = this.count; i < l; i++) {
  11652. _vector2$1.fromBufferAttribute(this, i);
  11653. _vector2$1.applyMatrix3(m);
  11654. this.setXY(i, _vector2$1.x, _vector2$1.y);
  11655. }
  11656. } else if (this.itemSize === 3) {
  11657. for (var _i = 0, _l = this.count; _i < _l; _i++) {
  11658. _vector$3.fromBufferAttribute(this, _i);
  11659. _vector$3.applyMatrix3(m);
  11660. this.setXYZ(_i, _vector$3.x, _vector$3.y, _vector$3.z);
  11661. }
  11662. }
  11663. return this;
  11664. },
  11665. applyMatrix4: function applyMatrix4(m) {
  11666. for (var i = 0, l = this.count; i < l; i++) {
  11667. _vector$3.x = this.getX(i);
  11668. _vector$3.y = this.getY(i);
  11669. _vector$3.z = this.getZ(i);
  11670. _vector$3.applyMatrix4(m);
  11671. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  11672. }
  11673. return this;
  11674. },
  11675. applyNormalMatrix: function applyNormalMatrix(m) {
  11676. for (var i = 0, l = this.count; i < l; i++) {
  11677. _vector$3.x = this.getX(i);
  11678. _vector$3.y = this.getY(i);
  11679. _vector$3.z = this.getZ(i);
  11680. _vector$3.applyNormalMatrix(m);
  11681. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  11682. }
  11683. return this;
  11684. },
  11685. transformDirection: function transformDirection(m) {
  11686. for (var i = 0, l = this.count; i < l; i++) {
  11687. _vector$3.x = this.getX(i);
  11688. _vector$3.y = this.getY(i);
  11689. _vector$3.z = this.getZ(i);
  11690. _vector$3.transformDirection(m);
  11691. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  11692. }
  11693. return this;
  11694. },
  11695. set: function set(value, offset) {
  11696. if (offset === void 0) {
  11697. offset = 0;
  11698. }
  11699. this.array.set(value, offset);
  11700. return this;
  11701. },
  11702. getX: function getX(index) {
  11703. return this.array[index * this.itemSize];
  11704. },
  11705. setX: function setX(index, x) {
  11706. this.array[index * this.itemSize] = x;
  11707. return this;
  11708. },
  11709. getY: function getY(index) {
  11710. return this.array[index * this.itemSize + 1];
  11711. },
  11712. setY: function setY(index, y) {
  11713. this.array[index * this.itemSize + 1] = y;
  11714. return this;
  11715. },
  11716. getZ: function getZ(index) {
  11717. return this.array[index * this.itemSize + 2];
  11718. },
  11719. setZ: function setZ(index, z) {
  11720. this.array[index * this.itemSize + 2] = z;
  11721. return this;
  11722. },
  11723. getW: function getW(index) {
  11724. return this.array[index * this.itemSize + 3];
  11725. },
  11726. setW: function setW(index, w) {
  11727. this.array[index * this.itemSize + 3] = w;
  11728. return this;
  11729. },
  11730. setXY: function setXY(index, x, y) {
  11731. index *= this.itemSize;
  11732. this.array[index + 0] = x;
  11733. this.array[index + 1] = y;
  11734. return this;
  11735. },
  11736. setXYZ: function setXYZ(index, x, y, z) {
  11737. index *= this.itemSize;
  11738. this.array[index + 0] = x;
  11739. this.array[index + 1] = y;
  11740. this.array[index + 2] = z;
  11741. return this;
  11742. },
  11743. setXYZW: function setXYZW(index, x, y, z, w) {
  11744. index *= this.itemSize;
  11745. this.array[index + 0] = x;
  11746. this.array[index + 1] = y;
  11747. this.array[index + 2] = z;
  11748. this.array[index + 3] = w;
  11749. return this;
  11750. },
  11751. onUpload: function onUpload(callback) {
  11752. this.onUploadCallback = callback;
  11753. return this;
  11754. },
  11755. clone: function clone() {
  11756. return new this.constructor(this.array, this.itemSize).copy(this);
  11757. },
  11758. toJSON: function toJSON() {
  11759. return {
  11760. itemSize: this.itemSize,
  11761. type: this.array.constructor.name,
  11762. array: Array.prototype.slice.call(this.array),
  11763. normalized: this.normalized
  11764. };
  11765. }
  11766. }); //
  11767. function Int8BufferAttribute(array, itemSize, normalized) {
  11768. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  11769. }
  11770. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11771. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11772. function Uint8BufferAttribute(array, itemSize, normalized) {
  11773. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  11774. }
  11775. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11776. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11777. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  11778. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  11779. }
  11780. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11781. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11782. function Int16BufferAttribute(array, itemSize, normalized) {
  11783. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  11784. }
  11785. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11786. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11787. function Uint16BufferAttribute(array, itemSize, normalized) {
  11788. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  11789. }
  11790. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11791. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11792. function Int32BufferAttribute(array, itemSize, normalized) {
  11793. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  11794. }
  11795. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11796. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11797. function Uint32BufferAttribute(array, itemSize, normalized) {
  11798. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  11799. }
  11800. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11801. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11802. function Float16BufferAttribute(array, itemSize, normalized) {
  11803. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  11804. }
  11805. Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11806. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  11807. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  11808. function Float32BufferAttribute(array, itemSize, normalized) {
  11809. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  11810. }
  11811. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11812. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11813. function Float64BufferAttribute(array, itemSize, normalized) {
  11814. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  11815. }
  11816. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  11817. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; //
  11818. var DirectGeometry = /*#__PURE__*/function () {
  11819. function DirectGeometry() {
  11820. this.vertices = [];
  11821. this.normals = [];
  11822. this.colors = [];
  11823. this.uvs = [];
  11824. this.uvs2 = [];
  11825. this.groups = [];
  11826. this.morphTargets = {};
  11827. this.skinWeights = [];
  11828. this.skinIndices = []; // this.lineDistances = [];
  11829. this.boundingBox = null;
  11830. this.boundingSphere = null; // update flags
  11831. this.verticesNeedUpdate = false;
  11832. this.normalsNeedUpdate = false;
  11833. this.colorsNeedUpdate = false;
  11834. this.uvsNeedUpdate = false;
  11835. this.groupsNeedUpdate = false;
  11836. }
  11837. var _proto = DirectGeometry.prototype;
  11838. _proto.computeGroups = function computeGroups(geometry) {
  11839. var groups = [];
  11840. var group, i;
  11841. var materialIndex = undefined;
  11842. var faces = geometry.faces;
  11843. for (i = 0; i < faces.length; i++) {
  11844. var face = faces[i]; // materials
  11845. if (face.materialIndex !== materialIndex) {
  11846. materialIndex = face.materialIndex;
  11847. if (group !== undefined) {
  11848. group.count = i * 3 - group.start;
  11849. groups.push(group);
  11850. }
  11851. group = {
  11852. start: i * 3,
  11853. materialIndex: materialIndex
  11854. };
  11855. }
  11856. }
  11857. if (group !== undefined) {
  11858. group.count = i * 3 - group.start;
  11859. groups.push(group);
  11860. }
  11861. this.groups = groups;
  11862. };
  11863. _proto.fromGeometry = function fromGeometry(geometry) {
  11864. var faces = geometry.faces;
  11865. var vertices = geometry.vertices;
  11866. var faceVertexUvs = geometry.faceVertexUvs;
  11867. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  11868. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  11869. var morphTargets = geometry.morphTargets;
  11870. var morphTargetsLength = morphTargets.length;
  11871. var morphTargetsPosition;
  11872. if (morphTargetsLength > 0) {
  11873. morphTargetsPosition = [];
  11874. for (var i = 0; i < morphTargetsLength; i++) {
  11875. morphTargetsPosition[i] = {
  11876. name: morphTargets[i].name,
  11877. data: []
  11878. };
  11879. }
  11880. this.morphTargets.position = morphTargetsPosition;
  11881. }
  11882. var morphNormals = geometry.morphNormals;
  11883. var morphNormalsLength = morphNormals.length;
  11884. var morphTargetsNormal;
  11885. if (morphNormalsLength > 0) {
  11886. morphTargetsNormal = [];
  11887. for (var _i = 0; _i < morphNormalsLength; _i++) {
  11888. morphTargetsNormal[_i] = {
  11889. name: morphNormals[_i].name,
  11890. data: []
  11891. };
  11892. }
  11893. this.morphTargets.normal = morphTargetsNormal;
  11894. } // skins
  11895. var skinIndices = geometry.skinIndices;
  11896. var skinWeights = geometry.skinWeights;
  11897. var hasSkinIndices = skinIndices.length === vertices.length;
  11898. var hasSkinWeights = skinWeights.length === vertices.length; //
  11899. if (vertices.length > 0 && faces.length === 0) {
  11900. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  11901. }
  11902. for (var _i2 = 0; _i2 < faces.length; _i2++) {
  11903. var face = faces[_i2];
  11904. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  11905. var vertexNormals = face.vertexNormals;
  11906. if (vertexNormals.length === 3) {
  11907. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  11908. } else {
  11909. var normal = face.normal;
  11910. this.normals.push(normal, normal, normal);
  11911. }
  11912. var vertexColors = face.vertexColors;
  11913. if (vertexColors.length === 3) {
  11914. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  11915. } else {
  11916. var color = face.color;
  11917. this.colors.push(color, color, color);
  11918. }
  11919. if (hasFaceVertexUv === true) {
  11920. var vertexUvs = faceVertexUvs[0][_i2];
  11921. if (vertexUvs !== undefined) {
  11922. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  11923. } else {
  11924. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', _i2);
  11925. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  11926. }
  11927. }
  11928. if (hasFaceVertexUv2 === true) {
  11929. var _vertexUvs = faceVertexUvs[1][_i2];
  11930. if (_vertexUvs !== undefined) {
  11931. this.uvs2.push(_vertexUvs[0], _vertexUvs[1], _vertexUvs[2]);
  11932. } else {
  11933. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', _i2);
  11934. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  11935. }
  11936. } // morphs
  11937. for (var j = 0; j < morphTargetsLength; j++) {
  11938. var morphTarget = morphTargets[j].vertices;
  11939. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  11940. }
  11941. for (var _j = 0; _j < morphNormalsLength; _j++) {
  11942. var morphNormal = morphNormals[_j].vertexNormals[_i2];
  11943. morphTargetsNormal[_j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  11944. } // skins
  11945. if (hasSkinIndices) {
  11946. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  11947. }
  11948. if (hasSkinWeights) {
  11949. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  11950. }
  11951. }
  11952. this.computeGroups(geometry);
  11953. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11954. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11955. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11956. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11957. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11958. if (geometry.boundingSphere !== null) {
  11959. this.boundingSphere = geometry.boundingSphere.clone();
  11960. }
  11961. if (geometry.boundingBox !== null) {
  11962. this.boundingBox = geometry.boundingBox.clone();
  11963. }
  11964. return this;
  11965. };
  11966. return DirectGeometry;
  11967. }();
  11968. function arrayMax(array) {
  11969. if (array.length === 0) return -Infinity;
  11970. var max = array[0];
  11971. for (var i = 1, l = array.length; i < l; ++i) {
  11972. if (array[i] > max) max = array[i];
  11973. }
  11974. return max;
  11975. }
  11976. var TYPED_ARRAYS = {
  11977. Int8Array: Int8Array,
  11978. Uint8Array: Uint8Array,
  11979. // Workaround for IE11 pre KB2929437. See #11440
  11980. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  11981. Int16Array: Int16Array,
  11982. Uint16Array: Uint16Array,
  11983. Int32Array: Int32Array,
  11984. Uint32Array: Uint32Array,
  11985. Float32Array: Float32Array,
  11986. Float64Array: Float64Array
  11987. };
  11988. function getTypedArray(type, buffer) {
  11989. return new TYPED_ARRAYS[type](buffer);
  11990. }
  11991. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11992. var _m1$2 = new Matrix4();
  11993. var _obj = new Object3D();
  11994. var _offset = new Vector3();
  11995. var _box$2 = new Box3();
  11996. var _boxMorphTargets = new Box3();
  11997. var _vector$4 = new Vector3();
  11998. function BufferGeometry() {
  11999. Object.defineProperty(this, 'id', {
  12000. value: _bufferGeometryId += 2
  12001. });
  12002. this.uuid = MathUtils.generateUUID();
  12003. this.name = '';
  12004. this.type = 'BufferGeometry';
  12005. this.index = null;
  12006. this.attributes = {};
  12007. this.morphAttributes = {};
  12008. this.morphTargetsRelative = false;
  12009. this.groups = [];
  12010. this.boundingBox = null;
  12011. this.boundingSphere = null;
  12012. this.drawRange = {
  12013. start: 0,
  12014. count: Infinity
  12015. };
  12016. this.userData = {};
  12017. }
  12018. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  12019. constructor: BufferGeometry,
  12020. isBufferGeometry: true,
  12021. getIndex: function getIndex() {
  12022. return this.index;
  12023. },
  12024. setIndex: function setIndex(index) {
  12025. if (Array.isArray(index)) {
  12026. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  12027. } else {
  12028. this.index = index;
  12029. }
  12030. return this;
  12031. },
  12032. getAttribute: function getAttribute(name) {
  12033. return this.attributes[name];
  12034. },
  12035. setAttribute: function setAttribute(name, attribute) {
  12036. this.attributes[name] = attribute;
  12037. return this;
  12038. },
  12039. deleteAttribute: function deleteAttribute(name) {
  12040. delete this.attributes[name];
  12041. return this;
  12042. },
  12043. hasAttribute: function hasAttribute(name) {
  12044. return this.attributes[name] !== undefined;
  12045. },
  12046. addGroup: function addGroup(start, count, materialIndex) {
  12047. if (materialIndex === void 0) {
  12048. materialIndex = 0;
  12049. }
  12050. this.groups.push({
  12051. start: start,
  12052. count: count,
  12053. materialIndex: materialIndex
  12054. });
  12055. },
  12056. clearGroups: function clearGroups() {
  12057. this.groups = [];
  12058. },
  12059. setDrawRange: function setDrawRange(start, count) {
  12060. this.drawRange.start = start;
  12061. this.drawRange.count = count;
  12062. },
  12063. applyMatrix4: function applyMatrix4(matrix) {
  12064. var position = this.attributes.position;
  12065. if (position !== undefined) {
  12066. position.applyMatrix4(matrix);
  12067. position.needsUpdate = true;
  12068. }
  12069. var normal = this.attributes.normal;
  12070. if (normal !== undefined) {
  12071. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  12072. normal.applyNormalMatrix(normalMatrix);
  12073. normal.needsUpdate = true;
  12074. }
  12075. var tangent = this.attributes.tangent;
  12076. if (tangent !== undefined) {
  12077. tangent.transformDirection(matrix);
  12078. tangent.needsUpdate = true;
  12079. }
  12080. if (this.boundingBox !== null) {
  12081. this.computeBoundingBox();
  12082. }
  12083. if (this.boundingSphere !== null) {
  12084. this.computeBoundingSphere();
  12085. }
  12086. return this;
  12087. },
  12088. rotateX: function rotateX(angle) {
  12089. // rotate geometry around world x-axis
  12090. _m1$2.makeRotationX(angle);
  12091. this.applyMatrix4(_m1$2);
  12092. return this;
  12093. },
  12094. rotateY: function rotateY(angle) {
  12095. // rotate geometry around world y-axis
  12096. _m1$2.makeRotationY(angle);
  12097. this.applyMatrix4(_m1$2);
  12098. return this;
  12099. },
  12100. rotateZ: function rotateZ(angle) {
  12101. // rotate geometry around world z-axis
  12102. _m1$2.makeRotationZ(angle);
  12103. this.applyMatrix4(_m1$2);
  12104. return this;
  12105. },
  12106. translate: function translate(x, y, z) {
  12107. // translate geometry
  12108. _m1$2.makeTranslation(x, y, z);
  12109. this.applyMatrix4(_m1$2);
  12110. return this;
  12111. },
  12112. scale: function scale(x, y, z) {
  12113. // scale geometry
  12114. _m1$2.makeScale(x, y, z);
  12115. this.applyMatrix4(_m1$2);
  12116. return this;
  12117. },
  12118. lookAt: function lookAt(vector) {
  12119. _obj.lookAt(vector);
  12120. _obj.updateMatrix();
  12121. this.applyMatrix4(_obj.matrix);
  12122. return this;
  12123. },
  12124. center: function center() {
  12125. this.computeBoundingBox();
  12126. this.boundingBox.getCenter(_offset).negate();
  12127. this.translate(_offset.x, _offset.y, _offset.z);
  12128. return this;
  12129. },
  12130. setFromObject: function setFromObject(object) {
  12131. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  12132. var geometry = object.geometry;
  12133. if (object.isPoints || object.isLine) {
  12134. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  12135. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  12136. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  12137. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  12138. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  12139. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  12140. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  12141. }
  12142. if (geometry.boundingSphere !== null) {
  12143. this.boundingSphere = geometry.boundingSphere.clone();
  12144. }
  12145. if (geometry.boundingBox !== null) {
  12146. this.boundingBox = geometry.boundingBox.clone();
  12147. }
  12148. } else if (object.isMesh) {
  12149. if (geometry && geometry.isGeometry) {
  12150. this.fromGeometry(geometry);
  12151. }
  12152. }
  12153. return this;
  12154. },
  12155. setFromPoints: function setFromPoints(points) {
  12156. var position = [];
  12157. for (var i = 0, l = points.length; i < l; i++) {
  12158. var point = points[i];
  12159. position.push(point.x, point.y, point.z || 0);
  12160. }
  12161. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  12162. return this;
  12163. },
  12164. updateFromObject: function updateFromObject(object) {
  12165. var geometry = object.geometry;
  12166. if (object.isMesh) {
  12167. var direct = geometry.__directGeometry;
  12168. if (geometry.elementsNeedUpdate === true) {
  12169. direct = undefined;
  12170. geometry.elementsNeedUpdate = false;
  12171. }
  12172. if (direct === undefined) {
  12173. return this.fromGeometry(geometry);
  12174. }
  12175. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12176. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12177. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12178. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12179. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12180. geometry.verticesNeedUpdate = false;
  12181. geometry.normalsNeedUpdate = false;
  12182. geometry.colorsNeedUpdate = false;
  12183. geometry.uvsNeedUpdate = false;
  12184. geometry.groupsNeedUpdate = false;
  12185. geometry = direct;
  12186. }
  12187. if (geometry.verticesNeedUpdate === true) {
  12188. var attribute = this.attributes.position;
  12189. if (attribute !== undefined) {
  12190. attribute.copyVector3sArray(geometry.vertices);
  12191. attribute.needsUpdate = true;
  12192. }
  12193. geometry.verticesNeedUpdate = false;
  12194. }
  12195. if (geometry.normalsNeedUpdate === true) {
  12196. var _attribute = this.attributes.normal;
  12197. if (_attribute !== undefined) {
  12198. _attribute.copyVector3sArray(geometry.normals);
  12199. _attribute.needsUpdate = true;
  12200. }
  12201. geometry.normalsNeedUpdate = false;
  12202. }
  12203. if (geometry.colorsNeedUpdate === true) {
  12204. var _attribute2 = this.attributes.color;
  12205. if (_attribute2 !== undefined) {
  12206. _attribute2.copyColorsArray(geometry.colors);
  12207. _attribute2.needsUpdate = true;
  12208. }
  12209. geometry.colorsNeedUpdate = false;
  12210. }
  12211. if (geometry.uvsNeedUpdate) {
  12212. var _attribute3 = this.attributes.uv;
  12213. if (_attribute3 !== undefined) {
  12214. _attribute3.copyVector2sArray(geometry.uvs);
  12215. _attribute3.needsUpdate = true;
  12216. }
  12217. geometry.uvsNeedUpdate = false;
  12218. }
  12219. if (geometry.lineDistancesNeedUpdate) {
  12220. var _attribute4 = this.attributes.lineDistance;
  12221. if (_attribute4 !== undefined) {
  12222. _attribute4.copyArray(geometry.lineDistances);
  12223. _attribute4.needsUpdate = true;
  12224. }
  12225. geometry.lineDistancesNeedUpdate = false;
  12226. }
  12227. if (geometry.groupsNeedUpdate) {
  12228. geometry.computeGroups(object.geometry);
  12229. this.groups = geometry.groups;
  12230. geometry.groupsNeedUpdate = false;
  12231. }
  12232. return this;
  12233. },
  12234. fromGeometry: function fromGeometry(geometry) {
  12235. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  12236. return this.fromDirectGeometry(geometry.__directGeometry);
  12237. },
  12238. fromDirectGeometry: function fromDirectGeometry(geometry) {
  12239. var positions = new Float32Array(geometry.vertices.length * 3);
  12240. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  12241. if (geometry.normals.length > 0) {
  12242. var normals = new Float32Array(geometry.normals.length * 3);
  12243. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  12244. }
  12245. if (geometry.colors.length > 0) {
  12246. var colors = new Float32Array(geometry.colors.length * 3);
  12247. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  12248. }
  12249. if (geometry.uvs.length > 0) {
  12250. var uvs = new Float32Array(geometry.uvs.length * 2);
  12251. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  12252. }
  12253. if (geometry.uvs2.length > 0) {
  12254. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  12255. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  12256. } // groups
  12257. this.groups = geometry.groups; // morphs
  12258. for (var name in geometry.morphTargets) {
  12259. var array = [];
  12260. var morphTargets = geometry.morphTargets[name];
  12261. for (var i = 0, l = morphTargets.length; i < l; i++) {
  12262. var morphTarget = morphTargets[i];
  12263. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  12264. attribute.name = morphTarget.name;
  12265. array.push(attribute.copyVector3sArray(morphTarget.data));
  12266. }
  12267. this.morphAttributes[name] = array;
  12268. } // skinning
  12269. if (geometry.skinIndices.length > 0) {
  12270. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  12271. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  12272. }
  12273. if (geometry.skinWeights.length > 0) {
  12274. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  12275. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  12276. } //
  12277. if (geometry.boundingSphere !== null) {
  12278. this.boundingSphere = geometry.boundingSphere.clone();
  12279. }
  12280. if (geometry.boundingBox !== null) {
  12281. this.boundingBox = geometry.boundingBox.clone();
  12282. }
  12283. return this;
  12284. },
  12285. computeBoundingBox: function computeBoundingBox() {
  12286. if (this.boundingBox === null) {
  12287. this.boundingBox = new Box3();
  12288. }
  12289. var position = this.attributes.position;
  12290. var morphAttributesPosition = this.morphAttributes.position;
  12291. if (position && position.isGLBufferAttribute) {
  12292. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  12293. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  12294. return;
  12295. }
  12296. if (position !== undefined) {
  12297. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  12298. if (morphAttributesPosition) {
  12299. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  12300. var morphAttribute = morphAttributesPosition[i];
  12301. _box$2.setFromBufferAttribute(morphAttribute);
  12302. if (this.morphTargetsRelative) {
  12303. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  12304. this.boundingBox.expandByPoint(_vector$4);
  12305. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  12306. this.boundingBox.expandByPoint(_vector$4);
  12307. } else {
  12308. this.boundingBox.expandByPoint(_box$2.min);
  12309. this.boundingBox.expandByPoint(_box$2.max);
  12310. }
  12311. }
  12312. }
  12313. } else {
  12314. this.boundingBox.makeEmpty();
  12315. }
  12316. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  12317. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  12318. }
  12319. },
  12320. computeBoundingSphere: function computeBoundingSphere() {
  12321. if (this.boundingSphere === null) {
  12322. this.boundingSphere = new Sphere();
  12323. }
  12324. var position = this.attributes.position;
  12325. var morphAttributesPosition = this.morphAttributes.position;
  12326. if (position && position.isGLBufferAttribute) {
  12327. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  12328. this.boundingSphere.set(new Vector3(), Infinity);
  12329. return;
  12330. }
  12331. if (position) {
  12332. // first, find the center of the bounding sphere
  12333. var center = this.boundingSphere.center;
  12334. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  12335. if (morphAttributesPosition) {
  12336. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  12337. var morphAttribute = morphAttributesPosition[i];
  12338. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  12339. if (this.morphTargetsRelative) {
  12340. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  12341. _box$2.expandByPoint(_vector$4);
  12342. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  12343. _box$2.expandByPoint(_vector$4);
  12344. } else {
  12345. _box$2.expandByPoint(_boxMorphTargets.min);
  12346. _box$2.expandByPoint(_boxMorphTargets.max);
  12347. }
  12348. }
  12349. }
  12350. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  12351. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12352. var maxRadiusSq = 0;
  12353. for (var _i = 0, _il = position.count; _i < _il; _i++) {
  12354. _vector$4.fromBufferAttribute(position, _i);
  12355. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  12356. } // process morph attributes if present
  12357. if (morphAttributesPosition) {
  12358. for (var _i2 = 0, _il2 = morphAttributesPosition.length; _i2 < _il2; _i2++) {
  12359. var _morphAttribute = morphAttributesPosition[_i2];
  12360. var morphTargetsRelative = this.morphTargetsRelative;
  12361. for (var j = 0, jl = _morphAttribute.count; j < jl; j++) {
  12362. _vector$4.fromBufferAttribute(_morphAttribute, j);
  12363. if (morphTargetsRelative) {
  12364. _offset.fromBufferAttribute(position, j);
  12365. _vector$4.add(_offset);
  12366. }
  12367. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  12368. }
  12369. }
  12370. }
  12371. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  12372. if (isNaN(this.boundingSphere.radius)) {
  12373. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  12374. }
  12375. }
  12376. },
  12377. computeFaceNormals: function computeFaceNormals() {// backwards compatibility
  12378. },
  12379. computeVertexNormals: function computeVertexNormals() {
  12380. var index = this.index;
  12381. var positionAttribute = this.getAttribute('position');
  12382. if (positionAttribute !== undefined) {
  12383. var normalAttribute = this.getAttribute('normal');
  12384. if (normalAttribute === undefined) {
  12385. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  12386. this.setAttribute('normal', normalAttribute);
  12387. } else {
  12388. // reset existing normals to zero
  12389. for (var i = 0, il = normalAttribute.count; i < il; i++) {
  12390. normalAttribute.setXYZ(i, 0, 0, 0);
  12391. }
  12392. }
  12393. var pA = new Vector3(),
  12394. pB = new Vector3(),
  12395. pC = new Vector3();
  12396. var nA = new Vector3(),
  12397. nB = new Vector3(),
  12398. nC = new Vector3();
  12399. var cb = new Vector3(),
  12400. ab = new Vector3(); // indexed elements
  12401. if (index) {
  12402. for (var _i3 = 0, _il3 = index.count; _i3 < _il3; _i3 += 3) {
  12403. var vA = index.getX(_i3 + 0);
  12404. var vB = index.getX(_i3 + 1);
  12405. var vC = index.getX(_i3 + 2);
  12406. pA.fromBufferAttribute(positionAttribute, vA);
  12407. pB.fromBufferAttribute(positionAttribute, vB);
  12408. pC.fromBufferAttribute(positionAttribute, vC);
  12409. cb.subVectors(pC, pB);
  12410. ab.subVectors(pA, pB);
  12411. cb.cross(ab);
  12412. nA.fromBufferAttribute(normalAttribute, vA);
  12413. nB.fromBufferAttribute(normalAttribute, vB);
  12414. nC.fromBufferAttribute(normalAttribute, vC);
  12415. nA.add(cb);
  12416. nB.add(cb);
  12417. nC.add(cb);
  12418. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  12419. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  12420. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  12421. }
  12422. } else {
  12423. // non-indexed elements (unconnected triangle soup)
  12424. for (var _i4 = 0, _il4 = positionAttribute.count; _i4 < _il4; _i4 += 3) {
  12425. pA.fromBufferAttribute(positionAttribute, _i4 + 0);
  12426. pB.fromBufferAttribute(positionAttribute, _i4 + 1);
  12427. pC.fromBufferAttribute(positionAttribute, _i4 + 2);
  12428. cb.subVectors(pC, pB);
  12429. ab.subVectors(pA, pB);
  12430. cb.cross(ab);
  12431. normalAttribute.setXYZ(_i4 + 0, cb.x, cb.y, cb.z);
  12432. normalAttribute.setXYZ(_i4 + 1, cb.x, cb.y, cb.z);
  12433. normalAttribute.setXYZ(_i4 + 2, cb.x, cb.y, cb.z);
  12434. }
  12435. }
  12436. this.normalizeNormals();
  12437. normalAttribute.needsUpdate = true;
  12438. }
  12439. },
  12440. merge: function merge(geometry, offset) {
  12441. if (!(geometry && geometry.isBufferGeometry)) {
  12442. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  12443. return;
  12444. }
  12445. if (offset === undefined) {
  12446. offset = 0;
  12447. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  12448. }
  12449. var attributes = this.attributes;
  12450. for (var key in attributes) {
  12451. if (geometry.attributes[key] === undefined) continue;
  12452. var attribute1 = attributes[key];
  12453. var attributeArray1 = attribute1.array;
  12454. var attribute2 = geometry.attributes[key];
  12455. var attributeArray2 = attribute2.array;
  12456. var attributeOffset = attribute2.itemSize * offset;
  12457. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  12458. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  12459. attributeArray1[j] = attributeArray2[i];
  12460. }
  12461. }
  12462. return this;
  12463. },
  12464. normalizeNormals: function normalizeNormals() {
  12465. var normals = this.attributes.normal;
  12466. for (var i = 0, il = normals.count; i < il; i++) {
  12467. _vector$4.fromBufferAttribute(normals, i);
  12468. _vector$4.normalize();
  12469. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  12470. }
  12471. },
  12472. toNonIndexed: function toNonIndexed() {
  12473. function convertBufferAttribute(attribute, indices) {
  12474. var array = attribute.array;
  12475. var itemSize = attribute.itemSize;
  12476. var normalized = attribute.normalized;
  12477. var array2 = new array.constructor(indices.length * itemSize);
  12478. var index = 0,
  12479. index2 = 0;
  12480. for (var i = 0, l = indices.length; i < l; i++) {
  12481. index = indices[i] * itemSize;
  12482. for (var j = 0; j < itemSize; j++) {
  12483. array2[index2++] = array[index++];
  12484. }
  12485. }
  12486. return new BufferAttribute(array2, itemSize, normalized);
  12487. } //
  12488. if (this.index === null) {
  12489. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  12490. return this;
  12491. }
  12492. var geometry2 = new BufferGeometry();
  12493. var indices = this.index.array;
  12494. var attributes = this.attributes; // attributes
  12495. for (var name in attributes) {
  12496. var attribute = attributes[name];
  12497. var newAttribute = convertBufferAttribute(attribute, indices);
  12498. geometry2.setAttribute(name, newAttribute);
  12499. } // morph attributes
  12500. var morphAttributes = this.morphAttributes;
  12501. for (var _name in morphAttributes) {
  12502. var morphArray = [];
  12503. var morphAttribute = morphAttributes[_name]; // morphAttribute: array of Float32BufferAttributes
  12504. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  12505. var _attribute5 = morphAttribute[i];
  12506. var _newAttribute = convertBufferAttribute(_attribute5, indices);
  12507. morphArray.push(_newAttribute);
  12508. }
  12509. geometry2.morphAttributes[_name] = morphArray;
  12510. }
  12511. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  12512. var groups = this.groups;
  12513. for (var _i5 = 0, l = groups.length; _i5 < l; _i5++) {
  12514. var group = groups[_i5];
  12515. geometry2.addGroup(group.start, group.count, group.materialIndex);
  12516. }
  12517. return geometry2;
  12518. },
  12519. toJSON: function toJSON() {
  12520. var data = {
  12521. metadata: {
  12522. version: 4.5,
  12523. type: 'BufferGeometry',
  12524. generator: 'BufferGeometry.toJSON'
  12525. }
  12526. }; // standard BufferGeometry serialization
  12527. data.uuid = this.uuid;
  12528. data.type = this.type;
  12529. if (this.name !== '') data.name = this.name;
  12530. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  12531. if (this.parameters !== undefined) {
  12532. var parameters = this.parameters;
  12533. for (var key in parameters) {
  12534. if (parameters[key] !== undefined) data[key] = parameters[key];
  12535. }
  12536. return data;
  12537. }
  12538. data.data = {
  12539. attributes: {}
  12540. };
  12541. var index = this.index;
  12542. if (index !== null) {
  12543. data.data.index = {
  12544. type: index.array.constructor.name,
  12545. array: Array.prototype.slice.call(index.array)
  12546. };
  12547. }
  12548. var attributes = this.attributes;
  12549. for (var _key in attributes) {
  12550. var attribute = attributes[_key];
  12551. var attributeData = attribute.toJSON(data.data);
  12552. if (attribute.name !== '') attributeData.name = attribute.name;
  12553. data.data.attributes[_key] = attributeData;
  12554. }
  12555. var morphAttributes = {};
  12556. var hasMorphAttributes = false;
  12557. for (var _key2 in this.morphAttributes) {
  12558. var attributeArray = this.morphAttributes[_key2];
  12559. var array = [];
  12560. for (var i = 0, il = attributeArray.length; i < il; i++) {
  12561. var _attribute6 = attributeArray[i];
  12562. var _attributeData = _attribute6.toJSON(data.data);
  12563. if (_attribute6.name !== '') _attributeData.name = _attribute6.name;
  12564. array.push(_attributeData);
  12565. }
  12566. if (array.length > 0) {
  12567. morphAttributes[_key2] = array;
  12568. hasMorphAttributes = true;
  12569. }
  12570. }
  12571. if (hasMorphAttributes) {
  12572. data.data.morphAttributes = morphAttributes;
  12573. data.data.morphTargetsRelative = this.morphTargetsRelative;
  12574. }
  12575. var groups = this.groups;
  12576. if (groups.length > 0) {
  12577. data.data.groups = JSON.parse(JSON.stringify(groups));
  12578. }
  12579. var boundingSphere = this.boundingSphere;
  12580. if (boundingSphere !== null) {
  12581. data.data.boundingSphere = {
  12582. center: boundingSphere.center.toArray(),
  12583. radius: boundingSphere.radius
  12584. };
  12585. }
  12586. return data;
  12587. },
  12588. clone: function clone() {
  12589. /*
  12590. // Handle primitives
  12591. const parameters = this.parameters;
  12592. if ( parameters !== undefined ) {
  12593. const values = [];
  12594. for ( const key in parameters ) {
  12595. values.push( parameters[ key ] );
  12596. }
  12597. const geometry = Object.create( this.constructor.prototype );
  12598. this.constructor.apply( geometry, values );
  12599. return geometry;
  12600. }
  12601. return new this.constructor().copy( this );
  12602. */
  12603. return new BufferGeometry().copy(this);
  12604. },
  12605. copy: function copy(source) {
  12606. // reset
  12607. this.index = null;
  12608. this.attributes = {};
  12609. this.morphAttributes = {};
  12610. this.groups = [];
  12611. this.boundingBox = null;
  12612. this.boundingSphere = null; // used for storing cloned, shared data
  12613. var data = {}; // name
  12614. this.name = source.name; // index
  12615. var index = source.index;
  12616. if (index !== null) {
  12617. this.setIndex(index.clone(data));
  12618. } // attributes
  12619. var attributes = source.attributes;
  12620. for (var name in attributes) {
  12621. var attribute = attributes[name];
  12622. this.setAttribute(name, attribute.clone(data));
  12623. } // morph attributes
  12624. var morphAttributes = source.morphAttributes;
  12625. for (var _name2 in morphAttributes) {
  12626. var array = [];
  12627. var morphAttribute = morphAttributes[_name2]; // morphAttribute: array of Float32BufferAttributes
  12628. for (var i = 0, l = morphAttribute.length; i < l; i++) {
  12629. array.push(morphAttribute[i].clone(data));
  12630. }
  12631. this.morphAttributes[_name2] = array;
  12632. }
  12633. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  12634. var groups = source.groups;
  12635. for (var _i6 = 0, _l = groups.length; _i6 < _l; _i6++) {
  12636. var group = groups[_i6];
  12637. this.addGroup(group.start, group.count, group.materialIndex);
  12638. } // bounding box
  12639. var boundingBox = source.boundingBox;
  12640. if (boundingBox !== null) {
  12641. this.boundingBox = boundingBox.clone();
  12642. } // bounding sphere
  12643. var boundingSphere = source.boundingSphere;
  12644. if (boundingSphere !== null) {
  12645. this.boundingSphere = boundingSphere.clone();
  12646. } // draw range
  12647. this.drawRange.start = source.drawRange.start;
  12648. this.drawRange.count = source.drawRange.count; // user data
  12649. this.userData = source.userData;
  12650. return this;
  12651. },
  12652. dispose: function dispose() {
  12653. this.dispatchEvent({
  12654. type: 'dispose'
  12655. });
  12656. }
  12657. });
  12658. var _inverseMatrix = new Matrix4();
  12659. var _ray = new Ray();
  12660. var _sphere = new Sphere();
  12661. var _vA = new Vector3();
  12662. var _vB = new Vector3();
  12663. var _vC = new Vector3();
  12664. var _tempA = new Vector3();
  12665. var _tempB = new Vector3();
  12666. var _tempC = new Vector3();
  12667. var _morphA = new Vector3();
  12668. var _morphB = new Vector3();
  12669. var _morphC = new Vector3();
  12670. var _uvA = new Vector2();
  12671. var _uvB = new Vector2();
  12672. var _uvC = new Vector2();
  12673. var _intersectionPoint = new Vector3();
  12674. var _intersectionPointWorld = new Vector3();
  12675. function Mesh(geometry, material) {
  12676. Object3D.call(this);
  12677. this.type = 'Mesh';
  12678. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12679. this.material = material !== undefined ? material : new MeshBasicMaterial();
  12680. this.updateMorphTargets();
  12681. }
  12682. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  12683. constructor: Mesh,
  12684. isMesh: true,
  12685. copy: function copy(source) {
  12686. Object3D.prototype.copy.call(this, source);
  12687. if (source.morphTargetInfluences !== undefined) {
  12688. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12689. }
  12690. if (source.morphTargetDictionary !== undefined) {
  12691. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  12692. }
  12693. this.material = source.material;
  12694. this.geometry = source.geometry;
  12695. return this;
  12696. },
  12697. updateMorphTargets: function updateMorphTargets() {
  12698. var geometry = this.geometry;
  12699. if (geometry.isBufferGeometry) {
  12700. var morphAttributes = geometry.morphAttributes;
  12701. var keys = Object.keys(morphAttributes);
  12702. if (keys.length > 0) {
  12703. var morphAttribute = morphAttributes[keys[0]];
  12704. if (morphAttribute !== undefined) {
  12705. this.morphTargetInfluences = [];
  12706. this.morphTargetDictionary = {};
  12707. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  12708. var name = morphAttribute[m].name || String(m);
  12709. this.morphTargetInfluences.push(0);
  12710. this.morphTargetDictionary[name] = m;
  12711. }
  12712. }
  12713. }
  12714. } else {
  12715. var morphTargets = geometry.morphTargets;
  12716. if (morphTargets !== undefined && morphTargets.length > 0) {
  12717. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  12718. }
  12719. }
  12720. },
  12721. raycast: function raycast(raycaster, intersects) {
  12722. var geometry = this.geometry;
  12723. var material = this.material;
  12724. var matrixWorld = this.matrixWorld;
  12725. if (material === undefined) return; // Checking boundingSphere distance to ray
  12726. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  12727. _sphere.copy(geometry.boundingSphere);
  12728. _sphere.applyMatrix4(matrixWorld);
  12729. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  12730. _inverseMatrix.copy(matrixWorld).invert();
  12731. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  12732. if (geometry.boundingBox !== null) {
  12733. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  12734. }
  12735. var intersection;
  12736. if (geometry.isBufferGeometry) {
  12737. var index = geometry.index;
  12738. var position = geometry.attributes.position;
  12739. var morphPosition = geometry.morphAttributes.position;
  12740. var morphTargetsRelative = geometry.morphTargetsRelative;
  12741. var uv = geometry.attributes.uv;
  12742. var uv2 = geometry.attributes.uv2;
  12743. var groups = geometry.groups;
  12744. var drawRange = geometry.drawRange;
  12745. if (index !== null) {
  12746. // indexed buffer geometry
  12747. if (Array.isArray(material)) {
  12748. for (var i = 0, il = groups.length; i < il; i++) {
  12749. var group = groups[i];
  12750. var groupMaterial = material[group.materialIndex];
  12751. var start = Math.max(group.start, drawRange.start);
  12752. var end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  12753. for (var j = start, jl = end; j < jl; j += 3) {
  12754. var a = index.getX(j);
  12755. var b = index.getX(j + 1);
  12756. var c = index.getX(j + 2);
  12757. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  12758. if (intersection) {
  12759. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  12760. intersection.face.materialIndex = group.materialIndex;
  12761. intersects.push(intersection);
  12762. }
  12763. }
  12764. }
  12765. } else {
  12766. var _start = Math.max(0, drawRange.start);
  12767. var _end = Math.min(index.count, drawRange.start + drawRange.count);
  12768. for (var _i = _start, _il = _end; _i < _il; _i += 3) {
  12769. var _a = index.getX(_i);
  12770. var _b = index.getX(_i + 1);
  12771. var _c = index.getX(_i + 2);
  12772. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a, _b, _c);
  12773. if (intersection) {
  12774. intersection.faceIndex = Math.floor(_i / 3); // triangle number in indexed buffer semantics
  12775. intersects.push(intersection);
  12776. }
  12777. }
  12778. }
  12779. } else if (position !== undefined) {
  12780. // non-indexed buffer geometry
  12781. if (Array.isArray(material)) {
  12782. for (var _i2 = 0, _il2 = groups.length; _i2 < _il2; _i2++) {
  12783. var _group = groups[_i2];
  12784. var _groupMaterial = material[_group.materialIndex];
  12785. var _start2 = Math.max(_group.start, drawRange.start);
  12786. var _end2 = Math.min(_group.start + _group.count, drawRange.start + drawRange.count);
  12787. for (var _j = _start2, _jl = _end2; _j < _jl; _j += 3) {
  12788. var _a2 = _j;
  12789. var _b2 = _j + 1;
  12790. var _c2 = _j + 2;
  12791. intersection = checkBufferGeometryIntersection(this, _groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a2, _b2, _c2);
  12792. if (intersection) {
  12793. intersection.faceIndex = Math.floor(_j / 3); // triangle number in non-indexed buffer semantics
  12794. intersection.face.materialIndex = _group.materialIndex;
  12795. intersects.push(intersection);
  12796. }
  12797. }
  12798. }
  12799. } else {
  12800. var _start3 = Math.max(0, drawRange.start);
  12801. var _end3 = Math.min(position.count, drawRange.start + drawRange.count);
  12802. for (var _i3 = _start3, _il3 = _end3; _i3 < _il3; _i3 += 3) {
  12803. var _a3 = _i3;
  12804. var _b3 = _i3 + 1;
  12805. var _c3 = _i3 + 2;
  12806. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a3, _b3, _c3);
  12807. if (intersection) {
  12808. intersection.faceIndex = Math.floor(_i3 / 3); // triangle number in non-indexed buffer semantics
  12809. intersects.push(intersection);
  12810. }
  12811. }
  12812. }
  12813. }
  12814. } else if (geometry.isGeometry) {
  12815. var isMultiMaterial = Array.isArray(material);
  12816. var vertices = geometry.vertices;
  12817. var faces = geometry.faces;
  12818. var uvs;
  12819. var faceVertexUvs = geometry.faceVertexUvs[0];
  12820. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  12821. for (var f = 0, fl = faces.length; f < fl; f++) {
  12822. var face = faces[f];
  12823. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  12824. if (faceMaterial === undefined) continue;
  12825. var fvA = vertices[face.a];
  12826. var fvB = vertices[face.b];
  12827. var fvC = vertices[face.c];
  12828. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  12829. if (intersection) {
  12830. if (uvs && uvs[f]) {
  12831. var uvs_f = uvs[f];
  12832. _uvA.copy(uvs_f[0]);
  12833. _uvB.copy(uvs_f[1]);
  12834. _uvC.copy(uvs_f[2]);
  12835. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  12836. }
  12837. intersection.face = face;
  12838. intersection.faceIndex = f;
  12839. intersects.push(intersection);
  12840. }
  12841. }
  12842. }
  12843. }
  12844. });
  12845. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  12846. var intersect;
  12847. if (material.side === BackSide) {
  12848. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  12849. } else {
  12850. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  12851. }
  12852. if (intersect === null) return null;
  12853. _intersectionPointWorld.copy(point);
  12854. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  12855. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  12856. if (distance < raycaster.near || distance > raycaster.far) return null;
  12857. return {
  12858. distance: distance,
  12859. point: _intersectionPointWorld.clone(),
  12860. object: object
  12861. };
  12862. }
  12863. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  12864. _vA.fromBufferAttribute(position, a);
  12865. _vB.fromBufferAttribute(position, b);
  12866. _vC.fromBufferAttribute(position, c);
  12867. var morphInfluences = object.morphTargetInfluences;
  12868. if (material.morphTargets && morphPosition && morphInfluences) {
  12869. _morphA.set(0, 0, 0);
  12870. _morphB.set(0, 0, 0);
  12871. _morphC.set(0, 0, 0);
  12872. for (var i = 0, il = morphPosition.length; i < il; i++) {
  12873. var influence = morphInfluences[i];
  12874. var morphAttribute = morphPosition[i];
  12875. if (influence === 0) continue;
  12876. _tempA.fromBufferAttribute(morphAttribute, a);
  12877. _tempB.fromBufferAttribute(morphAttribute, b);
  12878. _tempC.fromBufferAttribute(morphAttribute, c);
  12879. if (morphTargetsRelative) {
  12880. _morphA.addScaledVector(_tempA, influence);
  12881. _morphB.addScaledVector(_tempB, influence);
  12882. _morphC.addScaledVector(_tempC, influence);
  12883. } else {
  12884. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  12885. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  12886. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  12887. }
  12888. }
  12889. _vA.add(_morphA);
  12890. _vB.add(_morphB);
  12891. _vC.add(_morphC);
  12892. }
  12893. if (object.isSkinnedMesh) {
  12894. object.boneTransform(a, _vA);
  12895. object.boneTransform(b, _vB);
  12896. object.boneTransform(c, _vC);
  12897. }
  12898. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  12899. if (intersection) {
  12900. if (uv) {
  12901. _uvA.fromBufferAttribute(uv, a);
  12902. _uvB.fromBufferAttribute(uv, b);
  12903. _uvC.fromBufferAttribute(uv, c);
  12904. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  12905. }
  12906. if (uv2) {
  12907. _uvA.fromBufferAttribute(uv2, a);
  12908. _uvB.fromBufferAttribute(uv2, b);
  12909. _uvC.fromBufferAttribute(uv2, c);
  12910. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  12911. }
  12912. var face = new Face3(a, b, c);
  12913. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  12914. intersection.face = face;
  12915. }
  12916. return intersection;
  12917. }
  12918. var BoxBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  12919. _inheritsLoose(BoxBufferGeometry, _BufferGeometry);
  12920. function BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
  12921. var _this;
  12922. if (width === void 0) {
  12923. width = 1;
  12924. }
  12925. if (height === void 0) {
  12926. height = 1;
  12927. }
  12928. if (depth === void 0) {
  12929. depth = 1;
  12930. }
  12931. if (widthSegments === void 0) {
  12932. widthSegments = 1;
  12933. }
  12934. if (heightSegments === void 0) {
  12935. heightSegments = 1;
  12936. }
  12937. if (depthSegments === void 0) {
  12938. depthSegments = 1;
  12939. }
  12940. _this = _BufferGeometry.call(this) || this;
  12941. _this.type = 'BoxBufferGeometry';
  12942. _this.parameters = {
  12943. width: width,
  12944. height: height,
  12945. depth: depth,
  12946. widthSegments: widthSegments,
  12947. heightSegments: heightSegments,
  12948. depthSegments: depthSegments
  12949. };
  12950. var scope = _assertThisInitialized(_this); // segments
  12951. widthSegments = Math.floor(widthSegments);
  12952. heightSegments = Math.floor(heightSegments);
  12953. depthSegments = Math.floor(depthSegments); // buffers
  12954. var indices = [];
  12955. var vertices = [];
  12956. var normals = [];
  12957. var uvs = []; // helper variables
  12958. var numberOfVertices = 0;
  12959. var groupStart = 0; // build each side of the box geometry
  12960. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  12961. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  12962. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  12963. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  12964. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  12965. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  12966. // build geometry
  12967. _this.setIndex(indices);
  12968. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  12969. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  12970. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  12971. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  12972. var segmentWidth = width / gridX;
  12973. var segmentHeight = height / gridY;
  12974. var widthHalf = width / 2;
  12975. var heightHalf = height / 2;
  12976. var depthHalf = depth / 2;
  12977. var gridX1 = gridX + 1;
  12978. var gridY1 = gridY + 1;
  12979. var vertexCounter = 0;
  12980. var groupCount = 0;
  12981. var vector = new Vector3(); // generate vertices, normals and uvs
  12982. for (var iy = 0; iy < gridY1; iy++) {
  12983. var y = iy * segmentHeight - heightHalf;
  12984. for (var ix = 0; ix < gridX1; ix++) {
  12985. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  12986. vector[u] = x * udir;
  12987. vector[v] = y * vdir;
  12988. vector[w] = depthHalf; // now apply vector to vertex buffer
  12989. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  12990. vector[u] = 0;
  12991. vector[v] = 0;
  12992. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  12993. normals.push(vector.x, vector.y, vector.z); // uvs
  12994. uvs.push(ix / gridX);
  12995. uvs.push(1 - iy / gridY); // counters
  12996. vertexCounter += 1;
  12997. }
  12998. } // indices
  12999. // 1. you need three indices to draw a single face
  13000. // 2. a single segment consists of two faces
  13001. // 3. so we need to generate six (2*3) indices per segment
  13002. for (var _iy = 0; _iy < gridY; _iy++) {
  13003. for (var _ix = 0; _ix < gridX; _ix++) {
  13004. var a = numberOfVertices + _ix + gridX1 * _iy;
  13005. var b = numberOfVertices + _ix + gridX1 * (_iy + 1);
  13006. var c = numberOfVertices + (_ix + 1) + gridX1 * (_iy + 1);
  13007. var d = numberOfVertices + (_ix + 1) + gridX1 * _iy; // faces
  13008. indices.push(a, b, d);
  13009. indices.push(b, c, d); // increase counter
  13010. groupCount += 6;
  13011. }
  13012. } // add a group to the geometry. this will ensure multi material support
  13013. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  13014. groupStart += groupCount; // update total number of vertices
  13015. numberOfVertices += vertexCounter;
  13016. }
  13017. return _this;
  13018. }
  13019. return BoxBufferGeometry;
  13020. }(BufferGeometry);
  13021. /**
  13022. * Uniform Utilities
  13023. */
  13024. function cloneUniforms(src) {
  13025. var dst = {};
  13026. for (var u in src) {
  13027. dst[u] = {};
  13028. for (var p in src[u]) {
  13029. var property = src[u][p];
  13030. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  13031. dst[u][p] = property.clone();
  13032. } else if (Array.isArray(property)) {
  13033. dst[u][p] = property.slice();
  13034. } else {
  13035. dst[u][p] = property;
  13036. }
  13037. }
  13038. }
  13039. return dst;
  13040. }
  13041. function mergeUniforms(uniforms) {
  13042. var merged = {};
  13043. for (var u = 0; u < uniforms.length; u++) {
  13044. var tmp = cloneUniforms(uniforms[u]);
  13045. for (var p in tmp) {
  13046. merged[p] = tmp[p];
  13047. }
  13048. }
  13049. return merged;
  13050. } // Legacy
  13051. var UniformsUtils = {
  13052. clone: cloneUniforms,
  13053. merge: mergeUniforms
  13054. };
  13055. var default_vertex = /* glsl */
  13056. "\nvoid main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}\n";
  13057. var default_fragment = /* glsl */
  13058. "\nvoid main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}\n";
  13059. /**
  13060. * parameters = {
  13061. * defines: { "label" : "value" },
  13062. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13063. *
  13064. * fragmentShader: <string>,
  13065. * vertexShader: <string>,
  13066. *
  13067. * wireframe: <boolean>,
  13068. * wireframeLinewidth: <float>,
  13069. *
  13070. * lights: <bool>,
  13071. *
  13072. * skinning: <bool>,
  13073. * morphTargets: <bool>,
  13074. * morphNormals: <bool>
  13075. * }
  13076. */
  13077. function ShaderMaterial(parameters) {
  13078. Material.call(this);
  13079. this.type = 'ShaderMaterial';
  13080. this.defines = {};
  13081. this.uniforms = {};
  13082. this.vertexShader = default_vertex;
  13083. this.fragmentShader = default_fragment;
  13084. this.linewidth = 1;
  13085. this.wireframe = false;
  13086. this.wireframeLinewidth = 1;
  13087. this.fog = false; // set to use scene fog
  13088. this.lights = false; // set to use scene lights
  13089. this.clipping = false; // set to use user-defined clipping planes
  13090. this.skinning = false; // set to use skinning attribute streams
  13091. this.morphTargets = false; // set to use morph targets
  13092. this.morphNormals = false; // set to use morph normals
  13093. this.extensions = {
  13094. derivatives: false,
  13095. // set to use derivatives
  13096. fragDepth: false,
  13097. // set to use fragment depth values
  13098. drawBuffers: false,
  13099. // set to use draw buffers
  13100. shaderTextureLOD: false // set to use shader texture LOD
  13101. }; // When rendered geometry doesn't include these attributes but the material does,
  13102. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13103. this.defaultAttributeValues = {
  13104. 'color': [1, 1, 1],
  13105. 'uv': [0, 0],
  13106. 'uv2': [0, 0]
  13107. };
  13108. this.index0AttributeName = undefined;
  13109. this.uniformsNeedUpdate = false;
  13110. this.glslVersion = null;
  13111. if (parameters !== undefined) {
  13112. if (parameters.attributes !== undefined) {
  13113. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  13114. }
  13115. this.setValues(parameters);
  13116. }
  13117. }
  13118. ShaderMaterial.prototype = Object.create(Material.prototype);
  13119. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13120. ShaderMaterial.prototype.isShaderMaterial = true;
  13121. ShaderMaterial.prototype.copy = function (source) {
  13122. Material.prototype.copy.call(this, source);
  13123. this.fragmentShader = source.fragmentShader;
  13124. this.vertexShader = source.vertexShader;
  13125. this.uniforms = cloneUniforms(source.uniforms);
  13126. this.defines = Object.assign({}, source.defines);
  13127. this.wireframe = source.wireframe;
  13128. this.wireframeLinewidth = source.wireframeLinewidth;
  13129. this.lights = source.lights;
  13130. this.clipping = source.clipping;
  13131. this.skinning = source.skinning;
  13132. this.morphTargets = source.morphTargets;
  13133. this.morphNormals = source.morphNormals;
  13134. this.extensions = Object.assign({}, source.extensions);
  13135. this.glslVersion = source.glslVersion;
  13136. return this;
  13137. };
  13138. ShaderMaterial.prototype.toJSON = function (meta) {
  13139. var data = Material.prototype.toJSON.call(this, meta);
  13140. data.glslVersion = this.glslVersion;
  13141. data.uniforms = {};
  13142. for (var name in this.uniforms) {
  13143. var uniform = this.uniforms[name];
  13144. var value = uniform.value;
  13145. if (value && value.isTexture) {
  13146. data.uniforms[name] = {
  13147. type: 't',
  13148. value: value.toJSON(meta).uuid
  13149. };
  13150. } else if (value && value.isColor) {
  13151. data.uniforms[name] = {
  13152. type: 'c',
  13153. value: value.getHex()
  13154. };
  13155. } else if (value && value.isVector2) {
  13156. data.uniforms[name] = {
  13157. type: 'v2',
  13158. value: value.toArray()
  13159. };
  13160. } else if (value && value.isVector3) {
  13161. data.uniforms[name] = {
  13162. type: 'v3',
  13163. value: value.toArray()
  13164. };
  13165. } else if (value && value.isVector4) {
  13166. data.uniforms[name] = {
  13167. type: 'v4',
  13168. value: value.toArray()
  13169. };
  13170. } else if (value && value.isMatrix3) {
  13171. data.uniforms[name] = {
  13172. type: 'm3',
  13173. value: value.toArray()
  13174. };
  13175. } else if (value && value.isMatrix4) {
  13176. data.uniforms[name] = {
  13177. type: 'm4',
  13178. value: value.toArray()
  13179. };
  13180. } else {
  13181. data.uniforms[name] = {
  13182. value: value
  13183. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  13184. }
  13185. }
  13186. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  13187. data.vertexShader = this.vertexShader;
  13188. data.fragmentShader = this.fragmentShader;
  13189. var extensions = {};
  13190. for (var key in this.extensions) {
  13191. if (this.extensions[key] === true) extensions[key] = true;
  13192. }
  13193. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  13194. return data;
  13195. };
  13196. function Camera() {
  13197. Object3D.call(this);
  13198. this.type = 'Camera';
  13199. this.matrixWorldInverse = new Matrix4();
  13200. this.projectionMatrix = new Matrix4();
  13201. this.projectionMatrixInverse = new Matrix4();
  13202. }
  13203. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  13204. constructor: Camera,
  13205. isCamera: true,
  13206. copy: function copy(source, recursive) {
  13207. Object3D.prototype.copy.call(this, source, recursive);
  13208. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  13209. this.projectionMatrix.copy(source.projectionMatrix);
  13210. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  13211. return this;
  13212. },
  13213. getWorldDirection: function getWorldDirection(target) {
  13214. if (target === undefined) {
  13215. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  13216. target = new Vector3();
  13217. }
  13218. this.updateWorldMatrix(true, false);
  13219. var e = this.matrixWorld.elements;
  13220. return target.set(-e[8], -e[9], -e[10]).normalize();
  13221. },
  13222. updateMatrixWorld: function updateMatrixWorld(force) {
  13223. Object3D.prototype.updateMatrixWorld.call(this, force);
  13224. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  13225. },
  13226. updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
  13227. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  13228. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  13229. },
  13230. clone: function clone() {
  13231. return new this.constructor().copy(this);
  13232. }
  13233. });
  13234. function PerspectiveCamera(fov, aspect, near, far) {
  13235. if (fov === void 0) {
  13236. fov = 50;
  13237. }
  13238. if (aspect === void 0) {
  13239. aspect = 1;
  13240. }
  13241. if (near === void 0) {
  13242. near = 0.1;
  13243. }
  13244. if (far === void 0) {
  13245. far = 2000;
  13246. }
  13247. Camera.call(this);
  13248. this.type = 'PerspectiveCamera';
  13249. this.fov = fov;
  13250. this.zoom = 1;
  13251. this.near = near;
  13252. this.far = far;
  13253. this.focus = 10;
  13254. this.aspect = aspect;
  13255. this.view = null;
  13256. this.filmGauge = 35; // width of the film (default in millimeters)
  13257. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13258. this.updateProjectionMatrix();
  13259. }
  13260. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  13261. constructor: PerspectiveCamera,
  13262. isPerspectiveCamera: true,
  13263. copy: function copy(source, recursive) {
  13264. Camera.prototype.copy.call(this, source, recursive);
  13265. this.fov = source.fov;
  13266. this.zoom = source.zoom;
  13267. this.near = source.near;
  13268. this.far = source.far;
  13269. this.focus = source.focus;
  13270. this.aspect = source.aspect;
  13271. this.view = source.view === null ? null : Object.assign({}, source.view);
  13272. this.filmGauge = source.filmGauge;
  13273. this.filmOffset = source.filmOffset;
  13274. return this;
  13275. },
  13276. /**
  13277. * Sets the FOV by focal length in respect to the current .filmGauge.
  13278. *
  13279. * The default film gauge is 35, so that the focal length can be specified for
  13280. * a 35mm (full frame) camera.
  13281. *
  13282. * Values for focal length and film gauge must have the same unit.
  13283. */
  13284. setFocalLength: function setFocalLength(focalLength) {
  13285. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13286. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13287. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  13288. this.updateProjectionMatrix();
  13289. },
  13290. /**
  13291. * Calculates the focal length from the current .fov and .filmGauge.
  13292. */
  13293. getFocalLength: function getFocalLength() {
  13294. var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  13295. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13296. },
  13297. getEffectiveFOV: function getEffectiveFOV() {
  13298. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  13299. },
  13300. getFilmWidth: function getFilmWidth() {
  13301. // film not completely covered in portrait format (aspect < 1)
  13302. return this.filmGauge * Math.min(this.aspect, 1);
  13303. },
  13304. getFilmHeight: function getFilmHeight() {
  13305. // film not completely covered in landscape format (aspect > 1)
  13306. return this.filmGauge / Math.max(this.aspect, 1);
  13307. },
  13308. /**
  13309. * Sets an offset in a larger frustum. This is useful for multi-window or
  13310. * multi-monitor/multi-machine setups.
  13311. *
  13312. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13313. * the monitors are in grid like this
  13314. *
  13315. * +---+---+---+
  13316. * | A | B | C |
  13317. * +---+---+---+
  13318. * | D | E | F |
  13319. * +---+---+---+
  13320. *
  13321. * then for each monitor you would call it like this
  13322. *
  13323. * const w = 1920;
  13324. * const h = 1080;
  13325. * const fullWidth = w * 3;
  13326. * const fullHeight = h * 2;
  13327. *
  13328. * --A--
  13329. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13330. * --B--
  13331. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13332. * --C--
  13333. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13334. * --D--
  13335. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13336. * --E--
  13337. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13338. * --F--
  13339. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13340. *
  13341. * Note there is no reason monitors have to be the same size or in a grid.
  13342. */
  13343. setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  13344. this.aspect = fullWidth / fullHeight;
  13345. if (this.view === null) {
  13346. this.view = {
  13347. enabled: true,
  13348. fullWidth: 1,
  13349. fullHeight: 1,
  13350. offsetX: 0,
  13351. offsetY: 0,
  13352. width: 1,
  13353. height: 1
  13354. };
  13355. }
  13356. this.view.enabled = true;
  13357. this.view.fullWidth = fullWidth;
  13358. this.view.fullHeight = fullHeight;
  13359. this.view.offsetX = x;
  13360. this.view.offsetY = y;
  13361. this.view.width = width;
  13362. this.view.height = height;
  13363. this.updateProjectionMatrix();
  13364. },
  13365. clearViewOffset: function clearViewOffset() {
  13366. if (this.view !== null) {
  13367. this.view.enabled = false;
  13368. }
  13369. this.updateProjectionMatrix();
  13370. },
  13371. updateProjectionMatrix: function updateProjectionMatrix() {
  13372. var near = this.near;
  13373. var top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
  13374. var height = 2 * top;
  13375. var width = this.aspect * height;
  13376. var left = -0.5 * width;
  13377. var view = this.view;
  13378. if (this.view !== null && this.view.enabled) {
  13379. var fullWidth = view.fullWidth,
  13380. fullHeight = view.fullHeight;
  13381. left += view.offsetX * width / fullWidth;
  13382. top -= view.offsetY * height / fullHeight;
  13383. width *= view.width / fullWidth;
  13384. height *= view.height / fullHeight;
  13385. }
  13386. var skew = this.filmOffset;
  13387. if (skew !== 0) left += near * skew / this.getFilmWidth();
  13388. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  13389. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  13390. },
  13391. toJSON: function toJSON(meta) {
  13392. var data = Object3D.prototype.toJSON.call(this, meta);
  13393. data.object.fov = this.fov;
  13394. data.object.zoom = this.zoom;
  13395. data.object.near = this.near;
  13396. data.object.far = this.far;
  13397. data.object.focus = this.focus;
  13398. data.object.aspect = this.aspect;
  13399. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  13400. data.object.filmGauge = this.filmGauge;
  13401. data.object.filmOffset = this.filmOffset;
  13402. return data;
  13403. }
  13404. });
  13405. var fov = 90,
  13406. aspect = 1;
  13407. function CubeCamera(near, far, renderTarget) {
  13408. Object3D.call(this);
  13409. this.type = 'CubeCamera';
  13410. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  13411. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  13412. return;
  13413. }
  13414. this.renderTarget = renderTarget;
  13415. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  13416. cameraPX.layers = this.layers;
  13417. cameraPX.up.set(0, -1, 0);
  13418. cameraPX.lookAt(new Vector3(1, 0, 0));
  13419. this.add(cameraPX);
  13420. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  13421. cameraNX.layers = this.layers;
  13422. cameraNX.up.set(0, -1, 0);
  13423. cameraNX.lookAt(new Vector3(-1, 0, 0));
  13424. this.add(cameraNX);
  13425. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  13426. cameraPY.layers = this.layers;
  13427. cameraPY.up.set(0, 0, 1);
  13428. cameraPY.lookAt(new Vector3(0, 1, 0));
  13429. this.add(cameraPY);
  13430. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  13431. cameraNY.layers = this.layers;
  13432. cameraNY.up.set(0, 0, -1);
  13433. cameraNY.lookAt(new Vector3(0, -1, 0));
  13434. this.add(cameraNY);
  13435. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  13436. cameraPZ.layers = this.layers;
  13437. cameraPZ.up.set(0, -1, 0);
  13438. cameraPZ.lookAt(new Vector3(0, 0, 1));
  13439. this.add(cameraPZ);
  13440. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  13441. cameraNZ.layers = this.layers;
  13442. cameraNZ.up.set(0, -1, 0);
  13443. cameraNZ.lookAt(new Vector3(0, 0, -1));
  13444. this.add(cameraNZ);
  13445. this.update = function (renderer, scene) {
  13446. if (this.parent === null) this.updateMatrixWorld();
  13447. var currentXrEnabled = renderer.xr.enabled;
  13448. var currentRenderTarget = renderer.getRenderTarget();
  13449. renderer.xr.enabled = false;
  13450. var generateMipmaps = renderTarget.texture.generateMipmaps;
  13451. renderTarget.texture.generateMipmaps = false;
  13452. renderer.setRenderTarget(renderTarget, 0);
  13453. renderer.render(scene, cameraPX);
  13454. renderer.setRenderTarget(renderTarget, 1);
  13455. renderer.render(scene, cameraNX);
  13456. renderer.setRenderTarget(renderTarget, 2);
  13457. renderer.render(scene, cameraPY);
  13458. renderer.setRenderTarget(renderTarget, 3);
  13459. renderer.render(scene, cameraNY);
  13460. renderer.setRenderTarget(renderTarget, 4);
  13461. renderer.render(scene, cameraPZ);
  13462. renderTarget.texture.generateMipmaps = generateMipmaps;
  13463. renderer.setRenderTarget(renderTarget, 5);
  13464. renderer.render(scene, cameraNZ);
  13465. renderer.setRenderTarget(currentRenderTarget);
  13466. renderer.xr.enabled = currentXrEnabled;
  13467. };
  13468. }
  13469. CubeCamera.prototype = Object.create(Object3D.prototype);
  13470. CubeCamera.prototype.constructor = CubeCamera;
  13471. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  13472. images = images !== undefined ? images : [];
  13473. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13474. format = format !== undefined ? format : RGBFormat;
  13475. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  13476. this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
  13477. //
  13478. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  13479. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  13480. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  13481. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  13482. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  13483. // when using WebGLCubeRenderTarget.texture as a cube texture.
  13484. this._needsFlipEnvMap = true;
  13485. }
  13486. CubeTexture.prototype = Object.create(Texture.prototype);
  13487. CubeTexture.prototype.constructor = CubeTexture;
  13488. CubeTexture.prototype.isCubeTexture = true;
  13489. Object.defineProperty(CubeTexture.prototype, 'images', {
  13490. get: function get() {
  13491. return this.image;
  13492. },
  13493. set: function set(value) {
  13494. this.image = value;
  13495. }
  13496. });
  13497. function WebGLCubeRenderTarget(size, options, dummy) {
  13498. if (Number.isInteger(options)) {
  13499. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  13500. options = dummy;
  13501. }
  13502. WebGLRenderTarget.call(this, size, size, options);
  13503. options = options || {};
  13504. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  13505. this.texture._needsFlipEnvMap = false;
  13506. }
  13507. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  13508. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  13509. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  13510. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  13511. this.texture.type = texture.type;
  13512. this.texture.format = RGBAFormat; // see #18859
  13513. this.texture.encoding = texture.encoding;
  13514. this.texture.generateMipmaps = texture.generateMipmaps;
  13515. this.texture.minFilter = texture.minFilter;
  13516. this.texture.magFilter = texture.magFilter;
  13517. var shader = {
  13518. uniforms: {
  13519. tEquirect: {
  13520. value: null
  13521. }
  13522. },
  13523. vertexShader:
  13524. /* glsl */
  13525. "\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t#include <begin_vertex>\n\t\t\t\t#include <project_vertex>\n\n\t\t\t}\n\t\t",
  13526. fragmentShader:
  13527. /* glsl */
  13528. "\n\n\t\t\tuniform sampler2D tEquirect;\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t}\n\t\t"
  13529. };
  13530. var geometry = new BoxBufferGeometry(5, 5, 5);
  13531. var material = new ShaderMaterial({
  13532. name: 'CubemapFromEquirect',
  13533. uniforms: cloneUniforms(shader.uniforms),
  13534. vertexShader: shader.vertexShader,
  13535. fragmentShader: shader.fragmentShader,
  13536. side: BackSide,
  13537. blending: NoBlending
  13538. });
  13539. material.uniforms.tEquirect.value = texture;
  13540. var mesh = new Mesh(geometry, material);
  13541. var currentMinFilter = texture.minFilter; // Avoid blurred poles
  13542. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  13543. var camera = new CubeCamera(1, 10, this);
  13544. camera.update(renderer, mesh);
  13545. texture.minFilter = currentMinFilter;
  13546. mesh.geometry.dispose();
  13547. mesh.material.dispose();
  13548. return this;
  13549. };
  13550. WebGLCubeRenderTarget.prototype.clear = function (renderer, color, depth, stencil) {
  13551. var currentRenderTarget = renderer.getRenderTarget();
  13552. for (var i = 0; i < 6; i++) {
  13553. renderer.setRenderTarget(this, i);
  13554. renderer.clear(color, depth, stencil);
  13555. }
  13556. renderer.setRenderTarget(currentRenderTarget);
  13557. };
  13558. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  13559. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  13560. this.image = {
  13561. data: data || null,
  13562. width: width || 1,
  13563. height: height || 1
  13564. };
  13565. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13566. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13567. this.generateMipmaps = false;
  13568. this.flipY = false;
  13569. this.unpackAlignment = 1;
  13570. this.needsUpdate = true;
  13571. }
  13572. DataTexture.prototype = Object.create(Texture.prototype);
  13573. DataTexture.prototype.constructor = DataTexture;
  13574. DataTexture.prototype.isDataTexture = true;
  13575. var _sphere$1 = /*@__PURE__*/new Sphere();
  13576. var _vector$5 = /*@__PURE__*/new Vector3();
  13577. var Frustum = /*#__PURE__*/function () {
  13578. function Frustum(p0, p1, p2, p3, p4, p5) {
  13579. this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
  13580. }
  13581. var _proto = Frustum.prototype;
  13582. _proto.set = function set(p0, p1, p2, p3, p4, p5) {
  13583. var planes = this.planes;
  13584. planes[0].copy(p0);
  13585. planes[1].copy(p1);
  13586. planes[2].copy(p2);
  13587. planes[3].copy(p3);
  13588. planes[4].copy(p4);
  13589. planes[5].copy(p5);
  13590. return this;
  13591. };
  13592. _proto.clone = function clone() {
  13593. return new this.constructor().copy(this);
  13594. };
  13595. _proto.copy = function copy(frustum) {
  13596. var planes = this.planes;
  13597. for (var i = 0; i < 6; i++) {
  13598. planes[i].copy(frustum.planes[i]);
  13599. }
  13600. return this;
  13601. };
  13602. _proto.setFromProjectionMatrix = function setFromProjectionMatrix(m) {
  13603. var planes = this.planes;
  13604. var me = m.elements;
  13605. var me0 = me[0],
  13606. me1 = me[1],
  13607. me2 = me[2],
  13608. me3 = me[3];
  13609. var me4 = me[4],
  13610. me5 = me[5],
  13611. me6 = me[6],
  13612. me7 = me[7];
  13613. var me8 = me[8],
  13614. me9 = me[9],
  13615. me10 = me[10],
  13616. me11 = me[11];
  13617. var me12 = me[12],
  13618. me13 = me[13],
  13619. me14 = me[14],
  13620. me15 = me[15];
  13621. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  13622. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  13623. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  13624. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  13625. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  13626. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  13627. return this;
  13628. };
  13629. _proto.intersectsObject = function intersectsObject(object) {
  13630. var geometry = object.geometry;
  13631. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  13632. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  13633. return this.intersectsSphere(_sphere$1);
  13634. };
  13635. _proto.intersectsSprite = function intersectsSprite(sprite) {
  13636. _sphere$1.center.set(0, 0, 0);
  13637. _sphere$1.radius = 0.7071067811865476;
  13638. _sphere$1.applyMatrix4(sprite.matrixWorld);
  13639. return this.intersectsSphere(_sphere$1);
  13640. };
  13641. _proto.intersectsSphere = function intersectsSphere(sphere) {
  13642. var planes = this.planes;
  13643. var center = sphere.center;
  13644. var negRadius = -sphere.radius;
  13645. for (var i = 0; i < 6; i++) {
  13646. var distance = planes[i].distanceToPoint(center);
  13647. if (distance < negRadius) {
  13648. return false;
  13649. }
  13650. }
  13651. return true;
  13652. };
  13653. _proto.intersectsBox = function intersectsBox(box) {
  13654. var planes = this.planes;
  13655. for (var i = 0; i < 6; i++) {
  13656. var plane = planes[i]; // corner at max distance
  13657. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  13658. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  13659. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  13660. if (plane.distanceToPoint(_vector$5) < 0) {
  13661. return false;
  13662. }
  13663. }
  13664. return true;
  13665. };
  13666. _proto.containsPoint = function containsPoint(point) {
  13667. var planes = this.planes;
  13668. for (var i = 0; i < 6; i++) {
  13669. if (planes[i].distanceToPoint(point) < 0) {
  13670. return false;
  13671. }
  13672. }
  13673. return true;
  13674. };
  13675. return Frustum;
  13676. }();
  13677. function WebGLAnimation() {
  13678. var context = null;
  13679. var isAnimating = false;
  13680. var animationLoop = null;
  13681. var requestId = null;
  13682. function onAnimationFrame(time, frame) {
  13683. animationLoop(time, frame);
  13684. requestId = context.requestAnimationFrame(onAnimationFrame);
  13685. }
  13686. return {
  13687. start: function start() {
  13688. if (isAnimating === true) return;
  13689. if (animationLoop === null) return;
  13690. requestId = context.requestAnimationFrame(onAnimationFrame);
  13691. isAnimating = true;
  13692. },
  13693. stop: function stop() {
  13694. context.cancelAnimationFrame(requestId);
  13695. isAnimating = false;
  13696. },
  13697. setAnimationLoop: function setAnimationLoop(callback) {
  13698. animationLoop = callback;
  13699. },
  13700. setContext: function setContext(value) {
  13701. context = value;
  13702. }
  13703. };
  13704. }
  13705. function WebGLAttributes(gl, capabilities) {
  13706. var isWebGL2 = capabilities.isWebGL2;
  13707. var buffers = new WeakMap();
  13708. function createBuffer(attribute, bufferType) {
  13709. var array = attribute.array;
  13710. var usage = attribute.usage;
  13711. var buffer = gl.createBuffer();
  13712. gl.bindBuffer(bufferType, buffer);
  13713. gl.bufferData(bufferType, array, usage);
  13714. attribute.onUploadCallback();
  13715. var type = 5126;
  13716. if (array instanceof Float32Array) {
  13717. type = 5126;
  13718. } else if (array instanceof Float64Array) {
  13719. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  13720. } else if (array instanceof Uint16Array) {
  13721. if (attribute.isFloat16BufferAttribute) {
  13722. if (isWebGL2) {
  13723. type = 5131;
  13724. } else {
  13725. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  13726. }
  13727. } else {
  13728. type = 5123;
  13729. }
  13730. } else if (array instanceof Int16Array) {
  13731. type = 5122;
  13732. } else if (array instanceof Uint32Array) {
  13733. type = 5125;
  13734. } else if (array instanceof Int32Array) {
  13735. type = 5124;
  13736. } else if (array instanceof Int8Array) {
  13737. type = 5120;
  13738. } else if (array instanceof Uint8Array) {
  13739. type = 5121;
  13740. }
  13741. return {
  13742. buffer: buffer,
  13743. type: type,
  13744. bytesPerElement: array.BYTES_PER_ELEMENT,
  13745. version: attribute.version
  13746. };
  13747. }
  13748. function updateBuffer(buffer, attribute, bufferType) {
  13749. var array = attribute.array;
  13750. var updateRange = attribute.updateRange;
  13751. gl.bindBuffer(bufferType, buffer);
  13752. if (updateRange.count === -1) {
  13753. // Not using update ranges
  13754. gl.bufferSubData(bufferType, 0, array);
  13755. } else {
  13756. if (isWebGL2) {
  13757. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  13758. } else {
  13759. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  13760. }
  13761. updateRange.count = -1; // reset range
  13762. }
  13763. } //
  13764. function get(attribute) {
  13765. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  13766. return buffers.get(attribute);
  13767. }
  13768. function remove(attribute) {
  13769. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  13770. var data = buffers.get(attribute);
  13771. if (data) {
  13772. gl.deleteBuffer(data.buffer);
  13773. buffers.delete(attribute);
  13774. }
  13775. }
  13776. function update(attribute, bufferType) {
  13777. if (attribute.isGLBufferAttribute) {
  13778. var cached = buffers.get(attribute);
  13779. if (!cached || cached.version < attribute.version) {
  13780. buffers.set(attribute, {
  13781. buffer: attribute.buffer,
  13782. type: attribute.type,
  13783. bytesPerElement: attribute.elementSize,
  13784. version: attribute.version
  13785. });
  13786. }
  13787. return;
  13788. }
  13789. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  13790. var data = buffers.get(attribute);
  13791. if (data === undefined) {
  13792. buffers.set(attribute, createBuffer(attribute, bufferType));
  13793. } else if (data.version < attribute.version) {
  13794. updateBuffer(data.buffer, attribute, bufferType);
  13795. data.version = attribute.version;
  13796. }
  13797. }
  13798. return {
  13799. get: get,
  13800. remove: remove,
  13801. update: update
  13802. };
  13803. }
  13804. var PlaneBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  13805. _inheritsLoose(PlaneBufferGeometry, _BufferGeometry);
  13806. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  13807. var _this;
  13808. if (width === void 0) {
  13809. width = 1;
  13810. }
  13811. if (height === void 0) {
  13812. height = 1;
  13813. }
  13814. if (widthSegments === void 0) {
  13815. widthSegments = 1;
  13816. }
  13817. if (heightSegments === void 0) {
  13818. heightSegments = 1;
  13819. }
  13820. _this = _BufferGeometry.call(this) || this;
  13821. _this.type = 'PlaneBufferGeometry';
  13822. _this.parameters = {
  13823. width: width,
  13824. height: height,
  13825. widthSegments: widthSegments,
  13826. heightSegments: heightSegments
  13827. };
  13828. var width_half = width / 2;
  13829. var height_half = height / 2;
  13830. var gridX = Math.floor(widthSegments);
  13831. var gridY = Math.floor(heightSegments);
  13832. var gridX1 = gridX + 1;
  13833. var gridY1 = gridY + 1;
  13834. var segment_width = width / gridX;
  13835. var segment_height = height / gridY; //
  13836. var indices = [];
  13837. var vertices = [];
  13838. var normals = [];
  13839. var uvs = [];
  13840. for (var iy = 0; iy < gridY1; iy++) {
  13841. var y = iy * segment_height - height_half;
  13842. for (var ix = 0; ix < gridX1; ix++) {
  13843. var x = ix * segment_width - width_half;
  13844. vertices.push(x, -y, 0);
  13845. normals.push(0, 0, 1);
  13846. uvs.push(ix / gridX);
  13847. uvs.push(1 - iy / gridY);
  13848. }
  13849. }
  13850. for (var _iy = 0; _iy < gridY; _iy++) {
  13851. for (var _ix = 0; _ix < gridX; _ix++) {
  13852. var a = _ix + gridX1 * _iy;
  13853. var b = _ix + gridX1 * (_iy + 1);
  13854. var c = _ix + 1 + gridX1 * (_iy + 1);
  13855. var d = _ix + 1 + gridX1 * _iy;
  13856. indices.push(a, b, d);
  13857. indices.push(b, c, d);
  13858. }
  13859. }
  13860. _this.setIndex(indices);
  13861. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  13862. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  13863. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  13864. return _this;
  13865. }
  13866. return PlaneBufferGeometry;
  13867. }(BufferGeometry);
  13868. var alphamap_fragment = /* glsl */
  13869. "\n#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  13870. var alphamap_pars_fragment = /* glsl */
  13871. "\n#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n";
  13872. var alphatest_fragment = /* glsl */
  13873. "\n#ifdef ALPHATEST\n\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  13874. var aomap_fragment = /* glsl */
  13875. "\n#ifdef USE_AOMAP\n\n\t// reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\n\t#endif\n\n#endif\n";
  13876. var aomap_pars_fragment = /* glsl */
  13877. "\n#ifdef USE_AOMAP\n\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n\n#endif\n";
  13878. var begin_vertex = /* glsl */
  13879. "\nvec3 transformed = vec3( position );\n";
  13880. var beginnormal_vertex = /* glsl */
  13881. "\nvec3 objectNormal = vec3( normal );\n\n#ifdef USE_TANGENT\n\n\tvec3 objectTangent = vec3( tangent.xyz );\n\n#endif\n";
  13882. var bsdfs = /* glsl */
  13883. "\n\n// Analytical approximation of the DFG LUT, one half of the\n// split-sum approximation used in indirect specular lighting.\n// via 'environmentBRDF' from \"Physically Based Shading on Mobile\"\n// https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\n\tvec4 r = roughness * c0 + c1;\n\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n\n}\n\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\n\t// based upon Frostbite 3 Moving to Physically-based Rendering\n\t// page 32, equation 26: E[window1]\n\t// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\n\t// this is intended to be used on spot and point lights who are represented as luminous intensity\n\t// but who must be converted to luminous irradiance for surface lighting calculation\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\n\tif( cutoffDistance > 0.0 ) {\n\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\n\t}\n\n\treturn distanceFalloff;\n\n#else\n\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n\t}\n\n\treturn 1.0;\n\n#endif\n\n}\n\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\n\treturn RECIPROCAL_PI * diffuseColor;\n\n} // validated\n\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n\n} // validated\n\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\n\t// See F_Schlick\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\n\treturn Fr * fresnel + F0;\n\n}\n\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney\u2019s reparameterization\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\t// geometry term (normalized) = G(l)\u22C5G(v) / 4(n\u22C5l)(n\u22C5v)\n\t// also see #12151\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\n\treturn 1.0 / ( gl * gv );\n\n} // validated\n\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n\n}\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney\u2019s reparameterization\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\n\tfloat D = D_GGX( alpha, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// Rect Area Light\n\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\n// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\n// code: https://github.com/selfshadow/ltc_code/\n\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\n\tfloat dotNV = saturate( dot( N, V ) );\n\n\t// texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\n\treturn uv;\n\n}\n\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\n\t// Real-Time Area Lighting: a Journey from Research to Production (p.102)\n\t// An approximation of the form factor of a horizon-clipped rectangle.\n\n\tfloat l = length( f );\n\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n\n}\n\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\n\tfloat x = dot( v1, v2 );\n\n\tfloat y = abs( x );\n\n\t// rational polynomial approximation to theta / sin( theta ) / 2PI\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\n\treturn cross( v1, v2 ) * theta_sintheta;\n\n}\n\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\n\t// bail if point is on back side of plane of light\n\t// assumes ccw winding order of light vertices\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\n\t// construct orthonormal basis around N\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 ); // negated from paper; possibly due to a different handedness of world coordinate system\n\n\t// compute transform\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\n\t// transform rect\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\n\t// project rect onto sphere\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\n\t// calculate vector form factor\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\n\t// adjust for horizon clipping\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\n/*\n\t// alternate method of adjusting for horizon clipping (see referece)\n\t// refactoring required\n\tfloat len = length( vectorFormFactor );\n\tfloat z = vectorFormFactor.z / len;\n\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\n\t// tabulated horizon-clipped sphere, apparently...\n\tvec2 uv = vec2( z * 0.5 + 0.5, len );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\n\tfloat scale = texture2D( ltc_2, uv ).w;\n\n\tfloat result = len * scale;\n*/\n\n\treturn vec3( result );\n\n}\n\n// End Rect Area Light\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\n\treturn specularColor * brdf.x + brdf.y;\n\n} // validated\n\n// Fdez-Ag\xFCera's \"Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting\"\n// Approximates multiscattering in order to preserve energy.\n// http://www.jcgt.org/published/0008/01/03/\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619; // 1/21\n\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n\n}\n\nfloat G_BlinnPhong_Implicit( /* const in float dotNL, const in float dotNV */ ) {\n\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\n\treturn 0.25;\n\n}\n\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\n\tfloat G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\n\treturn F * ( G * D );\n\n} // validated\n\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\n\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n\n#if defined( USE_SHEEN )\n\n// https://github.com/google/filament/blob/master/shaders/src/brdf.fs#L94\nfloat D_Charlie(float roughness, float NoH) {\n\t// Estevez and Kulla 2017, \"Production Friendly Microfacet Sheen BRDF\"\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16\n\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\n\n// https://github.com/google/filament/blob/master/shaders/src/brdf.fs#L136\nfloat V_Neubelt(float NoV, float NoL) {\n\t// Neubelt and Pettineo 2013, \"Crafting a Next-gen Material Pipeline for The Order: 1886\"\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\n\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n\n}\n\n#endif\n";
  13884. var bumpmap_pars_fragment = /* glsl */
  13885. "\n#ifdef USE_BUMPMAP\n\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\n\t// Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen\n\t// http://api.unrealengine.com/attachments/Engine/Rendering/LightingAndShadows/BumpMappingWithoutTangentSpace/mm_sfgrad_bump.pdf\n\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n\tvec2 dHdxy_fwd() {\n\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n\t\treturn vec2( dBx, dBy );\n\n\t}\n\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\t\t// normalized\n\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\n\t}\n\n#endif\n";
  13886. var clipping_planes_fragment = /* glsl */
  13887. "\n#if NUM_CLIPPING_PLANES > 0\n\n\tvec4 plane;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\n\t\tbool clipped = true;\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\n\t\tif ( clipped ) discard;\n\n\t#endif\n\n#endif\n";
  13888. var clipping_planes_pars_fragment = /* glsl */
  13889. "\n#if NUM_CLIPPING_PLANES > 0\n\n\tvarying vec3 vClipPosition;\n\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n\n#endif\n";
  13890. var clipping_planes_pars_vertex = /* glsl */
  13891. "\n#if NUM_CLIPPING_PLANES > 0\n\n\tvarying vec3 vClipPosition;\n\n#endif\n";
  13892. var clipping_planes_vertex = /* glsl */
  13893. "\n#if NUM_CLIPPING_PLANES > 0\n\n\tvClipPosition = - mvPosition.xyz;\n\n#endif\n";
  13894. var color_fragment = /* glsl */
  13895. "\n#ifdef USE_COLOR\n\n\tdiffuseColor.rgb *= vColor;\n\n#endif\n";
  13896. var color_pars_fragment = /* glsl */
  13897. "\n#ifdef USE_COLOR\n\n\tvarying vec3 vColor;\n\n#endif\n";
  13898. var color_pars_vertex = /* glsl */
  13899. "\n#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\n\tvarying vec3 vColor;\n\n#endif\n";
  13900. var color_vertex = /* glsl */
  13901. "\n#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\n\tvColor = vec3( 1.0 );\n\n#endif\n\n#ifdef USE_COLOR\n\n\tvColor.xyz *= color.xyz;\n\n#endif\n\n#ifdef USE_INSTANCING_COLOR\n\n\tvColor.xyz *= instanceColor.xyz;\n\n#endif\n";
  13902. var common = /* glsl */
  13903. "\n#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n\n#ifndef saturate\n// <tonemapping_pars_fragment> may have defined saturate() already\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\n\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\n\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n}\n\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t// dir can be either a direction vector or a normal vector\n\t// upper-left 3x3 of matrix is assumed to be orthogonal\n\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\n\treturn - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n\nmat3 transposeMat3( const in mat3 m ) {\n\n\tmat3 tmp;\n\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\n\treturn tmp;\n\n}\n\n// https://en.wikipedia.org/wiki/Relative_luminance\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\n\treturn dot( weights, color.rgb );\n\n}\n\nbool isPerspectiveMatrix( mat4 m ) {\n\n\treturn m[ 2 ][ 3 ] == - 1.0;\n\n}\n\nvec2 equirectUv( in vec3 dir ) {\n\n\t// dir is assumed to be unit length\n\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\n\treturn vec2( u, v );\n\n}\n";
  13904. var cube_uv_reflection_fragment = /* glsl */
  13905. "\n#ifdef ENVMAP_TYPE_CUBE_UV\n\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\n\t// These shader functions convert between the UV coordinates of a single face of\n\t// a cubemap, the 0-5 integer index of a cube face, and the direction vector for\n\t// sampling a textureCube (not generally normalized ).\n\n\tfloat getFace( vec3 direction ) {\n\n\t\tvec3 absDirection = abs( direction );\n\n\t\tfloat face = - 1.0;\n\n\t\tif ( absDirection.x > absDirection.z ) {\n\n\t\t\tif ( absDirection.x > absDirection.y )\n\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\n\t\t\telse\n\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\n\t\t} else {\n\n\t\t\tif ( absDirection.z > absDirection.y )\n\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\n\t\t\telse\n\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\n\t\t}\n\n\t\treturn face;\n\n\t}\n\n\t// RH coordinate system; PMREM face-indexing convention\n\tvec2 getUV( vec3 direction, float face ) {\n\n\t\tvec2 uv;\n\n\t\tif ( face == 0.0 ) {\n\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x ); // pos x\n\n\t\t} else if ( face == 1.0 ) {\n\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y ); // pos y\n\n\t\t} else if ( face == 2.0 ) {\n\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z ); // pos z\n\n\t\t} else if ( face == 3.0 ) {\n\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x ); // neg x\n\n\t\t} else if ( face == 4.0 ) {\n\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y ); // neg y\n\n\t\t} else {\n\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z ); // neg z\n\n\t\t}\n\n\t\treturn 0.5 * ( uv + 1.0 );\n\n\t}\n\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\n\t\tfloat face = getFace( direction );\n\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\n\t\tfloat faceSize = exp2( mipInt );\n\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\n\t\tvec2 f = fract( uv );\n\n\t\tuv += 0.5 - f;\n\n\t\tif ( face > 2.0 ) {\n\n\t\t\tuv.y += faceSize;\n\n\t\t\tface -= 3.0;\n\n\t\t}\n\n\t\tuv.x += face * faceSize;\n\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\n\t\t}\n\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\n\t\tuv *= texelSize;\n\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\n\t\tuv.x += texelSize;\n\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\n\t\tuv.y += texelSize;\n\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\n\t\tuv.x -= texelSize;\n\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\n\t\tvec3 tm = mix( tl, tr, f.x );\n\n\t\tvec3 bm = mix( bl, br, f.x );\n\n\t\treturn mix( tm, bm, f.y );\n\n\t}\n\n\t// These defines must match with PMREMGenerator\n\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\n\tfloat roughnessToMip( float roughness ) {\n\n\t\tfloat mip = 0.0;\n\n\t\tif ( roughness >= r1 ) {\n\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\n\t\t} else if ( roughness >= r4 ) {\n\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\n\t\t} else if ( roughness >= r5 ) {\n\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\n\t\t} else if ( roughness >= r6 ) {\n\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\n\t\t} else {\n\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness ); // 1.16 = 1.79^0.25\n\t\t}\n\n\t\treturn mip;\n\n\t}\n\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\n\t\tfloat mipF = fract( mip );\n\n\t\tfloat mipInt = floor( mip );\n\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\n\t\tif ( mipF == 0.0 ) {\n\n\t\t\treturn vec4( color0, 1.0 );\n\n\t\t} else {\n\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\n\t\t}\n\n\t}\n\n#endif\n";
  13906. var defaultnormal_vertex = /* glsl */
  13907. "\nvec3 transformedNormal = objectNormal;\n\n#ifdef USE_INSTANCING\n\n\t// this is in lieu of a per-instance normal-matrix\n\t// shear transforms in the instance matrix are not supported\n\n\tmat3 m = mat3( instanceMatrix );\n\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\n\ttransformedNormal = m * transformedNormal;\n\n#endif\n\ntransformedNormal = normalMatrix * transformedNormal;\n\n#ifdef FLIP_SIDED\n\n\ttransformedNormal = - transformedNormal;\n\n#endif\n\n#ifdef USE_TANGENT\n\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\n\t#ifdef FLIP_SIDED\n\n\t\ttransformedTangent = - transformedTangent;\n\n\t#endif\n\n#endif\n";
  13908. var displacementmap_pars_vertex = /* glsl */
  13909. "\n#ifdef USE_DISPLACEMENTMAP\n\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n\n#endif\n";
  13910. var displacementmap_vertex = /* glsl */
  13911. "\n#ifdef USE_DISPLACEMENTMAP\n\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n\n#endif\n";
  13912. var emissivemap_fragment = /* glsl */
  13913. "\n#ifdef USE_EMISSIVEMAP\n\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n\n#endif\n";
  13914. var emissivemap_pars_fragment = /* glsl */
  13915. "\n#ifdef USE_EMISSIVEMAP\n\n\tuniform sampler2D emissiveMap;\n\n#endif\n";
  13916. var encodings_fragment = /* glsl */
  13917. "\ngl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  13918. var encodings_pars_fragment = /* glsl */
  13919. "\n// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\n\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\n\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\n\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\n\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\n\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\n\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\n\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n\t// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\n\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\n\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\n\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\t// NOTE: The implementation with min causes the shader to not compile on\n\t// a common Alcatel A502DL in Chrome 78/Android 8.1. Some research suggests \n\t// that the chipset is Mediatek MT6739 w/ IMG PowerVR GE8100 GPU.\n\t// D = min( floor( D ) / 255.0, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\n\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\n\n// M matrix, for encoding\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\n\n// Inverse M matrix, for decoding\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}\n";
  13920. var envmap_fragment = /* glsl */
  13921. "\n#ifdef USE_ENVMAP\n\n\t#ifdef ENV_WORLDPOS\n\n\t\tvec3 cameraToFrag;\n\n\t\tif ( isOrthographic ) {\n\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\n\t\t} else {\n\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\n\t\t}\n\n\t\t// Transforming Normal Vectors with the Inverse Transformation\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#else\n\n\t\tvec3 reflectVec = vReflect;\n\n\t#endif\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\n\t#else\n\n\t\tvec4 envColor = vec4( 0.0 );\n\n\t#endif\n\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\n\t\tenvColor = envMapTexelToLinear( envColor );\n\n\t#endif\n\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n\t#endif\n\n#endif\n";
  13922. var envmap_common_pars_fragment = /* glsl */
  13923. "\n#ifdef USE_ENVMAP\n\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif\n";
  13924. var envmap_pars_fragment = /* glsl */
  13925. "\n#ifdef USE_ENVMAP\n\n\tuniform float reflectivity;\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n\t\t#define ENV_WORLDPOS\n\n\t#endif\n\n\t#ifdef ENV_WORLDPOS\n\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n\n#endif\n";
  13926. var envmap_pars_vertex = /* glsl */
  13927. "\n#ifdef USE_ENVMAP\n\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\n\t\t#define ENV_WORLDPOS\n\n\t#endif\n\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\n\t#else\n\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\n\t#endif\n\n#endif\n";
  13928. var envmap_vertex = /* glsl */
  13929. "\n#ifdef USE_ENVMAP\n\n\t#ifdef ENV_WORLDPOS\n\n\t\tvWorldPosition = worldPosition.xyz;\n\n\t#else\n\n\t\tvec3 cameraToVertex;\n\n\t\tif ( isOrthographic ) {\n\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\n\t\t} else {\n\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n\t\t}\n\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\n\t\t#else\n\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n";
  13930. var fog_vertex = /* glsl */
  13931. "\n#ifdef USE_FOG\n\n\tfogDepth = - mvPosition.z;\n\n#endif\n";
  13932. var fog_pars_vertex = /* glsl */
  13933. "\n#ifdef USE_FOG\n\n\tvarying float fogDepth;\n\n#endif\n";
  13934. var fog_fragment = /* glsl */
  13935. "\n#ifdef USE_FOG\n\n\t#ifdef FOG_EXP2\n\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\n\t#else\n\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\n\t#endif\n\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\n#endif\n";
  13936. var fog_pars_fragment = /* glsl */
  13937. "\n#ifdef USE_FOG\n\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\n\t#ifdef FOG_EXP2\n\n\t\tuniform float fogDensity;\n\n\t#else\n\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\n\t#endif\n\n#endif\n";
  13938. var gradientmap_pars_fragment = /* glsl */
  13939. "\n\n#ifdef USE_GRADIENTMAP\n\n\tuniform sampler2D gradientMap;\n\n#endif\n\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\n\t// dotNL will be from -1.0 to 1.0\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\n\t#ifdef USE_GRADIENTMAP\n\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\n\t#else\n\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\n\t#endif\n\n}\n";
  13940. var lightmap_fragment = /* glsl */
  13941. "\n#ifdef USE_LIGHTMAP\n\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\n#endif\n";
  13942. var lightmap_pars_fragment = /* glsl */
  13943. "\n#ifdef USE_LIGHTMAP\n\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n\n#endif\n";
  13944. var lights_lambert_vertex = /* glsl */
  13945. "\nvec3 diffuse = vec3( 1.0 );\n\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\n\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\n\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\n\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\n\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n\n#ifdef DOUBLE_SIDED\n\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n\n#endif\n\n#if NUM_POINT_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if NUM_SPOT_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n/*\n#if NUM_RECT_AREA_LIGHTS > 0\n\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n\t\t// TODO (abelnation): implement\n\n\t}\n\n#endif\n*/\n\n#if NUM_DIR_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\n\t\t#endif\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if NUM_HEMI_LIGHTS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\n\t\t#endif\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n";
  13946. var lights_pars_begin = /* glsl */
  13947. "\nuniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\n\n// get the irradiance (radiance convolved with cosine lobe) at the point 'normal' on the unit sphere\n// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\n\t// normal is assumed to have unit length\n\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\n\t// band 0\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\n\t// band 1\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\n\t// band 2\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\n\treturn result;\n\n}\n\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\n\treturn irradiance;\n\n}\n\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\n\tvec3 irradiance = ambientLightColor;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI;\n\n\t#endif\n\n\treturn irradiance;\n\n}\n\n#if NUM_DIR_LIGHTS > 0\n\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\n\t}\n\n#endif\n\n\n#if NUM_POINT_LIGHTS > 0\n\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\n\t}\n\n#endif\n\n\n#if NUM_SPOT_LIGHTS > 0\n\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\n\t\tif ( angleCos > spotLight.coneCos ) {\n\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\n\t\t} else {\n\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\n\t\t}\n\t}\n\n#endif\n\n\n#if NUM_RECT_AREA_LIGHTS > 0\n\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\n\t// Pre-computed values of LinearTransformedCosine approximation of BRDF\n\t// BRDF approximation Texture is 64x64\n\tuniform sampler2D ltc_1; // RGBA Float\n\tuniform sampler2D ltc_2; // RGBA Float\n\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n\n#endif\n\n\n#if NUM_HEMI_LIGHTS > 0\n\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tirradiance *= PI;\n\n\t\t#endif\n\n\t\treturn irradiance;\n\n\t}\n\n#endif\n";
  13948. var envmap_physical_pars_fragment = /* glsl */
  13949. "\n#if defined( USE_ENVMAP )\n\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\n\tvec3 getLightProbeIndirectIrradiance( /*const in SpecularLightProbe specularLightProbe,*/ const in GeometricContext geometry, const in int maxMIPLevel ) {\n\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#else\n\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\n\t\t#else\n\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\n\t\t#endif\n\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\n\t}\n\n\t// Trowbridge-Reitz distribution to Mip level, following the logic of http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\n\t\t// clamp to allowable LOD ranges.\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\n\t}\n\n\tvec3 getLightProbeIndirectRadiance( /*const in SpecularLightProbe specularLightProbe,*/ const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\n\t\t\t// Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\n\t\t#else\n\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\n\t\t#endif\n\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#else\n\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\n\t\t\t#endif\n\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\n\t\t#endif\n\n\t\treturn envMapColor.rgb * envMapIntensity;\n\n\t}\n\n#endif\n";
  13950. var lights_toon_fragment = /* glsl */
  13951. "\nToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\n";
  13952. var lights_toon_pars_fragment = /* glsl */
  13953. "\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct ToonMaterial {\n\n\tvec3 diffuseColor;\n\n};\n\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n\n#define Material_LightProbeLOD( material )\t(0)\n";
  13954. var lights_phong_fragment = /* glsl */
  13955. "\nBlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  13956. var lights_phong_pars_fragment = /* glsl */
  13957. "\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n\nstruct BlinnPhongMaterial {\n\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n\n};\n\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n\n}\n\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n\n#define Material_LightProbeLOD( material )\t(0)\n";
  13958. var lights_physical_fragment = /* glsl */
  13959. "\nPhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\n\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\n\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.\nmaterial.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n\n#ifdef REFLECTIVITY\n\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\n#else\n\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n\n#endif\n\n#ifdef CLEARCOAT\n\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\n\t#ifdef USE_CLEARCOATMAP\n\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\n\t#endif\n\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\n\t#endif\n\n\tmaterial.clearcoat = saturate( material.clearcoat ); // Burley clearcoat model\n\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n\n#endif\n\n#ifdef USE_SHEEN\n\n\tmaterial.sheenColor = sheen;\n\n#endif\n";
  13960. var lights_physical_pars_fragment = /* glsl */
  13961. "\nstruct PhysicalMaterial {\n\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n\n};\n\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\n\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n\n}\n\n#if NUM_RECT_AREA_LIGHTS > 0\n\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight; // counterclockwise; light shines in local neg z direction\n\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\n\t\t// LTC Fresnel Approximation by Stephen Hill\n\t\t// http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\n\t}\n\n#endif\n\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\n\tvec3 irradiance = dotNL * directLight.color;\n\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\tirradiance *= PI; // punctual light\n\n\t#endif\n\n\t#ifdef CLEARCOAT\n\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tccIrradiance *= PI; // punctual light\n\n\t\t#endif\n\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\n\t#else\n\n\t\tfloat clearcoatDHR = 0.0;\n\n\t#endif\n\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n}\n\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\n\t#ifdef CLEARCOAT\n\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\n\t#else\n\n\t\tfloat clearcoatDHR = 0.0;\n\n\t#endif\n\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\n\t// Both indirect specular and indirect diffuse light accumulate here\n\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n\n}\n\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n\n// ref: https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n\n}\n";
  13962. var lights_fragment_begin = /* glsl */
  13963. "\n/**\n * This is a template that can be used to light a material, it uses pluggable\n * RenderEquations (RE)for specific lighting scenarios.\n *\n * Instructions for use:\n * - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined\n * - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ???\n * - Create a material parameter that is to be passed as the third parameter to your lighting functions.\n *\n * TODO:\n * - Add area light support.\n * - Add sphere light support.\n * - Add diffuse light probe (irradiance cubemap) support.\n */\n\nGeometricContext geometry;\n\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n#ifdef CLEARCOAT\n\n\tgeometry.clearcoatNormal = clearcoatNormal;\n\n#endif\n\nIncidentLight directLight;\n\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n\t\tpointLight = pointLights[ i ];\n\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n\t\tspotLight = spotLights[ i ];\n\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\tdirectionalLight = directionalLights[ i ];\n\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\n\tRectAreaLight rectAreaLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\n\t}\n\t#pragma unroll_loop_end\n\n#endif\n\n#if defined( RE_IndirectDiffuse )\n\n\tvec3 iblIrradiance = vec3( 0.0 );\n\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\n\t#endif\n\n#endif\n\n#if defined( RE_IndirectSpecular )\n\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n\n#endif\n";
  13964. var lights_fragment_maps = /* glsl */
  13965. "\n#if defined( RE_IndirectDiffuse )\n\n\t#ifdef USE_LIGHTMAP\n\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\n\n\t\t#endif\n\n\t\tirradiance += lightMapIrradiance;\n\n\t#endif\n\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( /*lightProbe,*/ geometry, maxMipLevel );\n\n\t#endif\n\n#endif\n\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\n\tradiance += getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\n\t#ifdef CLEARCOAT\n\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( /*specularLightProbe,*/ geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\n\t#endif\n\n#endif\n";
  13966. var lights_fragment_end = /* glsl */
  13967. "\n#if defined( RE_IndirectDiffuse )\n\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n\n#endif\n\n#if defined( RE_IndirectSpecular )\n\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n\n#endif\n";
  13968. var logdepthbuf_fragment = /* glsl */
  13969. "\n#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\n\t// Doing a strict comparison with == 1.0 can cause noise artifacts\n\t// on some platforms. See issue #17623.\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n\n#endif\n";
  13970. var logdepthbuf_pars_fragment = /* glsl */
  13971. "\n#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n\n#endif\n";
  13972. var logdepthbuf_pars_vertex = /* glsl */
  13973. "\n#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\n\t#else\n\n\t\tuniform float logDepthBufFC;\n\n\t#endif\n\n#endif\n";
  13974. var logdepthbuf_vertex = /* glsl */
  13975. "\n#ifdef USE_LOGDEPTHBUF\n\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\n\t#else\n\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\n\t\t\tgl_Position.z *= gl_Position.w;\n\n\t\t}\n\n\t#endif\n\n#endif\n";
  13976. var map_fragment = /* glsl */
  13977. "\n#ifdef USE_MAP\n\n\tvec4 texelColor = texture2D( map, vUv );\n\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n\n#endif\n";
  13978. var map_pars_fragment = /* glsl */
  13979. "\n#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n";
  13980. var map_particle_fragment = /* glsl */
  13981. "\n#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\n#endif\n\n#ifdef USE_MAP\n\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n\n#endif\n\n#ifdef USE_ALPHAMAP\n\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n\n#endif\n";
  13982. var map_particle_pars_fragment = /* glsl */
  13983. "\n#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\n\tuniform mat3 uvTransform;\n\n#endif\n\n#ifdef USE_MAP\n\n\tuniform sampler2D map;\n\n#endif\n\n#ifdef USE_ALPHAMAP\n\n\tuniform sampler2D alphaMap;\n\n#endif\n";
  13984. var metalnessmap_fragment = /* glsl */
  13985. "\nfloat metalnessFactor = metalness;\n\n#ifdef USE_METALNESSMAP\n\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\n\t// reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n\tmetalnessFactor *= texelMetalness.b;\n\n#endif\n";
  13986. var metalnessmap_pars_fragment = /* glsl */
  13987. "\n#ifdef USE_METALNESSMAP\n\n\tuniform sampler2D metalnessMap;\n\n#endif\n";
  13988. var morphnormal_vertex = /* glsl */
  13989. "\n#ifdef USE_MORPHNORMALS\n\n\t// morphTargetBaseInfluence is set based on BufferGeometry.morphTargetsRelative value:\n\t// When morphTargetsRelative is false, this is set to 1 - sum(influences); this results in normal = sum((target - base) * influence)\n\t// When morphTargetsRelative is true, this is set to 1; as a result, all morph targets are simply added to the base after weighting\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\n#endif\n";
  13990. var morphtarget_pars_vertex = /* glsl */
  13991. "\n#ifdef USE_MORPHTARGETS\n\n\tuniform float morphTargetBaseInfluence;\n\n\t#ifndef USE_MORPHNORMALS\n\n\t\tuniform float morphTargetInfluences[ 8 ];\n\n\t#else\n\n\t\tuniform float morphTargetInfluences[ 4 ];\n\n\t#endif\n\n#endif\n";
  13992. var morphtarget_vertex = /* glsl */
  13993. "\n#ifdef USE_MORPHTARGETS\n\n\t// morphTargetBaseInfluence is set based on BufferGeometry.morphTargetsRelative value:\n\t// When morphTargetsRelative is false, this is set to 1 - sum(influences); this results in position = sum((target - base) * influence)\n\t// When morphTargetsRelative is true, this is set to 1; as a result, all morph targets are simply added to the base after weighting\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\n\t#ifndef USE_MORPHNORMALS\n\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\n\t#endif\n\n#endif\n";
  13994. var normal_fragment_begin = /* glsl */
  13995. "\n#ifdef FLAT_SHADED\n\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\n\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n\n#else\n\n\tvec3 normal = normalize( vNormal );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t#endif\n\n\t#ifdef USE_TANGENT\n\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\n\t\t#ifdef DOUBLE_SIDED\n\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t\t#endif\n\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\n\t\t#endif\n\n\t#endif\n\n#endif\n\n// non perturbed normal for clearcoat among others\n\nvec3 geometryNormal = normal;\n\n";
  13996. var normal_fragment_maps = /* glsl */
  13997. "\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n\t#ifdef FLIP_SIDED\n\n\t\tnormal = - normal;\n\n\t#endif\n\n\t#ifdef DOUBLE_SIDED\n\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t#endif\n\n\tnormal = normalize( normalMatrix * normal );\n\n#elif defined( TANGENTSPACE_NORMALMAP )\n\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\n\t#ifdef USE_TANGENT\n\n\t\tnormal = normalize( vTBN * mapN );\n\n\t#else\n\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\n\t#endif\n\n#elif defined( USE_BUMPMAP )\n\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n";
  13998. var normalmap_pars_fragment = /* glsl */
  13999. "\n#ifdef USE_NORMALMAP\n\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\n#endif\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n\tuniform mat3 normalMatrix;\n\n#endif\n\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\n\t// Per-Pixel Tangent Space Normal Mapping\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\n\t\tmat3 tsn = mat3( S, T, N );\n\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n\t\treturn normalize( tsn * mapN );\n\n\t}\n\n#endif\n";
  14000. var clearcoat_normal_fragment_begin = /* glsl */
  14001. "\n#ifdef CLEARCOAT\n\n\tvec3 clearcoatNormal = geometryNormal;\n\n#endif\n";
  14002. var clearcoat_normal_fragment_maps = /* glsl */
  14003. "\n#ifdef USE_CLEARCOAT_NORMALMAP\n\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\n\t#ifdef USE_TANGENT\n\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\n\t#else\n\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\n\t#endif\n\n#endif\n";
  14004. var clearcoat_pars_fragment = /* glsl */
  14005. "\n\n#ifdef USE_CLEARCOATMAP\n\n\tuniform sampler2D clearcoatMap;\n\n#endif\n\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\n\tuniform sampler2D clearcoatRoughnessMap;\n\n#endif\n\n#ifdef USE_CLEARCOAT_NORMALMAP\n\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n\n#endif\n";
  14006. var packing = /* glsl */
  14007. "\nvec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\n\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\n\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\n\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\n\nconst float ShiftRight8 = 1. / 256.;\n\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n}\n\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\n\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\n\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\n\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\n\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  14008. var premultiplied_alpha_fragment = /* glsl */
  14009. "\n#ifdef PREMULTIPLIED_ALPHA\n\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\n\tgl_FragColor.rgb *= gl_FragColor.a;\n\n#endif\n";
  14010. var project_vertex = /* glsl */
  14011. "\nvec4 mvPosition = vec4( transformed, 1.0 );\n\n#ifdef USE_INSTANCING\n\n\tmvPosition = instanceMatrix * mvPosition;\n\n#endif\n\nmvPosition = modelViewMatrix * mvPosition;\n\ngl_Position = projectionMatrix * mvPosition;\n";
  14012. var dithering_fragment = /* glsl */
  14013. "\n#ifdef DITHERING\n\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n\n#endif\n";
  14014. var dithering_pars_fragment = /* glsl */
  14015. "\n#ifdef DITHERING\n\n\t// based on https://www.shadertoy.com/view/MslGR8\n\tvec3 dithering( vec3 color ) {\n\t\t//Calculate grid position\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\n\t\t//Shift the individual colors differently, thus making it even harder to see the dithering pattern\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\n\t\t//modify shift acording to grid position.\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\n\t\t//shift the color by dither_shift\n\t\treturn color + dither_shift_RGB;\n\t}\n\n#endif\n";
  14016. var roughnessmap_fragment = /* glsl */
  14017. "\nfloat roughnessFactor = roughness;\n\n#ifdef USE_ROUGHNESSMAP\n\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\n\t// reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n\troughnessFactor *= texelRoughness.g;\n\n#endif\n";
  14018. var roughnessmap_pars_fragment = /* glsl */
  14019. "\n#ifdef USE_ROUGHNESSMAP\n\n\tuniform sampler2D roughnessMap;\n\n#endif\n";
  14020. var shadowmap_pars_fragment = /* glsl */
  14021. "\n#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): create uniforms for area light shadows\n\n\t#endif\n\t*/\n\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\n\t}\n\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\n\t}\n\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\n\t\tfloat occlusion = 1.0;\n\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\n\t\tfloat hard_shadow = step( compare , distribution.x ); // Hard Shadow\n\n\t\tif (hard_shadow != 1.0 ) {\n\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance ); // Chebeyshevs inequality\n\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); // 0.3 reduces light bleed\n\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\n\t\t}\n\t\treturn occlusion;\n\n\t}\n\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\n\t\tfloat shadow = 1.0;\n\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\n\t\t// if ( all( something, something ) ) using this instead\n\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n\t\tbool frustumTest = all( frustumTestVec );\n\n\t\tif ( frustumTest ) {\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#else // no percentage-closer filtering:\n\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\n\t\t#endif\n\n\t\t}\n\n\t\treturn shadow;\n\n\t}\n\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\n\t// 2D texture:\n\t//\n\t// xzXZ\n\t// y Y\n\t//\n\t// Y - Positive y direction\n\t// y - Negative y direction\n\t// X - Positive x direction\n\t// x - Negative x direction\n\t// Z - Positive z direction\n\t// z - Negative z direction\n\t//\n\t// Source and test bed:\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\n\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\n\t\t// Number of texels to avoid at the edge of each square\n\n\t\tvec3 absV = abs( v );\n\n\t\t// Intersect unit cube\n\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\n\t\t// Apply scale to avoid seams\n\n\t\t// two texels less per square (one texel will do for NEAREST)\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\n\t\t// Unwrap\n\n\t\t// space: -1 ... 1 range for each square\n\t\t//\n\t\t// #X##\t\tdim := ( 4 , 2 )\n\t\t// # #\t\tcenter := ( 1 , 1 )\n\n\t\tvec2 planar = v.xy;\n\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\n\t\tif ( absV.z >= almostOne ) {\n\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\n\t\t} else if ( absV.x >= almostOne ) {\n\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\n\t\t} else if ( absV.y >= almostOne ) {\n\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\n\t\t}\n\n\t\t// Transform to UV space\n\n\t\t// scale := 0.5 / dim\n\t\t// translate := ( center + 0.5 ) / dim\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\n\t}\n\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\n\t\t// the vector from the light to the world-space position of the fragment.\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\n\t\t// dp = normalized distance from light to fragment position\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); // need to clamp?\n\t\tdp += shadowBias;\n\n\t\t// bd3D = base direction 3D\n\t\tvec3 bd3D = normalize( lightToPosition );\n\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\n\t\t#else // no percentage-closer filtering\n\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\n\t\t#endif\n\n\t}\n\n#endif\n";
  14022. var shadowmap_pars_vertex = /* glsl */
  14023. "\n#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): uniforms for area light shadows\n\n\t#endif\n\t*/\n\n#endif\n";
  14024. var shadowmap_vertex = /* glsl */
  14025. "\n#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\n\t\t// Offsetting the position used for querying occlusion along the world normal can be used to reduce shadow acne.\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\n\t#endif\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): update vAreaShadowCoord with area light info\n\n\t#endif\n\t*/\n\n#endif\n";
  14026. var shadowmask_pars_fragment = /* glsl */
  14027. "\nfloat getShadowMask() {\n\n\tfloat shadow = 1.0;\n\n\t#ifdef USE_SHADOWMAP\n\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\n\tDirectionalLightShadow directionalLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\n\tSpotLightShadow spotLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\n\tPointLightShadow pointLight;\n\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\n\t}\n\t#pragma unroll_loop_end\n\n\t#endif\n\n\t/*\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\n\t\t// TODO (abelnation): update shadow for Area light\n\n\t#endif\n\t*/\n\n\t#endif\n\n\treturn shadow;\n\n}\n";
  14028. var skinbase_vertex = /* glsl */
  14029. "\n#ifdef USE_SKINNING\n\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif\n";
  14030. var skinning_pars_vertex = /* glsl */
  14031. "\n#ifdef USE_SKINNING\n\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\n\t#ifdef BONE_TEXTURE\n\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\n\t\t\ty = dy * ( y + 0.5 );\n\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\n\t\t\treturn bone;\n\n\t\t}\n\n\t#else\n\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\n\t\tmat4 getBoneMatrix( const in float i ) {\n\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\n\t\t}\n\n\t#endif\n\n#endif\n";
  14032. var skinning_vertex = /* glsl */
  14033. "\n#ifdef USE_SKINNING\n\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n\n#endif\n";
  14034. var skinnormal_vertex = /* glsl */
  14035. "\n#ifdef USE_SKINNING\n\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\n\t#ifdef USE_TANGENT\n\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\n\t#endif\n\n#endif\n";
  14036. var specularmap_fragment = /* glsl */
  14037. "\nfloat specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n\n#else\n\n\tspecularStrength = 1.0;\n\n#endif\n";
  14038. var specularmap_pars_fragment = /* glsl */
  14039. "\n#ifdef USE_SPECULARMAP\n\n\tuniform sampler2D specularMap;\n\n#endif\n";
  14040. var tonemapping_fragment = /* glsl */
  14041. "\n#if defined( TONE_MAPPING )\n\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n\n#endif\n";
  14042. var tonemapping_pars_fragment = /* glsl */
  14043. "\n#ifndef saturate\n// <common> may have defined saturate() already\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform float toneMappingExposure;\n\n// exposure only\nvec3 LinearToneMapping( vec3 color ) {\n\n\treturn toneMappingExposure * color;\n\n}\n\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\nvec3 ReinhardToneMapping( vec3 color ) {\n\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\n\t// optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n\n}\n\n// source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs\nvec3 RRTAndODTFit( vec3 v ) {\n\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n\n}\n\n// this implementation of ACES is modified to accommodate a brighter viewing environment.\n// the scale factor of 1/0.6 is subjective. see discussion in #19621.\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\n\t// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\n\t// ODT_SAT => XYZ => D60_2_D65 => sRGB\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\n\tcolor *= toneMappingExposure / 0.6;\n\n\tcolor = ACESInputMat * color;\n\n\t// Apply RRT and ODT\n\tcolor = RRTAndODTFit( color );\n\n\tcolor = ACESOutputMat * color;\n\n\t// Clamp to [0, 1]\n\treturn saturate( color );\n\n}\n\nvec3 CustomToneMapping( vec3 color ) { return color; }\n";
  14044. var transmissionmap_fragment = /* glsl */
  14045. "\n#ifdef USE_TRANSMISSIONMAP\n\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n\n#endif\n";
  14046. var transmissionmap_pars_fragment = /* glsl */
  14047. "\n#ifdef USE_TRANSMISSIONMAP\n\n\tuniform sampler2D transmissionMap;\n\n#endif\n";
  14048. var uv_pars_fragment = /* glsl */
  14049. "\n#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\n\tvarying vec2 vUv;\n\n#endif\n";
  14050. var uv_pars_vertex = /* glsl */
  14051. "\n#ifdef USE_UV\n\n\t#ifdef UVS_VERTEX_ONLY\n\n\t\tvec2 vUv;\n\n\t#else\n\n\t\tvarying vec2 vUv;\n\n\t#endif\n\n\tuniform mat3 uvTransform;\n\n#endif\n";
  14052. var uv_vertex = /* glsl */
  14053. "\n#ifdef USE_UV\n\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\n#endif\n";
  14054. var uv2_pars_fragment = /* glsl */
  14055. "\n#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvarying vec2 vUv2;\n\n#endif\n";
  14056. var uv2_pars_vertex = /* glsl */
  14057. "\n#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\n\tuniform mat3 uv2Transform;\n\n#endif\n";
  14058. var uv2_vertex = /* glsl */
  14059. "\n#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n\n#endif\n";
  14060. var worldpos_vertex = /* glsl */
  14061. "\n#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\n\t#ifdef USE_INSTANCING\n\n\t\tworldPosition = instanceMatrix * worldPosition;\n\n\t#endif\n\n\tworldPosition = modelMatrix * worldPosition;\n\n#endif\n";
  14062. var background_frag = /* glsl */
  14063. "\nuniform sampler2D t2D;\n\nvarying vec2 vUv;\n\nvoid main() {\n\n\tvec4 texColor = texture2D( t2D, vUv );\n\n\tgl_FragColor = mapTexelToLinear( texColor );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\n}\n";
  14064. var background_vert = /* glsl */
  14065. "\nvarying vec2 vUv;\nuniform mat3 uvTransform;\n\nvoid main() {\n\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n\n}\n";
  14066. var cube_frag = /* glsl */
  14067. "\n#include <envmap_common_pars_fragment>\nuniform float opacity;\n\nvarying vec3 vWorldDirection;\n\n#include <cube_uv_reflection_fragment>\n\nvoid main() {\n\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\n}\n";
  14068. var cube_vert = /* glsl */
  14069. "\nvarying vec3 vWorldDirection;\n\n#include <common>\n\nvoid main() {\n\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\n\tgl_Position.z = gl_Position.w; // set z to camera.far\n\n}\n";
  14070. var depth_frag = /* glsl */
  14071. "\n#if DEPTH_PACKING == 3200\n\n\tuniform float opacity;\n\n#endif\n\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvarying vec2 vHighPrecisionZW;\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tdiffuseColor.a = opacity;\n\n\t#endif\n\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\n\t#include <logdepthbuf_fragment>\n\n\t// Higher precision equivalent of gl_FragCoord.z. This assumes depthRange has been left to its default values.\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\n\t#if DEPTH_PACKING == 3200\n\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\n\t#elif DEPTH_PACKING == 3201\n\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\n\t#endif\n\n}\n";
  14072. var depth_vert = /* glsl */
  14073. "\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n// This is used for computing an equivalent of gl_FragCoord.z that is as high precision as possible.\n// Some platforms compute gl_FragCoord at a lower precision which makes the manually computed value better for\n// depth-based postprocessing effects. Reproduced on iPad with A10 processor / iPadOS 13.3.1.\nvarying vec2 vHighPrecisionZW;\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\t#include <skinbase_vertex>\n\n\t#ifdef USE_DISPLACEMENTMAP\n\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvHighPrecisionZW = gl_Position.zw;\n\n}\n";
  14074. var distanceRGBA_frag = /* glsl */
  14075. "\n#define DISTANCE\n\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main () {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( 1.0 );\n\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist ); // clamp to [ 0, 1 ]\n\n\tgl_FragColor = packDepthToRGBA( dist );\n\n}\n";
  14076. var distanceRGBA_vert = /* glsl */
  14077. "\n#define DISTANCE\n\nvarying vec3 vWorldPosition;\n\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\t#include <skinbase_vertex>\n\n\t#ifdef USE_DISPLACEMENTMAP\n\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvWorldPosition = worldPosition.xyz;\n\n}\n";
  14078. var equirect_frag = /* glsl */
  14079. "\nuniform sampler2D tEquirect;\n\nvarying vec3 vWorldDirection;\n\n#include <common>\n\nvoid main() {\n\n\tvec3 direction = normalize( vWorldDirection );\n\n\tvec2 sampleUV = equirectUv( direction );\n\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\n\tgl_FragColor = mapTexelToLinear( texColor );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\n}\n";
  14080. var equirect_vert = /* glsl */
  14081. "\nvarying vec3 vWorldDirection;\n\n#include <common>\n\nvoid main() {\n\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\n}\n";
  14082. var linedashed_frag = /* glsl */
  14083. "\nuniform vec3 diffuse;\nuniform float opacity;\n\nuniform float dashSize;\nuniform float totalSize;\n\nvarying float vLineDistance;\n\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\n\t\tdiscard;\n\n\t}\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\n\toutgoingLight = diffuseColor.rgb; // simple shader\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\n}\n";
  14084. var linedashed_vert = /* glsl */
  14085. "\nuniform float scale;\nattribute float lineDistance;\n\nvarying float vLineDistance;\n\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\tvLineDistance = scale * lineDistance;\n\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14086. var meshbasic_frag = /* glsl */
  14087. "\nuniform vec3 diffuse;\nuniform float opacity;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\n\t// accumulation (baked indirect lighting only)\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\n\t#else\n\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\n\t#endif\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n\t#include <envmap_fragment>\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14088. var meshbasic_vert = /* glsl */
  14089. "\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\n\t#ifdef USE_ENVMAP\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14090. var meshlambert_frag = /* glsl */
  14091. "\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\n\t// accumulation\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\n\t#else\n\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\n\t#endif\n\n\t#include <lightmap_fragment>\n\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\n\t#ifdef DOUBLE_SIDED\n\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\n\t#else\n\n\t\treflectedLight.directDiffuse = vLightFront;\n\n\t#endif\n\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\n\t// modulation\n\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include <envmap_fragment>\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  14092. var meshlambert_vert = /* glsl */
  14093. "\n#define LAMBERT\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  14094. var meshmatcap_frag = /* glsl */
  14095. "\n#define MATCAP\n\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks\n\n\t#ifdef USE_MATCAP\n\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\n\t#else\n\n\t\tvec4 matcapColor = vec4( 1.0 );\n\n\t#endif\n\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14096. var meshmatcap_vert = /* glsl */
  14097. "\n#define MATCAP\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\t\tvNormal = normalize( transformedNormal );\n\n\t#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n}\n";
  14098. var meshtoon_frag = /* glsl */
  14099. "\n#define TOON\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\n\t// accumulation\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14100. var meshtoon_vert = /* glsl */
  14101. "\n#define TOON\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14102. var meshphong_frag = /* glsl */
  14103. "\n#define PHONG\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\n\t// accumulation\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t#include <envmap_fragment>\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14104. var meshphong_vert = /* glsl */
  14105. "\n#define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14106. var meshphysical_frag = /* glsl */
  14107. "\n#define STANDARD\n\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\n\t// accumulation\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\n\t// modulation\n\t#include <aomap_fragment>\n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\n\t// this is a stub for the transmission model\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n\n}\n";
  14108. var meshphysical_vert = /* glsl */
  14109. "\n#define STANDARD\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n\t#ifdef USE_TANGENT\n\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\n\t#endif\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14110. var normal_frag = /* glsl */
  14111. "\n#define NORMAL\n\nuniform float opacity;\n\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\n\tvarying vec3 vViewPosition;\n\n#endif\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\n}\n";
  14112. var normal_vert = /* glsl */
  14113. "\n#define NORMAL\n\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\n\tvarying vec3 vViewPosition;\n\n#endif\n\n#ifndef FLAT_SHADED\n\n\tvarying vec3 vNormal;\n\n\t#ifdef USE_TANGENT\n\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\n\t#endif\n\n#endif\n\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n\n\tvNormal = normalize( transformedNormal );\n\n\t#ifdef USE_TANGENT\n\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\n\t#endif\n\n#endif\n\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\n\tvViewPosition = - mvPosition.xyz;\n\n#endif\n\n}\n";
  14114. var points_frag = /* glsl */
  14115. "\nuniform vec3 diffuse;\nuniform float opacity;\n\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\n}\n";
  14116. var points_vert = /* glsl */
  14117. "\nuniform float size;\nuniform float scale;\n\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\n\tgl_PointSize = size;\n\n\t#ifdef USE_SIZEATTENUATION\n\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\n\t#endif\n\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14118. var shadow_frag = /* glsl */
  14119. "\nuniform vec3 color;\nuniform float opacity;\n\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n\nvoid main() {\n\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\n}\n";
  14120. var shadow_vert = /* glsl */
  14121. "\n#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n\nvoid main() {\n\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14122. var sprite_frag = /* glsl */
  14123. "\nuniform vec3 diffuse;\nuniform float opacity;\n\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\nvoid main() {\n\n\t#include <clipping_planes_fragment>\n\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\n\toutgoingLight = diffuseColor.rgb;\n\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\n}\n";
  14124. var sprite_vert = /* glsl */
  14125. "\nuniform float rotation;\nuniform vec2 center;\n\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n\t#include <uv_vertex>\n\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\n\t#ifndef USE_SIZEATTENUATION\n\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\n\t#endif\n\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\n\tmvPosition.xy += rotatedPosition;\n\n\tgl_Position = projectionMatrix * mvPosition;\n\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\n}\n";
  14126. var ShaderChunk = {
  14127. alphamap_fragment: alphamap_fragment,
  14128. alphamap_pars_fragment: alphamap_pars_fragment,
  14129. alphatest_fragment: alphatest_fragment,
  14130. aomap_fragment: aomap_fragment,
  14131. aomap_pars_fragment: aomap_pars_fragment,
  14132. begin_vertex: begin_vertex,
  14133. beginnormal_vertex: beginnormal_vertex,
  14134. bsdfs: bsdfs,
  14135. bumpmap_pars_fragment: bumpmap_pars_fragment,
  14136. clipping_planes_fragment: clipping_planes_fragment,
  14137. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  14138. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  14139. clipping_planes_vertex: clipping_planes_vertex,
  14140. color_fragment: color_fragment,
  14141. color_pars_fragment: color_pars_fragment,
  14142. color_pars_vertex: color_pars_vertex,
  14143. color_vertex: color_vertex,
  14144. common: common,
  14145. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  14146. defaultnormal_vertex: defaultnormal_vertex,
  14147. displacementmap_pars_vertex: displacementmap_pars_vertex,
  14148. displacementmap_vertex: displacementmap_vertex,
  14149. emissivemap_fragment: emissivemap_fragment,
  14150. emissivemap_pars_fragment: emissivemap_pars_fragment,
  14151. encodings_fragment: encodings_fragment,
  14152. encodings_pars_fragment: encodings_pars_fragment,
  14153. envmap_fragment: envmap_fragment,
  14154. envmap_common_pars_fragment: envmap_common_pars_fragment,
  14155. envmap_pars_fragment: envmap_pars_fragment,
  14156. envmap_pars_vertex: envmap_pars_vertex,
  14157. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  14158. envmap_vertex: envmap_vertex,
  14159. fog_vertex: fog_vertex,
  14160. fog_pars_vertex: fog_pars_vertex,
  14161. fog_fragment: fog_fragment,
  14162. fog_pars_fragment: fog_pars_fragment,
  14163. gradientmap_pars_fragment: gradientmap_pars_fragment,
  14164. lightmap_fragment: lightmap_fragment,
  14165. lightmap_pars_fragment: lightmap_pars_fragment,
  14166. lights_lambert_vertex: lights_lambert_vertex,
  14167. lights_pars_begin: lights_pars_begin,
  14168. lights_toon_fragment: lights_toon_fragment,
  14169. lights_toon_pars_fragment: lights_toon_pars_fragment,
  14170. lights_phong_fragment: lights_phong_fragment,
  14171. lights_phong_pars_fragment: lights_phong_pars_fragment,
  14172. lights_physical_fragment: lights_physical_fragment,
  14173. lights_physical_pars_fragment: lights_physical_pars_fragment,
  14174. lights_fragment_begin: lights_fragment_begin,
  14175. lights_fragment_maps: lights_fragment_maps,
  14176. lights_fragment_end: lights_fragment_end,
  14177. logdepthbuf_fragment: logdepthbuf_fragment,
  14178. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  14179. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  14180. logdepthbuf_vertex: logdepthbuf_vertex,
  14181. map_fragment: map_fragment,
  14182. map_pars_fragment: map_pars_fragment,
  14183. map_particle_fragment: map_particle_fragment,
  14184. map_particle_pars_fragment: map_particle_pars_fragment,
  14185. metalnessmap_fragment: metalnessmap_fragment,
  14186. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  14187. morphnormal_vertex: morphnormal_vertex,
  14188. morphtarget_pars_vertex: morphtarget_pars_vertex,
  14189. morphtarget_vertex: morphtarget_vertex,
  14190. normal_fragment_begin: normal_fragment_begin,
  14191. normal_fragment_maps: normal_fragment_maps,
  14192. normalmap_pars_fragment: normalmap_pars_fragment,
  14193. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  14194. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  14195. clearcoat_pars_fragment: clearcoat_pars_fragment,
  14196. packing: packing,
  14197. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  14198. project_vertex: project_vertex,
  14199. dithering_fragment: dithering_fragment,
  14200. dithering_pars_fragment: dithering_pars_fragment,
  14201. roughnessmap_fragment: roughnessmap_fragment,
  14202. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  14203. shadowmap_pars_fragment: shadowmap_pars_fragment,
  14204. shadowmap_pars_vertex: shadowmap_pars_vertex,
  14205. shadowmap_vertex: shadowmap_vertex,
  14206. shadowmask_pars_fragment: shadowmask_pars_fragment,
  14207. skinbase_vertex: skinbase_vertex,
  14208. skinning_pars_vertex: skinning_pars_vertex,
  14209. skinning_vertex: skinning_vertex,
  14210. skinnormal_vertex: skinnormal_vertex,
  14211. specularmap_fragment: specularmap_fragment,
  14212. specularmap_pars_fragment: specularmap_pars_fragment,
  14213. tonemapping_fragment: tonemapping_fragment,
  14214. tonemapping_pars_fragment: tonemapping_pars_fragment,
  14215. transmissionmap_fragment: transmissionmap_fragment,
  14216. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  14217. uv_pars_fragment: uv_pars_fragment,
  14218. uv_pars_vertex: uv_pars_vertex,
  14219. uv_vertex: uv_vertex,
  14220. uv2_pars_fragment: uv2_pars_fragment,
  14221. uv2_pars_vertex: uv2_pars_vertex,
  14222. uv2_vertex: uv2_vertex,
  14223. worldpos_vertex: worldpos_vertex,
  14224. background_frag: background_frag,
  14225. background_vert: background_vert,
  14226. cube_frag: cube_frag,
  14227. cube_vert: cube_vert,
  14228. depth_frag: depth_frag,
  14229. depth_vert: depth_vert,
  14230. distanceRGBA_frag: distanceRGBA_frag,
  14231. distanceRGBA_vert: distanceRGBA_vert,
  14232. equirect_frag: equirect_frag,
  14233. equirect_vert: equirect_vert,
  14234. linedashed_frag: linedashed_frag,
  14235. linedashed_vert: linedashed_vert,
  14236. meshbasic_frag: meshbasic_frag,
  14237. meshbasic_vert: meshbasic_vert,
  14238. meshlambert_frag: meshlambert_frag,
  14239. meshlambert_vert: meshlambert_vert,
  14240. meshmatcap_frag: meshmatcap_frag,
  14241. meshmatcap_vert: meshmatcap_vert,
  14242. meshtoon_frag: meshtoon_frag,
  14243. meshtoon_vert: meshtoon_vert,
  14244. meshphong_frag: meshphong_frag,
  14245. meshphong_vert: meshphong_vert,
  14246. meshphysical_frag: meshphysical_frag,
  14247. meshphysical_vert: meshphysical_vert,
  14248. normal_frag: normal_frag,
  14249. normal_vert: normal_vert,
  14250. points_frag: points_frag,
  14251. points_vert: points_vert,
  14252. shadow_frag: shadow_frag,
  14253. shadow_vert: shadow_vert,
  14254. sprite_frag: sprite_frag,
  14255. sprite_vert: sprite_vert
  14256. };
  14257. /**
  14258. * Uniforms library for shared webgl shaders
  14259. */
  14260. var UniformsLib = {
  14261. common: {
  14262. diffuse: {
  14263. value: new Color(0xeeeeee)
  14264. },
  14265. opacity: {
  14266. value: 1.0
  14267. },
  14268. map: {
  14269. value: null
  14270. },
  14271. uvTransform: {
  14272. value: new Matrix3()
  14273. },
  14274. uv2Transform: {
  14275. value: new Matrix3()
  14276. },
  14277. alphaMap: {
  14278. value: null
  14279. }
  14280. },
  14281. specularmap: {
  14282. specularMap: {
  14283. value: null
  14284. }
  14285. },
  14286. envmap: {
  14287. envMap: {
  14288. value: null
  14289. },
  14290. flipEnvMap: {
  14291. value: -1
  14292. },
  14293. reflectivity: {
  14294. value: 1.0
  14295. },
  14296. refractionRatio: {
  14297. value: 0.98
  14298. },
  14299. maxMipLevel: {
  14300. value: 0
  14301. }
  14302. },
  14303. aomap: {
  14304. aoMap: {
  14305. value: null
  14306. },
  14307. aoMapIntensity: {
  14308. value: 1
  14309. }
  14310. },
  14311. lightmap: {
  14312. lightMap: {
  14313. value: null
  14314. },
  14315. lightMapIntensity: {
  14316. value: 1
  14317. }
  14318. },
  14319. emissivemap: {
  14320. emissiveMap: {
  14321. value: null
  14322. }
  14323. },
  14324. bumpmap: {
  14325. bumpMap: {
  14326. value: null
  14327. },
  14328. bumpScale: {
  14329. value: 1
  14330. }
  14331. },
  14332. normalmap: {
  14333. normalMap: {
  14334. value: null
  14335. },
  14336. normalScale: {
  14337. value: new Vector2(1, 1)
  14338. }
  14339. },
  14340. displacementmap: {
  14341. displacementMap: {
  14342. value: null
  14343. },
  14344. displacementScale: {
  14345. value: 1
  14346. },
  14347. displacementBias: {
  14348. value: 0
  14349. }
  14350. },
  14351. roughnessmap: {
  14352. roughnessMap: {
  14353. value: null
  14354. }
  14355. },
  14356. metalnessmap: {
  14357. metalnessMap: {
  14358. value: null
  14359. }
  14360. },
  14361. gradientmap: {
  14362. gradientMap: {
  14363. value: null
  14364. }
  14365. },
  14366. fog: {
  14367. fogDensity: {
  14368. value: 0.00025
  14369. },
  14370. fogNear: {
  14371. value: 1
  14372. },
  14373. fogFar: {
  14374. value: 2000
  14375. },
  14376. fogColor: {
  14377. value: new Color(0xffffff)
  14378. }
  14379. },
  14380. lights: {
  14381. ambientLightColor: {
  14382. value: []
  14383. },
  14384. lightProbe: {
  14385. value: []
  14386. },
  14387. directionalLights: {
  14388. value: [],
  14389. properties: {
  14390. direction: {},
  14391. color: {}
  14392. }
  14393. },
  14394. directionalLightShadows: {
  14395. value: [],
  14396. properties: {
  14397. shadowBias: {},
  14398. shadowNormalBias: {},
  14399. shadowRadius: {},
  14400. shadowMapSize: {}
  14401. }
  14402. },
  14403. directionalShadowMap: {
  14404. value: []
  14405. },
  14406. directionalShadowMatrix: {
  14407. value: []
  14408. },
  14409. spotLights: {
  14410. value: [],
  14411. properties: {
  14412. color: {},
  14413. position: {},
  14414. direction: {},
  14415. distance: {},
  14416. coneCos: {},
  14417. penumbraCos: {},
  14418. decay: {}
  14419. }
  14420. },
  14421. spotLightShadows: {
  14422. value: [],
  14423. properties: {
  14424. shadowBias: {},
  14425. shadowNormalBias: {},
  14426. shadowRadius: {},
  14427. shadowMapSize: {}
  14428. }
  14429. },
  14430. spotShadowMap: {
  14431. value: []
  14432. },
  14433. spotShadowMatrix: {
  14434. value: []
  14435. },
  14436. pointLights: {
  14437. value: [],
  14438. properties: {
  14439. color: {},
  14440. position: {},
  14441. decay: {},
  14442. distance: {}
  14443. }
  14444. },
  14445. pointLightShadows: {
  14446. value: [],
  14447. properties: {
  14448. shadowBias: {},
  14449. shadowNormalBias: {},
  14450. shadowRadius: {},
  14451. shadowMapSize: {},
  14452. shadowCameraNear: {},
  14453. shadowCameraFar: {}
  14454. }
  14455. },
  14456. pointShadowMap: {
  14457. value: []
  14458. },
  14459. pointShadowMatrix: {
  14460. value: []
  14461. },
  14462. hemisphereLights: {
  14463. value: [],
  14464. properties: {
  14465. direction: {},
  14466. skyColor: {},
  14467. groundColor: {}
  14468. }
  14469. },
  14470. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  14471. rectAreaLights: {
  14472. value: [],
  14473. properties: {
  14474. color: {},
  14475. position: {},
  14476. width: {},
  14477. height: {}
  14478. }
  14479. },
  14480. ltc_1: {
  14481. value: null
  14482. },
  14483. ltc_2: {
  14484. value: null
  14485. }
  14486. },
  14487. points: {
  14488. diffuse: {
  14489. value: new Color(0xeeeeee)
  14490. },
  14491. opacity: {
  14492. value: 1.0
  14493. },
  14494. size: {
  14495. value: 1.0
  14496. },
  14497. scale: {
  14498. value: 1.0
  14499. },
  14500. map: {
  14501. value: null
  14502. },
  14503. alphaMap: {
  14504. value: null
  14505. },
  14506. uvTransform: {
  14507. value: new Matrix3()
  14508. }
  14509. },
  14510. sprite: {
  14511. diffuse: {
  14512. value: new Color(0xeeeeee)
  14513. },
  14514. opacity: {
  14515. value: 1.0
  14516. },
  14517. center: {
  14518. value: new Vector2(0.5, 0.5)
  14519. },
  14520. rotation: {
  14521. value: 0.0
  14522. },
  14523. map: {
  14524. value: null
  14525. },
  14526. alphaMap: {
  14527. value: null
  14528. },
  14529. uvTransform: {
  14530. value: new Matrix3()
  14531. }
  14532. }
  14533. };
  14534. var ShaderLib = {
  14535. basic: {
  14536. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  14537. vertexShader: ShaderChunk.meshbasic_vert,
  14538. fragmentShader: ShaderChunk.meshbasic_frag
  14539. },
  14540. lambert: {
  14541. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  14542. emissive: {
  14543. value: new Color(0x000000)
  14544. }
  14545. }]),
  14546. vertexShader: ShaderChunk.meshlambert_vert,
  14547. fragmentShader: ShaderChunk.meshlambert_frag
  14548. },
  14549. phong: {
  14550. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  14551. emissive: {
  14552. value: new Color(0x000000)
  14553. },
  14554. specular: {
  14555. value: new Color(0x111111)
  14556. },
  14557. shininess: {
  14558. value: 30
  14559. }
  14560. }]),
  14561. vertexShader: ShaderChunk.meshphong_vert,
  14562. fragmentShader: ShaderChunk.meshphong_frag
  14563. },
  14564. standard: {
  14565. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  14566. emissive: {
  14567. value: new Color(0x000000)
  14568. },
  14569. roughness: {
  14570. value: 1.0
  14571. },
  14572. metalness: {
  14573. value: 0.0
  14574. },
  14575. envMapIntensity: {
  14576. value: 1
  14577. } // temporary
  14578. }]),
  14579. vertexShader: ShaderChunk.meshphysical_vert,
  14580. fragmentShader: ShaderChunk.meshphysical_frag
  14581. },
  14582. toon: {
  14583. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  14584. emissive: {
  14585. value: new Color(0x000000)
  14586. }
  14587. }]),
  14588. vertexShader: ShaderChunk.meshtoon_vert,
  14589. fragmentShader: ShaderChunk.meshtoon_frag
  14590. },
  14591. matcap: {
  14592. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  14593. matcap: {
  14594. value: null
  14595. }
  14596. }]),
  14597. vertexShader: ShaderChunk.meshmatcap_vert,
  14598. fragmentShader: ShaderChunk.meshmatcap_frag
  14599. },
  14600. points: {
  14601. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  14602. vertexShader: ShaderChunk.points_vert,
  14603. fragmentShader: ShaderChunk.points_frag
  14604. },
  14605. dashed: {
  14606. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  14607. scale: {
  14608. value: 1
  14609. },
  14610. dashSize: {
  14611. value: 1
  14612. },
  14613. totalSize: {
  14614. value: 2
  14615. }
  14616. }]),
  14617. vertexShader: ShaderChunk.linedashed_vert,
  14618. fragmentShader: ShaderChunk.linedashed_frag
  14619. },
  14620. depth: {
  14621. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  14622. vertexShader: ShaderChunk.depth_vert,
  14623. fragmentShader: ShaderChunk.depth_frag
  14624. },
  14625. normal: {
  14626. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  14627. opacity: {
  14628. value: 1.0
  14629. }
  14630. }]),
  14631. vertexShader: ShaderChunk.normal_vert,
  14632. fragmentShader: ShaderChunk.normal_frag
  14633. },
  14634. sprite: {
  14635. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  14636. vertexShader: ShaderChunk.sprite_vert,
  14637. fragmentShader: ShaderChunk.sprite_frag
  14638. },
  14639. background: {
  14640. uniforms: {
  14641. uvTransform: {
  14642. value: new Matrix3()
  14643. },
  14644. t2D: {
  14645. value: null
  14646. }
  14647. },
  14648. vertexShader: ShaderChunk.background_vert,
  14649. fragmentShader: ShaderChunk.background_frag
  14650. },
  14651. /* -------------------------------------------------------------------------
  14652. // Cube map shader
  14653. ------------------------------------------------------------------------- */
  14654. cube: {
  14655. uniforms: mergeUniforms([UniformsLib.envmap, {
  14656. opacity: {
  14657. value: 1.0
  14658. }
  14659. }]),
  14660. vertexShader: ShaderChunk.cube_vert,
  14661. fragmentShader: ShaderChunk.cube_frag
  14662. },
  14663. equirect: {
  14664. uniforms: {
  14665. tEquirect: {
  14666. value: null
  14667. }
  14668. },
  14669. vertexShader: ShaderChunk.equirect_vert,
  14670. fragmentShader: ShaderChunk.equirect_frag
  14671. },
  14672. distanceRGBA: {
  14673. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  14674. referencePosition: {
  14675. value: new Vector3()
  14676. },
  14677. nearDistance: {
  14678. value: 1
  14679. },
  14680. farDistance: {
  14681. value: 1000
  14682. }
  14683. }]),
  14684. vertexShader: ShaderChunk.distanceRGBA_vert,
  14685. fragmentShader: ShaderChunk.distanceRGBA_frag
  14686. },
  14687. shadow: {
  14688. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  14689. color: {
  14690. value: new Color(0x00000)
  14691. },
  14692. opacity: {
  14693. value: 1.0
  14694. }
  14695. }]),
  14696. vertexShader: ShaderChunk.shadow_vert,
  14697. fragmentShader: ShaderChunk.shadow_frag
  14698. }
  14699. };
  14700. ShaderLib.physical = {
  14701. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  14702. clearcoat: {
  14703. value: 0
  14704. },
  14705. clearcoatMap: {
  14706. value: null
  14707. },
  14708. clearcoatRoughness: {
  14709. value: 0
  14710. },
  14711. clearcoatRoughnessMap: {
  14712. value: null
  14713. },
  14714. clearcoatNormalScale: {
  14715. value: new Vector2(1, 1)
  14716. },
  14717. clearcoatNormalMap: {
  14718. value: null
  14719. },
  14720. sheen: {
  14721. value: new Color(0x000000)
  14722. },
  14723. transmission: {
  14724. value: 0
  14725. },
  14726. transmissionMap: {
  14727. value: null
  14728. }
  14729. }]),
  14730. vertexShader: ShaderChunk.meshphysical_vert,
  14731. fragmentShader: ShaderChunk.meshphysical_frag
  14732. };
  14733. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  14734. var clearColor = new Color(0x000000);
  14735. var clearAlpha = 0;
  14736. var planeMesh;
  14737. var boxMesh;
  14738. var currentBackground = null;
  14739. var currentBackgroundVersion = 0;
  14740. var currentTonemapping = null;
  14741. function render(renderList, scene, camera, forceClear) {
  14742. var background = scene.isScene === true ? scene.background : null;
  14743. if (background && background.isTexture) {
  14744. background = cubemaps.get(background);
  14745. } // Ignore background in AR
  14746. // TODO: Reconsider this.
  14747. var xr = renderer.xr;
  14748. var session = xr.getSession && xr.getSession();
  14749. if (session && session.environmentBlendMode === 'additive') {
  14750. background = null;
  14751. }
  14752. if (background === null) {
  14753. setClear(clearColor, clearAlpha);
  14754. } else if (background && background.isColor) {
  14755. setClear(background, 1);
  14756. forceClear = true;
  14757. }
  14758. if (renderer.autoClear || forceClear) {
  14759. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  14760. }
  14761. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  14762. if (boxMesh === undefined) {
  14763. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  14764. name: 'BackgroundCubeMaterial',
  14765. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  14766. vertexShader: ShaderLib.cube.vertexShader,
  14767. fragmentShader: ShaderLib.cube.fragmentShader,
  14768. side: BackSide,
  14769. depthTest: false,
  14770. depthWrite: false,
  14771. fog: false
  14772. }));
  14773. boxMesh.geometry.deleteAttribute('normal');
  14774. boxMesh.geometry.deleteAttribute('uv');
  14775. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  14776. this.matrixWorld.copyPosition(camera.matrixWorld);
  14777. }; // enable code injection for non-built-in material
  14778. Object.defineProperty(boxMesh.material, 'envMap', {
  14779. get: function get() {
  14780. return this.uniforms.envMap.value;
  14781. }
  14782. });
  14783. objects.update(boxMesh);
  14784. }
  14785. if (background.isWebGLCubeRenderTarget) {
  14786. // TODO Deprecate
  14787. background = background.texture;
  14788. }
  14789. boxMesh.material.uniforms.envMap.value = background;
  14790. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  14791. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  14792. boxMesh.material.needsUpdate = true;
  14793. currentBackground = background;
  14794. currentBackgroundVersion = background.version;
  14795. currentTonemapping = renderer.toneMapping;
  14796. } // push to the pre-sorted opaque render list
  14797. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  14798. } else if (background && background.isTexture) {
  14799. if (planeMesh === undefined) {
  14800. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  14801. name: 'BackgroundMaterial',
  14802. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  14803. vertexShader: ShaderLib.background.vertexShader,
  14804. fragmentShader: ShaderLib.background.fragmentShader,
  14805. side: FrontSide,
  14806. depthTest: false,
  14807. depthWrite: false,
  14808. fog: false
  14809. }));
  14810. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  14811. Object.defineProperty(planeMesh.material, 'map', {
  14812. get: function get() {
  14813. return this.uniforms.t2D.value;
  14814. }
  14815. });
  14816. objects.update(planeMesh);
  14817. }
  14818. planeMesh.material.uniforms.t2D.value = background;
  14819. if (background.matrixAutoUpdate === true) {
  14820. background.updateMatrix();
  14821. }
  14822. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  14823. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  14824. planeMesh.material.needsUpdate = true;
  14825. currentBackground = background;
  14826. currentBackgroundVersion = background.version;
  14827. currentTonemapping = renderer.toneMapping;
  14828. } // push to the pre-sorted opaque render list
  14829. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  14830. }
  14831. }
  14832. function setClear(color, alpha) {
  14833. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  14834. }
  14835. return {
  14836. getClearColor: function getClearColor() {
  14837. return clearColor;
  14838. },
  14839. setClearColor: function setClearColor(color, alpha) {
  14840. if (alpha === void 0) {
  14841. alpha = 1;
  14842. }
  14843. clearColor.set(color);
  14844. clearAlpha = alpha;
  14845. setClear(clearColor, clearAlpha);
  14846. },
  14847. getClearAlpha: function getClearAlpha() {
  14848. return clearAlpha;
  14849. },
  14850. setClearAlpha: function setClearAlpha(alpha) {
  14851. clearAlpha = alpha;
  14852. setClear(clearColor, clearAlpha);
  14853. },
  14854. render: render
  14855. };
  14856. }
  14857. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  14858. var maxVertexAttributes = gl.getParameter(34921);
  14859. var extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  14860. var vaoAvailable = capabilities.isWebGL2 || extension !== null;
  14861. var bindingStates = {};
  14862. var defaultState = createBindingState(null);
  14863. var currentState = defaultState;
  14864. function setup(object, material, program, geometry, index) {
  14865. var updateBuffers = false;
  14866. if (vaoAvailable) {
  14867. var state = getBindingState(geometry, program, material);
  14868. if (currentState !== state) {
  14869. currentState = state;
  14870. bindVertexArrayObject(currentState.object);
  14871. }
  14872. updateBuffers = needsUpdate(geometry, index);
  14873. if (updateBuffers) saveCache(geometry, index);
  14874. } else {
  14875. var wireframe = material.wireframe === true;
  14876. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  14877. currentState.geometry = geometry.id;
  14878. currentState.program = program.id;
  14879. currentState.wireframe = wireframe;
  14880. updateBuffers = true;
  14881. }
  14882. }
  14883. if (object.isInstancedMesh === true) {
  14884. updateBuffers = true;
  14885. }
  14886. if (index !== null) {
  14887. attributes.update(index, 34963);
  14888. }
  14889. if (updateBuffers) {
  14890. setupVertexAttributes(object, material, program, geometry);
  14891. if (index !== null) {
  14892. gl.bindBuffer(34963, attributes.get(index).buffer);
  14893. }
  14894. }
  14895. }
  14896. function createVertexArrayObject() {
  14897. if (capabilities.isWebGL2) return gl.createVertexArray();
  14898. return extension.createVertexArrayOES();
  14899. }
  14900. function bindVertexArrayObject(vao) {
  14901. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  14902. return extension.bindVertexArrayOES(vao);
  14903. }
  14904. function deleteVertexArrayObject(vao) {
  14905. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  14906. return extension.deleteVertexArrayOES(vao);
  14907. }
  14908. function getBindingState(geometry, program, material) {
  14909. var wireframe = material.wireframe === true;
  14910. var programMap = bindingStates[geometry.id];
  14911. if (programMap === undefined) {
  14912. programMap = {};
  14913. bindingStates[geometry.id] = programMap;
  14914. }
  14915. var stateMap = programMap[program.id];
  14916. if (stateMap === undefined) {
  14917. stateMap = {};
  14918. programMap[program.id] = stateMap;
  14919. }
  14920. var state = stateMap[wireframe];
  14921. if (state === undefined) {
  14922. state = createBindingState(createVertexArrayObject());
  14923. stateMap[wireframe] = state;
  14924. }
  14925. return state;
  14926. }
  14927. function createBindingState(vao) {
  14928. var newAttributes = [];
  14929. var enabledAttributes = [];
  14930. var attributeDivisors = [];
  14931. for (var i = 0; i < maxVertexAttributes; i++) {
  14932. newAttributes[i] = 0;
  14933. enabledAttributes[i] = 0;
  14934. attributeDivisors[i] = 0;
  14935. }
  14936. return {
  14937. // for backward compatibility on non-VAO support browser
  14938. geometry: null,
  14939. program: null,
  14940. wireframe: false,
  14941. newAttributes: newAttributes,
  14942. enabledAttributes: enabledAttributes,
  14943. attributeDivisors: attributeDivisors,
  14944. object: vao,
  14945. attributes: {},
  14946. index: null
  14947. };
  14948. }
  14949. function needsUpdate(geometry, index) {
  14950. var cachedAttributes = currentState.attributes;
  14951. var geometryAttributes = geometry.attributes;
  14952. var attributesNum = 0;
  14953. for (var key in geometryAttributes) {
  14954. var cachedAttribute = cachedAttributes[key];
  14955. var geometryAttribute = geometryAttributes[key];
  14956. if (cachedAttribute === undefined) return true;
  14957. if (cachedAttribute.attribute !== geometryAttribute) return true;
  14958. if (cachedAttribute.data !== geometryAttribute.data) return true;
  14959. attributesNum++;
  14960. }
  14961. if (currentState.attributesNum !== attributesNum) return true;
  14962. if (currentState.index !== index) return true;
  14963. return false;
  14964. }
  14965. function saveCache(geometry, index) {
  14966. var cache = {};
  14967. var attributes = geometry.attributes;
  14968. var attributesNum = 0;
  14969. for (var key in attributes) {
  14970. var attribute = attributes[key];
  14971. var data = {};
  14972. data.attribute = attribute;
  14973. if (attribute.data) {
  14974. data.data = attribute.data;
  14975. }
  14976. cache[key] = data;
  14977. attributesNum++;
  14978. }
  14979. currentState.attributes = cache;
  14980. currentState.attributesNum = attributesNum;
  14981. currentState.index = index;
  14982. }
  14983. function initAttributes() {
  14984. var newAttributes = currentState.newAttributes;
  14985. for (var i = 0, il = newAttributes.length; i < il; i++) {
  14986. newAttributes[i] = 0;
  14987. }
  14988. }
  14989. function enableAttribute(attribute) {
  14990. enableAttributeAndDivisor(attribute, 0);
  14991. }
  14992. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  14993. var newAttributes = currentState.newAttributes;
  14994. var enabledAttributes = currentState.enabledAttributes;
  14995. var attributeDivisors = currentState.attributeDivisors;
  14996. newAttributes[attribute] = 1;
  14997. if (enabledAttributes[attribute] === 0) {
  14998. gl.enableVertexAttribArray(attribute);
  14999. enabledAttributes[attribute] = 1;
  15000. }
  15001. if (attributeDivisors[attribute] !== meshPerAttribute) {
  15002. var _extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  15003. _extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  15004. attributeDivisors[attribute] = meshPerAttribute;
  15005. }
  15006. }
  15007. function disableUnusedAttributes() {
  15008. var newAttributes = currentState.newAttributes;
  15009. var enabledAttributes = currentState.enabledAttributes;
  15010. for (var i = 0, il = enabledAttributes.length; i < il; i++) {
  15011. if (enabledAttributes[i] !== newAttributes[i]) {
  15012. gl.disableVertexAttribArray(i);
  15013. enabledAttributes[i] = 0;
  15014. }
  15015. }
  15016. }
  15017. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  15018. if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
  15019. gl.vertexAttribIPointer(index, size, type, stride, offset);
  15020. } else {
  15021. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  15022. }
  15023. }
  15024. function setupVertexAttributes(object, material, program, geometry) {
  15025. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  15026. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  15027. }
  15028. initAttributes();
  15029. var geometryAttributes = geometry.attributes;
  15030. var programAttributes = program.getAttributes();
  15031. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15032. for (var name in programAttributes) {
  15033. var programAttribute = programAttributes[name];
  15034. if (programAttribute >= 0) {
  15035. var geometryAttribute = geometryAttributes[name];
  15036. if (geometryAttribute !== undefined) {
  15037. var normalized = geometryAttribute.normalized;
  15038. var size = geometryAttribute.itemSize;
  15039. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  15040. if (attribute === undefined) continue;
  15041. var buffer = attribute.buffer;
  15042. var type = attribute.type;
  15043. var bytesPerElement = attribute.bytesPerElement;
  15044. if (geometryAttribute.isInterleavedBufferAttribute) {
  15045. var data = geometryAttribute.data;
  15046. var stride = data.stride;
  15047. var offset = geometryAttribute.offset;
  15048. if (data && data.isInstancedInterleavedBuffer) {
  15049. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  15050. if (geometry._maxInstanceCount === undefined) {
  15051. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  15052. }
  15053. } else {
  15054. enableAttribute(programAttribute);
  15055. }
  15056. gl.bindBuffer(34962, buffer);
  15057. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  15058. } else {
  15059. if (geometryAttribute.isInstancedBufferAttribute) {
  15060. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  15061. if (geometry._maxInstanceCount === undefined) {
  15062. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15063. }
  15064. } else {
  15065. enableAttribute(programAttribute);
  15066. }
  15067. gl.bindBuffer(34962, buffer);
  15068. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  15069. }
  15070. } else if (name === 'instanceMatrix') {
  15071. var _attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  15072. if (_attribute === undefined) continue;
  15073. var _buffer = _attribute.buffer;
  15074. var _type = _attribute.type;
  15075. enableAttributeAndDivisor(programAttribute + 0, 1);
  15076. enableAttributeAndDivisor(programAttribute + 1, 1);
  15077. enableAttributeAndDivisor(programAttribute + 2, 1);
  15078. enableAttributeAndDivisor(programAttribute + 3, 1);
  15079. gl.bindBuffer(34962, _buffer);
  15080. gl.vertexAttribPointer(programAttribute + 0, 4, _type, false, 64, 0);
  15081. gl.vertexAttribPointer(programAttribute + 1, 4, _type, false, 64, 16);
  15082. gl.vertexAttribPointer(programAttribute + 2, 4, _type, false, 64, 32);
  15083. gl.vertexAttribPointer(programAttribute + 3, 4, _type, false, 64, 48);
  15084. } else if (name === 'instanceColor') {
  15085. var _attribute2 = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  15086. if (_attribute2 === undefined) continue;
  15087. var _buffer2 = _attribute2.buffer;
  15088. var _type2 = _attribute2.type;
  15089. enableAttributeAndDivisor(programAttribute, 1);
  15090. gl.bindBuffer(34962, _buffer2);
  15091. gl.vertexAttribPointer(programAttribute, 3, _type2, false, 12, 0);
  15092. } else if (materialDefaultAttributeValues !== undefined) {
  15093. var value = materialDefaultAttributeValues[name];
  15094. if (value !== undefined) {
  15095. switch (value.length) {
  15096. case 2:
  15097. gl.vertexAttrib2fv(programAttribute, value);
  15098. break;
  15099. case 3:
  15100. gl.vertexAttrib3fv(programAttribute, value);
  15101. break;
  15102. case 4:
  15103. gl.vertexAttrib4fv(programAttribute, value);
  15104. break;
  15105. default:
  15106. gl.vertexAttrib1fv(programAttribute, value);
  15107. }
  15108. }
  15109. }
  15110. }
  15111. }
  15112. disableUnusedAttributes();
  15113. }
  15114. function dispose() {
  15115. reset();
  15116. for (var geometryId in bindingStates) {
  15117. var programMap = bindingStates[geometryId];
  15118. for (var programId in programMap) {
  15119. var stateMap = programMap[programId];
  15120. for (var wireframe in stateMap) {
  15121. deleteVertexArrayObject(stateMap[wireframe].object);
  15122. delete stateMap[wireframe];
  15123. }
  15124. delete programMap[programId];
  15125. }
  15126. delete bindingStates[geometryId];
  15127. }
  15128. }
  15129. function releaseStatesOfGeometry(geometry) {
  15130. if (bindingStates[geometry.id] === undefined) return;
  15131. var programMap = bindingStates[geometry.id];
  15132. for (var programId in programMap) {
  15133. var stateMap = programMap[programId];
  15134. for (var wireframe in stateMap) {
  15135. deleteVertexArrayObject(stateMap[wireframe].object);
  15136. delete stateMap[wireframe];
  15137. }
  15138. delete programMap[programId];
  15139. }
  15140. delete bindingStates[geometry.id];
  15141. }
  15142. function releaseStatesOfProgram(program) {
  15143. for (var geometryId in bindingStates) {
  15144. var programMap = bindingStates[geometryId];
  15145. if (programMap[program.id] === undefined) continue;
  15146. var stateMap = programMap[program.id];
  15147. for (var wireframe in stateMap) {
  15148. deleteVertexArrayObject(stateMap[wireframe].object);
  15149. delete stateMap[wireframe];
  15150. }
  15151. delete programMap[program.id];
  15152. }
  15153. }
  15154. function reset() {
  15155. resetDefaultState();
  15156. if (currentState === defaultState) return;
  15157. currentState = defaultState;
  15158. bindVertexArrayObject(currentState.object);
  15159. } // for backward-compatilibity
  15160. function resetDefaultState() {
  15161. defaultState.geometry = null;
  15162. defaultState.program = null;
  15163. defaultState.wireframe = false;
  15164. }
  15165. return {
  15166. setup: setup,
  15167. reset: reset,
  15168. resetDefaultState: resetDefaultState,
  15169. dispose: dispose,
  15170. releaseStatesOfGeometry: releaseStatesOfGeometry,
  15171. releaseStatesOfProgram: releaseStatesOfProgram,
  15172. initAttributes: initAttributes,
  15173. enableAttribute: enableAttribute,
  15174. disableUnusedAttributes: disableUnusedAttributes
  15175. };
  15176. }
  15177. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  15178. var isWebGL2 = capabilities.isWebGL2;
  15179. var mode;
  15180. function setMode(value) {
  15181. mode = value;
  15182. }
  15183. function render(start, count) {
  15184. gl.drawArrays(mode, start, count);
  15185. info.update(count, mode, 1);
  15186. }
  15187. function renderInstances(start, count, primcount) {
  15188. if (primcount === 0) return;
  15189. var extension, methodName;
  15190. if (isWebGL2) {
  15191. extension = gl;
  15192. methodName = 'drawArraysInstanced';
  15193. } else {
  15194. extension = extensions.get('ANGLE_instanced_arrays');
  15195. methodName = 'drawArraysInstancedANGLE';
  15196. if (extension === null) {
  15197. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  15198. return;
  15199. }
  15200. }
  15201. extension[methodName](mode, start, count, primcount);
  15202. info.update(count, mode, primcount);
  15203. } //
  15204. this.setMode = setMode;
  15205. this.render = render;
  15206. this.renderInstances = renderInstances;
  15207. }
  15208. function WebGLCapabilities(gl, extensions, parameters) {
  15209. var maxAnisotropy;
  15210. function getMaxAnisotropy() {
  15211. if (maxAnisotropy !== undefined) return maxAnisotropy;
  15212. var extension = extensions.get('EXT_texture_filter_anisotropic');
  15213. if (extension !== null) {
  15214. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  15215. } else {
  15216. maxAnisotropy = 0;
  15217. }
  15218. return maxAnisotropy;
  15219. }
  15220. function getMaxPrecision(precision) {
  15221. if (precision === 'highp') {
  15222. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  15223. return 'highp';
  15224. }
  15225. precision = 'mediump';
  15226. }
  15227. if (precision === 'mediump') {
  15228. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  15229. return 'mediump';
  15230. }
  15231. }
  15232. return 'lowp';
  15233. }
  15234. /* eslint-disable no-undef */
  15235. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  15236. /* eslint-enable no-undef */
  15237. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15238. var maxPrecision = getMaxPrecision(precision);
  15239. if (maxPrecision !== precision) {
  15240. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  15241. precision = maxPrecision;
  15242. }
  15243. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  15244. var maxTextures = gl.getParameter(34930);
  15245. var maxVertexTextures = gl.getParameter(35660);
  15246. var maxTextureSize = gl.getParameter(3379);
  15247. var maxCubemapSize = gl.getParameter(34076);
  15248. var maxAttributes = gl.getParameter(34921);
  15249. var maxVertexUniforms = gl.getParameter(36347);
  15250. var maxVaryings = gl.getParameter(36348);
  15251. var maxFragmentUniforms = gl.getParameter(36349);
  15252. var vertexTextures = maxVertexTextures > 0;
  15253. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  15254. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15255. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  15256. return {
  15257. isWebGL2: isWebGL2,
  15258. getMaxAnisotropy: getMaxAnisotropy,
  15259. getMaxPrecision: getMaxPrecision,
  15260. precision: precision,
  15261. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15262. maxTextures: maxTextures,
  15263. maxVertexTextures: maxVertexTextures,
  15264. maxTextureSize: maxTextureSize,
  15265. maxCubemapSize: maxCubemapSize,
  15266. maxAttributes: maxAttributes,
  15267. maxVertexUniforms: maxVertexUniforms,
  15268. maxVaryings: maxVaryings,
  15269. maxFragmentUniforms: maxFragmentUniforms,
  15270. vertexTextures: vertexTextures,
  15271. floatFragmentTextures: floatFragmentTextures,
  15272. floatVertexTextures: floatVertexTextures,
  15273. maxSamples: maxSamples
  15274. };
  15275. }
  15276. function WebGLClipping(properties) {
  15277. var scope = this;
  15278. var globalState = null,
  15279. numGlobalPlanes = 0,
  15280. localClippingEnabled = false,
  15281. renderingShadows = false;
  15282. var plane = new Plane(),
  15283. viewNormalMatrix = new Matrix3(),
  15284. uniform = {
  15285. value: null,
  15286. needsUpdate: false
  15287. };
  15288. this.uniform = uniform;
  15289. this.numPlanes = 0;
  15290. this.numIntersection = 0;
  15291. this.init = function (planes, enableLocalClipping, camera) {
  15292. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  15293. // run another frame in order to reset the state:
  15294. numGlobalPlanes !== 0 || localClippingEnabled;
  15295. localClippingEnabled = enableLocalClipping;
  15296. globalState = projectPlanes(planes, camera, 0);
  15297. numGlobalPlanes = planes.length;
  15298. return enabled;
  15299. };
  15300. this.beginShadows = function () {
  15301. renderingShadows = true;
  15302. projectPlanes(null);
  15303. };
  15304. this.endShadows = function () {
  15305. renderingShadows = false;
  15306. resetGlobalState();
  15307. };
  15308. this.setState = function (material, camera, useCache) {
  15309. var planes = material.clippingPlanes,
  15310. clipIntersection = material.clipIntersection,
  15311. clipShadows = material.clipShadows;
  15312. var materialProperties = properties.get(material);
  15313. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  15314. // there's no local clipping
  15315. if (renderingShadows) {
  15316. // there's no global clipping
  15317. projectPlanes(null);
  15318. } else {
  15319. resetGlobalState();
  15320. }
  15321. } else {
  15322. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15323. lGlobal = nGlobal * 4;
  15324. var dstArray = materialProperties.clippingState || null;
  15325. uniform.value = dstArray; // ensure unique state
  15326. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  15327. for (var i = 0; i !== lGlobal; ++i) {
  15328. dstArray[i] = globalState[i];
  15329. }
  15330. materialProperties.clippingState = dstArray;
  15331. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15332. this.numPlanes += nGlobal;
  15333. }
  15334. };
  15335. function resetGlobalState() {
  15336. if (uniform.value !== globalState) {
  15337. uniform.value = globalState;
  15338. uniform.needsUpdate = numGlobalPlanes > 0;
  15339. }
  15340. scope.numPlanes = numGlobalPlanes;
  15341. scope.numIntersection = 0;
  15342. }
  15343. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  15344. var nPlanes = planes !== null ? planes.length : 0;
  15345. var dstArray = null;
  15346. if (nPlanes !== 0) {
  15347. dstArray = uniform.value;
  15348. if (skipTransform !== true || dstArray === null) {
  15349. var flatSize = dstOffset + nPlanes * 4,
  15350. viewMatrix = camera.matrixWorldInverse;
  15351. viewNormalMatrix.getNormalMatrix(viewMatrix);
  15352. if (dstArray === null || dstArray.length < flatSize) {
  15353. dstArray = new Float32Array(flatSize);
  15354. }
  15355. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  15356. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  15357. plane.normal.toArray(dstArray, i4);
  15358. dstArray[i4 + 3] = plane.constant;
  15359. }
  15360. }
  15361. uniform.value = dstArray;
  15362. uniform.needsUpdate = true;
  15363. }
  15364. scope.numPlanes = nPlanes;
  15365. scope.numIntersection = 0;
  15366. return dstArray;
  15367. }
  15368. }
  15369. function WebGLCubeMaps(renderer) {
  15370. var cubemaps = new WeakMap();
  15371. function mapTextureMapping(texture, mapping) {
  15372. if (mapping === EquirectangularReflectionMapping) {
  15373. texture.mapping = CubeReflectionMapping;
  15374. } else if (mapping === EquirectangularRefractionMapping) {
  15375. texture.mapping = CubeRefractionMapping;
  15376. }
  15377. return texture;
  15378. }
  15379. function get(texture) {
  15380. if (texture && texture.isTexture) {
  15381. var mapping = texture.mapping;
  15382. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  15383. if (cubemaps.has(texture)) {
  15384. var cubemap = cubemaps.get(texture).texture;
  15385. return mapTextureMapping(cubemap, texture.mapping);
  15386. } else {
  15387. var image = texture.image;
  15388. if (image && image.height > 0) {
  15389. var currentRenderList = renderer.getRenderList();
  15390. var currentRenderTarget = renderer.getRenderTarget();
  15391. var currentRenderState = renderer.getRenderState();
  15392. var renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  15393. renderTarget.fromEquirectangularTexture(renderer, texture);
  15394. cubemaps.set(texture, renderTarget);
  15395. renderer.setRenderTarget(currentRenderTarget);
  15396. renderer.setRenderList(currentRenderList);
  15397. renderer.setRenderState(currentRenderState);
  15398. texture.addEventListener('dispose', onTextureDispose);
  15399. return mapTextureMapping(renderTarget.texture, texture.mapping);
  15400. } else {
  15401. // image not yet ready. try the conversion next frame
  15402. return null;
  15403. }
  15404. }
  15405. }
  15406. }
  15407. return texture;
  15408. }
  15409. function onTextureDispose(event) {
  15410. var texture = event.target;
  15411. texture.removeEventListener('dispose', onTextureDispose);
  15412. var cubemap = cubemaps.get(texture);
  15413. if (cubemap !== undefined) {
  15414. cubemaps.delete(texture);
  15415. cubemap.dispose();
  15416. }
  15417. }
  15418. function dispose() {
  15419. cubemaps = new WeakMap();
  15420. }
  15421. return {
  15422. get: get,
  15423. dispose: dispose
  15424. };
  15425. }
  15426. function WebGLExtensions(gl) {
  15427. var extensions = {};
  15428. return {
  15429. has: function has(name) {
  15430. if (extensions[name] !== undefined) {
  15431. return extensions[name] !== null;
  15432. }
  15433. var extension;
  15434. switch (name) {
  15435. case 'WEBGL_depth_texture':
  15436. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  15437. break;
  15438. case 'EXT_texture_filter_anisotropic':
  15439. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  15440. break;
  15441. case 'WEBGL_compressed_texture_s3tc':
  15442. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  15443. break;
  15444. case 'WEBGL_compressed_texture_pvrtc':
  15445. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  15446. break;
  15447. default:
  15448. extension = gl.getExtension(name);
  15449. }
  15450. extensions[name] = extension;
  15451. return extension !== null;
  15452. },
  15453. get: function get(name) {
  15454. if (!this.has(name)) {
  15455. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  15456. }
  15457. return extensions[name];
  15458. }
  15459. };
  15460. }
  15461. function WebGLGeometries(gl, attributes, info, bindingStates) {
  15462. var geometries = new WeakMap();
  15463. var wireframeAttributes = new WeakMap();
  15464. function onGeometryDispose(event) {
  15465. var geometry = event.target;
  15466. var buffergeometry = geometries.get(geometry);
  15467. if (buffergeometry.index !== null) {
  15468. attributes.remove(buffergeometry.index);
  15469. }
  15470. for (var name in buffergeometry.attributes) {
  15471. attributes.remove(buffergeometry.attributes[name]);
  15472. }
  15473. geometry.removeEventListener('dispose', onGeometryDispose);
  15474. geometries.delete(geometry);
  15475. var attribute = wireframeAttributes.get(buffergeometry);
  15476. if (attribute) {
  15477. attributes.remove(attribute);
  15478. wireframeAttributes.delete(buffergeometry);
  15479. }
  15480. bindingStates.releaseStatesOfGeometry(buffergeometry);
  15481. if (geometry.isInstancedBufferGeometry === true) {
  15482. delete geometry._maxInstanceCount;
  15483. } //
  15484. info.memory.geometries--;
  15485. }
  15486. function get(object, geometry) {
  15487. var buffergeometry = geometries.get(geometry);
  15488. if (buffergeometry) return buffergeometry;
  15489. geometry.addEventListener('dispose', onGeometryDispose);
  15490. if (geometry.isBufferGeometry) {
  15491. buffergeometry = geometry;
  15492. } else if (geometry.isGeometry) {
  15493. if (geometry._bufferGeometry === undefined) {
  15494. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  15495. }
  15496. buffergeometry = geometry._bufferGeometry;
  15497. }
  15498. geometries.set(geometry, buffergeometry);
  15499. info.memory.geometries++;
  15500. return buffergeometry;
  15501. }
  15502. function update(geometry) {
  15503. var geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  15504. for (var name in geometryAttributes) {
  15505. attributes.update(geometryAttributes[name], 34962);
  15506. } // morph targets
  15507. var morphAttributes = geometry.morphAttributes;
  15508. for (var _name in morphAttributes) {
  15509. var array = morphAttributes[_name];
  15510. for (var i = 0, l = array.length; i < l; i++) {
  15511. attributes.update(array[i], 34962);
  15512. }
  15513. }
  15514. }
  15515. function updateWireframeAttribute(geometry) {
  15516. var indices = [];
  15517. var geometryIndex = geometry.index;
  15518. var geometryPosition = geometry.attributes.position;
  15519. var version = 0;
  15520. if (geometryIndex !== null) {
  15521. var array = geometryIndex.array;
  15522. version = geometryIndex.version;
  15523. for (var i = 0, l = array.length; i < l; i += 3) {
  15524. var a = array[i + 0];
  15525. var b = array[i + 1];
  15526. var c = array[i + 2];
  15527. indices.push(a, b, b, c, c, a);
  15528. }
  15529. } else {
  15530. var _array = geometryPosition.array;
  15531. version = geometryPosition.version;
  15532. for (var _i = 0, _l = _array.length / 3 - 1; _i < _l; _i += 3) {
  15533. var _a = _i + 0;
  15534. var _b = _i + 1;
  15535. var _c = _i + 2;
  15536. indices.push(_a, _b, _b, _c, _c, _a);
  15537. }
  15538. }
  15539. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  15540. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  15541. //
  15542. var previousAttribute = wireframeAttributes.get(geometry);
  15543. if (previousAttribute) attributes.remove(previousAttribute); //
  15544. wireframeAttributes.set(geometry, attribute);
  15545. }
  15546. function getWireframeAttribute(geometry) {
  15547. var currentAttribute = wireframeAttributes.get(geometry);
  15548. if (currentAttribute) {
  15549. var geometryIndex = geometry.index;
  15550. if (geometryIndex !== null) {
  15551. // if the attribute is obsolete, create a new one
  15552. if (currentAttribute.version < geometryIndex.version) {
  15553. updateWireframeAttribute(geometry);
  15554. }
  15555. }
  15556. } else {
  15557. updateWireframeAttribute(geometry);
  15558. }
  15559. return wireframeAttributes.get(geometry);
  15560. }
  15561. return {
  15562. get: get,
  15563. update: update,
  15564. getWireframeAttribute: getWireframeAttribute
  15565. };
  15566. }
  15567. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  15568. var isWebGL2 = capabilities.isWebGL2;
  15569. var mode;
  15570. function setMode(value) {
  15571. mode = value;
  15572. }
  15573. var type, bytesPerElement;
  15574. function setIndex(value) {
  15575. type = value.type;
  15576. bytesPerElement = value.bytesPerElement;
  15577. }
  15578. function render(start, count) {
  15579. gl.drawElements(mode, count, type, start * bytesPerElement);
  15580. info.update(count, mode, 1);
  15581. }
  15582. function renderInstances(start, count, primcount) {
  15583. if (primcount === 0) return;
  15584. var extension, methodName;
  15585. if (isWebGL2) {
  15586. extension = gl;
  15587. methodName = 'drawElementsInstanced';
  15588. } else {
  15589. extension = extensions.get('ANGLE_instanced_arrays');
  15590. methodName = 'drawElementsInstancedANGLE';
  15591. if (extension === null) {
  15592. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  15593. return;
  15594. }
  15595. }
  15596. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  15597. info.update(count, mode, primcount);
  15598. } //
  15599. this.setMode = setMode;
  15600. this.setIndex = setIndex;
  15601. this.render = render;
  15602. this.renderInstances = renderInstances;
  15603. }
  15604. function WebGLInfo(gl) {
  15605. var memory = {
  15606. geometries: 0,
  15607. textures: 0
  15608. };
  15609. var render = {
  15610. frame: 0,
  15611. calls: 0,
  15612. triangles: 0,
  15613. points: 0,
  15614. lines: 0
  15615. };
  15616. function update(count, mode, instanceCount) {
  15617. render.calls++;
  15618. switch (mode) {
  15619. case 4:
  15620. render.triangles += instanceCount * (count / 3);
  15621. break;
  15622. case 1:
  15623. render.lines += instanceCount * (count / 2);
  15624. break;
  15625. case 3:
  15626. render.lines += instanceCount * (count - 1);
  15627. break;
  15628. case 2:
  15629. render.lines += instanceCount * count;
  15630. break;
  15631. case 0:
  15632. render.points += instanceCount * count;
  15633. break;
  15634. default:
  15635. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  15636. break;
  15637. }
  15638. }
  15639. function reset() {
  15640. render.frame++;
  15641. render.calls = 0;
  15642. render.triangles = 0;
  15643. render.points = 0;
  15644. render.lines = 0;
  15645. }
  15646. return {
  15647. memory: memory,
  15648. render: render,
  15649. programs: null,
  15650. autoReset: true,
  15651. reset: reset,
  15652. update: update
  15653. };
  15654. }
  15655. function numericalSort(a, b) {
  15656. return a[0] - b[0];
  15657. }
  15658. function absNumericalSort(a, b) {
  15659. return Math.abs(b[1]) - Math.abs(a[1]);
  15660. }
  15661. function WebGLMorphtargets(gl) {
  15662. var influencesList = {};
  15663. var morphInfluences = new Float32Array(8);
  15664. var workInfluences = [];
  15665. for (var i = 0; i < 8; i++) {
  15666. workInfluences[i] = [i, 0];
  15667. }
  15668. function update(object, geometry, material, program) {
  15669. var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  15670. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  15671. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  15672. var influences = influencesList[geometry.id];
  15673. if (influences === undefined) {
  15674. // initialise list
  15675. influences = [];
  15676. for (var _i = 0; _i < length; _i++) {
  15677. influences[_i] = [_i, 0];
  15678. }
  15679. influencesList[geometry.id] = influences;
  15680. } // Collect influences
  15681. for (var _i2 = 0; _i2 < length; _i2++) {
  15682. var influence = influences[_i2];
  15683. influence[0] = _i2;
  15684. influence[1] = objectInfluences[_i2];
  15685. }
  15686. influences.sort(absNumericalSort);
  15687. for (var _i3 = 0; _i3 < 8; _i3++) {
  15688. if (_i3 < length && influences[_i3][1]) {
  15689. workInfluences[_i3][0] = influences[_i3][0];
  15690. workInfluences[_i3][1] = influences[_i3][1];
  15691. } else {
  15692. workInfluences[_i3][0] = Number.MAX_SAFE_INTEGER;
  15693. workInfluences[_i3][1] = 0;
  15694. }
  15695. }
  15696. workInfluences.sort(numericalSort);
  15697. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  15698. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  15699. var morphInfluencesSum = 0;
  15700. for (var _i4 = 0; _i4 < 8; _i4++) {
  15701. var _influence = workInfluences[_i4];
  15702. var index = _influence[0];
  15703. var value = _influence[1];
  15704. if (index !== Number.MAX_SAFE_INTEGER && value) {
  15705. if (morphTargets && geometry.getAttribute('morphTarget' + _i4) !== morphTargets[index]) {
  15706. geometry.setAttribute('morphTarget' + _i4, morphTargets[index]);
  15707. }
  15708. if (morphNormals && geometry.getAttribute('morphNormal' + _i4) !== morphNormals[index]) {
  15709. geometry.setAttribute('morphNormal' + _i4, morphNormals[index]);
  15710. }
  15711. morphInfluences[_i4] = value;
  15712. morphInfluencesSum += value;
  15713. } else {
  15714. if (morphTargets && geometry.hasAttribute('morphTarget' + _i4) === true) {
  15715. geometry.deleteAttribute('morphTarget' + _i4);
  15716. }
  15717. if (morphNormals && geometry.hasAttribute('morphNormal' + _i4) === true) {
  15718. geometry.deleteAttribute('morphNormal' + _i4);
  15719. }
  15720. morphInfluences[_i4] = 0;
  15721. }
  15722. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  15723. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  15724. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  15725. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  15726. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  15727. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  15728. }
  15729. return {
  15730. update: update
  15731. };
  15732. }
  15733. function WebGLObjects(gl, geometries, attributes, info) {
  15734. var updateMap = new WeakMap();
  15735. function update(object) {
  15736. var frame = info.render.frame;
  15737. var geometry = object.geometry;
  15738. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  15739. if (updateMap.get(buffergeometry) !== frame) {
  15740. if (geometry.isGeometry) {
  15741. buffergeometry.updateFromObject(object);
  15742. }
  15743. geometries.update(buffergeometry);
  15744. updateMap.set(buffergeometry, frame);
  15745. }
  15746. if (object.isInstancedMesh) {
  15747. attributes.update(object.instanceMatrix, 34962);
  15748. if (object.instanceColor !== null) {
  15749. attributes.update(object.instanceColor, 34962);
  15750. }
  15751. }
  15752. return buffergeometry;
  15753. }
  15754. function dispose() {
  15755. updateMap = new WeakMap();
  15756. }
  15757. return {
  15758. update: update,
  15759. dispose: dispose
  15760. };
  15761. }
  15762. function DataTexture2DArray(data, width, height, depth) {
  15763. if (data === void 0) {
  15764. data = null;
  15765. }
  15766. if (width === void 0) {
  15767. width = 1;
  15768. }
  15769. if (height === void 0) {
  15770. height = 1;
  15771. }
  15772. if (depth === void 0) {
  15773. depth = 1;
  15774. }
  15775. Texture.call(this, null);
  15776. this.image = {
  15777. data: data,
  15778. width: width,
  15779. height: height,
  15780. depth: depth
  15781. };
  15782. this.magFilter = NearestFilter;
  15783. this.minFilter = NearestFilter;
  15784. this.wrapR = ClampToEdgeWrapping;
  15785. this.generateMipmaps = false;
  15786. this.flipY = false;
  15787. this.needsUpdate = true;
  15788. }
  15789. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  15790. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  15791. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  15792. function DataTexture3D(data, width, height, depth) {
  15793. if (data === void 0) {
  15794. data = null;
  15795. }
  15796. if (width === void 0) {
  15797. width = 1;
  15798. }
  15799. if (height === void 0) {
  15800. height = 1;
  15801. }
  15802. if (depth === void 0) {
  15803. depth = 1;
  15804. }
  15805. // We're going to add .setXXX() methods for setting properties later.
  15806. // Users can still set in DataTexture3D directly.
  15807. //
  15808. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  15809. // texture.anisotropy = 16;
  15810. //
  15811. // See #14839
  15812. Texture.call(this, null);
  15813. this.image = {
  15814. data: data,
  15815. width: width,
  15816. height: height,
  15817. depth: depth
  15818. };
  15819. this.magFilter = NearestFilter;
  15820. this.minFilter = NearestFilter;
  15821. this.wrapR = ClampToEdgeWrapping;
  15822. this.generateMipmaps = false;
  15823. this.flipY = false;
  15824. this.needsUpdate = true;
  15825. }
  15826. DataTexture3D.prototype = Object.create(Texture.prototype);
  15827. DataTexture3D.prototype.constructor = DataTexture3D;
  15828. DataTexture3D.prototype.isDataTexture3D = true;
  15829. /**
  15830. * Uniforms of a program.
  15831. * Those form a tree structure with a special top-level container for the root,
  15832. * which you get by calling 'new WebGLUniforms( gl, program )'.
  15833. *
  15834. *
  15835. * Properties of inner nodes including the top-level container:
  15836. *
  15837. * .seq - array of nested uniforms
  15838. * .map - nested uniforms by name
  15839. *
  15840. *
  15841. * Methods of all nodes except the top-level container:
  15842. *
  15843. * .setValue( gl, value, [textures] )
  15844. *
  15845. * uploads a uniform value(s)
  15846. * the 'textures' parameter is needed for sampler uniforms
  15847. *
  15848. *
  15849. * Static methods of the top-level container (textures factorizations):
  15850. *
  15851. * .upload( gl, seq, values, textures )
  15852. *
  15853. * sets uniforms in 'seq' to 'values[id].value'
  15854. *
  15855. * .seqWithValue( seq, values ) : filteredSeq
  15856. *
  15857. * filters 'seq' entries with corresponding entry in values
  15858. *
  15859. *
  15860. * Methods of the top-level container (textures factorizations):
  15861. *
  15862. * .setValue( gl, name, value, textures )
  15863. *
  15864. * sets uniform with name 'name' to 'value'
  15865. *
  15866. * .setOptional( gl, obj, prop )
  15867. *
  15868. * like .set for an optional property of the object
  15869. *
  15870. */
  15871. var emptyTexture = new Texture();
  15872. var emptyTexture2dArray = new DataTexture2DArray();
  15873. var emptyTexture3d = new DataTexture3D();
  15874. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  15875. // Array Caches (provide typed arrays for temporary by size)
  15876. var arrayCacheF32 = [];
  15877. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  15878. var mat4array = new Float32Array(16);
  15879. var mat3array = new Float32Array(9);
  15880. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  15881. function flatten(array, nBlocks, blockSize) {
  15882. var firstElem = array[0];
  15883. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  15884. // see http://jacksondunstan.com/articles/983
  15885. var n = nBlocks * blockSize;
  15886. var r = arrayCacheF32[n];
  15887. if (r === undefined) {
  15888. r = new Float32Array(n);
  15889. arrayCacheF32[n] = r;
  15890. }
  15891. if (nBlocks !== 0) {
  15892. firstElem.toArray(r, 0);
  15893. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  15894. offset += blockSize;
  15895. array[i].toArray(r, offset);
  15896. }
  15897. }
  15898. return r;
  15899. }
  15900. function arraysEqual(a, b) {
  15901. if (a.length !== b.length) return false;
  15902. for (var i = 0, l = a.length; i < l; i++) {
  15903. if (a[i] !== b[i]) return false;
  15904. }
  15905. return true;
  15906. }
  15907. function copyArray(a, b) {
  15908. for (var i = 0, l = b.length; i < l; i++) {
  15909. a[i] = b[i];
  15910. }
  15911. } // Texture unit allocation
  15912. function allocTexUnits(textures, n) {
  15913. var r = arrayCacheI32[n];
  15914. if (r === undefined) {
  15915. r = new Int32Array(n);
  15916. arrayCacheI32[n] = r;
  15917. }
  15918. for (var i = 0; i !== n; ++i) {
  15919. r[i] = textures.allocateTextureUnit();
  15920. }
  15921. return r;
  15922. } // --- Setters ---
  15923. // Note: Defining these methods externally, because they come in a bunch
  15924. // and this way their names minify.
  15925. // Single scalar
  15926. function setValueV1f(gl, v) {
  15927. var cache = this.cache;
  15928. if (cache[0] === v) return;
  15929. gl.uniform1f(this.addr, v);
  15930. cache[0] = v;
  15931. } // Single float vector (from flat array or THREE.VectorN)
  15932. function setValueV2f(gl, v) {
  15933. var cache = this.cache;
  15934. if (v.x !== undefined) {
  15935. if (cache[0] !== v.x || cache[1] !== v.y) {
  15936. gl.uniform2f(this.addr, v.x, v.y);
  15937. cache[0] = v.x;
  15938. cache[1] = v.y;
  15939. }
  15940. } else {
  15941. if (arraysEqual(cache, v)) return;
  15942. gl.uniform2fv(this.addr, v);
  15943. copyArray(cache, v);
  15944. }
  15945. }
  15946. function setValueV3f(gl, v) {
  15947. var cache = this.cache;
  15948. if (v.x !== undefined) {
  15949. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  15950. gl.uniform3f(this.addr, v.x, v.y, v.z);
  15951. cache[0] = v.x;
  15952. cache[1] = v.y;
  15953. cache[2] = v.z;
  15954. }
  15955. } else if (v.r !== undefined) {
  15956. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  15957. gl.uniform3f(this.addr, v.r, v.g, v.b);
  15958. cache[0] = v.r;
  15959. cache[1] = v.g;
  15960. cache[2] = v.b;
  15961. }
  15962. } else {
  15963. if (arraysEqual(cache, v)) return;
  15964. gl.uniform3fv(this.addr, v);
  15965. copyArray(cache, v);
  15966. }
  15967. }
  15968. function setValueV4f(gl, v) {
  15969. var cache = this.cache;
  15970. if (v.x !== undefined) {
  15971. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  15972. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  15973. cache[0] = v.x;
  15974. cache[1] = v.y;
  15975. cache[2] = v.z;
  15976. cache[3] = v.w;
  15977. }
  15978. } else {
  15979. if (arraysEqual(cache, v)) return;
  15980. gl.uniform4fv(this.addr, v);
  15981. copyArray(cache, v);
  15982. }
  15983. } // Single matrix (from flat array or MatrixN)
  15984. function setValueM2(gl, v) {
  15985. var cache = this.cache;
  15986. var elements = v.elements;
  15987. if (elements === undefined) {
  15988. if (arraysEqual(cache, v)) return;
  15989. gl.uniformMatrix2fv(this.addr, false, v);
  15990. copyArray(cache, v);
  15991. } else {
  15992. if (arraysEqual(cache, elements)) return;
  15993. mat2array.set(elements);
  15994. gl.uniformMatrix2fv(this.addr, false, mat2array);
  15995. copyArray(cache, elements);
  15996. }
  15997. }
  15998. function setValueM3(gl, v) {
  15999. var cache = this.cache;
  16000. var elements = v.elements;
  16001. if (elements === undefined) {
  16002. if (arraysEqual(cache, v)) return;
  16003. gl.uniformMatrix3fv(this.addr, false, v);
  16004. copyArray(cache, v);
  16005. } else {
  16006. if (arraysEqual(cache, elements)) return;
  16007. mat3array.set(elements);
  16008. gl.uniformMatrix3fv(this.addr, false, mat3array);
  16009. copyArray(cache, elements);
  16010. }
  16011. }
  16012. function setValueM4(gl, v) {
  16013. var cache = this.cache;
  16014. var elements = v.elements;
  16015. if (elements === undefined) {
  16016. if (arraysEqual(cache, v)) return;
  16017. gl.uniformMatrix4fv(this.addr, false, v);
  16018. copyArray(cache, v);
  16019. } else {
  16020. if (arraysEqual(cache, elements)) return;
  16021. mat4array.set(elements);
  16022. gl.uniformMatrix4fv(this.addr, false, mat4array);
  16023. copyArray(cache, elements);
  16024. }
  16025. } // Single texture (2D / Cube)
  16026. function setValueT1(gl, v, textures) {
  16027. var cache = this.cache;
  16028. var unit = textures.allocateTextureUnit();
  16029. if (cache[0] !== unit) {
  16030. gl.uniform1i(this.addr, unit);
  16031. cache[0] = unit;
  16032. }
  16033. textures.safeSetTexture2D(v || emptyTexture, unit);
  16034. }
  16035. function setValueT2DArray1(gl, v, textures) {
  16036. var cache = this.cache;
  16037. var unit = textures.allocateTextureUnit();
  16038. if (cache[0] !== unit) {
  16039. gl.uniform1i(this.addr, unit);
  16040. cache[0] = unit;
  16041. }
  16042. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  16043. }
  16044. function setValueT3D1(gl, v, textures) {
  16045. var cache = this.cache;
  16046. var unit = textures.allocateTextureUnit();
  16047. if (cache[0] !== unit) {
  16048. gl.uniform1i(this.addr, unit);
  16049. cache[0] = unit;
  16050. }
  16051. textures.setTexture3D(v || emptyTexture3d, unit);
  16052. }
  16053. function setValueT6(gl, v, textures) {
  16054. var cache = this.cache;
  16055. var unit = textures.allocateTextureUnit();
  16056. if (cache[0] !== unit) {
  16057. gl.uniform1i(this.addr, unit);
  16058. cache[0] = unit;
  16059. }
  16060. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  16061. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16062. function setValueV1i(gl, v) {
  16063. var cache = this.cache;
  16064. if (cache[0] === v) return;
  16065. gl.uniform1i(this.addr, v);
  16066. cache[0] = v;
  16067. }
  16068. function setValueV2i(gl, v) {
  16069. var cache = this.cache;
  16070. if (arraysEqual(cache, v)) return;
  16071. gl.uniform2iv(this.addr, v);
  16072. copyArray(cache, v);
  16073. }
  16074. function setValueV3i(gl, v) {
  16075. var cache = this.cache;
  16076. if (arraysEqual(cache, v)) return;
  16077. gl.uniform3iv(this.addr, v);
  16078. copyArray(cache, v);
  16079. }
  16080. function setValueV4i(gl, v) {
  16081. var cache = this.cache;
  16082. if (arraysEqual(cache, v)) return;
  16083. gl.uniform4iv(this.addr, v);
  16084. copyArray(cache, v);
  16085. } // uint
  16086. function setValueV1ui(gl, v) {
  16087. var cache = this.cache;
  16088. if (cache[0] === v) return;
  16089. gl.uniform1ui(this.addr, v);
  16090. cache[0] = v;
  16091. } // Helper to pick the right setter for the singular case
  16092. function getSingularSetter(type) {
  16093. switch (type) {
  16094. case 0x1406:
  16095. return setValueV1f;
  16096. // FLOAT
  16097. case 0x8b50:
  16098. return setValueV2f;
  16099. // _VEC2
  16100. case 0x8b51:
  16101. return setValueV3f;
  16102. // _VEC3
  16103. case 0x8b52:
  16104. return setValueV4f;
  16105. // _VEC4
  16106. case 0x8b5a:
  16107. return setValueM2;
  16108. // _MAT2
  16109. case 0x8b5b:
  16110. return setValueM3;
  16111. // _MAT3
  16112. case 0x8b5c:
  16113. return setValueM4;
  16114. // _MAT4
  16115. case 0x1404:
  16116. case 0x8b56:
  16117. return setValueV1i;
  16118. // INT, BOOL
  16119. case 0x8b53:
  16120. case 0x8b57:
  16121. return setValueV2i;
  16122. // _VEC2
  16123. case 0x8b54:
  16124. case 0x8b58:
  16125. return setValueV3i;
  16126. // _VEC3
  16127. case 0x8b55:
  16128. case 0x8b59:
  16129. return setValueV4i;
  16130. // _VEC4
  16131. case 0x1405:
  16132. return setValueV1ui;
  16133. // UINT
  16134. case 0x8b5e: // SAMPLER_2D
  16135. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16136. case 0x8dca: // INT_SAMPLER_2D
  16137. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16138. case 0x8b62:
  16139. // SAMPLER_2D_SHADOW
  16140. return setValueT1;
  16141. case 0x8b5f: // SAMPLER_3D
  16142. case 0x8dcb: // INT_SAMPLER_3D
  16143. case 0x8dd3:
  16144. // UNSIGNED_INT_SAMPLER_3D
  16145. return setValueT3D1;
  16146. case 0x8b60: // SAMPLER_CUBE
  16147. case 0x8dcc: // INT_SAMPLER_CUBE
  16148. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16149. case 0x8dc5:
  16150. // SAMPLER_CUBE_SHADOW
  16151. return setValueT6;
  16152. case 0x8dc1: // SAMPLER_2D_ARRAY
  16153. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  16154. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  16155. case 0x8dc4:
  16156. // SAMPLER_2D_ARRAY_SHADOW
  16157. return setValueT2DArray1;
  16158. }
  16159. } // Array of scalars
  16160. function setValueV1fArray(gl, v) {
  16161. gl.uniform1fv(this.addr, v);
  16162. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16163. function setValueV1iArray(gl, v) {
  16164. gl.uniform1iv(this.addr, v);
  16165. }
  16166. function setValueV2iArray(gl, v) {
  16167. gl.uniform2iv(this.addr, v);
  16168. }
  16169. function setValueV3iArray(gl, v) {
  16170. gl.uniform3iv(this.addr, v);
  16171. }
  16172. function setValueV4iArray(gl, v) {
  16173. gl.uniform4iv(this.addr, v);
  16174. } // Array of vectors (flat or from THREE classes)
  16175. function setValueV2fArray(gl, v) {
  16176. var data = flatten(v, this.size, 2);
  16177. gl.uniform2fv(this.addr, data);
  16178. }
  16179. function setValueV3fArray(gl, v) {
  16180. var data = flatten(v, this.size, 3);
  16181. gl.uniform3fv(this.addr, data);
  16182. }
  16183. function setValueV4fArray(gl, v) {
  16184. var data = flatten(v, this.size, 4);
  16185. gl.uniform4fv(this.addr, data);
  16186. } // Array of matrices (flat or from THREE clases)
  16187. function setValueM2Array(gl, v) {
  16188. var data = flatten(v, this.size, 4);
  16189. gl.uniformMatrix2fv(this.addr, false, data);
  16190. }
  16191. function setValueM3Array(gl, v) {
  16192. var data = flatten(v, this.size, 9);
  16193. gl.uniformMatrix3fv(this.addr, false, data);
  16194. }
  16195. function setValueM4Array(gl, v) {
  16196. var data = flatten(v, this.size, 16);
  16197. gl.uniformMatrix4fv(this.addr, false, data);
  16198. } // Array of textures (2D / Cube)
  16199. function setValueT1Array(gl, v, textures) {
  16200. var n = v.length;
  16201. var units = allocTexUnits(textures, n);
  16202. gl.uniform1iv(this.addr, units);
  16203. for (var i = 0; i !== n; ++i) {
  16204. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  16205. }
  16206. }
  16207. function setValueT6Array(gl, v, textures) {
  16208. var n = v.length;
  16209. var units = allocTexUnits(textures, n);
  16210. gl.uniform1iv(this.addr, units);
  16211. for (var i = 0; i !== n; ++i) {
  16212. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  16213. }
  16214. } // Helper to pick the right setter for a pure (bottom-level) array
  16215. function getPureArraySetter(type) {
  16216. switch (type) {
  16217. case 0x1406:
  16218. return setValueV1fArray;
  16219. // FLOAT
  16220. case 0x8b50:
  16221. return setValueV2fArray;
  16222. // _VEC2
  16223. case 0x8b51:
  16224. return setValueV3fArray;
  16225. // _VEC3
  16226. case 0x8b52:
  16227. return setValueV4fArray;
  16228. // _VEC4
  16229. case 0x8b5a:
  16230. return setValueM2Array;
  16231. // _MAT2
  16232. case 0x8b5b:
  16233. return setValueM3Array;
  16234. // _MAT3
  16235. case 0x8b5c:
  16236. return setValueM4Array;
  16237. // _MAT4
  16238. case 0x1404:
  16239. case 0x8b56:
  16240. return setValueV1iArray;
  16241. // INT, BOOL
  16242. case 0x8b53:
  16243. case 0x8b57:
  16244. return setValueV2iArray;
  16245. // _VEC2
  16246. case 0x8b54:
  16247. case 0x8b58:
  16248. return setValueV3iArray;
  16249. // _VEC3
  16250. case 0x8b55:
  16251. case 0x8b59:
  16252. return setValueV4iArray;
  16253. // _VEC4
  16254. case 0x8b5e: // SAMPLER_2D
  16255. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16256. case 0x8dca: // INT_SAMPLER_2D
  16257. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16258. case 0x8b62:
  16259. // SAMPLER_2D_SHADOW
  16260. return setValueT1Array;
  16261. case 0x8b60: // SAMPLER_CUBE
  16262. case 0x8dcc: // INT_SAMPLER_CUBE
  16263. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16264. case 0x8dc5:
  16265. // SAMPLER_CUBE_SHADOW
  16266. return setValueT6Array;
  16267. }
  16268. } // --- Uniform Classes ---
  16269. function SingleUniform(id, activeInfo, addr) {
  16270. this.id = id;
  16271. this.addr = addr;
  16272. this.cache = [];
  16273. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16274. }
  16275. function PureArrayUniform(id, activeInfo, addr) {
  16276. this.id = id;
  16277. this.addr = addr;
  16278. this.cache = [];
  16279. this.size = activeInfo.size;
  16280. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16281. }
  16282. PureArrayUniform.prototype.updateCache = function (data) {
  16283. var cache = this.cache;
  16284. if (data instanceof Float32Array && cache.length !== data.length) {
  16285. this.cache = new Float32Array(data.length);
  16286. }
  16287. copyArray(cache, data);
  16288. };
  16289. function StructuredUniform(id) {
  16290. this.id = id;
  16291. this.seq = [];
  16292. this.map = {};
  16293. }
  16294. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  16295. var seq = this.seq;
  16296. for (var i = 0, n = seq.length; i !== n; ++i) {
  16297. var u = seq[i];
  16298. u.setValue(gl, value[u.id], textures);
  16299. }
  16300. }; // --- Top-level ---
  16301. // Parser - builds up the property tree from the path strings
  16302. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  16303. // - the identifier (member name or array index)
  16304. // - followed by an optional right bracket (found when array index)
  16305. // - followed by an optional left bracket or dot (type of subscript)
  16306. //
  16307. // Note: These portions can be read in a non-overlapping fashion and
  16308. // allow straightforward parsing of the hierarchy that WebGL encodes
  16309. // in the uniform names.
  16310. function addUniform(container, uniformObject) {
  16311. container.seq.push(uniformObject);
  16312. container.map[uniformObject.id] = uniformObject;
  16313. }
  16314. function parseUniform(activeInfo, addr, container) {
  16315. var path = activeInfo.name,
  16316. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  16317. RePathPart.lastIndex = 0;
  16318. while (true) {
  16319. var match = RePathPart.exec(path),
  16320. matchEnd = RePathPart.lastIndex;
  16321. var id = match[1];
  16322. var idIsIndex = match[2] === ']',
  16323. subscript = match[3];
  16324. if (idIsIndex) id = id | 0; // convert to integer
  16325. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  16326. // bare name or "pure" bottom-level array "[0]" suffix
  16327. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  16328. break;
  16329. } else {
  16330. // step into inner node / create it in case it doesn't exist
  16331. var map = container.map;
  16332. var next = map[id];
  16333. if (next === undefined) {
  16334. next = new StructuredUniform(id);
  16335. addUniform(container, next);
  16336. }
  16337. container = next;
  16338. }
  16339. }
  16340. } // Root Container
  16341. function WebGLUniforms(gl, program) {
  16342. this.seq = [];
  16343. this.map = {};
  16344. var n = gl.getProgramParameter(program, 35718);
  16345. for (var i = 0; i < n; ++i) {
  16346. var info = gl.getActiveUniform(program, i),
  16347. addr = gl.getUniformLocation(program, info.name);
  16348. parseUniform(info, addr, this);
  16349. }
  16350. }
  16351. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  16352. var u = this.map[name];
  16353. if (u !== undefined) u.setValue(gl, value, textures);
  16354. };
  16355. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  16356. var v = object[name];
  16357. if (v !== undefined) this.setValue(gl, name, v);
  16358. }; // Static interface
  16359. WebGLUniforms.upload = function (gl, seq, values, textures) {
  16360. for (var i = 0, n = seq.length; i !== n; ++i) {
  16361. var u = seq[i],
  16362. v = values[u.id];
  16363. if (v.needsUpdate !== false) {
  16364. // note: always updating when .needsUpdate is undefined
  16365. u.setValue(gl, v.value, textures);
  16366. }
  16367. }
  16368. };
  16369. WebGLUniforms.seqWithValue = function (seq, values) {
  16370. var r = [];
  16371. for (var i = 0, n = seq.length; i !== n; ++i) {
  16372. var u = seq[i];
  16373. if (u.id in values) r.push(u);
  16374. }
  16375. return r;
  16376. };
  16377. function WebGLShader(gl, type, string) {
  16378. var shader = gl.createShader(type);
  16379. gl.shaderSource(shader, string);
  16380. gl.compileShader(shader);
  16381. return shader;
  16382. }
  16383. var programIdCount = 0;
  16384. function addLineNumbers(string) {
  16385. var lines = string.split('\n');
  16386. for (var i = 0; i < lines.length; i++) {
  16387. lines[i] = i + 1 + ': ' + lines[i];
  16388. }
  16389. return lines.join('\n');
  16390. }
  16391. function getEncodingComponents(encoding) {
  16392. switch (encoding) {
  16393. case LinearEncoding:
  16394. return ['Linear', '( value )'];
  16395. case sRGBEncoding:
  16396. return ['sRGB', '( value )'];
  16397. case RGBEEncoding:
  16398. return ['RGBE', '( value )'];
  16399. case RGBM7Encoding:
  16400. return ['RGBM', '( value, 7.0 )'];
  16401. case RGBM16Encoding:
  16402. return ['RGBM', '( value, 16.0 )'];
  16403. case RGBDEncoding:
  16404. return ['RGBD', '( value, 256.0 )'];
  16405. case GammaEncoding:
  16406. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  16407. case LogLuvEncoding:
  16408. return ['LogLuv', '( value )'];
  16409. default:
  16410. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  16411. return ['Linear', '( value )'];
  16412. }
  16413. }
  16414. function getShaderErrors(gl, shader, type) {
  16415. var status = gl.getShaderParameter(shader, 35713);
  16416. var log = gl.getShaderInfoLog(shader).trim();
  16417. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  16418. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  16419. var source = gl.getShaderSource(shader);
  16420. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  16421. }
  16422. function getTexelDecodingFunction(functionName, encoding) {
  16423. var components = getEncodingComponents(encoding);
  16424. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  16425. }
  16426. function getTexelEncodingFunction(functionName, encoding) {
  16427. var components = getEncodingComponents(encoding);
  16428. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  16429. }
  16430. function getToneMappingFunction(functionName, toneMapping) {
  16431. var toneMappingName;
  16432. switch (toneMapping) {
  16433. case LinearToneMapping:
  16434. toneMappingName = 'Linear';
  16435. break;
  16436. case ReinhardToneMapping:
  16437. toneMappingName = 'Reinhard';
  16438. break;
  16439. case CineonToneMapping:
  16440. toneMappingName = 'OptimizedCineon';
  16441. break;
  16442. case ACESFilmicToneMapping:
  16443. toneMappingName = 'ACESFilmic';
  16444. break;
  16445. case CustomToneMapping:
  16446. toneMappingName = 'Custom';
  16447. break;
  16448. default:
  16449. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  16450. toneMappingName = 'Linear';
  16451. }
  16452. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  16453. }
  16454. function generateExtensions(parameters) {
  16455. var chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  16456. return chunks.filter(filterEmptyLine).join('\n');
  16457. }
  16458. function generateDefines(defines) {
  16459. var chunks = [];
  16460. for (var name in defines) {
  16461. var value = defines[name];
  16462. if (value === false) continue;
  16463. chunks.push('#define ' + name + ' ' + value);
  16464. }
  16465. return chunks.join('\n');
  16466. }
  16467. function fetchAttributeLocations(gl, program) {
  16468. var attributes = {};
  16469. var n = gl.getProgramParameter(program, 35721);
  16470. for (var i = 0; i < n; i++) {
  16471. var info = gl.getActiveAttrib(program, i);
  16472. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  16473. attributes[name] = gl.getAttribLocation(program, name);
  16474. }
  16475. return attributes;
  16476. }
  16477. function filterEmptyLine(string) {
  16478. return string !== '';
  16479. }
  16480. function replaceLightNums(string, parameters) {
  16481. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  16482. }
  16483. function replaceClippingPlaneNums(string, parameters) {
  16484. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  16485. } // Resolve Includes
  16486. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16487. function resolveIncludes(string) {
  16488. return string.replace(includePattern, includeReplacer);
  16489. }
  16490. function includeReplacer(match, include) {
  16491. var string = ShaderChunk[include];
  16492. if (string === undefined) {
  16493. throw new Error('Can not resolve #include <' + include + '>');
  16494. }
  16495. return resolveIncludes(string);
  16496. } // Unroll Loops
  16497. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16498. var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  16499. function unrollLoops(string) {
  16500. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  16501. }
  16502. function deprecatedLoopReplacer(match, start, end, snippet) {
  16503. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  16504. return loopReplacer(match, start, end, snippet);
  16505. }
  16506. function loopReplacer(match, start, end, snippet) {
  16507. var string = '';
  16508. for (var i = parseInt(start); i < parseInt(end); i++) {
  16509. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  16510. }
  16511. return string;
  16512. } //
  16513. function generatePrecision(parameters) {
  16514. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  16515. if (parameters.precision === "highp") {
  16516. precisionstring += "\n#define HIGH_PRECISION";
  16517. } else if (parameters.precision === "mediump") {
  16518. precisionstring += "\n#define MEDIUM_PRECISION";
  16519. } else if (parameters.precision === "lowp") {
  16520. precisionstring += "\n#define LOW_PRECISION";
  16521. }
  16522. return precisionstring;
  16523. }
  16524. function generateShadowMapTypeDefine(parameters) {
  16525. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16526. if (parameters.shadowMapType === PCFShadowMap) {
  16527. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16528. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  16529. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16530. } else if (parameters.shadowMapType === VSMShadowMap) {
  16531. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16532. }
  16533. return shadowMapTypeDefine;
  16534. }
  16535. function generateEnvMapTypeDefine(parameters) {
  16536. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16537. if (parameters.envMap) {
  16538. switch (parameters.envMapMode) {
  16539. case CubeReflectionMapping:
  16540. case CubeRefractionMapping:
  16541. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16542. break;
  16543. case CubeUVReflectionMapping:
  16544. case CubeUVRefractionMapping:
  16545. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16546. break;
  16547. }
  16548. }
  16549. return envMapTypeDefine;
  16550. }
  16551. function generateEnvMapModeDefine(parameters) {
  16552. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16553. if (parameters.envMap) {
  16554. switch (parameters.envMapMode) {
  16555. case CubeRefractionMapping:
  16556. case CubeUVRefractionMapping:
  16557. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16558. break;
  16559. }
  16560. }
  16561. return envMapModeDefine;
  16562. }
  16563. function generateEnvMapBlendingDefine(parameters) {
  16564. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  16565. if (parameters.envMap) {
  16566. switch (parameters.combine) {
  16567. case MultiplyOperation:
  16568. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16569. break;
  16570. case MixOperation:
  16571. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16572. break;
  16573. case AddOperation:
  16574. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16575. break;
  16576. }
  16577. }
  16578. return envMapBlendingDefine;
  16579. }
  16580. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  16581. var gl = renderer.getContext();
  16582. var defines = parameters.defines;
  16583. var vertexShader = parameters.vertexShader;
  16584. var fragmentShader = parameters.fragmentShader;
  16585. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  16586. var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  16587. var envMapModeDefine = generateEnvMapModeDefine(parameters);
  16588. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  16589. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  16590. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  16591. var customDefines = generateDefines(defines);
  16592. var program = gl.createProgram();
  16593. var prefixVertex, prefixFragment;
  16594. var versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + "\n" : '';
  16595. if (parameters.isRawShaderMaterial) {
  16596. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  16597. if (prefixVertex.length > 0) {
  16598. prefixVertex += '\n';
  16599. }
  16600. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  16601. if (prefixFragment.length > 0) {
  16602. prefixFragment += '\n';
  16603. }
  16604. } else {
  16605. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  16606. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  16607. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  16608. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  16609. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  16610. }
  16611. vertexShader = resolveIncludes(vertexShader);
  16612. vertexShader = replaceLightNums(vertexShader, parameters);
  16613. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  16614. fragmentShader = resolveIncludes(fragmentShader);
  16615. fragmentShader = replaceLightNums(fragmentShader, parameters);
  16616. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  16617. vertexShader = unrollLoops(vertexShader);
  16618. fragmentShader = unrollLoops(fragmentShader);
  16619. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  16620. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  16621. versionString = '#version 300 es\n';
  16622. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  16623. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  16624. }
  16625. var vertexGlsl = versionString + prefixVertex + vertexShader;
  16626. var fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  16627. // console.log( '*FRAGMENT*', fragmentGlsl );
  16628. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  16629. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  16630. gl.attachShader(program, glVertexShader);
  16631. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  16632. if (parameters.index0AttributeName !== undefined) {
  16633. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  16634. } else if (parameters.morphTargets === true) {
  16635. // programs with morphTargets displace position out of attribute 0
  16636. gl.bindAttribLocation(program, 0, 'position');
  16637. }
  16638. gl.linkProgram(program); // check for link errors
  16639. if (renderer.debug.checkShaderErrors) {
  16640. var programLog = gl.getProgramInfoLog(program).trim();
  16641. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  16642. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  16643. var runnable = true;
  16644. var haveDiagnostics = true;
  16645. if (gl.getProgramParameter(program, 35714) === false) {
  16646. runnable = false;
  16647. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  16648. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  16649. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  16650. } else if (programLog !== '') {
  16651. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  16652. } else if (vertexLog === '' || fragmentLog === '') {
  16653. haveDiagnostics = false;
  16654. }
  16655. if (haveDiagnostics) {
  16656. this.diagnostics = {
  16657. runnable: runnable,
  16658. programLog: programLog,
  16659. vertexShader: {
  16660. log: vertexLog,
  16661. prefix: prefixVertex
  16662. },
  16663. fragmentShader: {
  16664. log: fragmentLog,
  16665. prefix: prefixFragment
  16666. }
  16667. };
  16668. }
  16669. } // Clean up
  16670. // Crashes in iOS9 and iOS10. #18402
  16671. // gl.detachShader( program, glVertexShader );
  16672. // gl.detachShader( program, glFragmentShader );
  16673. gl.deleteShader(glVertexShader);
  16674. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  16675. var cachedUniforms;
  16676. this.getUniforms = function () {
  16677. if (cachedUniforms === undefined) {
  16678. cachedUniforms = new WebGLUniforms(gl, program);
  16679. }
  16680. return cachedUniforms;
  16681. }; // set up caching for attribute locations
  16682. var cachedAttributes;
  16683. this.getAttributes = function () {
  16684. if (cachedAttributes === undefined) {
  16685. cachedAttributes = fetchAttributeLocations(gl, program);
  16686. }
  16687. return cachedAttributes;
  16688. }; // free resource
  16689. this.destroy = function () {
  16690. bindingStates.releaseStatesOfProgram(this);
  16691. gl.deleteProgram(program);
  16692. this.program = undefined;
  16693. }; //
  16694. this.name = parameters.shaderName;
  16695. this.id = programIdCount++;
  16696. this.cacheKey = cacheKey;
  16697. this.usedTimes = 1;
  16698. this.program = program;
  16699. this.vertexShader = glVertexShader;
  16700. this.fragmentShader = glFragmentShader;
  16701. return this;
  16702. }
  16703. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  16704. var programs = [];
  16705. var isWebGL2 = capabilities.isWebGL2;
  16706. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  16707. var floatVertexTextures = capabilities.floatVertexTextures;
  16708. var maxVertexUniforms = capabilities.maxVertexUniforms;
  16709. var vertexTextures = capabilities.vertexTextures;
  16710. var precision = capabilities.precision;
  16711. var shaderIDs = {
  16712. MeshDepthMaterial: 'depth',
  16713. MeshDistanceMaterial: 'distanceRGBA',
  16714. MeshNormalMaterial: 'normal',
  16715. MeshBasicMaterial: 'basic',
  16716. MeshLambertMaterial: 'lambert',
  16717. MeshPhongMaterial: 'phong',
  16718. MeshToonMaterial: 'toon',
  16719. MeshStandardMaterial: 'physical',
  16720. MeshPhysicalMaterial: 'physical',
  16721. MeshMatcapMaterial: 'matcap',
  16722. LineBasicMaterial: 'basic',
  16723. LineDashedMaterial: 'dashed',
  16724. PointsMaterial: 'points',
  16725. ShadowMaterial: 'shadow',
  16726. SpriteMaterial: 'sprite'
  16727. };
  16728. var parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "instancingColor", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen", "transmissionMap"];
  16729. function getMaxBones(object) {
  16730. var skeleton = object.skeleton;
  16731. var bones = skeleton.bones;
  16732. if (floatVertexTextures) {
  16733. return 1024;
  16734. } else {
  16735. // default for when object is not specified
  16736. // ( for example when prebuilding shader to be used with multiple objects )
  16737. //
  16738. // - leave some extra space for other uniforms
  16739. // - limit here is ANGLE's 254 max uniform vectors
  16740. // (up to 54 should be safe)
  16741. var nVertexUniforms = maxVertexUniforms;
  16742. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  16743. var maxBones = Math.min(nVertexMatrices, bones.length);
  16744. if (maxBones < bones.length) {
  16745. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  16746. return 0;
  16747. }
  16748. return maxBones;
  16749. }
  16750. }
  16751. function getTextureEncodingFromMap(map) {
  16752. var encoding;
  16753. if (!map) {
  16754. encoding = LinearEncoding;
  16755. } else if (map.isTexture) {
  16756. encoding = map.encoding;
  16757. } else if (map.isWebGLRenderTarget) {
  16758. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  16759. encoding = map.texture.encoding;
  16760. }
  16761. return encoding;
  16762. }
  16763. function getParameters(material, lights, shadows, scene, object) {
  16764. var fog = scene.fog;
  16765. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  16766. var envMap = cubemaps.get(material.envMap || environment);
  16767. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  16768. // (not to blow over maxLights budget)
  16769. var maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  16770. if (material.precision !== null) {
  16771. precision = capabilities.getMaxPrecision(material.precision);
  16772. if (precision !== material.precision) {
  16773. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  16774. }
  16775. }
  16776. var vertexShader, fragmentShader;
  16777. if (shaderID) {
  16778. var shader = ShaderLib[shaderID];
  16779. vertexShader = shader.vertexShader;
  16780. fragmentShader = shader.fragmentShader;
  16781. } else {
  16782. vertexShader = material.vertexShader;
  16783. fragmentShader = material.fragmentShader;
  16784. }
  16785. var currentRenderTarget = renderer.getRenderTarget();
  16786. var parameters = {
  16787. isWebGL2: isWebGL2,
  16788. shaderID: shaderID,
  16789. shaderName: material.type,
  16790. vertexShader: vertexShader,
  16791. fragmentShader: fragmentShader,
  16792. defines: material.defines,
  16793. isRawShaderMaterial: material.isRawShaderMaterial === true,
  16794. glslVersion: material.glslVersion,
  16795. precision: precision,
  16796. instancing: object.isInstancedMesh === true,
  16797. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  16798. supportsVertexTextures: vertexTextures,
  16799. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  16800. map: !!material.map,
  16801. mapEncoding: getTextureEncodingFromMap(material.map),
  16802. matcap: !!material.matcap,
  16803. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  16804. envMap: !!envMap,
  16805. envMapMode: envMap && envMap.mapping,
  16806. envMapEncoding: getTextureEncodingFromMap(envMap),
  16807. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  16808. lightMap: !!material.lightMap,
  16809. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  16810. aoMap: !!material.aoMap,
  16811. emissiveMap: !!material.emissiveMap,
  16812. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  16813. bumpMap: !!material.bumpMap,
  16814. normalMap: !!material.normalMap,
  16815. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  16816. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  16817. clearcoatMap: !!material.clearcoatMap,
  16818. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  16819. clearcoatNormalMap: !!material.clearcoatNormalMap,
  16820. displacementMap: !!material.displacementMap,
  16821. roughnessMap: !!material.roughnessMap,
  16822. metalnessMap: !!material.metalnessMap,
  16823. specularMap: !!material.specularMap,
  16824. alphaMap: !!material.alphaMap,
  16825. gradientMap: !!material.gradientMap,
  16826. sheen: !!material.sheen,
  16827. transmissionMap: !!material.transmissionMap,
  16828. combine: material.combine,
  16829. vertexTangents: material.normalMap && material.vertexTangents,
  16830. vertexColors: material.vertexColors,
  16831. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap,
  16832. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  16833. fog: !!fog,
  16834. useFog: material.fog,
  16835. fogExp2: fog && fog.isFogExp2,
  16836. flatShading: material.flatShading,
  16837. sizeAttenuation: material.sizeAttenuation,
  16838. logarithmicDepthBuffer: logarithmicDepthBuffer,
  16839. skinning: material.skinning && maxBones > 0,
  16840. maxBones: maxBones,
  16841. useVertexTexture: floatVertexTextures,
  16842. morphTargets: material.morphTargets,
  16843. morphNormals: material.morphNormals,
  16844. maxMorphTargets: renderer.maxMorphTargets,
  16845. maxMorphNormals: renderer.maxMorphNormals,
  16846. numDirLights: lights.directional.length,
  16847. numPointLights: lights.point.length,
  16848. numSpotLights: lights.spot.length,
  16849. numRectAreaLights: lights.rectArea.length,
  16850. numHemiLights: lights.hemi.length,
  16851. numDirLightShadows: lights.directionalShadowMap.length,
  16852. numPointLightShadows: lights.pointShadowMap.length,
  16853. numSpotLightShadows: lights.spotShadowMap.length,
  16854. numClippingPlanes: clipping.numPlanes,
  16855. numClipIntersection: clipping.numIntersection,
  16856. dithering: material.dithering,
  16857. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  16858. shadowMapType: renderer.shadowMap.type,
  16859. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  16860. physicallyCorrectLights: renderer.physicallyCorrectLights,
  16861. premultipliedAlpha: material.premultipliedAlpha,
  16862. alphaTest: material.alphaTest,
  16863. doubleSided: material.side === DoubleSide,
  16864. flipSided: material.side === BackSide,
  16865. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  16866. index0AttributeName: material.index0AttributeName,
  16867. extensionDerivatives: material.extensions && material.extensions.derivatives,
  16868. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  16869. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  16870. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  16871. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  16872. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  16873. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  16874. customProgramCacheKey: material.customProgramCacheKey()
  16875. };
  16876. return parameters;
  16877. }
  16878. function getProgramCacheKey(parameters) {
  16879. var array = [];
  16880. if (parameters.shaderID) {
  16881. array.push(parameters.shaderID);
  16882. } else {
  16883. array.push(parameters.fragmentShader);
  16884. array.push(parameters.vertexShader);
  16885. }
  16886. if (parameters.defines !== undefined) {
  16887. for (var name in parameters.defines) {
  16888. array.push(name);
  16889. array.push(parameters.defines[name]);
  16890. }
  16891. }
  16892. if (parameters.isRawShaderMaterial === false) {
  16893. for (var i = 0; i < parameterNames.length; i++) {
  16894. array.push(parameters[parameterNames[i]]);
  16895. }
  16896. array.push(renderer.outputEncoding);
  16897. array.push(renderer.gammaFactor);
  16898. }
  16899. array.push(parameters.customProgramCacheKey);
  16900. return array.join();
  16901. }
  16902. function getUniforms(material) {
  16903. var shaderID = shaderIDs[material.type];
  16904. var uniforms;
  16905. if (shaderID) {
  16906. var shader = ShaderLib[shaderID];
  16907. uniforms = UniformsUtils.clone(shader.uniforms);
  16908. } else {
  16909. uniforms = material.uniforms;
  16910. }
  16911. return uniforms;
  16912. }
  16913. function acquireProgram(parameters, cacheKey) {
  16914. var program; // Check if code has been already compiled
  16915. for (var p = 0, pl = programs.length; p < pl; p++) {
  16916. var preexistingProgram = programs[p];
  16917. if (preexistingProgram.cacheKey === cacheKey) {
  16918. program = preexistingProgram;
  16919. ++program.usedTimes;
  16920. break;
  16921. }
  16922. }
  16923. if (program === undefined) {
  16924. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  16925. programs.push(program);
  16926. }
  16927. return program;
  16928. }
  16929. function releaseProgram(program) {
  16930. if (--program.usedTimes === 0) {
  16931. // Remove from unordered set
  16932. var i = programs.indexOf(program);
  16933. programs[i] = programs[programs.length - 1];
  16934. programs.pop(); // Free WebGL resources
  16935. program.destroy();
  16936. }
  16937. }
  16938. return {
  16939. getParameters: getParameters,
  16940. getProgramCacheKey: getProgramCacheKey,
  16941. getUniforms: getUniforms,
  16942. acquireProgram: acquireProgram,
  16943. releaseProgram: releaseProgram,
  16944. // Exposed for resource monitoring & error feedback via renderer.info:
  16945. programs: programs
  16946. };
  16947. }
  16948. function WebGLProperties() {
  16949. var properties = new WeakMap();
  16950. function get(object) {
  16951. var map = properties.get(object);
  16952. if (map === undefined) {
  16953. map = {};
  16954. properties.set(object, map);
  16955. }
  16956. return map;
  16957. }
  16958. function remove(object) {
  16959. properties.delete(object);
  16960. }
  16961. function update(object, key, value) {
  16962. properties.get(object)[key] = value;
  16963. }
  16964. function dispose() {
  16965. properties = new WeakMap();
  16966. }
  16967. return {
  16968. get: get,
  16969. remove: remove,
  16970. update: update,
  16971. dispose: dispose
  16972. };
  16973. }
  16974. function painterSortStable(a, b) {
  16975. if (a.groupOrder !== b.groupOrder) {
  16976. return a.groupOrder - b.groupOrder;
  16977. } else if (a.renderOrder !== b.renderOrder) {
  16978. return a.renderOrder - b.renderOrder;
  16979. } else if (a.program !== b.program) {
  16980. return a.program.id - b.program.id;
  16981. } else if (a.material.id !== b.material.id) {
  16982. return a.material.id - b.material.id;
  16983. } else if (a.z !== b.z) {
  16984. return a.z - b.z;
  16985. } else {
  16986. return a.id - b.id;
  16987. }
  16988. }
  16989. function reversePainterSortStable(a, b) {
  16990. if (a.groupOrder !== b.groupOrder) {
  16991. return a.groupOrder - b.groupOrder;
  16992. } else if (a.renderOrder !== b.renderOrder) {
  16993. return a.renderOrder - b.renderOrder;
  16994. } else if (a.z !== b.z) {
  16995. return b.z - a.z;
  16996. } else {
  16997. return a.id - b.id;
  16998. }
  16999. }
  17000. function WebGLRenderList(properties) {
  17001. var renderItems = [];
  17002. var renderItemsIndex = 0;
  17003. var opaque = [];
  17004. var transparent = [];
  17005. var defaultProgram = {
  17006. id: -1
  17007. };
  17008. function init() {
  17009. renderItemsIndex = 0;
  17010. opaque.length = 0;
  17011. transparent.length = 0;
  17012. }
  17013. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  17014. var renderItem = renderItems[renderItemsIndex];
  17015. var materialProperties = properties.get(material);
  17016. if (renderItem === undefined) {
  17017. renderItem = {
  17018. id: object.id,
  17019. object: object,
  17020. geometry: geometry,
  17021. material: material,
  17022. program: materialProperties.program || defaultProgram,
  17023. groupOrder: groupOrder,
  17024. renderOrder: object.renderOrder,
  17025. z: z,
  17026. group: group
  17027. };
  17028. renderItems[renderItemsIndex] = renderItem;
  17029. } else {
  17030. renderItem.id = object.id;
  17031. renderItem.object = object;
  17032. renderItem.geometry = geometry;
  17033. renderItem.material = material;
  17034. renderItem.program = materialProperties.program || defaultProgram;
  17035. renderItem.groupOrder = groupOrder;
  17036. renderItem.renderOrder = object.renderOrder;
  17037. renderItem.z = z;
  17038. renderItem.group = group;
  17039. }
  17040. renderItemsIndex++;
  17041. return renderItem;
  17042. }
  17043. function push(object, geometry, material, groupOrder, z, group) {
  17044. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17045. (material.transparent === true ? transparent : opaque).push(renderItem);
  17046. }
  17047. function unshift(object, geometry, material, groupOrder, z, group) {
  17048. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17049. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  17050. }
  17051. function sort(customOpaqueSort, customTransparentSort) {
  17052. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  17053. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  17054. }
  17055. function finish() {
  17056. // Clear references from inactive renderItems in the list
  17057. for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  17058. var renderItem = renderItems[i];
  17059. if (renderItem.id === null) break;
  17060. renderItem.id = null;
  17061. renderItem.object = null;
  17062. renderItem.geometry = null;
  17063. renderItem.material = null;
  17064. renderItem.program = null;
  17065. renderItem.group = null;
  17066. }
  17067. }
  17068. return {
  17069. opaque: opaque,
  17070. transparent: transparent,
  17071. init: init,
  17072. push: push,
  17073. unshift: unshift,
  17074. finish: finish,
  17075. sort: sort
  17076. };
  17077. }
  17078. function WebGLRenderLists(properties) {
  17079. var lists = new WeakMap();
  17080. function get(scene, camera) {
  17081. var cameras = lists.get(scene);
  17082. var list;
  17083. if (cameras === undefined) {
  17084. list = new WebGLRenderList(properties);
  17085. lists.set(scene, new WeakMap());
  17086. lists.get(scene).set(camera, list);
  17087. } else {
  17088. list = cameras.get(camera);
  17089. if (list === undefined) {
  17090. list = new WebGLRenderList(properties);
  17091. cameras.set(camera, list);
  17092. }
  17093. }
  17094. return list;
  17095. }
  17096. function dispose() {
  17097. lists = new WeakMap();
  17098. }
  17099. return {
  17100. get: get,
  17101. dispose: dispose
  17102. };
  17103. }
  17104. function UniformsCache() {
  17105. var lights = {};
  17106. return {
  17107. get: function get(light) {
  17108. if (lights[light.id] !== undefined) {
  17109. return lights[light.id];
  17110. }
  17111. var uniforms;
  17112. switch (light.type) {
  17113. case 'DirectionalLight':
  17114. uniforms = {
  17115. direction: new Vector3(),
  17116. color: new Color()
  17117. };
  17118. break;
  17119. case 'SpotLight':
  17120. uniforms = {
  17121. position: new Vector3(),
  17122. direction: new Vector3(),
  17123. color: new Color(),
  17124. distance: 0,
  17125. coneCos: 0,
  17126. penumbraCos: 0,
  17127. decay: 0
  17128. };
  17129. break;
  17130. case 'PointLight':
  17131. uniforms = {
  17132. position: new Vector3(),
  17133. color: new Color(),
  17134. distance: 0,
  17135. decay: 0
  17136. };
  17137. break;
  17138. case 'HemisphereLight':
  17139. uniforms = {
  17140. direction: new Vector3(),
  17141. skyColor: new Color(),
  17142. groundColor: new Color()
  17143. };
  17144. break;
  17145. case 'RectAreaLight':
  17146. uniforms = {
  17147. color: new Color(),
  17148. position: new Vector3(),
  17149. halfWidth: new Vector3(),
  17150. halfHeight: new Vector3()
  17151. };
  17152. break;
  17153. }
  17154. lights[light.id] = uniforms;
  17155. return uniforms;
  17156. }
  17157. };
  17158. }
  17159. function ShadowUniformsCache() {
  17160. var lights = {};
  17161. return {
  17162. get: function get(light) {
  17163. if (lights[light.id] !== undefined) {
  17164. return lights[light.id];
  17165. }
  17166. var uniforms;
  17167. switch (light.type) {
  17168. case 'DirectionalLight':
  17169. uniforms = {
  17170. shadowBias: 0,
  17171. shadowNormalBias: 0,
  17172. shadowRadius: 1,
  17173. shadowMapSize: new Vector2()
  17174. };
  17175. break;
  17176. case 'SpotLight':
  17177. uniforms = {
  17178. shadowBias: 0,
  17179. shadowNormalBias: 0,
  17180. shadowRadius: 1,
  17181. shadowMapSize: new Vector2()
  17182. };
  17183. break;
  17184. case 'PointLight':
  17185. uniforms = {
  17186. shadowBias: 0,
  17187. shadowNormalBias: 0,
  17188. shadowRadius: 1,
  17189. shadowMapSize: new Vector2(),
  17190. shadowCameraNear: 1,
  17191. shadowCameraFar: 1000
  17192. };
  17193. break;
  17194. // TODO (abelnation): set RectAreaLight shadow uniforms
  17195. }
  17196. lights[light.id] = uniforms;
  17197. return uniforms;
  17198. }
  17199. };
  17200. }
  17201. var nextVersion = 0;
  17202. function shadowCastingLightsFirst(lightA, lightB) {
  17203. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  17204. }
  17205. function WebGLLights(extensions, capabilities) {
  17206. var cache = new UniformsCache();
  17207. var shadowCache = ShadowUniformsCache();
  17208. var state = {
  17209. version: 0,
  17210. hash: {
  17211. directionalLength: -1,
  17212. pointLength: -1,
  17213. spotLength: -1,
  17214. rectAreaLength: -1,
  17215. hemiLength: -1,
  17216. numDirectionalShadows: -1,
  17217. numPointShadows: -1,
  17218. numSpotShadows: -1
  17219. },
  17220. ambient: [0, 0, 0],
  17221. probe: [],
  17222. directional: [],
  17223. directionalShadow: [],
  17224. directionalShadowMap: [],
  17225. directionalShadowMatrix: [],
  17226. spot: [],
  17227. spotShadow: [],
  17228. spotShadowMap: [],
  17229. spotShadowMatrix: [],
  17230. rectArea: [],
  17231. rectAreaLTC1: null,
  17232. rectAreaLTC2: null,
  17233. point: [],
  17234. pointShadow: [],
  17235. pointShadowMap: [],
  17236. pointShadowMatrix: [],
  17237. hemi: []
  17238. };
  17239. for (var i = 0; i < 9; i++) {
  17240. state.probe.push(new Vector3());
  17241. }
  17242. var vector3 = new Vector3();
  17243. var matrix4 = new Matrix4();
  17244. var matrix42 = new Matrix4();
  17245. function setup(lights, shadows, camera) {
  17246. var r = 0,
  17247. g = 0,
  17248. b = 0;
  17249. for (var _i = 0; _i < 9; _i++) {
  17250. state.probe[_i].set(0, 0, 0);
  17251. }
  17252. var directionalLength = 0;
  17253. var pointLength = 0;
  17254. var spotLength = 0;
  17255. var rectAreaLength = 0;
  17256. var hemiLength = 0;
  17257. var numDirectionalShadows = 0;
  17258. var numPointShadows = 0;
  17259. var numSpotShadows = 0;
  17260. var viewMatrix = camera.matrixWorldInverse;
  17261. lights.sort(shadowCastingLightsFirst);
  17262. for (var _i2 = 0, l = lights.length; _i2 < l; _i2++) {
  17263. var light = lights[_i2];
  17264. var color = light.color;
  17265. var intensity = light.intensity;
  17266. var distance = light.distance;
  17267. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  17268. if (light.isAmbientLight) {
  17269. r += color.r * intensity;
  17270. g += color.g * intensity;
  17271. b += color.b * intensity;
  17272. } else if (light.isLightProbe) {
  17273. for (var j = 0; j < 9; j++) {
  17274. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  17275. }
  17276. } else if (light.isDirectionalLight) {
  17277. var uniforms = cache.get(light);
  17278. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  17279. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17280. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17281. uniforms.direction.sub(vector3);
  17282. uniforms.direction.transformDirection(viewMatrix);
  17283. if (light.castShadow) {
  17284. var shadow = light.shadow;
  17285. var shadowUniforms = shadowCache.get(light);
  17286. shadowUniforms.shadowBias = shadow.bias;
  17287. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17288. shadowUniforms.shadowRadius = shadow.radius;
  17289. shadowUniforms.shadowMapSize = shadow.mapSize;
  17290. state.directionalShadow[directionalLength] = shadowUniforms;
  17291. state.directionalShadowMap[directionalLength] = shadowMap;
  17292. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  17293. numDirectionalShadows++;
  17294. }
  17295. state.directional[directionalLength] = uniforms;
  17296. directionalLength++;
  17297. } else if (light.isSpotLight) {
  17298. var _uniforms = cache.get(light);
  17299. _uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17300. _uniforms.position.applyMatrix4(viewMatrix);
  17301. _uniforms.color.copy(color).multiplyScalar(intensity);
  17302. _uniforms.distance = distance;
  17303. _uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17304. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17305. _uniforms.direction.sub(vector3);
  17306. _uniforms.direction.transformDirection(viewMatrix);
  17307. _uniforms.coneCos = Math.cos(light.angle);
  17308. _uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  17309. _uniforms.decay = light.decay;
  17310. if (light.castShadow) {
  17311. var _shadow = light.shadow;
  17312. var _shadowUniforms = shadowCache.get(light);
  17313. _shadowUniforms.shadowBias = _shadow.bias;
  17314. _shadowUniforms.shadowNormalBias = _shadow.normalBias;
  17315. _shadowUniforms.shadowRadius = _shadow.radius;
  17316. _shadowUniforms.shadowMapSize = _shadow.mapSize;
  17317. state.spotShadow[spotLength] = _shadowUniforms;
  17318. state.spotShadowMap[spotLength] = shadowMap;
  17319. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  17320. numSpotShadows++;
  17321. }
  17322. state.spot[spotLength] = _uniforms;
  17323. spotLength++;
  17324. } else if (light.isRectAreaLight) {
  17325. var _uniforms2 = cache.get(light); // (a) intensity is the total visible light emitted
  17326. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  17327. // (b) intensity is the brightness of the light
  17328. _uniforms2.color.copy(color).multiplyScalar(intensity);
  17329. _uniforms2.position.setFromMatrixPosition(light.matrixWorld);
  17330. _uniforms2.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  17331. matrix42.identity();
  17332. matrix4.copy(light.matrixWorld);
  17333. matrix4.premultiply(viewMatrix);
  17334. matrix42.extractRotation(matrix4);
  17335. _uniforms2.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17336. _uniforms2.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17337. _uniforms2.halfWidth.applyMatrix4(matrix42);
  17338. _uniforms2.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  17339. // uniforms.distance = distance;
  17340. state.rectArea[rectAreaLength] = _uniforms2;
  17341. rectAreaLength++;
  17342. } else if (light.isPointLight) {
  17343. var _uniforms3 = cache.get(light);
  17344. _uniforms3.position.setFromMatrixPosition(light.matrixWorld);
  17345. _uniforms3.position.applyMatrix4(viewMatrix);
  17346. _uniforms3.color.copy(light.color).multiplyScalar(light.intensity);
  17347. _uniforms3.distance = light.distance;
  17348. _uniforms3.decay = light.decay;
  17349. if (light.castShadow) {
  17350. var _shadow2 = light.shadow;
  17351. var _shadowUniforms2 = shadowCache.get(light);
  17352. _shadowUniforms2.shadowBias = _shadow2.bias;
  17353. _shadowUniforms2.shadowNormalBias = _shadow2.normalBias;
  17354. _shadowUniforms2.shadowRadius = _shadow2.radius;
  17355. _shadowUniforms2.shadowMapSize = _shadow2.mapSize;
  17356. _shadowUniforms2.shadowCameraNear = _shadow2.camera.near;
  17357. _shadowUniforms2.shadowCameraFar = _shadow2.camera.far;
  17358. state.pointShadow[pointLength] = _shadowUniforms2;
  17359. state.pointShadowMap[pointLength] = shadowMap;
  17360. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  17361. numPointShadows++;
  17362. }
  17363. state.point[pointLength] = _uniforms3;
  17364. pointLength++;
  17365. } else if (light.isHemisphereLight) {
  17366. var _uniforms4 = cache.get(light);
  17367. _uniforms4.direction.setFromMatrixPosition(light.matrixWorld);
  17368. _uniforms4.direction.transformDirection(viewMatrix);
  17369. _uniforms4.direction.normalize();
  17370. _uniforms4.skyColor.copy(light.color).multiplyScalar(intensity);
  17371. _uniforms4.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  17372. state.hemi[hemiLength] = _uniforms4;
  17373. hemiLength++;
  17374. }
  17375. }
  17376. if (rectAreaLength > 0) {
  17377. if (capabilities.isWebGL2) {
  17378. // WebGL 2
  17379. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17380. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17381. } else {
  17382. // WebGL 1
  17383. if (extensions.has('OES_texture_float_linear') === true) {
  17384. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17385. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17386. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  17387. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  17388. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  17389. } else {
  17390. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  17391. }
  17392. }
  17393. }
  17394. state.ambient[0] = r;
  17395. state.ambient[1] = g;
  17396. state.ambient[2] = b;
  17397. var hash = state.hash;
  17398. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  17399. state.directional.length = directionalLength;
  17400. state.spot.length = spotLength;
  17401. state.rectArea.length = rectAreaLength;
  17402. state.point.length = pointLength;
  17403. state.hemi.length = hemiLength;
  17404. state.directionalShadow.length = numDirectionalShadows;
  17405. state.directionalShadowMap.length = numDirectionalShadows;
  17406. state.pointShadow.length = numPointShadows;
  17407. state.pointShadowMap.length = numPointShadows;
  17408. state.spotShadow.length = numSpotShadows;
  17409. state.spotShadowMap.length = numSpotShadows;
  17410. state.directionalShadowMatrix.length = numDirectionalShadows;
  17411. state.pointShadowMatrix.length = numPointShadows;
  17412. state.spotShadowMatrix.length = numSpotShadows;
  17413. hash.directionalLength = directionalLength;
  17414. hash.pointLength = pointLength;
  17415. hash.spotLength = spotLength;
  17416. hash.rectAreaLength = rectAreaLength;
  17417. hash.hemiLength = hemiLength;
  17418. hash.numDirectionalShadows = numDirectionalShadows;
  17419. hash.numPointShadows = numPointShadows;
  17420. hash.numSpotShadows = numSpotShadows;
  17421. state.version = nextVersion++;
  17422. }
  17423. }
  17424. return {
  17425. setup: setup,
  17426. state: state
  17427. };
  17428. }
  17429. function WebGLRenderState(extensions, capabilities) {
  17430. var lights = new WebGLLights(extensions, capabilities);
  17431. var lightsArray = [];
  17432. var shadowsArray = [];
  17433. function init() {
  17434. lightsArray.length = 0;
  17435. shadowsArray.length = 0;
  17436. }
  17437. function pushLight(light) {
  17438. lightsArray.push(light);
  17439. }
  17440. function pushShadow(shadowLight) {
  17441. shadowsArray.push(shadowLight);
  17442. }
  17443. function setupLights(camera) {
  17444. lights.setup(lightsArray, shadowsArray, camera);
  17445. }
  17446. var state = {
  17447. lightsArray: lightsArray,
  17448. shadowsArray: shadowsArray,
  17449. lights: lights
  17450. };
  17451. return {
  17452. init: init,
  17453. state: state,
  17454. setupLights: setupLights,
  17455. pushLight: pushLight,
  17456. pushShadow: pushShadow
  17457. };
  17458. }
  17459. function WebGLRenderStates(extensions, capabilities) {
  17460. var renderStates = new WeakMap();
  17461. function get(scene, camera) {
  17462. var renderState;
  17463. if (renderStates.has(scene) === false) {
  17464. renderState = new WebGLRenderState(extensions, capabilities);
  17465. renderStates.set(scene, new WeakMap());
  17466. renderStates.get(scene).set(camera, renderState);
  17467. } else {
  17468. if (renderStates.get(scene).has(camera) === false) {
  17469. renderState = new WebGLRenderState(extensions, capabilities);
  17470. renderStates.get(scene).set(camera, renderState);
  17471. } else {
  17472. renderState = renderStates.get(scene).get(camera);
  17473. }
  17474. }
  17475. return renderState;
  17476. }
  17477. function dispose() {
  17478. renderStates = new WeakMap();
  17479. }
  17480. return {
  17481. get: get,
  17482. dispose: dispose
  17483. };
  17484. }
  17485. /**
  17486. * parameters = {
  17487. *
  17488. * opacity: <float>,
  17489. *
  17490. * map: new THREE.Texture( <Image> ),
  17491. *
  17492. * alphaMap: new THREE.Texture( <Image> ),
  17493. *
  17494. * displacementMap: new THREE.Texture( <Image> ),
  17495. * displacementScale: <float>,
  17496. * displacementBias: <float>,
  17497. *
  17498. * wireframe: <boolean>,
  17499. * wireframeLinewidth: <float>
  17500. * }
  17501. */
  17502. function MeshDepthMaterial(parameters) {
  17503. Material.call(this);
  17504. this.type = 'MeshDepthMaterial';
  17505. this.depthPacking = BasicDepthPacking;
  17506. this.skinning = false;
  17507. this.morphTargets = false;
  17508. this.map = null;
  17509. this.alphaMap = null;
  17510. this.displacementMap = null;
  17511. this.displacementScale = 1;
  17512. this.displacementBias = 0;
  17513. this.wireframe = false;
  17514. this.wireframeLinewidth = 1;
  17515. this.fog = false;
  17516. this.setValues(parameters);
  17517. }
  17518. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  17519. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  17520. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17521. MeshDepthMaterial.prototype.copy = function (source) {
  17522. Material.prototype.copy.call(this, source);
  17523. this.depthPacking = source.depthPacking;
  17524. this.skinning = source.skinning;
  17525. this.morphTargets = source.morphTargets;
  17526. this.map = source.map;
  17527. this.alphaMap = source.alphaMap;
  17528. this.displacementMap = source.displacementMap;
  17529. this.displacementScale = source.displacementScale;
  17530. this.displacementBias = source.displacementBias;
  17531. this.wireframe = source.wireframe;
  17532. this.wireframeLinewidth = source.wireframeLinewidth;
  17533. return this;
  17534. };
  17535. /**
  17536. * parameters = {
  17537. *
  17538. * referencePosition: <float>,
  17539. * nearDistance: <float>,
  17540. * farDistance: <float>,
  17541. *
  17542. * skinning: <bool>,
  17543. * morphTargets: <bool>,
  17544. *
  17545. * map: new THREE.Texture( <Image> ),
  17546. *
  17547. * alphaMap: new THREE.Texture( <Image> ),
  17548. *
  17549. * displacementMap: new THREE.Texture( <Image> ),
  17550. * displacementScale: <float>,
  17551. * displacementBias: <float>
  17552. *
  17553. * }
  17554. */
  17555. function MeshDistanceMaterial(parameters) {
  17556. Material.call(this);
  17557. this.type = 'MeshDistanceMaterial';
  17558. this.referencePosition = new Vector3();
  17559. this.nearDistance = 1;
  17560. this.farDistance = 1000;
  17561. this.skinning = false;
  17562. this.morphTargets = false;
  17563. this.map = null;
  17564. this.alphaMap = null;
  17565. this.displacementMap = null;
  17566. this.displacementScale = 1;
  17567. this.displacementBias = 0;
  17568. this.fog = false;
  17569. this.setValues(parameters);
  17570. }
  17571. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  17572. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  17573. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  17574. MeshDistanceMaterial.prototype.copy = function (source) {
  17575. Material.prototype.copy.call(this, source);
  17576. this.referencePosition.copy(source.referencePosition);
  17577. this.nearDistance = source.nearDistance;
  17578. this.farDistance = source.farDistance;
  17579. this.skinning = source.skinning;
  17580. this.morphTargets = source.morphTargets;
  17581. this.map = source.map;
  17582. this.alphaMap = source.alphaMap;
  17583. this.displacementMap = source.displacementMap;
  17584. this.displacementScale = source.displacementScale;
  17585. this.displacementBias = source.displacementBias;
  17586. return this;
  17587. };
  17588. var vsm_frag = /* glsl */
  17589. "\nuniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n\n#include <packing>\n\nvoid main() {\n\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\n\t// This seems totally useless but it's a crazy work around for a Adreno compiler bug\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\n\t\t#ifdef HORIZONAL_PASS\n\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\n\t\t#else\n\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\n\t\t#endif\n\n\t}\n\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n\n}\n";
  17590. var vsm_vert = /* glsl */
  17591. "\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}\n";
  17592. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  17593. var _frustum = new Frustum();
  17594. var _shadowMapSize = new Vector2(),
  17595. _viewportSize = new Vector2(),
  17596. _viewport = new Vector4(),
  17597. _depthMaterials = [],
  17598. _distanceMaterials = [],
  17599. _materialCache = {};
  17600. var shadowSide = {
  17601. 0: BackSide,
  17602. 1: FrontSide,
  17603. 2: DoubleSide
  17604. };
  17605. var shadowMaterialVertical = new ShaderMaterial({
  17606. defines: {
  17607. SAMPLE_RATE: 2.0 / 8.0,
  17608. HALF_SAMPLE_RATE: 1.0 / 8.0
  17609. },
  17610. uniforms: {
  17611. shadow_pass: {
  17612. value: null
  17613. },
  17614. resolution: {
  17615. value: new Vector2()
  17616. },
  17617. radius: {
  17618. value: 4.0
  17619. }
  17620. },
  17621. vertexShader: vsm_vert,
  17622. fragmentShader: vsm_frag
  17623. });
  17624. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  17625. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  17626. var fullScreenTri = new BufferGeometry();
  17627. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  17628. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  17629. var scope = this;
  17630. this.enabled = false;
  17631. this.autoUpdate = true;
  17632. this.needsUpdate = false;
  17633. this.type = PCFShadowMap;
  17634. this.render = function (lights, scene, camera) {
  17635. if (scope.enabled === false) return;
  17636. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  17637. if (lights.length === 0) return;
  17638. var currentRenderTarget = _renderer.getRenderTarget();
  17639. var activeCubeFace = _renderer.getActiveCubeFace();
  17640. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  17641. var _state = _renderer.state; // Set GL state for depth map.
  17642. _state.setBlending(NoBlending);
  17643. _state.buffers.color.setClear(1, 1, 1, 1);
  17644. _state.buffers.depth.setTest(true);
  17645. _state.setScissorTest(false); // render depth map
  17646. for (var i = 0, il = lights.length; i < il; i++) {
  17647. var light = lights[i];
  17648. var shadow = light.shadow;
  17649. if (shadow === undefined) {
  17650. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  17651. continue;
  17652. }
  17653. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  17654. _shadowMapSize.copy(shadow.mapSize);
  17655. var shadowFrameExtents = shadow.getFrameExtents();
  17656. _shadowMapSize.multiply(shadowFrameExtents);
  17657. _viewportSize.copy(shadow.mapSize);
  17658. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  17659. if (_shadowMapSize.x > maxTextureSize) {
  17660. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  17661. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  17662. shadow.mapSize.x = _viewportSize.x;
  17663. }
  17664. if (_shadowMapSize.y > maxTextureSize) {
  17665. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  17666. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  17667. shadow.mapSize.y = _viewportSize.y;
  17668. }
  17669. }
  17670. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  17671. var pars = {
  17672. minFilter: LinearFilter,
  17673. magFilter: LinearFilter,
  17674. format: RGBAFormat
  17675. };
  17676. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  17677. shadow.map.texture.name = light.name + ".shadowMap";
  17678. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  17679. shadow.camera.updateProjectionMatrix();
  17680. }
  17681. if (shadow.map === null) {
  17682. var _pars = {
  17683. minFilter: NearestFilter,
  17684. magFilter: NearestFilter,
  17685. format: RGBAFormat
  17686. };
  17687. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, _pars);
  17688. shadow.map.texture.name = light.name + ".shadowMap";
  17689. shadow.camera.updateProjectionMatrix();
  17690. }
  17691. _renderer.setRenderTarget(shadow.map);
  17692. _renderer.clear();
  17693. var viewportCount = shadow.getViewportCount();
  17694. for (var vp = 0; vp < viewportCount; vp++) {
  17695. var viewport = shadow.getViewport(vp);
  17696. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  17697. _state.viewport(_viewport);
  17698. shadow.updateMatrices(light, vp);
  17699. _frustum = shadow.getFrustum();
  17700. renderObject(scene, camera, shadow.camera, light, this.type);
  17701. } // do blur pass for VSM
  17702. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  17703. VSMPass(shadow, camera);
  17704. }
  17705. shadow.needsUpdate = false;
  17706. }
  17707. scope.needsUpdate = false;
  17708. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  17709. };
  17710. function VSMPass(shadow, camera) {
  17711. var geometry = _objects.update(fullScreenMesh); // vertical pass
  17712. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  17713. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  17714. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  17715. _renderer.setRenderTarget(shadow.mapPass);
  17716. _renderer.clear();
  17717. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  17718. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  17719. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  17720. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  17721. _renderer.setRenderTarget(shadow.map);
  17722. _renderer.clear();
  17723. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  17724. }
  17725. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  17726. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  17727. var material = _depthMaterials[index];
  17728. if (material === undefined) {
  17729. material = new MeshDepthMaterial({
  17730. depthPacking: RGBADepthPacking,
  17731. morphTargets: useMorphing,
  17732. skinning: useSkinning
  17733. });
  17734. _depthMaterials[index] = material;
  17735. }
  17736. return material;
  17737. }
  17738. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  17739. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  17740. var material = _distanceMaterials[index];
  17741. if (material === undefined) {
  17742. material = new MeshDistanceMaterial({
  17743. morphTargets: useMorphing,
  17744. skinning: useSkinning
  17745. });
  17746. _distanceMaterials[index] = material;
  17747. }
  17748. return material;
  17749. }
  17750. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  17751. var result = null;
  17752. var getMaterialVariant = getDepthMaterialVariant;
  17753. var customMaterial = object.customDepthMaterial;
  17754. if (light.isPointLight === true) {
  17755. getMaterialVariant = getDistanceMaterialVariant;
  17756. customMaterial = object.customDistanceMaterial;
  17757. }
  17758. if (customMaterial === undefined) {
  17759. var useMorphing = false;
  17760. if (material.morphTargets === true) {
  17761. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  17762. }
  17763. var useSkinning = false;
  17764. if (object.isSkinnedMesh === true) {
  17765. if (material.skinning === true) {
  17766. useSkinning = true;
  17767. } else {
  17768. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  17769. }
  17770. }
  17771. var useInstancing = object.isInstancedMesh === true;
  17772. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  17773. } else {
  17774. result = customMaterial;
  17775. }
  17776. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  17777. // in this case we need a unique material instance reflecting the
  17778. // appropriate state
  17779. var keyA = result.uuid,
  17780. keyB = material.uuid;
  17781. var materialsForVariant = _materialCache[keyA];
  17782. if (materialsForVariant === undefined) {
  17783. materialsForVariant = {};
  17784. _materialCache[keyA] = materialsForVariant;
  17785. }
  17786. var cachedMaterial = materialsForVariant[keyB];
  17787. if (cachedMaterial === undefined) {
  17788. cachedMaterial = result.clone();
  17789. materialsForVariant[keyB] = cachedMaterial;
  17790. }
  17791. result = cachedMaterial;
  17792. }
  17793. result.visible = material.visible;
  17794. result.wireframe = material.wireframe;
  17795. if (type === VSMShadowMap) {
  17796. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  17797. } else {
  17798. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  17799. }
  17800. result.clipShadows = material.clipShadows;
  17801. result.clippingPlanes = material.clippingPlanes;
  17802. result.clipIntersection = material.clipIntersection;
  17803. result.wireframeLinewidth = material.wireframeLinewidth;
  17804. result.linewidth = material.linewidth;
  17805. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  17806. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  17807. result.nearDistance = shadowCameraNear;
  17808. result.farDistance = shadowCameraFar;
  17809. }
  17810. return result;
  17811. }
  17812. function renderObject(object, camera, shadowCamera, light, type) {
  17813. if (object.visible === false) return;
  17814. var visible = object.layers.test(camera.layers);
  17815. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  17816. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  17817. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  17818. var geometry = _objects.update(object);
  17819. var material = object.material;
  17820. if (Array.isArray(material)) {
  17821. var groups = geometry.groups;
  17822. for (var k = 0, kl = groups.length; k < kl; k++) {
  17823. var group = groups[k];
  17824. var groupMaterial = material[group.materialIndex];
  17825. if (groupMaterial && groupMaterial.visible) {
  17826. var depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  17827. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  17828. }
  17829. }
  17830. } else if (material.visible) {
  17831. var _depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  17832. _renderer.renderBufferDirect(shadowCamera, null, geometry, _depthMaterial, object, null);
  17833. }
  17834. }
  17835. }
  17836. var children = object.children;
  17837. for (var i = 0, l = children.length; i < l; i++) {
  17838. renderObject(children[i], camera, shadowCamera, light, type);
  17839. }
  17840. }
  17841. }
  17842. function WebGLState(gl, extensions, capabilities) {
  17843. var _equationToGL, _factorToGL;
  17844. var isWebGL2 = capabilities.isWebGL2;
  17845. function ColorBuffer() {
  17846. var locked = false;
  17847. var color = new Vector4();
  17848. var currentColorMask = null;
  17849. var currentColorClear = new Vector4(0, 0, 0, 0);
  17850. return {
  17851. setMask: function setMask(colorMask) {
  17852. if (currentColorMask !== colorMask && !locked) {
  17853. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  17854. currentColorMask = colorMask;
  17855. }
  17856. },
  17857. setLocked: function setLocked(lock) {
  17858. locked = lock;
  17859. },
  17860. setClear: function setClear(r, g, b, a, premultipliedAlpha) {
  17861. if (premultipliedAlpha === true) {
  17862. r *= a;
  17863. g *= a;
  17864. b *= a;
  17865. }
  17866. color.set(r, g, b, a);
  17867. if (currentColorClear.equals(color) === false) {
  17868. gl.clearColor(r, g, b, a);
  17869. currentColorClear.copy(color);
  17870. }
  17871. },
  17872. reset: function reset() {
  17873. locked = false;
  17874. currentColorMask = null;
  17875. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  17876. }
  17877. };
  17878. }
  17879. function DepthBuffer() {
  17880. var locked = false;
  17881. var currentDepthMask = null;
  17882. var currentDepthFunc = null;
  17883. var currentDepthClear = null;
  17884. return {
  17885. setTest: function setTest(depthTest) {
  17886. if (depthTest) {
  17887. enable(2929);
  17888. } else {
  17889. disable(2929);
  17890. }
  17891. },
  17892. setMask: function setMask(depthMask) {
  17893. if (currentDepthMask !== depthMask && !locked) {
  17894. gl.depthMask(depthMask);
  17895. currentDepthMask = depthMask;
  17896. }
  17897. },
  17898. setFunc: function setFunc(depthFunc) {
  17899. if (currentDepthFunc !== depthFunc) {
  17900. if (depthFunc) {
  17901. switch (depthFunc) {
  17902. case NeverDepth:
  17903. gl.depthFunc(512);
  17904. break;
  17905. case AlwaysDepth:
  17906. gl.depthFunc(519);
  17907. break;
  17908. case LessDepth:
  17909. gl.depthFunc(513);
  17910. break;
  17911. case LessEqualDepth:
  17912. gl.depthFunc(515);
  17913. break;
  17914. case EqualDepth:
  17915. gl.depthFunc(514);
  17916. break;
  17917. case GreaterEqualDepth:
  17918. gl.depthFunc(518);
  17919. break;
  17920. case GreaterDepth:
  17921. gl.depthFunc(516);
  17922. break;
  17923. case NotEqualDepth:
  17924. gl.depthFunc(517);
  17925. break;
  17926. default:
  17927. gl.depthFunc(515);
  17928. }
  17929. } else {
  17930. gl.depthFunc(515);
  17931. }
  17932. currentDepthFunc = depthFunc;
  17933. }
  17934. },
  17935. setLocked: function setLocked(lock) {
  17936. locked = lock;
  17937. },
  17938. setClear: function setClear(depth) {
  17939. if (currentDepthClear !== depth) {
  17940. gl.clearDepth(depth);
  17941. currentDepthClear = depth;
  17942. }
  17943. },
  17944. reset: function reset() {
  17945. locked = false;
  17946. currentDepthMask = null;
  17947. currentDepthFunc = null;
  17948. currentDepthClear = null;
  17949. }
  17950. };
  17951. }
  17952. function StencilBuffer() {
  17953. var locked = false;
  17954. var currentStencilMask = null;
  17955. var currentStencilFunc = null;
  17956. var currentStencilRef = null;
  17957. var currentStencilFuncMask = null;
  17958. var currentStencilFail = null;
  17959. var currentStencilZFail = null;
  17960. var currentStencilZPass = null;
  17961. var currentStencilClear = null;
  17962. return {
  17963. setTest: function setTest(stencilTest) {
  17964. if (!locked) {
  17965. if (stencilTest) {
  17966. enable(2960);
  17967. } else {
  17968. disable(2960);
  17969. }
  17970. }
  17971. },
  17972. setMask: function setMask(stencilMask) {
  17973. if (currentStencilMask !== stencilMask && !locked) {
  17974. gl.stencilMask(stencilMask);
  17975. currentStencilMask = stencilMask;
  17976. }
  17977. },
  17978. setFunc: function setFunc(stencilFunc, stencilRef, stencilMask) {
  17979. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  17980. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  17981. currentStencilFunc = stencilFunc;
  17982. currentStencilRef = stencilRef;
  17983. currentStencilFuncMask = stencilMask;
  17984. }
  17985. },
  17986. setOp: function setOp(stencilFail, stencilZFail, stencilZPass) {
  17987. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  17988. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  17989. currentStencilFail = stencilFail;
  17990. currentStencilZFail = stencilZFail;
  17991. currentStencilZPass = stencilZPass;
  17992. }
  17993. },
  17994. setLocked: function setLocked(lock) {
  17995. locked = lock;
  17996. },
  17997. setClear: function setClear(stencil) {
  17998. if (currentStencilClear !== stencil) {
  17999. gl.clearStencil(stencil);
  18000. currentStencilClear = stencil;
  18001. }
  18002. },
  18003. reset: function reset() {
  18004. locked = false;
  18005. currentStencilMask = null;
  18006. currentStencilFunc = null;
  18007. currentStencilRef = null;
  18008. currentStencilFuncMask = null;
  18009. currentStencilFail = null;
  18010. currentStencilZFail = null;
  18011. currentStencilZPass = null;
  18012. currentStencilClear = null;
  18013. }
  18014. };
  18015. } //
  18016. var colorBuffer = new ColorBuffer();
  18017. var depthBuffer = new DepthBuffer();
  18018. var stencilBuffer = new StencilBuffer();
  18019. var enabledCapabilities = {};
  18020. var currentProgram = null;
  18021. var currentBlendingEnabled = null;
  18022. var currentBlending = null;
  18023. var currentBlendEquation = null;
  18024. var currentBlendSrc = null;
  18025. var currentBlendDst = null;
  18026. var currentBlendEquationAlpha = null;
  18027. var currentBlendSrcAlpha = null;
  18028. var currentBlendDstAlpha = null;
  18029. var currentPremultipledAlpha = false;
  18030. var currentFlipSided = null;
  18031. var currentCullFace = null;
  18032. var currentLineWidth = null;
  18033. var currentPolygonOffsetFactor = null;
  18034. var currentPolygonOffsetUnits = null;
  18035. var maxTextures = gl.getParameter(35661);
  18036. var lineWidthAvailable = false;
  18037. var version = 0;
  18038. var glVersion = gl.getParameter(7938);
  18039. if (glVersion.indexOf('WebGL') !== -1) {
  18040. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  18041. lineWidthAvailable = version >= 1.0;
  18042. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  18043. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  18044. lineWidthAvailable = version >= 2.0;
  18045. }
  18046. var currentTextureSlot = null;
  18047. var currentBoundTextures = {};
  18048. var currentScissor = new Vector4();
  18049. var currentViewport = new Vector4();
  18050. function createTexture(type, target, count) {
  18051. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  18052. var texture = gl.createTexture();
  18053. gl.bindTexture(type, texture);
  18054. gl.texParameteri(type, 10241, 9728);
  18055. gl.texParameteri(type, 10240, 9728);
  18056. for (var i = 0; i < count; i++) {
  18057. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  18058. }
  18059. return texture;
  18060. }
  18061. var emptyTextures = {};
  18062. emptyTextures[3553] = createTexture(3553, 3553, 1);
  18063. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  18064. colorBuffer.setClear(0, 0, 0, 1);
  18065. depthBuffer.setClear(1);
  18066. stencilBuffer.setClear(0);
  18067. enable(2929);
  18068. depthBuffer.setFunc(LessEqualDepth);
  18069. setFlipSided(false);
  18070. setCullFace(CullFaceBack);
  18071. enable(2884);
  18072. setBlending(NoBlending); //
  18073. function enable(id) {
  18074. if (enabledCapabilities[id] !== true) {
  18075. gl.enable(id);
  18076. enabledCapabilities[id] = true;
  18077. }
  18078. }
  18079. function disable(id) {
  18080. if (enabledCapabilities[id] !== false) {
  18081. gl.disable(id);
  18082. enabledCapabilities[id] = false;
  18083. }
  18084. }
  18085. function useProgram(program) {
  18086. if (currentProgram !== program) {
  18087. gl.useProgram(program);
  18088. currentProgram = program;
  18089. return true;
  18090. }
  18091. return false;
  18092. }
  18093. var equationToGL = (_equationToGL = {}, _equationToGL[AddEquation] = 32774, _equationToGL[SubtractEquation] = 32778, _equationToGL[ReverseSubtractEquation] = 32779, _equationToGL);
  18094. if (isWebGL2) {
  18095. equationToGL[MinEquation] = 32775;
  18096. equationToGL[MaxEquation] = 32776;
  18097. } else {
  18098. var extension = extensions.get('EXT_blend_minmax');
  18099. if (extension !== null) {
  18100. equationToGL[MinEquation] = extension.MIN_EXT;
  18101. equationToGL[MaxEquation] = extension.MAX_EXT;
  18102. }
  18103. }
  18104. var factorToGL = (_factorToGL = {}, _factorToGL[ZeroFactor] = 0, _factorToGL[OneFactor] = 1, _factorToGL[SrcColorFactor] = 768, _factorToGL[SrcAlphaFactor] = 770, _factorToGL[SrcAlphaSaturateFactor] = 776, _factorToGL[DstColorFactor] = 774, _factorToGL[DstAlphaFactor] = 772, _factorToGL[OneMinusSrcColorFactor] = 769, _factorToGL[OneMinusSrcAlphaFactor] = 771, _factorToGL[OneMinusDstColorFactor] = 775, _factorToGL[OneMinusDstAlphaFactor] = 773, _factorToGL);
  18105. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  18106. if (blending === NoBlending) {
  18107. if (currentBlendingEnabled) {
  18108. disable(3042);
  18109. currentBlendingEnabled = false;
  18110. }
  18111. return;
  18112. }
  18113. if (!currentBlendingEnabled) {
  18114. enable(3042);
  18115. currentBlendingEnabled = true;
  18116. }
  18117. if (blending !== CustomBlending) {
  18118. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  18119. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  18120. gl.blendEquation(32774);
  18121. currentBlendEquation = AddEquation;
  18122. currentBlendEquationAlpha = AddEquation;
  18123. }
  18124. if (premultipliedAlpha) {
  18125. switch (blending) {
  18126. case NormalBlending:
  18127. gl.blendFuncSeparate(1, 771, 1, 771);
  18128. break;
  18129. case AdditiveBlending:
  18130. gl.blendFunc(1, 1);
  18131. break;
  18132. case SubtractiveBlending:
  18133. gl.blendFuncSeparate(0, 0, 769, 771);
  18134. break;
  18135. case MultiplyBlending:
  18136. gl.blendFuncSeparate(0, 768, 0, 770);
  18137. break;
  18138. default:
  18139. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18140. break;
  18141. }
  18142. } else {
  18143. switch (blending) {
  18144. case NormalBlending:
  18145. gl.blendFuncSeparate(770, 771, 1, 771);
  18146. break;
  18147. case AdditiveBlending:
  18148. gl.blendFunc(770, 1);
  18149. break;
  18150. case SubtractiveBlending:
  18151. gl.blendFunc(0, 769);
  18152. break;
  18153. case MultiplyBlending:
  18154. gl.blendFunc(0, 768);
  18155. break;
  18156. default:
  18157. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18158. break;
  18159. }
  18160. }
  18161. currentBlendSrc = null;
  18162. currentBlendDst = null;
  18163. currentBlendSrcAlpha = null;
  18164. currentBlendDstAlpha = null;
  18165. currentBlending = blending;
  18166. currentPremultipledAlpha = premultipliedAlpha;
  18167. }
  18168. return;
  18169. } // custom blending
  18170. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18171. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18172. blendDstAlpha = blendDstAlpha || blendDst;
  18173. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  18174. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  18175. currentBlendEquation = blendEquation;
  18176. currentBlendEquationAlpha = blendEquationAlpha;
  18177. }
  18178. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  18179. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  18180. currentBlendSrc = blendSrc;
  18181. currentBlendDst = blendDst;
  18182. currentBlendSrcAlpha = blendSrcAlpha;
  18183. currentBlendDstAlpha = blendDstAlpha;
  18184. }
  18185. currentBlending = blending;
  18186. currentPremultipledAlpha = null;
  18187. }
  18188. function setMaterial(material, frontFaceCW) {
  18189. material.side === DoubleSide ? disable(2884) : enable(2884);
  18190. var flipSided = material.side === BackSide;
  18191. if (frontFaceCW) flipSided = !flipSided;
  18192. setFlipSided(flipSided);
  18193. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  18194. depthBuffer.setFunc(material.depthFunc);
  18195. depthBuffer.setTest(material.depthTest);
  18196. depthBuffer.setMask(material.depthWrite);
  18197. colorBuffer.setMask(material.colorWrite);
  18198. var stencilWrite = material.stencilWrite;
  18199. stencilBuffer.setTest(stencilWrite);
  18200. if (stencilWrite) {
  18201. stencilBuffer.setMask(material.stencilWriteMask);
  18202. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  18203. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  18204. }
  18205. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  18206. } //
  18207. function setFlipSided(flipSided) {
  18208. if (currentFlipSided !== flipSided) {
  18209. if (flipSided) {
  18210. gl.frontFace(2304);
  18211. } else {
  18212. gl.frontFace(2305);
  18213. }
  18214. currentFlipSided = flipSided;
  18215. }
  18216. }
  18217. function setCullFace(cullFace) {
  18218. if (cullFace !== CullFaceNone) {
  18219. enable(2884);
  18220. if (cullFace !== currentCullFace) {
  18221. if (cullFace === CullFaceBack) {
  18222. gl.cullFace(1029);
  18223. } else if (cullFace === CullFaceFront) {
  18224. gl.cullFace(1028);
  18225. } else {
  18226. gl.cullFace(1032);
  18227. }
  18228. }
  18229. } else {
  18230. disable(2884);
  18231. }
  18232. currentCullFace = cullFace;
  18233. }
  18234. function setLineWidth(width) {
  18235. if (width !== currentLineWidth) {
  18236. if (lineWidthAvailable) gl.lineWidth(width);
  18237. currentLineWidth = width;
  18238. }
  18239. }
  18240. function setPolygonOffset(polygonOffset, factor, units) {
  18241. if (polygonOffset) {
  18242. enable(32823);
  18243. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  18244. gl.polygonOffset(factor, units);
  18245. currentPolygonOffsetFactor = factor;
  18246. currentPolygonOffsetUnits = units;
  18247. }
  18248. } else {
  18249. disable(32823);
  18250. }
  18251. }
  18252. function setScissorTest(scissorTest) {
  18253. if (scissorTest) {
  18254. enable(3089);
  18255. } else {
  18256. disable(3089);
  18257. }
  18258. } // texture
  18259. function activeTexture(webglSlot) {
  18260. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  18261. if (currentTextureSlot !== webglSlot) {
  18262. gl.activeTexture(webglSlot);
  18263. currentTextureSlot = webglSlot;
  18264. }
  18265. }
  18266. function bindTexture(webglType, webglTexture) {
  18267. if (currentTextureSlot === null) {
  18268. activeTexture();
  18269. }
  18270. var boundTexture = currentBoundTextures[currentTextureSlot];
  18271. if (boundTexture === undefined) {
  18272. boundTexture = {
  18273. type: undefined,
  18274. texture: undefined
  18275. };
  18276. currentBoundTextures[currentTextureSlot] = boundTexture;
  18277. }
  18278. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  18279. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  18280. boundTexture.type = webglType;
  18281. boundTexture.texture = webglTexture;
  18282. }
  18283. }
  18284. function unbindTexture() {
  18285. var boundTexture = currentBoundTextures[currentTextureSlot];
  18286. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  18287. gl.bindTexture(boundTexture.type, null);
  18288. boundTexture.type = undefined;
  18289. boundTexture.texture = undefined;
  18290. }
  18291. }
  18292. function compressedTexImage2D() {
  18293. try {
  18294. gl.compressedTexImage2D.apply(gl, arguments);
  18295. } catch (error) {
  18296. console.error('THREE.WebGLState:', error);
  18297. }
  18298. }
  18299. function texImage2D() {
  18300. try {
  18301. gl.texImage2D.apply(gl, arguments);
  18302. } catch (error) {
  18303. console.error('THREE.WebGLState:', error);
  18304. }
  18305. }
  18306. function texImage3D() {
  18307. try {
  18308. gl.texImage3D.apply(gl, arguments);
  18309. } catch (error) {
  18310. console.error('THREE.WebGLState:', error);
  18311. }
  18312. } //
  18313. function scissor(scissor) {
  18314. if (currentScissor.equals(scissor) === false) {
  18315. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  18316. currentScissor.copy(scissor);
  18317. }
  18318. }
  18319. function viewport(viewport) {
  18320. if (currentViewport.equals(viewport) === false) {
  18321. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  18322. currentViewport.copy(viewport);
  18323. }
  18324. } //
  18325. function reset() {
  18326. enabledCapabilities = {};
  18327. currentTextureSlot = null;
  18328. currentBoundTextures = {};
  18329. currentProgram = null;
  18330. currentBlendingEnabled = null;
  18331. currentBlending = null;
  18332. currentBlendEquation = null;
  18333. currentBlendSrc = null;
  18334. currentBlendDst = null;
  18335. currentBlendEquationAlpha = null;
  18336. currentBlendSrcAlpha = null;
  18337. currentBlendDstAlpha = null;
  18338. currentPremultipledAlpha = false;
  18339. currentFlipSided = null;
  18340. currentCullFace = null;
  18341. currentLineWidth = null;
  18342. currentPolygonOffsetFactor = null;
  18343. currentPolygonOffsetUnits = null;
  18344. colorBuffer.reset();
  18345. depthBuffer.reset();
  18346. stencilBuffer.reset();
  18347. }
  18348. return {
  18349. buffers: {
  18350. color: colorBuffer,
  18351. depth: depthBuffer,
  18352. stencil: stencilBuffer
  18353. },
  18354. enable: enable,
  18355. disable: disable,
  18356. useProgram: useProgram,
  18357. setBlending: setBlending,
  18358. setMaterial: setMaterial,
  18359. setFlipSided: setFlipSided,
  18360. setCullFace: setCullFace,
  18361. setLineWidth: setLineWidth,
  18362. setPolygonOffset: setPolygonOffset,
  18363. setScissorTest: setScissorTest,
  18364. activeTexture: activeTexture,
  18365. bindTexture: bindTexture,
  18366. unbindTexture: unbindTexture,
  18367. compressedTexImage2D: compressedTexImage2D,
  18368. texImage2D: texImage2D,
  18369. texImage3D: texImage3D,
  18370. scissor: scissor,
  18371. viewport: viewport,
  18372. reset: reset
  18373. };
  18374. }
  18375. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  18376. var _wrappingToGL, _filterToGL;
  18377. var isWebGL2 = capabilities.isWebGL2;
  18378. var maxTextures = capabilities.maxTextures;
  18379. var maxCubemapSize = capabilities.maxCubemapSize;
  18380. var maxTextureSize = capabilities.maxTextureSize;
  18381. var maxSamples = capabilities.maxSamples;
  18382. var _videoTextures = new WeakMap();
  18383. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18384. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18385. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  18386. var useOffscreenCanvas = false;
  18387. try {
  18388. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  18389. } catch (err) {// Ignore any errors
  18390. }
  18391. function createCanvas(width, height) {
  18392. // Use OffscreenCanvas when available. Specially needed in web workers
  18393. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  18394. }
  18395. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  18396. var scale = 1; // handle case if texture exceeds max size
  18397. if (image.width > maxSize || image.height > maxSize) {
  18398. scale = maxSize / Math.max(image.width, image.height);
  18399. } // only perform resize if necessary
  18400. if (scale < 1 || needsPowerOfTwo === true) {
  18401. // only perform resize for certain image types
  18402. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  18403. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  18404. var width = floor(scale * image.width);
  18405. var height = floor(scale * image.height);
  18406. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  18407. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  18408. canvas.width = width;
  18409. canvas.height = height;
  18410. var context = canvas.getContext('2d');
  18411. context.drawImage(image, 0, 0, width, height);
  18412. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  18413. return canvas;
  18414. } else {
  18415. if ('data' in image) {
  18416. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  18417. }
  18418. return image;
  18419. }
  18420. }
  18421. return image;
  18422. }
  18423. function isPowerOfTwo(image) {
  18424. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  18425. }
  18426. function textureNeedsPowerOfTwo(texture) {
  18427. if (isWebGL2) return false;
  18428. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18429. }
  18430. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  18431. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18432. }
  18433. function generateMipmap(target, texture, width, height) {
  18434. _gl.generateMipmap(target);
  18435. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  18436. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  18437. }
  18438. function getInternalFormat(internalFormatName, glFormat, glType) {
  18439. if (isWebGL2 === false) return glFormat;
  18440. if (internalFormatName !== null) {
  18441. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  18442. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  18443. }
  18444. var internalFormat = glFormat;
  18445. if (glFormat === 6403) {
  18446. if (glType === 5126) internalFormat = 33326;
  18447. if (glType === 5131) internalFormat = 33325;
  18448. if (glType === 5121) internalFormat = 33321;
  18449. }
  18450. if (glFormat === 6407) {
  18451. if (glType === 5126) internalFormat = 34837;
  18452. if (glType === 5131) internalFormat = 34843;
  18453. if (glType === 5121) internalFormat = 32849;
  18454. }
  18455. if (glFormat === 6408) {
  18456. if (glType === 5126) internalFormat = 34836;
  18457. if (glType === 5131) internalFormat = 34842;
  18458. if (glType === 5121) internalFormat = 32856;
  18459. }
  18460. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  18461. extensions.get('EXT_color_buffer_float');
  18462. }
  18463. return internalFormat;
  18464. } // Fallback filters for non-power-of-2 textures
  18465. function filterFallback(f) {
  18466. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  18467. return 9728;
  18468. }
  18469. return 9729;
  18470. } //
  18471. function onTextureDispose(event) {
  18472. var texture = event.target;
  18473. texture.removeEventListener('dispose', onTextureDispose);
  18474. deallocateTexture(texture);
  18475. if (texture.isVideoTexture) {
  18476. _videoTextures.delete(texture);
  18477. }
  18478. info.memory.textures--;
  18479. }
  18480. function onRenderTargetDispose(event) {
  18481. var renderTarget = event.target;
  18482. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  18483. deallocateRenderTarget(renderTarget);
  18484. info.memory.textures--;
  18485. } //
  18486. function deallocateTexture(texture) {
  18487. var textureProperties = properties.get(texture);
  18488. if (textureProperties.__webglInit === undefined) return;
  18489. _gl.deleteTexture(textureProperties.__webglTexture);
  18490. properties.remove(texture);
  18491. }
  18492. function deallocateRenderTarget(renderTarget) {
  18493. var renderTargetProperties = properties.get(renderTarget);
  18494. var textureProperties = properties.get(renderTarget.texture);
  18495. if (!renderTarget) return;
  18496. if (textureProperties.__webglTexture !== undefined) {
  18497. _gl.deleteTexture(textureProperties.__webglTexture);
  18498. }
  18499. if (renderTarget.depthTexture) {
  18500. renderTarget.depthTexture.dispose();
  18501. }
  18502. if (renderTarget.isWebGLCubeRenderTarget) {
  18503. for (var i = 0; i < 6; i++) {
  18504. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  18505. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  18506. }
  18507. } else {
  18508. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  18509. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  18510. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  18511. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  18512. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  18513. }
  18514. properties.remove(renderTarget.texture);
  18515. properties.remove(renderTarget);
  18516. } //
  18517. var textureUnits = 0;
  18518. function resetTextureUnits() {
  18519. textureUnits = 0;
  18520. }
  18521. function allocateTextureUnit() {
  18522. var textureUnit = textureUnits;
  18523. if (textureUnit >= maxTextures) {
  18524. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  18525. }
  18526. textureUnits += 1;
  18527. return textureUnit;
  18528. } //
  18529. function setTexture2D(texture, slot) {
  18530. var textureProperties = properties.get(texture);
  18531. if (texture.isVideoTexture) updateVideoTexture(texture);
  18532. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  18533. var image = texture.image;
  18534. if (image === undefined) {
  18535. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  18536. } else if (image.complete === false) {
  18537. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  18538. } else {
  18539. uploadTexture(textureProperties, texture, slot);
  18540. return;
  18541. }
  18542. }
  18543. state.activeTexture(33984 + slot);
  18544. state.bindTexture(3553, textureProperties.__webglTexture);
  18545. }
  18546. function setTexture2DArray(texture, slot) {
  18547. var textureProperties = properties.get(texture);
  18548. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  18549. uploadTexture(textureProperties, texture, slot);
  18550. return;
  18551. }
  18552. state.activeTexture(33984 + slot);
  18553. state.bindTexture(35866, textureProperties.__webglTexture);
  18554. }
  18555. function setTexture3D(texture, slot) {
  18556. var textureProperties = properties.get(texture);
  18557. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  18558. uploadTexture(textureProperties, texture, slot);
  18559. return;
  18560. }
  18561. state.activeTexture(33984 + slot);
  18562. state.bindTexture(32879, textureProperties.__webglTexture);
  18563. }
  18564. function setTextureCube(texture, slot) {
  18565. var textureProperties = properties.get(texture);
  18566. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  18567. uploadCubeTexture(textureProperties, texture, slot);
  18568. return;
  18569. }
  18570. state.activeTexture(33984 + slot);
  18571. state.bindTexture(34067, textureProperties.__webglTexture);
  18572. }
  18573. var wrappingToGL = (_wrappingToGL = {}, _wrappingToGL[RepeatWrapping] = 10497, _wrappingToGL[ClampToEdgeWrapping] = 33071, _wrappingToGL[MirroredRepeatWrapping] = 33648, _wrappingToGL);
  18574. var filterToGL = (_filterToGL = {}, _filterToGL[NearestFilter] = 9728, _filterToGL[NearestMipmapNearestFilter] = 9984, _filterToGL[NearestMipmapLinearFilter] = 9986, _filterToGL[LinearFilter] = 9729, _filterToGL[LinearMipmapNearestFilter] = 9985, _filterToGL[LinearMipmapLinearFilter] = 9987, _filterToGL);
  18575. function setTextureParameters(textureType, texture, supportsMips) {
  18576. if (supportsMips) {
  18577. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  18578. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  18579. if (textureType === 32879 || textureType === 35866) {
  18580. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  18581. }
  18582. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  18583. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  18584. } else {
  18585. _gl.texParameteri(textureType, 10242, 33071);
  18586. _gl.texParameteri(textureType, 10243, 33071);
  18587. if (textureType === 32879 || textureType === 35866) {
  18588. _gl.texParameteri(textureType, 32882, 33071);
  18589. }
  18590. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  18591. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  18592. }
  18593. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  18594. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  18595. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  18596. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  18597. }
  18598. }
  18599. var extension = extensions.get('EXT_texture_filter_anisotropic');
  18600. if (extension) {
  18601. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  18602. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  18603. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  18604. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  18605. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  18606. }
  18607. }
  18608. }
  18609. function initTexture(textureProperties, texture) {
  18610. if (textureProperties.__webglInit === undefined) {
  18611. textureProperties.__webglInit = true;
  18612. texture.addEventListener('dispose', onTextureDispose);
  18613. textureProperties.__webglTexture = _gl.createTexture();
  18614. info.memory.textures++;
  18615. }
  18616. }
  18617. function uploadTexture(textureProperties, texture, slot) {
  18618. var textureType = 3553;
  18619. if (texture.isDataTexture2DArray) textureType = 35866;
  18620. if (texture.isDataTexture3D) textureType = 32879;
  18621. initTexture(textureProperties, texture);
  18622. state.activeTexture(33984 + slot);
  18623. state.bindTexture(textureType, textureProperties.__webglTexture);
  18624. _gl.pixelStorei(37440, texture.flipY);
  18625. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  18626. _gl.pixelStorei(3317, texture.unpackAlignment);
  18627. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  18628. var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  18629. var supportsMips = isPowerOfTwo(image) || isWebGL2,
  18630. glFormat = utils.convert(texture.format);
  18631. var glType = utils.convert(texture.type),
  18632. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  18633. setTextureParameters(textureType, texture, supportsMips);
  18634. var mipmap;
  18635. var mipmaps = texture.mipmaps;
  18636. if (texture.isDepthTexture) {
  18637. // populate depth texture with dummy data
  18638. glInternalFormat = 6402;
  18639. if (isWebGL2) {
  18640. if (texture.type === FloatType) {
  18641. glInternalFormat = 36012;
  18642. } else if (texture.type === UnsignedIntType) {
  18643. glInternalFormat = 33190;
  18644. } else if (texture.type === UnsignedInt248Type) {
  18645. glInternalFormat = 35056;
  18646. } else {
  18647. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  18648. }
  18649. } else {
  18650. if (texture.type === FloatType) {
  18651. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  18652. }
  18653. } // validation checks for WebGL 1
  18654. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  18655. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18656. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  18657. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18658. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  18659. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  18660. texture.type = UnsignedShortType;
  18661. glType = utils.convert(texture.type);
  18662. }
  18663. }
  18664. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  18665. // Depth stencil textures need the DEPTH_STENCIL internal format
  18666. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18667. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18668. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  18669. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18670. if (texture.type !== UnsignedInt248Type) {
  18671. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  18672. texture.type = UnsignedInt248Type;
  18673. glType = utils.convert(texture.type);
  18674. }
  18675. } //
  18676. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  18677. } else if (texture.isDataTexture) {
  18678. // use manually created mipmaps if available
  18679. // if there are no manual mipmaps
  18680. // set 0 level mipmap and then use GL to generate other mipmap levels
  18681. if (mipmaps.length > 0 && supportsMips) {
  18682. for (var i = 0, il = mipmaps.length; i < il; i++) {
  18683. mipmap = mipmaps[i];
  18684. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  18685. }
  18686. texture.generateMipmaps = false;
  18687. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18688. } else {
  18689. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  18690. textureProperties.__maxMipLevel = 0;
  18691. }
  18692. } else if (texture.isCompressedTexture) {
  18693. for (var _i = 0, _il = mipmaps.length; _i < _il; _i++) {
  18694. mipmap = mipmaps[_i];
  18695. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  18696. if (glFormat !== null) {
  18697. state.compressedTexImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  18698. } else {
  18699. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  18700. }
  18701. } else {
  18702. state.texImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  18703. }
  18704. }
  18705. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18706. } else if (texture.isDataTexture2DArray) {
  18707. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  18708. textureProperties.__maxMipLevel = 0;
  18709. } else if (texture.isDataTexture3D) {
  18710. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  18711. textureProperties.__maxMipLevel = 0;
  18712. } else {
  18713. // regular Texture (image, video, canvas)
  18714. // use manually created mipmaps if available
  18715. // if there are no manual mipmaps
  18716. // set 0 level mipmap and then use GL to generate other mipmap levels
  18717. if (mipmaps.length > 0 && supportsMips) {
  18718. for (var _i2 = 0, _il2 = mipmaps.length; _i2 < _il2; _i2++) {
  18719. mipmap = mipmaps[_i2];
  18720. state.texImage2D(3553, _i2, glInternalFormat, glFormat, glType, mipmap);
  18721. }
  18722. texture.generateMipmaps = false;
  18723. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18724. } else {
  18725. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  18726. textureProperties.__maxMipLevel = 0;
  18727. }
  18728. }
  18729. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  18730. generateMipmap(textureType, texture, image.width, image.height);
  18731. }
  18732. textureProperties.__version = texture.version;
  18733. if (texture.onUpdate) texture.onUpdate(texture);
  18734. }
  18735. function uploadCubeTexture(textureProperties, texture, slot) {
  18736. if (texture.image.length !== 6) return;
  18737. initTexture(textureProperties, texture);
  18738. state.activeTexture(33984 + slot);
  18739. state.bindTexture(34067, textureProperties.__webglTexture);
  18740. _gl.pixelStorei(37440, texture.flipY);
  18741. var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  18742. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  18743. var cubeImage = [];
  18744. for (var i = 0; i < 6; i++) {
  18745. if (!isCompressed && !isDataTexture) {
  18746. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  18747. } else {
  18748. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  18749. }
  18750. }
  18751. var image = cubeImage[0],
  18752. supportsMips = isPowerOfTwo(image) || isWebGL2,
  18753. glFormat = utils.convert(texture.format),
  18754. glType = utils.convert(texture.type),
  18755. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  18756. setTextureParameters(34067, texture, supportsMips);
  18757. var mipmaps;
  18758. if (isCompressed) {
  18759. for (var _i3 = 0; _i3 < 6; _i3++) {
  18760. mipmaps = cubeImage[_i3].mipmaps;
  18761. for (var j = 0; j < mipmaps.length; j++) {
  18762. var mipmap = mipmaps[j];
  18763. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  18764. if (glFormat !== null) {
  18765. state.compressedTexImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  18766. } else {
  18767. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  18768. }
  18769. } else {
  18770. state.texImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  18771. }
  18772. }
  18773. }
  18774. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18775. } else {
  18776. mipmaps = texture.mipmaps;
  18777. for (var _i4 = 0; _i4 < 6; _i4++) {
  18778. if (isDataTexture) {
  18779. state.texImage2D(34069 + _i4, 0, glInternalFormat, cubeImage[_i4].width, cubeImage[_i4].height, 0, glFormat, glType, cubeImage[_i4].data);
  18780. for (var _j = 0; _j < mipmaps.length; _j++) {
  18781. var _mipmap = mipmaps[_j];
  18782. var mipmapImage = _mipmap.image[_i4].image;
  18783. state.texImage2D(34069 + _i4, _j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  18784. }
  18785. } else {
  18786. state.texImage2D(34069 + _i4, 0, glInternalFormat, glFormat, glType, cubeImage[_i4]);
  18787. for (var _j2 = 0; _j2 < mipmaps.length; _j2++) {
  18788. var _mipmap2 = mipmaps[_j2];
  18789. state.texImage2D(34069 + _i4, _j2 + 1, glInternalFormat, glFormat, glType, _mipmap2.image[_i4]);
  18790. }
  18791. }
  18792. }
  18793. textureProperties.__maxMipLevel = mipmaps.length;
  18794. }
  18795. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  18796. // We assume images for cube map have the same size.
  18797. generateMipmap(34067, texture, image.width, image.height);
  18798. }
  18799. textureProperties.__version = texture.version;
  18800. if (texture.onUpdate) texture.onUpdate(texture);
  18801. } // Render targets
  18802. // Setup storage for target texture and bind it to correct framebuffer
  18803. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  18804. var glFormat = utils.convert(renderTarget.texture.format);
  18805. var glType = utils.convert(renderTarget.texture.type);
  18806. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  18807. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  18808. _gl.bindFramebuffer(36160, framebuffer);
  18809. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  18810. _gl.bindFramebuffer(36160, null);
  18811. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  18812. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  18813. _gl.bindRenderbuffer(36161, renderbuffer);
  18814. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  18815. var glInternalFormat = 33189;
  18816. if (isMultisample) {
  18817. var depthTexture = renderTarget.depthTexture;
  18818. if (depthTexture && depthTexture.isDepthTexture) {
  18819. if (depthTexture.type === FloatType) {
  18820. glInternalFormat = 36012;
  18821. } else if (depthTexture.type === UnsignedIntType) {
  18822. glInternalFormat = 33190;
  18823. }
  18824. }
  18825. var samples = getRenderTargetSamples(renderTarget);
  18826. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  18827. } else {
  18828. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  18829. }
  18830. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  18831. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  18832. if (isMultisample) {
  18833. var _samples = getRenderTargetSamples(renderTarget);
  18834. _gl.renderbufferStorageMultisample(36161, _samples, 35056, renderTarget.width, renderTarget.height);
  18835. } else {
  18836. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  18837. }
  18838. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  18839. } else {
  18840. var glFormat = utils.convert(renderTarget.texture.format);
  18841. var glType = utils.convert(renderTarget.texture.type);
  18842. var _glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  18843. if (isMultisample) {
  18844. var _samples2 = getRenderTargetSamples(renderTarget);
  18845. _gl.renderbufferStorageMultisample(36161, _samples2, _glInternalFormat, renderTarget.width, renderTarget.height);
  18846. } else {
  18847. _gl.renderbufferStorage(36161, _glInternalFormat, renderTarget.width, renderTarget.height);
  18848. }
  18849. }
  18850. _gl.bindRenderbuffer(36161, null);
  18851. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  18852. function setupDepthTexture(framebuffer, renderTarget) {
  18853. var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  18854. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  18855. _gl.bindFramebuffer(36160, framebuffer);
  18856. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  18857. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  18858. } // upload an empty depth texture with framebuffer size
  18859. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  18860. renderTarget.depthTexture.image.width = renderTarget.width;
  18861. renderTarget.depthTexture.image.height = renderTarget.height;
  18862. renderTarget.depthTexture.needsUpdate = true;
  18863. }
  18864. setTexture2D(renderTarget.depthTexture, 0);
  18865. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  18866. if (renderTarget.depthTexture.format === DepthFormat) {
  18867. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  18868. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  18869. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  18870. } else {
  18871. throw new Error('Unknown depthTexture format');
  18872. }
  18873. } // Setup GL resources for a non-texture depth buffer
  18874. function setupDepthRenderbuffer(renderTarget) {
  18875. var renderTargetProperties = properties.get(renderTarget);
  18876. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  18877. if (renderTarget.depthTexture) {
  18878. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  18879. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  18880. } else {
  18881. if (isCube) {
  18882. renderTargetProperties.__webglDepthbuffer = [];
  18883. for (var i = 0; i < 6; i++) {
  18884. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  18885. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  18886. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  18887. }
  18888. } else {
  18889. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  18890. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  18891. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  18892. }
  18893. }
  18894. _gl.bindFramebuffer(36160, null);
  18895. } // Set up GL resources for the render target
  18896. function setupRenderTarget(renderTarget) {
  18897. var renderTargetProperties = properties.get(renderTarget);
  18898. var textureProperties = properties.get(renderTarget.texture);
  18899. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  18900. textureProperties.__webglTexture = _gl.createTexture();
  18901. info.memory.textures++;
  18902. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  18903. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  18904. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  18905. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  18906. renderTarget.texture.format = RGBAFormat;
  18907. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  18908. } // Setup framebuffer
  18909. if (isCube) {
  18910. renderTargetProperties.__webglFramebuffer = [];
  18911. for (var i = 0; i < 6; i++) {
  18912. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  18913. }
  18914. } else {
  18915. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  18916. if (isMultisample) {
  18917. if (isWebGL2) {
  18918. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  18919. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  18920. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  18921. var glFormat = utils.convert(renderTarget.texture.format);
  18922. var glType = utils.convert(renderTarget.texture.type);
  18923. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  18924. var samples = getRenderTargetSamples(renderTarget);
  18925. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  18926. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  18927. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  18928. _gl.bindRenderbuffer(36161, null);
  18929. if (renderTarget.depthBuffer) {
  18930. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  18931. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  18932. }
  18933. _gl.bindFramebuffer(36160, null);
  18934. } else {
  18935. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  18936. }
  18937. }
  18938. } // Setup color buffer
  18939. if (isCube) {
  18940. state.bindTexture(34067, textureProperties.__webglTexture);
  18941. setTextureParameters(34067, renderTarget.texture, supportsMips);
  18942. for (var _i5 = 0; _i5 < 6; _i5++) {
  18943. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[_i5], renderTarget, 36064, 34069 + _i5);
  18944. }
  18945. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  18946. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  18947. }
  18948. state.bindTexture(34067, null);
  18949. } else {
  18950. state.bindTexture(3553, textureProperties.__webglTexture);
  18951. setTextureParameters(3553, renderTarget.texture, supportsMips);
  18952. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  18953. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  18954. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  18955. }
  18956. state.bindTexture(3553, null);
  18957. } // Setup depth and stencil buffers
  18958. if (renderTarget.depthBuffer) {
  18959. setupDepthRenderbuffer(renderTarget);
  18960. }
  18961. }
  18962. function updateRenderTargetMipmap(renderTarget) {
  18963. var texture = renderTarget.texture;
  18964. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  18965. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  18966. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  18967. var webglTexture = properties.get(texture).__webglTexture;
  18968. state.bindTexture(target, webglTexture);
  18969. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  18970. state.bindTexture(target, null);
  18971. }
  18972. }
  18973. function updateMultisampleRenderTarget(renderTarget) {
  18974. if (renderTarget.isWebGLMultisampleRenderTarget) {
  18975. if (isWebGL2) {
  18976. var renderTargetProperties = properties.get(renderTarget);
  18977. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  18978. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  18979. var width = renderTarget.width;
  18980. var height = renderTarget.height;
  18981. var mask = 16384;
  18982. if (renderTarget.depthBuffer) mask |= 256;
  18983. if (renderTarget.stencilBuffer) mask |= 1024;
  18984. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  18985. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  18986. } else {
  18987. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  18988. }
  18989. }
  18990. }
  18991. function getRenderTargetSamples(renderTarget) {
  18992. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  18993. }
  18994. function updateVideoTexture(texture) {
  18995. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  18996. if (_videoTextures.get(texture) !== frame) {
  18997. _videoTextures.set(texture, frame);
  18998. texture.update();
  18999. }
  19000. } // backwards compatibility
  19001. var warnedTexture2D = false;
  19002. var warnedTextureCube = false;
  19003. function safeSetTexture2D(texture, slot) {
  19004. if (texture && texture.isWebGLRenderTarget) {
  19005. if (warnedTexture2D === false) {
  19006. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  19007. warnedTexture2D = true;
  19008. }
  19009. texture = texture.texture;
  19010. }
  19011. setTexture2D(texture, slot);
  19012. }
  19013. function safeSetTextureCube(texture, slot) {
  19014. if (texture && texture.isWebGLCubeRenderTarget) {
  19015. if (warnedTextureCube === false) {
  19016. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  19017. warnedTextureCube = true;
  19018. }
  19019. texture = texture.texture;
  19020. }
  19021. setTextureCube(texture, slot);
  19022. } //
  19023. this.allocateTextureUnit = allocateTextureUnit;
  19024. this.resetTextureUnits = resetTextureUnits;
  19025. this.setTexture2D = setTexture2D;
  19026. this.setTexture2DArray = setTexture2DArray;
  19027. this.setTexture3D = setTexture3D;
  19028. this.setTextureCube = setTextureCube;
  19029. this.setupRenderTarget = setupRenderTarget;
  19030. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  19031. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  19032. this.safeSetTexture2D = safeSetTexture2D;
  19033. this.safeSetTextureCube = safeSetTextureCube;
  19034. }
  19035. function WebGLUtils(gl, extensions, capabilities) {
  19036. var isWebGL2 = capabilities.isWebGL2;
  19037. function convert(p) {
  19038. var extension;
  19039. if (p === UnsignedByteType) return 5121;
  19040. if (p === UnsignedShort4444Type) return 32819;
  19041. if (p === UnsignedShort5551Type) return 32820;
  19042. if (p === UnsignedShort565Type) return 33635;
  19043. if (p === ByteType) return 5120;
  19044. if (p === ShortType) return 5122;
  19045. if (p === UnsignedShortType) return 5123;
  19046. if (p === IntType) return 5124;
  19047. if (p === UnsignedIntType) return 5125;
  19048. if (p === FloatType) return 5126;
  19049. if (p === HalfFloatType) {
  19050. if (isWebGL2) return 5131;
  19051. extension = extensions.get('OES_texture_half_float');
  19052. if (extension !== null) {
  19053. return extension.HALF_FLOAT_OES;
  19054. } else {
  19055. return null;
  19056. }
  19057. }
  19058. if (p === AlphaFormat) return 6406;
  19059. if (p === RGBFormat) return 6407;
  19060. if (p === RGBAFormat) return 6408;
  19061. if (p === LuminanceFormat) return 6409;
  19062. if (p === LuminanceAlphaFormat) return 6410;
  19063. if (p === DepthFormat) return 6402;
  19064. if (p === DepthStencilFormat) return 34041;
  19065. if (p === RedFormat) return 6403; // WebGL2 formats.
  19066. if (p === RedIntegerFormat) return 36244;
  19067. if (p === RGFormat) return 33319;
  19068. if (p === RGIntegerFormat) return 33320;
  19069. if (p === RGBIntegerFormat) return 36248;
  19070. if (p === RGBAIntegerFormat) return 36249;
  19071. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  19072. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  19073. if (extension !== null) {
  19074. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19075. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19076. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19077. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19078. } else {
  19079. return null;
  19080. }
  19081. }
  19082. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  19083. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  19084. if (extension !== null) {
  19085. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19086. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19087. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19088. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19089. } else {
  19090. return null;
  19091. }
  19092. }
  19093. if (p === RGB_ETC1_Format) {
  19094. extension = extensions.get('WEBGL_compressed_texture_etc1');
  19095. if (extension !== null) {
  19096. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  19097. } else {
  19098. return null;
  19099. }
  19100. }
  19101. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  19102. extension = extensions.get('WEBGL_compressed_texture_etc');
  19103. if (extension !== null) {
  19104. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  19105. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  19106. }
  19107. }
  19108. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  19109. extension = extensions.get('WEBGL_compressed_texture_astc');
  19110. if (extension !== null) {
  19111. // TODO Complete?
  19112. return p;
  19113. } else {
  19114. return null;
  19115. }
  19116. }
  19117. if (p === RGBA_BPTC_Format) {
  19118. extension = extensions.get('EXT_texture_compression_bptc');
  19119. if (extension !== null) {
  19120. // TODO Complete?
  19121. return p;
  19122. } else {
  19123. return null;
  19124. }
  19125. }
  19126. if (p === UnsignedInt248Type) {
  19127. if (isWebGL2) return 34042;
  19128. extension = extensions.get('WEBGL_depth_texture');
  19129. if (extension !== null) {
  19130. return extension.UNSIGNED_INT_24_8_WEBGL;
  19131. } else {
  19132. return null;
  19133. }
  19134. }
  19135. }
  19136. return {
  19137. convert: convert
  19138. };
  19139. }
  19140. function Group() {
  19141. Object3D.call(this);
  19142. this.type = 'Group';
  19143. }
  19144. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  19145. constructor: Group,
  19146. isGroup: true
  19147. });
  19148. function ArrayCamera(array) {
  19149. if (array === void 0) {
  19150. array = [];
  19151. }
  19152. PerspectiveCamera.call(this);
  19153. this.cameras = array;
  19154. }
  19155. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  19156. constructor: ArrayCamera,
  19157. isArrayCamera: true
  19158. });
  19159. /**
  19160. * @author jsantell / https://www.jsantell.com/
  19161. * @author mrdoob / http://mrdoob.com/
  19162. */
  19163. var cameraLPos = new Vector3();
  19164. var cameraRPos = new Vector3();
  19165. /**
  19166. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19167. * the cameras' projection and world matrices have already been set.
  19168. * And that near and far planes are identical for both cameras.
  19169. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19170. */
  19171. function setProjectionFromUnion(camera, cameraL, cameraR) {
  19172. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  19173. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  19174. var ipd = cameraLPos.distanceTo(cameraRPos);
  19175. var projL = cameraL.projectionMatrix.elements;
  19176. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  19177. // most likely identical top and bottom frustum extents.
  19178. // Use the left camera for these values.
  19179. var near = projL[14] / (projL[10] - 1);
  19180. var far = projL[14] / (projL[10] + 1);
  19181. var topFov = (projL[9] + 1) / projL[5];
  19182. var bottomFov = (projL[9] - 1) / projL[5];
  19183. var leftFov = (projL[8] - 1) / projL[0];
  19184. var rightFov = (projR[8] + 1) / projR[0];
  19185. var left = near * leftFov;
  19186. var right = near * rightFov; // Calculate the new camera's position offset from the
  19187. // left camera. xOffset should be roughly half `ipd`.
  19188. var zOffset = ipd / (-leftFov + rightFov);
  19189. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  19190. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  19191. camera.translateX(xOffset);
  19192. camera.translateZ(zOffset);
  19193. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  19194. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  19195. // the values so that the near plane's position does not change in world space,
  19196. // although must now be relative to the new union camera.
  19197. var near2 = near + zOffset;
  19198. var far2 = far + zOffset;
  19199. var left2 = left - xOffset;
  19200. var right2 = right + (ipd - xOffset);
  19201. var top2 = topFov * far / far2 * near2;
  19202. var bottom2 = bottomFov * far / far2 * near2;
  19203. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  19204. }
  19205. /**
  19206. * @author mrdoob / http://mrdoob.com/
  19207. */
  19208. function WebVRManager(renderer) {
  19209. var renderWidth, renderHeight;
  19210. var scope = this;
  19211. var device = null;
  19212. var frameData = null;
  19213. var poseTarget = null;
  19214. var controllers = [];
  19215. var standingMatrix = new Matrix4();
  19216. var standingMatrixInverse = new Matrix4();
  19217. var framebufferScaleFactor = 1.0;
  19218. var referenceSpaceType = 'local-floor';
  19219. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  19220. frameData = new window.VRFrameData();
  19221. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  19222. }
  19223. var matrixWorldInverse = new Matrix4();
  19224. var tempQuaternion = new Quaternion();
  19225. var tempPosition = new Vector3();
  19226. var cameraL = new PerspectiveCamera();
  19227. cameraL.viewport = new Vector4();
  19228. cameraL.layers.enable(1);
  19229. var cameraR = new PerspectiveCamera();
  19230. cameraR.viewport = new Vector4();
  19231. cameraR.layers.enable(2);
  19232. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  19233. cameraVR.layers.enable(1);
  19234. cameraVR.layers.enable(2);
  19235. var currentSize = new Vector2(),
  19236. currentPixelRatio;
  19237. function onVRDisplayPresentChange() {
  19238. var isPresenting = scope.isPresenting = device !== null && device.isPresenting === true;
  19239. if (isPresenting) {
  19240. var eyeParameters = device.getEyeParameters('left');
  19241. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19242. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19243. currentPixelRatio = renderer.getPixelRatio();
  19244. renderer.getSize(currentSize);
  19245. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  19246. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  19247. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  19248. animation.start();
  19249. scope.dispatchEvent({
  19250. type: 'sessionstart'
  19251. });
  19252. } else {
  19253. if (scope.enabled) {
  19254. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  19255. }
  19256. animation.stop();
  19257. scope.dispatchEvent({
  19258. type: 'sessionend'
  19259. });
  19260. }
  19261. } //
  19262. var triggers = [];
  19263. var grips = [];
  19264. function findGamepad(id) {
  19265. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19266. for (var i = 0, l = gamepads.length; i < l; i++) {
  19267. var gamepad = gamepads[i];
  19268. if (gamepad && (gamepad.id === 'Daydream Controller' || gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith('Oculus Touch') || gamepad.id.startsWith('HTC Vive Focus') || gamepad.id.startsWith('Spatial Controller'))) {
  19269. var hand = gamepad.hand;
  19270. if (id === 0 && (hand === '' || hand === 'right')) return gamepad;
  19271. if (id === 1 && hand === 'left') return gamepad;
  19272. }
  19273. }
  19274. }
  19275. function updateControllers() {
  19276. for (var i = 0; i < controllers.length; i++) {
  19277. var controller = controllers[i];
  19278. var gamepad = findGamepad(i);
  19279. if (gamepad !== undefined && gamepad.pose !== undefined) {
  19280. if (gamepad.pose === null) return; // Pose
  19281. var pose = gamepad.pose;
  19282. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  19283. if (pose.position !== null) controller.position.fromArray(pose.position);
  19284. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  19285. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  19286. controller.matrix.premultiply(standingMatrix);
  19287. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  19288. controller.matrixWorldNeedsUpdate = true;
  19289. controller.visible = true; // Trigger
  19290. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19291. if (triggers[i] === undefined) triggers[i] = false;
  19292. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  19293. triggers[i] = gamepad.buttons[buttonId].pressed;
  19294. if (triggers[i] === true) {
  19295. controller.dispatchEvent({
  19296. type: 'selectstart'
  19297. });
  19298. } else {
  19299. controller.dispatchEvent({
  19300. type: 'selectend'
  19301. });
  19302. controller.dispatchEvent({
  19303. type: 'select'
  19304. });
  19305. }
  19306. } // Grip
  19307. buttonId = 2;
  19308. if (grips[i] === undefined) grips[i] = false; // Skip if the grip button doesn't exist on this controller
  19309. if (gamepad.buttons[buttonId] !== undefined) {
  19310. if (grips[i] !== gamepad.buttons[buttonId].pressed) {
  19311. grips[i] = gamepad.buttons[buttonId].pressed;
  19312. if (grips[i] === true) {
  19313. controller.dispatchEvent({
  19314. type: 'squeezestart'
  19315. });
  19316. } else {
  19317. controller.dispatchEvent({
  19318. type: 'squeezeend'
  19319. });
  19320. controller.dispatchEvent({
  19321. type: 'squeeze'
  19322. });
  19323. }
  19324. }
  19325. }
  19326. } else {
  19327. controller.visible = false;
  19328. }
  19329. }
  19330. }
  19331. function updateViewportFromBounds(viewport, bounds) {
  19332. if (bounds !== null && bounds.length === 4) {
  19333. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  19334. }
  19335. } //
  19336. this.enabled = false;
  19337. this.getController = function (id) {
  19338. var controller = controllers[id];
  19339. if (controller === undefined) {
  19340. controller = new Group();
  19341. controller.matrixAutoUpdate = false;
  19342. controller.visible = false;
  19343. controllers[id] = controller;
  19344. }
  19345. return controller;
  19346. };
  19347. this.getDevice = function () {
  19348. return device;
  19349. };
  19350. this.setDevice = function (value) {
  19351. if (value !== undefined) device = value;
  19352. animation.setContext(value);
  19353. };
  19354. this.setFramebufferScaleFactor = function (value) {
  19355. framebufferScaleFactor = value;
  19356. };
  19357. this.setReferenceSpaceType = function (value) {
  19358. referenceSpaceType = value;
  19359. };
  19360. this.setPoseTarget = function (object) {
  19361. if (object !== undefined) poseTarget = object;
  19362. };
  19363. this.getCamera = function (camera) {
  19364. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19365. device.depthNear = camera.near;
  19366. device.depthFar = camera.far;
  19367. device.getFrameData(frameData); //
  19368. if (referenceSpaceType === 'local-floor') {
  19369. var stageParameters = device.stageParameters;
  19370. if (stageParameters) {
  19371. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  19372. } else {
  19373. standingMatrix.makeTranslation(0, userHeight, 0);
  19374. }
  19375. }
  19376. var pose = frameData.pose;
  19377. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19378. poseObject.matrix.copy(standingMatrix);
  19379. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  19380. if (pose.orientation !== null) {
  19381. tempQuaternion.fromArray(pose.orientation);
  19382. poseObject.quaternion.multiply(tempQuaternion);
  19383. }
  19384. if (pose.position !== null) {
  19385. tempQuaternion.setFromRotationMatrix(standingMatrix);
  19386. tempPosition.fromArray(pose.position);
  19387. tempPosition.applyQuaternion(tempQuaternion);
  19388. poseObject.position.add(tempPosition);
  19389. }
  19390. poseObject.updateMatrixWorld();
  19391. var children = poseObject.children;
  19392. for (var i = 0, l = children.length; i < l; i++) {
  19393. children[i].updateMatrixWorld(true);
  19394. } //
  19395. cameraL.near = camera.near;
  19396. cameraR.near = camera.near;
  19397. cameraL.far = camera.far;
  19398. cameraR.far = camera.far;
  19399. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  19400. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  19401. standingMatrixInverse.getInverse(standingMatrix);
  19402. if (referenceSpaceType === 'local-floor') {
  19403. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  19404. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  19405. }
  19406. var parent = poseObject.parent;
  19407. if (parent !== null) {
  19408. matrixWorldInverse.getInverse(parent.matrixWorld);
  19409. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  19410. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  19411. } // envMap and Mirror needs camera.matrixWorld
  19412. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  19413. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  19414. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  19415. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  19416. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  19417. var layers = device.getLayers();
  19418. if (layers.length) {
  19419. var layer = layers[0];
  19420. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  19421. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  19422. }
  19423. updateControllers();
  19424. return cameraVR;
  19425. };
  19426. this.getStandingMatrix = function () {
  19427. return standingMatrix;
  19428. };
  19429. this.isPresenting = false; // Animation Loop
  19430. var animation = new WebGLAnimation();
  19431. this.setAnimationLoop = function (callback) {
  19432. animation.setAnimationLoop(callback);
  19433. if (this.isPresenting) animation.start();
  19434. };
  19435. this.submitFrame = function () {
  19436. if (this.isPresenting) device.submitFrame();
  19437. };
  19438. this.dispose = function () {
  19439. if (typeof window !== 'undefined') {
  19440. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  19441. }
  19442. }; // DEPRECATED
  19443. this.setFrameOfReferenceType = function () {
  19444. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  19445. };
  19446. }
  19447. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  19448. function WebXRController() {
  19449. this._targetRay = null;
  19450. this._grip = null;
  19451. this._hand = null;
  19452. }
  19453. Object.assign(WebXRController.prototype, {
  19454. constructor: WebXRController,
  19455. getHandSpace: function getHandSpace() {
  19456. if (this._hand === null) {
  19457. this._hand = new Group();
  19458. this._hand.matrixAutoUpdate = false;
  19459. this._hand.visible = false;
  19460. this._hand.joints = [];
  19461. this._hand.inputState = {
  19462. pinching: false
  19463. };
  19464. if (window.XRHand) {
  19465. for (var i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  19466. // The transform of this joint will be updated with the joint pose on each frame
  19467. var joint = new Group();
  19468. joint.matrixAutoUpdate = false;
  19469. joint.visible = false;
  19470. this._hand.joints.push(joint); // ??
  19471. this._hand.add(joint);
  19472. }
  19473. }
  19474. }
  19475. return this._hand;
  19476. },
  19477. getTargetRaySpace: function getTargetRaySpace() {
  19478. if (this._targetRay === null) {
  19479. this._targetRay = new Group();
  19480. this._targetRay.matrixAutoUpdate = false;
  19481. this._targetRay.visible = false;
  19482. }
  19483. return this._targetRay;
  19484. },
  19485. getGripSpace: function getGripSpace() {
  19486. if (this._grip === null) {
  19487. this._grip = new Group();
  19488. this._grip.matrixAutoUpdate = false;
  19489. this._grip.visible = false;
  19490. }
  19491. return this._grip;
  19492. },
  19493. dispatchEvent: function dispatchEvent(event) {
  19494. if (this._targetRay !== null) {
  19495. this._targetRay.dispatchEvent(event);
  19496. }
  19497. if (this._grip !== null) {
  19498. this._grip.dispatchEvent(event);
  19499. }
  19500. if (this._hand !== null) {
  19501. this._hand.dispatchEvent(event);
  19502. }
  19503. return this;
  19504. },
  19505. disconnect: function disconnect(inputSource) {
  19506. this.dispatchEvent({
  19507. type: 'disconnected',
  19508. data: inputSource
  19509. });
  19510. if (this._targetRay !== null) {
  19511. this._targetRay.visible = false;
  19512. }
  19513. if (this._grip !== null) {
  19514. this._grip.visible = false;
  19515. }
  19516. if (this._hand !== null) {
  19517. this._hand.visible = false;
  19518. }
  19519. return this;
  19520. },
  19521. update: function update(inputSource, frame, referenceSpace) {
  19522. var inputPose = null;
  19523. var gripPose = null;
  19524. var handPose = null;
  19525. var targetRay = this._targetRay;
  19526. var grip = this._grip;
  19527. var hand = this._hand;
  19528. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  19529. if (hand && inputSource.hand) {
  19530. handPose = true;
  19531. for (var i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  19532. if (inputSource.hand[i]) {
  19533. // Update the joints groups with the XRJoint poses
  19534. var jointPose = frame.getJointPose(inputSource.hand[i], referenceSpace);
  19535. var joint = hand.joints[i];
  19536. if (jointPose !== null) {
  19537. joint.matrix.fromArray(jointPose.transform.matrix);
  19538. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  19539. joint.jointRadius = jointPose.radius;
  19540. }
  19541. joint.visible = jointPose !== null; // Custom events
  19542. // Check pinch
  19543. var indexTip = hand.joints[window.XRHand.INDEX_PHALANX_TIP];
  19544. var thumbTip = hand.joints[window.XRHand.THUMB_PHALANX_TIP];
  19545. var distance = indexTip.position.distanceTo(thumbTip.position);
  19546. var distanceToPinch = 0.02;
  19547. var threshold = 0.005;
  19548. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  19549. hand.inputState.pinching = false;
  19550. this.dispatchEvent({
  19551. type: "pinchend",
  19552. handedness: inputSource.handedness,
  19553. target: this
  19554. });
  19555. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  19556. hand.inputState.pinching = true;
  19557. this.dispatchEvent({
  19558. type: "pinchstart",
  19559. handedness: inputSource.handedness,
  19560. target: this
  19561. });
  19562. }
  19563. }
  19564. }
  19565. } else {
  19566. if (targetRay !== null) {
  19567. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  19568. if (inputPose !== null) {
  19569. targetRay.matrix.fromArray(inputPose.transform.matrix);
  19570. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  19571. }
  19572. }
  19573. if (grip !== null && inputSource.gripSpace) {
  19574. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  19575. if (gripPose !== null) {
  19576. grip.matrix.fromArray(gripPose.transform.matrix);
  19577. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  19578. }
  19579. }
  19580. }
  19581. }
  19582. if (targetRay !== null) {
  19583. targetRay.visible = inputPose !== null;
  19584. }
  19585. if (grip !== null) {
  19586. grip.visible = gripPose !== null;
  19587. }
  19588. if (hand !== null) {
  19589. hand.visible = handPose !== null;
  19590. }
  19591. return this;
  19592. }
  19593. });
  19594. function WebXRManager(renderer, gl) {
  19595. var scope = this;
  19596. var session = null;
  19597. var framebufferScaleFactor = 1.0;
  19598. var referenceSpace = null;
  19599. var referenceSpaceType = 'local-floor';
  19600. var pose = null;
  19601. var poseTarget = null;
  19602. var controllers = [];
  19603. var inputSourcesMap = new Map();
  19604. var layers = [];
  19605. var baseLayer; //
  19606. var cameraL = new PerspectiveCamera();
  19607. cameraL.layers.enable(1);
  19608. cameraL.viewport = new Vector4();
  19609. var cameraR = new PerspectiveCamera();
  19610. cameraR.layers.enable(2);
  19611. cameraR.viewport = new Vector4();
  19612. var cameras = [cameraL, cameraR];
  19613. var cameraVR = new ArrayCamera();
  19614. cameraVR.layers.enable(1);
  19615. cameraVR.layers.enable(2);
  19616. var _currentDepthNear = null;
  19617. var _currentDepthFar = null; //
  19618. this.layersEnabled = false;
  19619. this.enabled = false;
  19620. this.isPresenting = false;
  19621. this.getCameraPose = function () {
  19622. return pose;
  19623. };
  19624. this.getController = function (id) {
  19625. var controller = controllers[index];
  19626. if (controller === undefined) {
  19627. controller = new WebXRController();
  19628. controllers[index] = controller;
  19629. }
  19630. return controller.getTargetRaySpace();
  19631. };
  19632. this.getControllerGrip = function (index) {
  19633. var controller = controllers[index];
  19634. if (controller === undefined) {
  19635. controller = new WebXRController();
  19636. controllers[index] = controller;
  19637. }
  19638. return controller.getGripSpace();
  19639. };
  19640. this.getHand = function (index) {
  19641. var controller = controllers[index];
  19642. if (controller === undefined) {
  19643. controller = new WebXRController();
  19644. controllers[index] = controller;
  19645. }
  19646. return controller.getHandSpace();
  19647. }; //
  19648. function onSessionEvent(event) {
  19649. var controller = inputSourcesMap.get(event.inputSource);
  19650. if (controller) {
  19651. controller.dispatchEvent({
  19652. type: event.type,
  19653. data: event.inputSource
  19654. });
  19655. }
  19656. }
  19657. function onSessionEnd() {
  19658. inputSourcesMap.forEach(function (controller, inputSource) {
  19659. controller.disconnect(inputSource);
  19660. });
  19661. inputSourcesMap.clear(); //
  19662. renderer.setFramebuffer(null);
  19663. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  19664. animation.stop();
  19665. scope.isPresenting = false;
  19666. scope.dispatchEvent({
  19667. type: 'sessionend'
  19668. });
  19669. }
  19670. function onRequestReferenceSpace(value) {
  19671. referenceSpace = value;
  19672. animation.setContext(session);
  19673. animation.start();
  19674. scope.isPresenting = true;
  19675. scope.dispatchEvent({
  19676. type: 'sessionstart'
  19677. });
  19678. }
  19679. this.setFramebufferScaleFactor = function (value) {
  19680. framebufferScaleFactor = value;
  19681. if (scope.isPresenting === true) {
  19682. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  19683. }
  19684. };
  19685. this.setReferenceSpaceType = function (value) {
  19686. referenceSpaceType = value;
  19687. if (scope.isPresenting === true) {
  19688. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  19689. }
  19690. };
  19691. this.getReferenceSpace = function () {
  19692. return referenceSpace;
  19693. };
  19694. this.getSession = function () {
  19695. return session;
  19696. };
  19697. this.addLayer = function (layer) {
  19698. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  19699. return;
  19700. }
  19701. layers.push(layer);
  19702. session.updateRenderState({
  19703. layers: layers
  19704. });
  19705. };
  19706. this.removeLayer = function (layer) {
  19707. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  19708. return;
  19709. }
  19710. layers.splice(layers.indexOf(layer), 1);
  19711. session.updateRenderState({
  19712. layers: layers
  19713. });
  19714. };
  19715. this.setSession = function (value) {
  19716. session = value;
  19717. if (session !== null) {
  19718. session.addEventListener('select', onSessionEvent);
  19719. session.addEventListener('selectstart', onSessionEvent);
  19720. session.addEventListener('selectend', onSessionEvent);
  19721. session.addEventListener('squeeze', onSessionEvent);
  19722. session.addEventListener('squeezestart', onSessionEvent);
  19723. session.addEventListener('squeezeend', onSessionEvent);
  19724. session.addEventListener('end', onSessionEnd);
  19725. var attributes = gl.getContextAttributes();
  19726. if (attributes.xrCompatible !== true) {
  19727. gl.makeXRCompatible();
  19728. }
  19729. var layerInit = {
  19730. antialias: attributes.antialias,
  19731. alpha: attributes.alpha,
  19732. depth: attributes.depth,
  19733. stencil: attributes.stencil,
  19734. framebufferScaleFactor: framebufferScaleFactor
  19735. }; // eslint-disable-next-line no-undef
  19736. baseLayer = new XRWebGLLayer(session, gl, layerInit);
  19737. if (window.XRWebGLBinding && this.layersEnabled) {
  19738. this.addLayer(baseLayer);
  19739. } else {
  19740. session.updateRenderState({
  19741. baseLayer: baseLayer
  19742. });
  19743. }
  19744. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  19745. session.addEventListener('inputsourceschange', updateInputSources);
  19746. }
  19747. };
  19748. function updateInputSources(event) {
  19749. var inputSources = session.inputSources; // Assign inputSources to available controllers
  19750. for (var i = 0; i < controllers.length; i++) {
  19751. inputSourcesMap.set(inputSources[i], controllers[i]);
  19752. } // Notify disconnected
  19753. for (var _i = 0; _i < event.removed.length; _i++) {
  19754. var inputSource = event.removed[_i];
  19755. var controller = inputSourcesMap.get(inputSource);
  19756. if (controller) {
  19757. controller.dispatchEvent({
  19758. type: 'disconnected',
  19759. data: inputSource
  19760. });
  19761. inputSourcesMap.delete(inputSource);
  19762. }
  19763. } // Notify connected
  19764. for (var _i2 = 0; _i2 < event.added.length; _i2++) {
  19765. var _inputSource = event.added[_i2];
  19766. var _controller = inputSourcesMap.get(_inputSource);
  19767. if (_controller) {
  19768. _controller.dispatchEvent({
  19769. type: 'connected',
  19770. data: _inputSource
  19771. });
  19772. }
  19773. }
  19774. } //
  19775. var cameraLPos = new Vector3();
  19776. var cameraRPos = new Vector3();
  19777. /**
  19778. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19779. * the cameras' projection and world matrices have already been set.
  19780. * And that near and far planes are identical for both cameras.
  19781. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19782. */
  19783. function setProjectionFromUnion(camera, cameraL, cameraR) {
  19784. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  19785. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  19786. var ipd = cameraLPos.distanceTo(cameraRPos);
  19787. var projL = cameraL.projectionMatrix.elements;
  19788. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  19789. // most likely identical top and bottom frustum extents.
  19790. // Use the left camera for these values.
  19791. var near = projL[14] / (projL[10] - 1);
  19792. var far = projL[14] / (projL[10] + 1);
  19793. var topFov = (projL[9] + 1) / projL[5];
  19794. var bottomFov = (projL[9] - 1) / projL[5];
  19795. var leftFov = (projL[8] - 1) / projL[0];
  19796. var rightFov = (projR[8] + 1) / projR[0];
  19797. var left = near * leftFov;
  19798. var right = near * rightFov; // Calculate the new camera's position offset from the
  19799. // left camera. xOffset should be roughly half `ipd`.
  19800. var zOffset = ipd / (-leftFov + rightFov);
  19801. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  19802. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  19803. camera.translateX(xOffset);
  19804. camera.translateZ(zOffset);
  19805. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  19806. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  19807. // the values so that the near plane's position does not change in world space,
  19808. // although must now be relative to the new union camera.
  19809. var near2 = near + zOffset;
  19810. var far2 = far + zOffset;
  19811. var left2 = left - xOffset;
  19812. var right2 = right + (ipd - xOffset);
  19813. var top2 = topFov * far / far2 * near2;
  19814. var bottom2 = bottomFov * far / far2 * near2;
  19815. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  19816. }
  19817. function updateCamera(camera, parent) {
  19818. if (parent === null) {
  19819. camera.matrixWorld.copy(camera.matrix);
  19820. } else {
  19821. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  19822. }
  19823. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  19824. }
  19825. this.setPoseTarget = function (object) {
  19826. if (object !== undefined) poseTarget = object;
  19827. };
  19828. this.getCamera = function (camera) {
  19829. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  19830. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  19831. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  19832. // Note that the new renderState won't apply until the next frame. See #18320
  19833. session.updateRenderState({
  19834. depthNear: cameraVR.near,
  19835. depthFar: cameraVR.far
  19836. });
  19837. _currentDepthNear = cameraVR.near;
  19838. _currentDepthFar = cameraVR.far;
  19839. }
  19840. var parent = camera.parent;
  19841. var cameras = cameraVR.cameras;
  19842. var object = poseTarget || camera;
  19843. updateCamera(cameraVR, parent);
  19844. for (var i = 0; i < cameras.length; i++) {
  19845. updateCamera(cameras[i], parent);
  19846. } // update camera and its children
  19847. object.matrixWorld.copy(cameraVR.matrixWorld);
  19848. var children = object.children;
  19849. for (var _i3 = 0, l = children.length; _i3 < l; _i3++) {
  19850. children[_i3].updateMatrixWorld(true);
  19851. } // update projection matrix for proper view frustum culling
  19852. if (cameras.length === 2) {
  19853. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  19854. } else {
  19855. // assume single camera setup (AR)
  19856. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  19857. }
  19858. return cameraVR;
  19859. }; // Animation Loop
  19860. var onAnimationFrameCallback = null;
  19861. function onAnimationFrame(time, frame) {
  19862. pose = frame.getViewerPose(referenceSpace);
  19863. if (pose !== null) {
  19864. var views = pose.views;
  19865. renderer.setFramebuffer(baseLayer.framebuffer);
  19866. var cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  19867. if (views.length !== cameraVR.cameras.length) {
  19868. cameraVR.cameras.length = 0;
  19869. cameraVRNeedsUpdate = true;
  19870. }
  19871. for (var i = 0; i < views.length; i++) {
  19872. var view = views[i];
  19873. var viewport = baseLayer.getViewport(view);
  19874. var camera = cameras[i];
  19875. camera.matrix.fromArray(view.transform.matrix);
  19876. camera.projectionMatrix.fromArray(view.projectionMatrix);
  19877. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  19878. if (i === 0) {
  19879. cameraVR.matrix.copy(camera.matrix);
  19880. }
  19881. if (cameraVRNeedsUpdate === true) {
  19882. cameraVR.cameras.push(camera);
  19883. }
  19884. }
  19885. } //
  19886. var inputSources = session.inputSources;
  19887. for (var _i4 = 0; _i4 < controllers.length; _i4++) {
  19888. var controller = controllers[_i4];
  19889. var inputSource = inputSources[_i4];
  19890. controller.update(inputSource, frame, referenceSpace);
  19891. }
  19892. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  19893. }
  19894. var animation = new WebGLAnimation();
  19895. animation.setAnimationLoop(onAnimationFrame);
  19896. this.setAnimationLoop = function (callback) {
  19897. onAnimationFrameCallback = callback;
  19898. };
  19899. this.dispose = function () {};
  19900. }
  19901. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  19902. function WebGLMaterials(properties) {
  19903. function refreshFogUniforms(uniforms, fog) {
  19904. uniforms.fogColor.value.copy(fog.color);
  19905. if (fog.isFog) {
  19906. uniforms.fogNear.value = fog.near;
  19907. uniforms.fogFar.value = fog.far;
  19908. } else if (fog.isFogExp2) {
  19909. uniforms.fogDensity.value = fog.density;
  19910. }
  19911. }
  19912. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  19913. if (material.isMeshBasicMaterial) {
  19914. refreshUniformsCommon(uniforms, material);
  19915. } else if (material.isMeshLambertMaterial) {
  19916. refreshUniformsCommon(uniforms, material);
  19917. refreshUniformsLambert(uniforms, material);
  19918. } else if (material.isMeshToonMaterial) {
  19919. refreshUniformsCommon(uniforms, material);
  19920. refreshUniformsToon(uniforms, material);
  19921. } else if (material.isMeshPhongMaterial) {
  19922. refreshUniformsCommon(uniforms, material);
  19923. refreshUniformsPhong(uniforms, material);
  19924. } else if (material.isMeshStandardMaterial) {
  19925. refreshUniformsCommon(uniforms, material);
  19926. if (material.isMeshPhysicalMaterial) {
  19927. refreshUniformsPhysical(uniforms, material);
  19928. } else {
  19929. refreshUniformsStandard(uniforms, material);
  19930. }
  19931. } else if (material.isMeshMatcapMaterial) {
  19932. refreshUniformsCommon(uniforms, material);
  19933. refreshUniformsMatcap(uniforms, material);
  19934. } else if (material.isMeshDepthMaterial) {
  19935. refreshUniformsCommon(uniforms, material);
  19936. refreshUniformsDepth(uniforms, material);
  19937. } else if (material.isMeshDistanceMaterial) {
  19938. refreshUniformsCommon(uniforms, material);
  19939. refreshUniformsDistance(uniforms, material);
  19940. } else if (material.isMeshNormalMaterial) {
  19941. refreshUniformsCommon(uniforms, material);
  19942. refreshUniformsNormal(uniforms, material);
  19943. } else if (material.isLineBasicMaterial) {
  19944. refreshUniformsLine(uniforms, material);
  19945. if (material.isLineDashedMaterial) {
  19946. refreshUniformsDash(uniforms, material);
  19947. }
  19948. } else if (material.isPointsMaterial) {
  19949. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  19950. } else if (material.isSpriteMaterial) {
  19951. refreshUniformsSprites(uniforms, material);
  19952. } else if (material.isShadowMaterial) {
  19953. uniforms.color.value.copy(material.color);
  19954. uniforms.opacity.value = material.opacity;
  19955. } else if (material.isShaderMaterial) {
  19956. material.uniformsNeedUpdate = false; // #15581
  19957. }
  19958. }
  19959. function refreshUniformsCommon(uniforms, material) {
  19960. uniforms.opacity.value = material.opacity;
  19961. if (material.color) {
  19962. uniforms.diffuse.value.copy(material.color);
  19963. }
  19964. if (material.emissive) {
  19965. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  19966. }
  19967. if (material.map) {
  19968. uniforms.map.value = material.map;
  19969. }
  19970. if (material.alphaMap) {
  19971. uniforms.alphaMap.value = material.alphaMap;
  19972. }
  19973. if (material.specularMap) {
  19974. uniforms.specularMap.value = material.specularMap;
  19975. }
  19976. var envMap = properties.get(material).envMap;
  19977. if (envMap) {
  19978. uniforms.envMap.value = envMap;
  19979. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  19980. uniforms.reflectivity.value = material.reflectivity;
  19981. uniforms.refractionRatio.value = material.refractionRatio;
  19982. var maxMipLevel = properties.get(envMap).__maxMipLevel;
  19983. if (maxMipLevel !== undefined) {
  19984. uniforms.maxMipLevel.value = maxMipLevel;
  19985. }
  19986. }
  19987. if (material.lightMap) {
  19988. uniforms.lightMap.value = material.lightMap;
  19989. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  19990. }
  19991. if (material.aoMap) {
  19992. uniforms.aoMap.value = material.aoMap;
  19993. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  19994. } // uv repeat and offset setting priorities
  19995. // 1. color map
  19996. // 2. specular map
  19997. // 3. displacementMap map
  19998. // 4. normal map
  19999. // 5. bump map
  20000. // 6. roughnessMap map
  20001. // 7. metalnessMap map
  20002. // 8. alphaMap map
  20003. // 9. emissiveMap map
  20004. // 10. clearcoat map
  20005. // 11. clearcoat normal map
  20006. // 12. clearcoat roughnessMap map
  20007. var uvScaleMap;
  20008. if (material.map) {
  20009. uvScaleMap = material.map;
  20010. } else if (material.specularMap) {
  20011. uvScaleMap = material.specularMap;
  20012. } else if (material.displacementMap) {
  20013. uvScaleMap = material.displacementMap;
  20014. } else if (material.normalMap) {
  20015. uvScaleMap = material.normalMap;
  20016. } else if (material.bumpMap) {
  20017. uvScaleMap = material.bumpMap;
  20018. } else if (material.roughnessMap) {
  20019. uvScaleMap = material.roughnessMap;
  20020. } else if (material.metalnessMap) {
  20021. uvScaleMap = material.metalnessMap;
  20022. } else if (material.alphaMap) {
  20023. uvScaleMap = material.alphaMap;
  20024. } else if (material.emissiveMap) {
  20025. uvScaleMap = material.emissiveMap;
  20026. } else if (material.clearcoatMap) {
  20027. uvScaleMap = material.clearcoatMap;
  20028. } else if (material.clearcoatNormalMap) {
  20029. uvScaleMap = material.clearcoatNormalMap;
  20030. } else if (material.clearcoatRoughnessMap) {
  20031. uvScaleMap = material.clearcoatRoughnessMap;
  20032. }
  20033. if (uvScaleMap !== undefined) {
  20034. // backwards compatibility
  20035. if (uvScaleMap.isWebGLRenderTarget) {
  20036. uvScaleMap = uvScaleMap.texture;
  20037. }
  20038. if (uvScaleMap.matrixAutoUpdate === true) {
  20039. uvScaleMap.updateMatrix();
  20040. }
  20041. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20042. } // uv repeat and offset setting priorities for uv2
  20043. // 1. ao map
  20044. // 2. light map
  20045. var uv2ScaleMap;
  20046. if (material.aoMap) {
  20047. uv2ScaleMap = material.aoMap;
  20048. } else if (material.lightMap) {
  20049. uv2ScaleMap = material.lightMap;
  20050. }
  20051. if (uv2ScaleMap !== undefined) {
  20052. // backwards compatibility
  20053. if (uv2ScaleMap.isWebGLRenderTarget) {
  20054. uv2ScaleMap = uv2ScaleMap.texture;
  20055. }
  20056. if (uv2ScaleMap.matrixAutoUpdate === true) {
  20057. uv2ScaleMap.updateMatrix();
  20058. }
  20059. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  20060. }
  20061. }
  20062. function refreshUniformsLine(uniforms, material) {
  20063. uniforms.diffuse.value.copy(material.color);
  20064. uniforms.opacity.value = material.opacity;
  20065. }
  20066. function refreshUniformsDash(uniforms, material) {
  20067. uniforms.dashSize.value = material.dashSize;
  20068. uniforms.totalSize.value = material.dashSize + material.gapSize;
  20069. uniforms.scale.value = material.scale;
  20070. }
  20071. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  20072. uniforms.diffuse.value.copy(material.color);
  20073. uniforms.opacity.value = material.opacity;
  20074. uniforms.size.value = material.size * pixelRatio;
  20075. uniforms.scale.value = height * 0.5;
  20076. if (material.map) {
  20077. uniforms.map.value = material.map;
  20078. }
  20079. if (material.alphaMap) {
  20080. uniforms.alphaMap.value = material.alphaMap;
  20081. } // uv repeat and offset setting priorities
  20082. // 1. color map
  20083. // 2. alpha map
  20084. var uvScaleMap;
  20085. if (material.map) {
  20086. uvScaleMap = material.map;
  20087. } else if (material.alphaMap) {
  20088. uvScaleMap = material.alphaMap;
  20089. }
  20090. if (uvScaleMap !== undefined) {
  20091. if (uvScaleMap.matrixAutoUpdate === true) {
  20092. uvScaleMap.updateMatrix();
  20093. }
  20094. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20095. }
  20096. }
  20097. function refreshUniformsSprites(uniforms, material) {
  20098. uniforms.diffuse.value.copy(material.color);
  20099. uniforms.opacity.value = material.opacity;
  20100. uniforms.rotation.value = material.rotation;
  20101. if (material.map) {
  20102. uniforms.map.value = material.map;
  20103. }
  20104. if (material.alphaMap) {
  20105. uniforms.alphaMap.value = material.alphaMap;
  20106. } // uv repeat and offset setting priorities
  20107. // 1. color map
  20108. // 2. alpha map
  20109. var uvScaleMap;
  20110. if (material.map) {
  20111. uvScaleMap = material.map;
  20112. } else if (material.alphaMap) {
  20113. uvScaleMap = material.alphaMap;
  20114. }
  20115. if (uvScaleMap !== undefined) {
  20116. if (uvScaleMap.matrixAutoUpdate === true) {
  20117. uvScaleMap.updateMatrix();
  20118. }
  20119. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20120. }
  20121. }
  20122. function refreshUniformsLambert(uniforms, material) {
  20123. if (material.emissiveMap) {
  20124. uniforms.emissiveMap.value = material.emissiveMap;
  20125. }
  20126. }
  20127. function refreshUniformsPhong(uniforms, material) {
  20128. uniforms.specular.value.copy(material.specular);
  20129. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  20130. if (material.emissiveMap) {
  20131. uniforms.emissiveMap.value = material.emissiveMap;
  20132. }
  20133. if (material.bumpMap) {
  20134. uniforms.bumpMap.value = material.bumpMap;
  20135. uniforms.bumpScale.value = material.bumpScale;
  20136. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20137. }
  20138. if (material.normalMap) {
  20139. uniforms.normalMap.value = material.normalMap;
  20140. uniforms.normalScale.value.copy(material.normalScale);
  20141. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20142. }
  20143. if (material.displacementMap) {
  20144. uniforms.displacementMap.value = material.displacementMap;
  20145. uniforms.displacementScale.value = material.displacementScale;
  20146. uniforms.displacementBias.value = material.displacementBias;
  20147. }
  20148. }
  20149. function refreshUniformsToon(uniforms, material) {
  20150. if (material.gradientMap) {
  20151. uniforms.gradientMap.value = material.gradientMap;
  20152. }
  20153. if (material.emissiveMap) {
  20154. uniforms.emissiveMap.value = material.emissiveMap;
  20155. }
  20156. if (material.bumpMap) {
  20157. uniforms.bumpMap.value = material.bumpMap;
  20158. uniforms.bumpScale.value = material.bumpScale;
  20159. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20160. }
  20161. if (material.normalMap) {
  20162. uniforms.normalMap.value = material.normalMap;
  20163. uniforms.normalScale.value.copy(material.normalScale);
  20164. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20165. }
  20166. if (material.displacementMap) {
  20167. uniforms.displacementMap.value = material.displacementMap;
  20168. uniforms.displacementScale.value = material.displacementScale;
  20169. uniforms.displacementBias.value = material.displacementBias;
  20170. }
  20171. }
  20172. function refreshUniformsStandard(uniforms, material) {
  20173. uniforms.roughness.value = material.roughness;
  20174. uniforms.metalness.value = material.metalness;
  20175. if (material.roughnessMap) {
  20176. uniforms.roughnessMap.value = material.roughnessMap;
  20177. }
  20178. if (material.metalnessMap) {
  20179. uniforms.metalnessMap.value = material.metalnessMap;
  20180. }
  20181. if (material.emissiveMap) {
  20182. uniforms.emissiveMap.value = material.emissiveMap;
  20183. }
  20184. if (material.bumpMap) {
  20185. uniforms.bumpMap.value = material.bumpMap;
  20186. uniforms.bumpScale.value = material.bumpScale;
  20187. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20188. }
  20189. if (material.normalMap) {
  20190. uniforms.normalMap.value = material.normalMap;
  20191. uniforms.normalScale.value.copy(material.normalScale);
  20192. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20193. }
  20194. if (material.displacementMap) {
  20195. uniforms.displacementMap.value = material.displacementMap;
  20196. uniforms.displacementScale.value = material.displacementScale;
  20197. uniforms.displacementBias.value = material.displacementBias;
  20198. }
  20199. var envMap = properties.get(material).envMap;
  20200. if (envMap) {
  20201. //uniforms.envMap.value = material.envMap; // part of uniforms common
  20202. uniforms.envMapIntensity.value = material.envMapIntensity;
  20203. }
  20204. }
  20205. function refreshUniformsPhysical(uniforms, material) {
  20206. refreshUniformsStandard(uniforms, material);
  20207. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  20208. uniforms.clearcoat.value = material.clearcoat;
  20209. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  20210. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  20211. if (material.clearcoatMap) {
  20212. uniforms.clearcoatMap.value = material.clearcoatMap;
  20213. }
  20214. if (material.clearcoatRoughnessMap) {
  20215. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  20216. }
  20217. if (material.clearcoatNormalMap) {
  20218. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  20219. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  20220. if (material.side === BackSide) {
  20221. uniforms.clearcoatNormalScale.value.negate();
  20222. }
  20223. }
  20224. uniforms.transmission.value = material.transmission;
  20225. if (material.transmissionMap) {
  20226. uniforms.transmissionMap.value = material.transmissionMap;
  20227. }
  20228. }
  20229. function refreshUniformsMatcap(uniforms, material) {
  20230. if (material.matcap) {
  20231. uniforms.matcap.value = material.matcap;
  20232. }
  20233. if (material.bumpMap) {
  20234. uniforms.bumpMap.value = material.bumpMap;
  20235. uniforms.bumpScale.value = material.bumpScale;
  20236. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20237. }
  20238. if (material.normalMap) {
  20239. uniforms.normalMap.value = material.normalMap;
  20240. uniforms.normalScale.value.copy(material.normalScale);
  20241. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20242. }
  20243. if (material.displacementMap) {
  20244. uniforms.displacementMap.value = material.displacementMap;
  20245. uniforms.displacementScale.value = material.displacementScale;
  20246. uniforms.displacementBias.value = material.displacementBias;
  20247. }
  20248. }
  20249. function refreshUniformsDepth(uniforms, material) {
  20250. if (material.displacementMap) {
  20251. uniforms.displacementMap.value = material.displacementMap;
  20252. uniforms.displacementScale.value = material.displacementScale;
  20253. uniforms.displacementBias.value = material.displacementBias;
  20254. }
  20255. }
  20256. function refreshUniformsDistance(uniforms, material) {
  20257. if (material.displacementMap) {
  20258. uniforms.displacementMap.value = material.displacementMap;
  20259. uniforms.displacementScale.value = material.displacementScale;
  20260. uniforms.displacementBias.value = material.displacementBias;
  20261. }
  20262. uniforms.referencePosition.value.copy(material.referencePosition);
  20263. uniforms.nearDistance.value = material.nearDistance;
  20264. uniforms.farDistance.value = material.farDistance;
  20265. }
  20266. function refreshUniformsNormal(uniforms, material) {
  20267. if (material.bumpMap) {
  20268. uniforms.bumpMap.value = material.bumpMap;
  20269. uniforms.bumpScale.value = material.bumpScale;
  20270. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20271. }
  20272. if (material.normalMap) {
  20273. uniforms.normalMap.value = material.normalMap;
  20274. uniforms.normalScale.value.copy(material.normalScale);
  20275. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20276. }
  20277. if (material.displacementMap) {
  20278. uniforms.displacementMap.value = material.displacementMap;
  20279. uniforms.displacementScale.value = material.displacementScale;
  20280. uniforms.displacementBias.value = material.displacementBias;
  20281. }
  20282. }
  20283. return {
  20284. refreshFogUniforms: refreshFogUniforms,
  20285. refreshMaterialUniforms: refreshMaterialUniforms
  20286. };
  20287. }
  20288. function createCanvasElement() {
  20289. var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  20290. canvas.style.display = 'block';
  20291. return canvas;
  20292. }
  20293. function WebGLRenderer(parameters) {
  20294. parameters = parameters || {};
  20295. var _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  20296. _context = parameters.context !== undefined ? parameters.context : null,
  20297. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  20298. _depth = parameters.depth !== undefined ? parameters.depth : true,
  20299. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  20300. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  20301. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  20302. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  20303. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  20304. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  20305. var currentRenderList = null;
  20306. var currentRenderState = null; // public properties
  20307. this.domElement = _canvas; // Debug configuration container
  20308. this.debug = {
  20309. /**
  20310. * Enables error checking and reporting when shader programs are being compiled
  20311. * @type {boolean}
  20312. */
  20313. checkShaderErrors: true
  20314. }; // clearing
  20315. this.autoClear = true;
  20316. this.autoClearColor = true;
  20317. this.autoClearDepth = true;
  20318. this.autoClearStencil = true; // scene graph
  20319. this.sortObjects = true; // user-defined clipping
  20320. this.clippingPlanes = [];
  20321. this.localClippingEnabled = false; // physically based shading
  20322. this.gammaFactor = 2.0; // for backwards compatibility
  20323. this.outputEncoding = LinearEncoding; // physical lights
  20324. this.physicallyCorrectLights = false; // tone mapping
  20325. this.toneMapping = NoToneMapping;
  20326. this.toneMappingExposure = 1.0; // morphs
  20327. this.maxMorphTargets = 8;
  20328. this.maxMorphNormals = 4; // internal properties
  20329. var _this = this;
  20330. var _isContextLost = false; // internal state cache
  20331. var _framebuffer = null;
  20332. var _currentActiveCubeFace = 0;
  20333. var _currentActiveMipmapLevel = 0;
  20334. var _currentRenderTarget = null;
  20335. var _currentFramebuffer = null;
  20336. var _currentMaterialId = -1;
  20337. var _currentCamera = null;
  20338. var _currentArrayCamera = null;
  20339. var _currentViewport = new Vector4();
  20340. var _currentScissor = new Vector4();
  20341. var _currentScissorTest = null; //
  20342. var _width = _canvas.width;
  20343. var _height = _canvas.height;
  20344. var _pixelRatio = 1;
  20345. var _opaqueSort = null;
  20346. var _transparentSort = null;
  20347. var _viewport = new Vector4(0, 0, _width, _height);
  20348. var _scissor = new Vector4(0, 0, _width, _height);
  20349. var _scissorTest = false; // frustum
  20350. var _frustum = new Frustum(); // clipping
  20351. var _clippingEnabled = false;
  20352. var _localClippingEnabled = false; // camera matrices cache
  20353. var _projScreenMatrix = new Matrix4();
  20354. var _vector3 = new Vector3();
  20355. var _emptyScene = {
  20356. background: null,
  20357. fog: null,
  20358. environment: null,
  20359. overrideMaterial: null,
  20360. isScene: true
  20361. };
  20362. function getTargetPixelRatio() {
  20363. return _currentRenderTarget === null ? _pixelRatio : 1;
  20364. } // initialize
  20365. var _gl = _context;
  20366. function getContext(contextNames, contextAttributes) {
  20367. for (var i = 0; i < contextNames.length; i++) {
  20368. var contextName = contextNames[i];
  20369. var context = _canvas.getContext(contextName, contextAttributes);
  20370. if (context !== null) return context;
  20371. }
  20372. return null;
  20373. }
  20374. try {
  20375. var contextAttributes = {
  20376. alpha: _alpha,
  20377. depth: _depth,
  20378. stencil: _stencil,
  20379. antialias: _antialias,
  20380. premultipliedAlpha: _premultipliedAlpha,
  20381. preserveDrawingBuffer: _preserveDrawingBuffer,
  20382. powerPreference: _powerPreference,
  20383. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  20384. }; // event listeners must be registered before WebGL context is created, see #12753
  20385. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  20386. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  20387. if (_gl === null) {
  20388. var contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  20389. if (_this.isWebGL1Renderer === true) {
  20390. contextNames.shift();
  20391. }
  20392. _gl = getContext(contextNames, contextAttributes);
  20393. if (_gl === null) {
  20394. if (getContext(contextNames)) {
  20395. throw new Error('Error creating WebGL context with your selected attributes.');
  20396. } else {
  20397. throw new Error('Error creating WebGL context.');
  20398. }
  20399. }
  20400. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  20401. if (_gl.getShaderPrecisionFormat === undefined) {
  20402. _gl.getShaderPrecisionFormat = function () {
  20403. return {
  20404. 'rangeMin': 1,
  20405. 'rangeMax': 1,
  20406. 'precision': 1
  20407. };
  20408. };
  20409. }
  20410. } catch (error) {
  20411. console.error('THREE.WebGLRenderer: ' + error.message);
  20412. throw error;
  20413. }
  20414. var extensions, capabilities, state, info;
  20415. var properties, textures, cubemaps, attributes, geometries, objects;
  20416. var programCache, materials, renderLists, renderStates, clipping;
  20417. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  20418. var utils, bindingStates;
  20419. function initGLContext() {
  20420. extensions = new WebGLExtensions(_gl);
  20421. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  20422. if (capabilities.isWebGL2 === false) {
  20423. extensions.get('WEBGL_depth_texture');
  20424. extensions.get('OES_texture_float');
  20425. extensions.get('OES_texture_half_float');
  20426. extensions.get('OES_texture_half_float_linear');
  20427. extensions.get('OES_standard_derivatives');
  20428. extensions.get('OES_element_index_uint');
  20429. extensions.get('OES_vertex_array_object');
  20430. extensions.get('ANGLE_instanced_arrays');
  20431. }
  20432. extensions.get('OES_texture_float_linear');
  20433. utils = new WebGLUtils(_gl, extensions, capabilities);
  20434. state = new WebGLState(_gl, extensions, capabilities);
  20435. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  20436. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  20437. info = new WebGLInfo(_gl);
  20438. properties = new WebGLProperties();
  20439. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  20440. cubemaps = new WebGLCubeMaps(_this);
  20441. attributes = new WebGLAttributes(_gl, capabilities);
  20442. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  20443. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  20444. objects = new WebGLObjects(_gl, geometries, attributes, info);
  20445. morphtargets = new WebGLMorphtargets(_gl);
  20446. clipping = new WebGLClipping(properties);
  20447. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  20448. materials = new WebGLMaterials(properties);
  20449. renderLists = new WebGLRenderLists(properties);
  20450. renderStates = new WebGLRenderStates(extensions, capabilities);
  20451. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  20452. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  20453. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  20454. info.programs = programCache.programs;
  20455. _this.capabilities = capabilities;
  20456. _this.extensions = extensions;
  20457. _this.properties = properties;
  20458. _this.renderLists = renderLists;
  20459. _this.state = state;
  20460. _this.info = info;
  20461. }
  20462. initGLContext();
  20463. var xr = typeof navigator !== 'undefined' && 'xr' in navigator ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  20464. this.xr = xr; // shadow map
  20465. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  20466. this.shadowMap = shadowMap; // API
  20467. this.getContext = function () {
  20468. return _gl;
  20469. };
  20470. this.getContextAttributes = function () {
  20471. return _gl.getContextAttributes();
  20472. };
  20473. this.forceContextLoss = function () {
  20474. var extension = extensions.get('WEBGL_lose_context');
  20475. if (extension) extension.loseContext();
  20476. };
  20477. this.forceContextRestore = function () {
  20478. var extension = extensions.get('WEBGL_lose_context');
  20479. if (extension) extension.restoreContext();
  20480. };
  20481. this.getPixelRatio = function () {
  20482. return _pixelRatio;
  20483. };
  20484. this.setPixelRatio = function (value) {
  20485. if (value === undefined) return;
  20486. _pixelRatio = value;
  20487. this.setSize(_width, _height, false);
  20488. };
  20489. this.getSize = function (target) {
  20490. if (target === undefined) {
  20491. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  20492. target = new Vector2();
  20493. }
  20494. return target.set(_width, _height);
  20495. };
  20496. this.setSize = function (width, height, updateStyle) {
  20497. if (xr.isPresenting) {
  20498. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  20499. return;
  20500. }
  20501. _width = width;
  20502. _height = height;
  20503. _canvas.width = Math.floor(width * _pixelRatio);
  20504. _canvas.height = Math.floor(height * _pixelRatio);
  20505. if (updateStyle !== false) {
  20506. _canvas.style.width = width + 'px';
  20507. _canvas.style.height = height + 'px';
  20508. }
  20509. this.setViewport(0, 0, width, height);
  20510. };
  20511. this.getDrawingBufferSize = function (target) {
  20512. if (target === undefined) {
  20513. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  20514. target = new Vector2();
  20515. }
  20516. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  20517. };
  20518. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  20519. _width = width;
  20520. _height = height;
  20521. _pixelRatio = pixelRatio;
  20522. _canvas.width = Math.floor(width * pixelRatio);
  20523. _canvas.height = Math.floor(height * pixelRatio);
  20524. this.setViewport(0, 0, width, height);
  20525. };
  20526. this.getCurrentViewport = function (target) {
  20527. if (target === undefined) {
  20528. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  20529. target = new Vector4();
  20530. }
  20531. return target.copy(_currentViewport);
  20532. };
  20533. this.getViewport = function (target) {
  20534. return target.copy(_viewport);
  20535. };
  20536. this.setViewport = function (x, y, width, height) {
  20537. if (x.isVector4) {
  20538. _viewport.set(x.x, x.y, x.z, x.w);
  20539. } else {
  20540. _viewport.set(x, y, width, height);
  20541. }
  20542. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  20543. };
  20544. this.getScissor = function (target) {
  20545. return target.copy(_scissor);
  20546. };
  20547. this.setScissor = function (x, y, width, height) {
  20548. if (x.isVector4) {
  20549. _scissor.set(x.x, x.y, x.z, x.w);
  20550. } else {
  20551. _scissor.set(x, y, width, height);
  20552. }
  20553. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  20554. };
  20555. this.getScissorTest = function () {
  20556. return _scissorTest;
  20557. };
  20558. this.setScissorTest = function (boolean) {
  20559. state.setScissorTest(_scissorTest = boolean);
  20560. };
  20561. this.setOpaqueSort = function (method) {
  20562. _opaqueSort = method;
  20563. };
  20564. this.setTransparentSort = function (method) {
  20565. _transparentSort = method;
  20566. }; // Clearing
  20567. this.getClearColor = function () {
  20568. return background.getClearColor();
  20569. };
  20570. this.setClearColor = function () {
  20571. background.setClearColor.apply(background, arguments);
  20572. };
  20573. this.getClearAlpha = function () {
  20574. return background.getClearAlpha();
  20575. };
  20576. this.setClearAlpha = function () {
  20577. background.setClearAlpha.apply(background, arguments);
  20578. };
  20579. this.clear = function (color, depth, stencil) {
  20580. var bits = 0;
  20581. if (color === undefined || color) bits |= 16384;
  20582. if (depth === undefined || depth) bits |= 256;
  20583. if (stencil === undefined || stencil) bits |= 1024;
  20584. _gl.clear(bits);
  20585. };
  20586. this.clearColor = function () {
  20587. this.clear(true, false, false);
  20588. };
  20589. this.clearDepth = function () {
  20590. this.clear(false, true, false);
  20591. };
  20592. this.clearStencil = function () {
  20593. this.clear(false, false, true);
  20594. }; //
  20595. this.dispose = function () {
  20596. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  20597. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  20598. renderLists.dispose();
  20599. renderStates.dispose();
  20600. properties.dispose();
  20601. cubemaps.dispose();
  20602. objects.dispose();
  20603. bindingStates.dispose();
  20604. xr.dispose();
  20605. animation.stop();
  20606. }; // Events
  20607. function onContextLost(event) {
  20608. event.preventDefault();
  20609. console.log('THREE.WebGLRenderer: Context Lost.');
  20610. _isContextLost = true;
  20611. }
  20612. function onContextRestore()
  20613. /* event */
  20614. {
  20615. console.log('THREE.WebGLRenderer: Context Restored.');
  20616. _isContextLost = false;
  20617. initGLContext();
  20618. }
  20619. function onMaterialDispose(event) {
  20620. var material = event.target;
  20621. material.removeEventListener('dispose', onMaterialDispose);
  20622. deallocateMaterial(material);
  20623. } // Buffer deallocation
  20624. function deallocateMaterial(material) {
  20625. releaseMaterialProgramReference(material);
  20626. properties.remove(material);
  20627. }
  20628. function releaseMaterialProgramReference(material) {
  20629. var programInfo = properties.get(material).program;
  20630. if (programInfo !== undefined) {
  20631. programCache.releaseProgram(programInfo);
  20632. }
  20633. } // Buffer rendering
  20634. function renderObjectImmediate(object, program) {
  20635. object.render(function (object) {
  20636. _this.renderBufferImmediate(object, program);
  20637. });
  20638. }
  20639. this.renderBufferImmediate = function (object, program) {
  20640. bindingStates.initAttributes();
  20641. var buffers = properties.get(object);
  20642. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  20643. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  20644. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  20645. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  20646. var programAttributes = program.getAttributes();
  20647. if (object.hasPositions) {
  20648. _gl.bindBuffer(34962, buffers.position);
  20649. _gl.bufferData(34962, object.positionArray, 35048);
  20650. bindingStates.enableAttribute(programAttributes.position);
  20651. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  20652. }
  20653. if (object.hasNormals) {
  20654. _gl.bindBuffer(34962, buffers.normal);
  20655. _gl.bufferData(34962, object.normalArray, 35048);
  20656. bindingStates.enableAttribute(programAttributes.normal);
  20657. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  20658. }
  20659. if (object.hasUvs) {
  20660. _gl.bindBuffer(34962, buffers.uv);
  20661. _gl.bufferData(34962, object.uvArray, 35048);
  20662. bindingStates.enableAttribute(programAttributes.uv);
  20663. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  20664. }
  20665. if (object.hasColors) {
  20666. _gl.bindBuffer(34962, buffers.color);
  20667. _gl.bufferData(34962, object.colorArray, 35048);
  20668. bindingStates.enableAttribute(programAttributes.color);
  20669. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  20670. }
  20671. bindingStates.disableUnusedAttributes();
  20672. _gl.drawArrays(4, 0, object.count);
  20673. object.count = 0;
  20674. };
  20675. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  20676. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  20677. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  20678. var program = setProgram(camera, scene, material, object);
  20679. state.setMaterial(material, frontFaceCW); //
  20680. var index = geometry.index;
  20681. var position = geometry.attributes.position; //
  20682. if (index === null) {
  20683. if (position === undefined || position.count === 0) return;
  20684. } else if (index.count === 0) {
  20685. return;
  20686. } //
  20687. var rangeFactor = 1;
  20688. if (material.wireframe === true) {
  20689. index = geometries.getWireframeAttribute(geometry);
  20690. rangeFactor = 2;
  20691. }
  20692. if (material.morphTargets || material.morphNormals) {
  20693. morphtargets.update(object, geometry, material, program);
  20694. }
  20695. bindingStates.setup(object, material, program, geometry, index);
  20696. var attribute;
  20697. var renderer = bufferRenderer;
  20698. if (index !== null) {
  20699. attribute = attributes.get(index);
  20700. renderer = indexedBufferRenderer;
  20701. renderer.setIndex(attribute);
  20702. } //
  20703. var dataCount = index !== null ? index.count : position.count;
  20704. var rangeStart = geometry.drawRange.start * rangeFactor;
  20705. var rangeCount = geometry.drawRange.count * rangeFactor;
  20706. var groupStart = group !== null ? group.start * rangeFactor : 0;
  20707. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  20708. var drawStart = Math.max(rangeStart, groupStart);
  20709. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  20710. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  20711. if (drawCount === 0) return; //
  20712. if (object.isMesh) {
  20713. if (material.wireframe === true) {
  20714. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  20715. renderer.setMode(1);
  20716. } else {
  20717. renderer.setMode(4);
  20718. }
  20719. } else if (object.isLine) {
  20720. var lineWidth = material.linewidth;
  20721. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  20722. state.setLineWidth(lineWidth * getTargetPixelRatio());
  20723. if (object.isLineSegments) {
  20724. renderer.setMode(1);
  20725. } else if (object.isLineLoop) {
  20726. renderer.setMode(2);
  20727. } else {
  20728. renderer.setMode(3);
  20729. }
  20730. } else if (object.isPoints) {
  20731. renderer.setMode(0);
  20732. } else if (object.isSprite) {
  20733. renderer.setMode(4);
  20734. }
  20735. if (object.isInstancedMesh) {
  20736. renderer.renderInstances(drawStart, drawCount, object.count);
  20737. } else if (geometry.isInstancedBufferGeometry) {
  20738. var instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  20739. renderer.renderInstances(drawStart, drawCount, instanceCount);
  20740. } else {
  20741. renderer.render(drawStart, drawCount);
  20742. }
  20743. }; // Compile
  20744. this.compile = function (scene, camera) {
  20745. currentRenderState = renderStates.get(scene, camera);
  20746. currentRenderState.init();
  20747. scene.traverseVisible(function (object) {
  20748. if (object.isLight && object.layers.test(camera.layers)) {
  20749. currentRenderState.pushLight(object);
  20750. if (object.castShadow) {
  20751. currentRenderState.pushShadow(object);
  20752. }
  20753. }
  20754. });
  20755. currentRenderState.setupLights(camera);
  20756. var compiled = new WeakMap();
  20757. scene.traverse(function (object) {
  20758. var material = object.material;
  20759. if (material) {
  20760. if (Array.isArray(material)) {
  20761. for (var i = 0; i < material.length; i++) {
  20762. var material2 = material[i];
  20763. if (compiled.has(material2) === false) {
  20764. initMaterial(material2, scene, object);
  20765. compiled.set(material2);
  20766. }
  20767. }
  20768. } else if (compiled.has(material) === false) {
  20769. initMaterial(material, scene, object);
  20770. compiled.set(material);
  20771. }
  20772. }
  20773. });
  20774. }; // Animation Loop
  20775. var onAnimationFrameCallback = null;
  20776. function onAnimationFrame(time) {
  20777. if (xr.isPresenting) return;
  20778. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  20779. }
  20780. var animation = new WebGLAnimation();
  20781. animation.setAnimationLoop(onAnimationFrame);
  20782. if (typeof window !== 'undefined') animation.setContext(window);
  20783. this.setAnimationLoop = function (callback) {
  20784. onAnimationFrameCallback = callback;
  20785. xr.setAnimationLoop(callback);
  20786. callback === null ? animation.stop() : animation.start();
  20787. }; // Rendering
  20788. this.render = function (scene, camera) {
  20789. var renderTarget, forceClear;
  20790. if (arguments[2] !== undefined) {
  20791. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  20792. renderTarget = arguments[2];
  20793. }
  20794. if (arguments[3] !== undefined) {
  20795. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  20796. forceClear = arguments[3];
  20797. }
  20798. if (camera !== undefined && camera.isCamera !== true) {
  20799. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  20800. return;
  20801. }
  20802. if (_isContextLost === true) return; // reset caching for this frame
  20803. bindingStates.resetDefaultState();
  20804. _currentMaterialId = -1;
  20805. _currentCamera = null; // update scene graph
  20806. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  20807. if (camera.parent === null) camera.updateMatrixWorld();
  20808. if (xr.enabled === true && xr.isPresenting === true) {
  20809. camera = xr.getCamera(camera);
  20810. } //
  20811. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  20812. currentRenderState = renderStates.get(scene, camera);
  20813. currentRenderState.init();
  20814. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  20815. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  20816. _localClippingEnabled = this.localClippingEnabled;
  20817. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  20818. currentRenderList = renderLists.get(scene, camera);
  20819. currentRenderList.init();
  20820. projectObject(scene, camera, 0, _this.sortObjects);
  20821. currentRenderList.finish();
  20822. if (_this.sortObjects === true) {
  20823. currentRenderList.sort(_opaqueSort, _transparentSort);
  20824. } //
  20825. if (_clippingEnabled === true) clipping.beginShadows();
  20826. var shadowsArray = currentRenderState.state.shadowsArray;
  20827. shadowMap.render(shadowsArray, scene, camera);
  20828. currentRenderState.setupLights(camera);
  20829. if (_clippingEnabled === true) clipping.endShadows(); //
  20830. if (this.info.autoReset === true) this.info.reset();
  20831. if (renderTarget !== undefined) {
  20832. this.setRenderTarget(renderTarget);
  20833. } //
  20834. background.render(currentRenderList, scene, camera, forceClear); // render scene
  20835. var opaqueObjects = currentRenderList.opaque;
  20836. var transparentObjects = currentRenderList.transparent;
  20837. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  20838. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  20839. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
  20840. if (_currentRenderTarget !== null) {
  20841. // Generate mipmap if we're using any kind of mipmap filtering
  20842. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  20843. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  20844. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  20845. state.buffers.depth.setTest(true);
  20846. state.buffers.depth.setMask(true);
  20847. state.buffers.color.setMask(true);
  20848. state.setPolygonOffset(false);
  20849. if (xr.enabled && xr.submitFrame) {
  20850. xr.submitFrame();
  20851. } // _gl.finish();
  20852. currentRenderList = null;
  20853. currentRenderState = null;
  20854. };
  20855. function projectObject(object, camera, groupOrder, sortObjects) {
  20856. if (object.visible === false) return;
  20857. var visible = object.layers.test(camera.layers);
  20858. if (visible) {
  20859. if (object.isGroup) {
  20860. groupOrder = object.renderOrder;
  20861. } else if (object.isLOD) {
  20862. if (object.autoUpdate === true) object.update(camera);
  20863. } else if (object.isLight) {
  20864. currentRenderState.pushLight(object);
  20865. if (object.castShadow) {
  20866. currentRenderState.pushShadow(object);
  20867. }
  20868. } else if (object.isSprite) {
  20869. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  20870. if (sortObjects) {
  20871. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  20872. }
  20873. var geometry = objects.update(object);
  20874. var material = object.material;
  20875. if (material.visible) {
  20876. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  20877. }
  20878. }
  20879. } else if (object.isImmediateRenderObject) {
  20880. if (sortObjects) {
  20881. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  20882. }
  20883. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  20884. } else if (object.isMesh || object.isLine || object.isPoints) {
  20885. if (object.isSkinnedMesh) {
  20886. // update skeleton only once in a frame
  20887. if (object.skeleton.frame !== info.render.frame) {
  20888. object.skeleton.update();
  20889. object.skeleton.frame = info.render.frame;
  20890. }
  20891. }
  20892. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  20893. if (sortObjects) {
  20894. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  20895. }
  20896. var _geometry = objects.update(object);
  20897. var _material = object.material;
  20898. if (Array.isArray(_material)) {
  20899. var groups = _geometry.groups;
  20900. for (var i = 0, l = groups.length; i < l; i++) {
  20901. var group = groups[i];
  20902. var groupMaterial = _material[group.materialIndex];
  20903. if (groupMaterial && groupMaterial.visible) {
  20904. currentRenderList.push(object, _geometry, groupMaterial, groupOrder, _vector3.z, group);
  20905. }
  20906. }
  20907. } else if (_material.visible) {
  20908. currentRenderList.push(object, _geometry, _material, groupOrder, _vector3.z, null);
  20909. }
  20910. }
  20911. }
  20912. }
  20913. var children = object.children;
  20914. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  20915. projectObject(children[_i], camera, groupOrder, sortObjects);
  20916. }
  20917. }
  20918. function renderObjects(renderList, scene, camera) {
  20919. var overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  20920. for (var i = 0, l = renderList.length; i < l; i++) {
  20921. var renderItem = renderList[i];
  20922. var object = renderItem.object;
  20923. var geometry = renderItem.geometry;
  20924. var material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  20925. var group = renderItem.group;
  20926. if (camera.isArrayCamera) {
  20927. _currentArrayCamera = camera;
  20928. var cameras = camera.cameras;
  20929. for (var j = 0, jl = cameras.length; j < jl; j++) {
  20930. var camera2 = cameras[j];
  20931. if (object.layers.test(camera2.layers)) {
  20932. state.viewport(_currentViewport.copy(camera2.viewport));
  20933. currentRenderState.setupLights(camera2);
  20934. renderObject(object, scene, camera2, geometry, material, group);
  20935. }
  20936. }
  20937. } else {
  20938. _currentArrayCamera = null;
  20939. renderObject(object, scene, camera, geometry, material, group);
  20940. }
  20941. }
  20942. }
  20943. function renderObject(object, scene, camera, geometry, material, group) {
  20944. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  20945. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  20946. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  20947. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  20948. if (object.isImmediateRenderObject) {
  20949. var program = setProgram(camera, scene, material, object);
  20950. state.setMaterial(material);
  20951. bindingStates.reset();
  20952. renderObjectImmediate(object, program);
  20953. } else {
  20954. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  20955. }
  20956. object.onAfterRender(_this, scene, camera, geometry, material, group);
  20957. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  20958. }
  20959. function initMaterial(material, scene, object) {
  20960. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  20961. var materialProperties = properties.get(material);
  20962. var lights = currentRenderState.state.lights;
  20963. var shadowsArray = currentRenderState.state.shadowsArray;
  20964. var lightsStateVersion = lights.state.version;
  20965. var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  20966. var programCacheKey = programCache.getProgramCacheKey(parameters);
  20967. var program = materialProperties.program;
  20968. var programChange = true;
  20969. if (program === undefined) {
  20970. // new material
  20971. material.addEventListener('dispose', onMaterialDispose);
  20972. } else if (program.cacheKey !== programCacheKey) {
  20973. // changed glsl or parameters
  20974. releaseMaterialProgramReference(material);
  20975. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  20976. programChange = false;
  20977. } else if (parameters.shaderID !== undefined) {
  20978. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  20979. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  20980. materialProperties.envMap = cubemaps.get(material.envMap || environment);
  20981. return;
  20982. } else {
  20983. // only rebuild uniform list
  20984. programChange = false;
  20985. }
  20986. if (programChange) {
  20987. parameters.uniforms = programCache.getUniforms(material);
  20988. material.onBeforeCompile(parameters, _this);
  20989. program = programCache.acquireProgram(parameters, programCacheKey);
  20990. materialProperties.program = program;
  20991. materialProperties.uniforms = parameters.uniforms;
  20992. materialProperties.outputEncoding = parameters.outputEncoding;
  20993. }
  20994. var uniforms = materialProperties.uniforms;
  20995. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  20996. materialProperties.numClippingPlanes = clipping.numPlanes;
  20997. materialProperties.numIntersection = clipping.numIntersection;
  20998. uniforms.clippingPlanes = clipping.uniform;
  20999. }
  21000. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  21001. materialProperties.fog = scene.fog;
  21002. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment); // store the light setup it was created for
  21003. materialProperties.needsLights = materialNeedsLights(material);
  21004. materialProperties.lightsStateVersion = lightsStateVersion;
  21005. if (materialProperties.needsLights) {
  21006. // wire up the material to this renderer's lighting state
  21007. uniforms.ambientLightColor.value = lights.state.ambient;
  21008. uniforms.lightProbe.value = lights.state.probe;
  21009. uniforms.directionalLights.value = lights.state.directional;
  21010. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  21011. uniforms.spotLights.value = lights.state.spot;
  21012. uniforms.spotLightShadows.value = lights.state.spotShadow;
  21013. uniforms.rectAreaLights.value = lights.state.rectArea;
  21014. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  21015. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  21016. uniforms.pointLights.value = lights.state.point;
  21017. uniforms.pointLightShadows.value = lights.state.pointShadow;
  21018. uniforms.hemisphereLights.value = lights.state.hemi;
  21019. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  21020. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  21021. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  21022. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  21023. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  21024. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  21025. }
  21026. var progUniforms = materialProperties.program.getUniforms();
  21027. var uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  21028. materialProperties.uniformsList = uniformsList;
  21029. }
  21030. function setProgram(camera, scene, material, object) {
  21031. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21032. textures.resetTextureUnits();
  21033. var fog = scene.fog;
  21034. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  21035. var encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  21036. var envMap = cubemaps.get(material.envMap || environment);
  21037. var materialProperties = properties.get(material);
  21038. var lights = currentRenderState.state.lights;
  21039. if (_clippingEnabled === true) {
  21040. if (_localClippingEnabled === true || camera !== _currentCamera) {
  21041. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  21042. // object instead of the material, once it becomes feasible
  21043. // (#8465, #8379)
  21044. clipping.setState(material, camera, useCache);
  21045. }
  21046. }
  21047. if (material.version === materialProperties.__version) {
  21048. if (material.fog && materialProperties.fog !== fog) {
  21049. initMaterial(material, scene, object);
  21050. } else if (materialProperties.environment !== environment) {
  21051. initMaterial(material, scene, object);
  21052. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  21053. initMaterial(material, scene, object);
  21054. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  21055. initMaterial(material, scene, object);
  21056. } else if (materialProperties.outputEncoding !== encoding) {
  21057. initMaterial(material, scene, object);
  21058. } else if (materialProperties.envMap !== envMap) {
  21059. initMaterial(material, scene, object);
  21060. }
  21061. } else {
  21062. initMaterial(material, scene, object);
  21063. materialProperties.__version = material.version;
  21064. }
  21065. var refreshProgram = false;
  21066. var refreshMaterial = false;
  21067. var refreshLights = false;
  21068. var program = materialProperties.program,
  21069. p_uniforms = program.getUniforms(),
  21070. m_uniforms = materialProperties.uniforms;
  21071. if (state.useProgram(program.program)) {
  21072. refreshProgram = true;
  21073. refreshMaterial = true;
  21074. refreshLights = true;
  21075. }
  21076. if (material.id !== _currentMaterialId) {
  21077. _currentMaterialId = material.id;
  21078. refreshMaterial = true;
  21079. }
  21080. if (refreshProgram || _currentCamera !== camera) {
  21081. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  21082. if (capabilities.logarithmicDepthBuffer) {
  21083. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  21084. }
  21085. if (_currentCamera !== camera) {
  21086. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  21087. // now, in case this material supports lights - or later, when
  21088. // the next material that does gets activated:
  21089. refreshMaterial = true; // set to true on material change
  21090. refreshLights = true; // remains set until update done
  21091. } // load material specific uniforms
  21092. // (shader material also gets them for the sake of genericity)
  21093. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  21094. var uCamPos = p_uniforms.map.cameraPosition;
  21095. if (uCamPos !== undefined) {
  21096. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  21097. }
  21098. }
  21099. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  21100. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  21101. }
  21102. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  21103. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  21104. }
  21105. } // skinning uniforms must be set even if material didn't change
  21106. // auto-setting of texture unit for bone texture must go before other textures
  21107. // otherwise textures used for skinning can take over texture units reserved for other material textures
  21108. if (material.skinning) {
  21109. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  21110. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  21111. var skeleton = object.skeleton;
  21112. if (skeleton) {
  21113. var bones = skeleton.bones;
  21114. if (capabilities.floatVertexTextures) {
  21115. if (skeleton.boneTexture === null) {
  21116. // layout (1 matrix = 4 pixels)
  21117. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  21118. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  21119. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  21120. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  21121. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  21122. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  21123. size = MathUtils.ceilPowerOfTwo(size);
  21124. size = Math.max(size, 4);
  21125. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  21126. boneMatrices.set(skeleton.boneMatrices); // copy current values
  21127. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  21128. skeleton.boneMatrices = boneMatrices;
  21129. skeleton.boneTexture = boneTexture;
  21130. skeleton.boneTextureSize = size;
  21131. }
  21132. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  21133. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  21134. } else {
  21135. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  21136. }
  21137. }
  21138. }
  21139. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  21140. materialProperties.receiveShadow = object.receiveShadow;
  21141. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  21142. }
  21143. if (refreshMaterial) {
  21144. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  21145. if (materialProperties.needsLights) {
  21146. // the current material requires lighting info
  21147. // note: all lighting uniforms are always set correctly
  21148. // they simply reference the renderer's state for their
  21149. // values
  21150. //
  21151. // use the current material's .needsUpdate flags to set
  21152. // the GL state when required
  21153. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  21154. } // refresh uniforms common to several materials
  21155. if (fog && material.fog) {
  21156. materials.refreshFogUniforms(m_uniforms, fog);
  21157. }
  21158. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  21159. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  21160. }
  21161. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  21162. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  21163. material.uniformsNeedUpdate = false;
  21164. }
  21165. if (material.isSpriteMaterial) {
  21166. p_uniforms.setValue(_gl, 'center', object.center);
  21167. } // common matrices
  21168. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  21169. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  21170. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  21171. return program;
  21172. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  21173. function markUniformsLightsNeedsUpdate(uniforms, value) {
  21174. uniforms.ambientLightColor.needsUpdate = value;
  21175. uniforms.lightProbe.needsUpdate = value;
  21176. uniforms.directionalLights.needsUpdate = value;
  21177. uniforms.directionalLightShadows.needsUpdate = value;
  21178. uniforms.pointLights.needsUpdate = value;
  21179. uniforms.pointLightShadows.needsUpdate = value;
  21180. uniforms.spotLights.needsUpdate = value;
  21181. uniforms.spotLightShadows.needsUpdate = value;
  21182. uniforms.rectAreaLights.needsUpdate = value;
  21183. uniforms.hemisphereLights.needsUpdate = value;
  21184. }
  21185. function materialNeedsLights(material) {
  21186. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  21187. } // this.setTexture2D = setTexture2D;
  21188. this.setTexture2D = function () {
  21189. var warned = false; // backwards compatibility: peel texture.texture
  21190. return function setTexture2D(texture, slot) {
  21191. if (texture && texture.isWebGLRenderTarget) {
  21192. if (!warned) {
  21193. console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead.");
  21194. warned = true;
  21195. }
  21196. texture = texture.texture;
  21197. }
  21198. textures.setTexture2D(texture, slot);
  21199. };
  21200. }(); //
  21201. this.setFramebuffer = function (value) {
  21202. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  21203. _framebuffer = value;
  21204. };
  21205. this.getActiveCubeFace = function () {
  21206. return _currentActiveCubeFace;
  21207. };
  21208. this.getActiveMipmapLevel = function () {
  21209. return _currentActiveMipmapLevel;
  21210. };
  21211. this.getRenderList = function () {
  21212. return currentRenderList;
  21213. };
  21214. this.setRenderList = function (renderList) {
  21215. currentRenderList = renderList;
  21216. };
  21217. this.getRenderState = function () {
  21218. return currentRenderState;
  21219. };
  21220. this.setRenderState = function (renderState) {
  21221. currentRenderState = renderState;
  21222. };
  21223. this.getRenderTarget = function () {
  21224. return _currentRenderTarget;
  21225. };
  21226. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  21227. if (activeCubeFace === void 0) {
  21228. activeCubeFace = 0;
  21229. }
  21230. if (activeMipmapLevel === void 0) {
  21231. activeMipmapLevel = 0;
  21232. }
  21233. _currentRenderTarget = renderTarget;
  21234. _currentActiveCubeFace = activeCubeFace;
  21235. _currentActiveMipmapLevel = activeMipmapLevel;
  21236. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  21237. textures.setupRenderTarget(renderTarget);
  21238. }
  21239. var framebuffer = _framebuffer;
  21240. var isCube = false;
  21241. if (renderTarget) {
  21242. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  21243. if (renderTarget.isWebGLCubeRenderTarget) {
  21244. framebuffer = __webglFramebuffer[activeCubeFace];
  21245. isCube = true;
  21246. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  21247. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  21248. } else {
  21249. framebuffer = __webglFramebuffer;
  21250. }
  21251. _currentViewport.copy(renderTarget.viewport);
  21252. _currentScissor.copy(renderTarget.scissor);
  21253. _currentScissorTest = renderTarget.scissorTest;
  21254. } else {
  21255. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  21256. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  21257. _currentScissorTest = _scissorTest;
  21258. }
  21259. if (_currentFramebuffer !== framebuffer) {
  21260. _gl.bindFramebuffer(36160, framebuffer);
  21261. _currentFramebuffer = framebuffer;
  21262. }
  21263. state.viewport(_currentViewport);
  21264. state.scissor(_currentScissor);
  21265. state.setScissorTest(_currentScissorTest);
  21266. if (isCube) {
  21267. var textureProperties = properties.get(renderTarget.texture);
  21268. _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  21269. }
  21270. };
  21271. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  21272. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  21273. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  21274. return;
  21275. }
  21276. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  21277. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  21278. framebuffer = framebuffer[activeCubeFaceIndex];
  21279. }
  21280. if (framebuffer) {
  21281. var restore = false;
  21282. if (framebuffer !== _currentFramebuffer) {
  21283. _gl.bindFramebuffer(36160, framebuffer);
  21284. restore = true;
  21285. }
  21286. try {
  21287. var texture = renderTarget.texture;
  21288. var textureFormat = texture.format;
  21289. var textureType = texture.type;
  21290. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  21291. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  21292. return;
  21293. }
  21294. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  21295. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  21296. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  21297. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  21298. return;
  21299. }
  21300. if (_gl.checkFramebufferStatus(36160) === 36053) {
  21301. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  21302. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  21303. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  21304. }
  21305. } else {
  21306. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  21307. }
  21308. } finally {
  21309. if (restore) {
  21310. _gl.bindFramebuffer(36160, _currentFramebuffer);
  21311. }
  21312. }
  21313. }
  21314. };
  21315. this.copyFramebufferToTexture = function (position, texture, level) {
  21316. if (level === void 0) {
  21317. level = 0;
  21318. }
  21319. var levelScale = Math.pow(2, -level);
  21320. var width = Math.floor(texture.image.width * levelScale);
  21321. var height = Math.floor(texture.image.height * levelScale);
  21322. var glFormat = utils.convert(texture.format);
  21323. textures.setTexture2D(texture, 0);
  21324. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  21325. state.unbindTexture();
  21326. };
  21327. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  21328. if (level === void 0) {
  21329. level = 0;
  21330. }
  21331. var width = srcTexture.image.width;
  21332. var height = srcTexture.image.height;
  21333. var glFormat = utils.convert(dstTexture.format);
  21334. var glType = utils.convert(dstTexture.type);
  21335. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  21336. // parameters, make sure they are correct for the dstTexture
  21337. _gl.pixelStorei(37440, dstTexture.flipY);
  21338. _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
  21339. _gl.pixelStorei(3317, dstTexture.unpackAlignment);
  21340. if (srcTexture.isDataTexture) {
  21341. _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  21342. } else {
  21343. if (srcTexture.isCompressedTexture) {
  21344. _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  21345. } else {
  21346. _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
  21347. }
  21348. } // Generate mipmaps only when copying level 0
  21349. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
  21350. state.unbindTexture();
  21351. };
  21352. this.initTexture = function (texture) {
  21353. textures.setTexture2D(texture, 0);
  21354. state.unbindTexture();
  21355. };
  21356. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  21357. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  21358. detail: this
  21359. })); // eslint-disable-line no-undef
  21360. }
  21361. }
  21362. function WebGL1Renderer(parameters) {
  21363. WebGLRenderer.call(this, parameters);
  21364. }
  21365. WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
  21366. constructor: WebGL1Renderer,
  21367. isWebGL1Renderer: true
  21368. });
  21369. var FogExp2 = /*#__PURE__*/function () {
  21370. function FogExp2(color, density) {
  21371. Object.defineProperty(this, 'isFogExp2', {
  21372. value: true
  21373. });
  21374. this.name = '';
  21375. this.color = new Color(color);
  21376. this.density = density !== undefined ? density : 0.00025;
  21377. }
  21378. var _proto = FogExp2.prototype;
  21379. _proto.clone = function clone() {
  21380. return new FogExp2(this.color, this.density);
  21381. };
  21382. _proto.toJSON = function toJSON()
  21383. /* meta */
  21384. {
  21385. return {
  21386. type: 'FogExp2',
  21387. color: this.color.getHex(),
  21388. density: this.density
  21389. };
  21390. };
  21391. return FogExp2;
  21392. }();
  21393. var Fog = /*#__PURE__*/function () {
  21394. function Fog(color, near, far) {
  21395. Object.defineProperty(this, 'isFog', {
  21396. value: true
  21397. });
  21398. this.name = '';
  21399. this.color = new Color(color);
  21400. this.near = near !== undefined ? near : 1;
  21401. this.far = far !== undefined ? far : 1000;
  21402. }
  21403. var _proto = Fog.prototype;
  21404. _proto.clone = function clone() {
  21405. return new Fog(this.color, this.near, this.far);
  21406. };
  21407. _proto.toJSON = function toJSON()
  21408. /* meta */
  21409. {
  21410. return {
  21411. type: 'Fog',
  21412. color: this.color.getHex(),
  21413. near: this.near,
  21414. far: this.far
  21415. };
  21416. };
  21417. return Fog;
  21418. }();
  21419. var Scene = /*#__PURE__*/function (_Object3D) {
  21420. _inheritsLoose(Scene, _Object3D);
  21421. function Scene() {
  21422. var _this;
  21423. _this = _Object3D.call(this) || this;
  21424. Object.defineProperty(_assertThisInitialized(_this), 'isScene', {
  21425. value: true
  21426. });
  21427. _this.type = 'Scene';
  21428. _this.background = null;
  21429. _this.environment = null;
  21430. _this.fog = null;
  21431. _this.overrideMaterial = null;
  21432. _this.autoUpdate = true; // checked by the renderer
  21433. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  21434. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  21435. detail: _assertThisInitialized(_this)
  21436. })); // eslint-disable-line no-undef
  21437. }
  21438. return _this;
  21439. }
  21440. var _proto = Scene.prototype;
  21441. _proto.copy = function copy(source, recursive) {
  21442. _Object3D.prototype.copy.call(this, source, recursive);
  21443. if (source.background !== null) this.background = source.background.clone();
  21444. if (source.environment !== null) this.environment = source.environment.clone();
  21445. if (source.fog !== null) this.fog = source.fog.clone();
  21446. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  21447. this.autoUpdate = source.autoUpdate;
  21448. this.matrixAutoUpdate = source.matrixAutoUpdate;
  21449. return this;
  21450. };
  21451. _proto.toJSON = function toJSON(meta) {
  21452. var data = _Object3D.prototype.toJSON.call(this, meta);
  21453. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  21454. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  21455. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  21456. return data;
  21457. };
  21458. return Scene;
  21459. }(Object3D);
  21460. function InterleavedBuffer(array, stride) {
  21461. this.array = array;
  21462. this.stride = stride;
  21463. this.count = array !== undefined ? array.length / stride : 0;
  21464. this.usage = StaticDrawUsage;
  21465. this.updateRange = {
  21466. offset: 0,
  21467. count: -1
  21468. };
  21469. this.version = 0;
  21470. this.uuid = MathUtils.generateUUID();
  21471. }
  21472. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  21473. set: function set(value) {
  21474. if (value === true) this.version++;
  21475. }
  21476. });
  21477. Object.assign(InterleavedBuffer.prototype, {
  21478. isInterleavedBuffer: true,
  21479. onUploadCallback: function onUploadCallback() {},
  21480. setUsage: function setUsage(value) {
  21481. this.usage = value;
  21482. return this;
  21483. },
  21484. copy: function copy(source) {
  21485. this.array = new source.array.constructor(source.array);
  21486. this.count = source.count;
  21487. this.stride = source.stride;
  21488. this.usage = source.usage;
  21489. return this;
  21490. },
  21491. copyAt: function copyAt(index1, attribute, index2) {
  21492. index1 *= this.stride;
  21493. index2 *= attribute.stride;
  21494. for (var i = 0, l = this.stride; i < l; i++) {
  21495. this.array[index1 + i] = attribute.array[index2 + i];
  21496. }
  21497. return this;
  21498. },
  21499. set: function set(value, offset) {
  21500. if (offset === void 0) {
  21501. offset = 0;
  21502. }
  21503. this.array.set(value, offset);
  21504. return this;
  21505. },
  21506. clone: function clone(data) {
  21507. if (data.arrayBuffers === undefined) {
  21508. data.arrayBuffers = {};
  21509. }
  21510. if (this.array.buffer._uuid === undefined) {
  21511. this.array.buffer._uuid = MathUtils.generateUUID();
  21512. }
  21513. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  21514. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  21515. }
  21516. var array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  21517. var ib = new InterleavedBuffer(array, this.stride);
  21518. ib.setUsage(this.usage);
  21519. return ib;
  21520. },
  21521. onUpload: function onUpload(callback) {
  21522. this.onUploadCallback = callback;
  21523. return this;
  21524. },
  21525. toJSON: function toJSON(data) {
  21526. if (data.arrayBuffers === undefined) {
  21527. data.arrayBuffers = {};
  21528. } // generate UUID for array buffer if necessary
  21529. if (this.array.buffer._uuid === undefined) {
  21530. this.array.buffer._uuid = MathUtils.generateUUID();
  21531. }
  21532. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  21533. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  21534. } //
  21535. return {
  21536. uuid: this.uuid,
  21537. buffer: this.array.buffer._uuid,
  21538. type: this.array.constructor.name,
  21539. stride: this.stride
  21540. };
  21541. }
  21542. });
  21543. var _vector$6 = new Vector3();
  21544. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  21545. this.name = '';
  21546. this.data = interleavedBuffer;
  21547. this.itemSize = itemSize;
  21548. this.offset = offset;
  21549. this.normalized = normalized === true;
  21550. }
  21551. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  21552. count: {
  21553. get: function get() {
  21554. return this.data.count;
  21555. }
  21556. },
  21557. array: {
  21558. get: function get() {
  21559. return this.data.array;
  21560. }
  21561. },
  21562. needsUpdate: {
  21563. set: function set(value) {
  21564. this.data.needsUpdate = value;
  21565. }
  21566. }
  21567. });
  21568. Object.assign(InterleavedBufferAttribute.prototype, {
  21569. isInterleavedBufferAttribute: true,
  21570. applyMatrix4: function applyMatrix4(m) {
  21571. for (var i = 0, l = this.data.count; i < l; i++) {
  21572. _vector$6.x = this.getX(i);
  21573. _vector$6.y = this.getY(i);
  21574. _vector$6.z = this.getZ(i);
  21575. _vector$6.applyMatrix4(m);
  21576. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  21577. }
  21578. return this;
  21579. },
  21580. setX: function setX(index, x) {
  21581. this.data.array[index * this.data.stride + this.offset] = x;
  21582. return this;
  21583. },
  21584. setY: function setY(index, y) {
  21585. this.data.array[index * this.data.stride + this.offset + 1] = y;
  21586. return this;
  21587. },
  21588. setZ: function setZ(index, z) {
  21589. this.data.array[index * this.data.stride + this.offset + 2] = z;
  21590. return this;
  21591. },
  21592. setW: function setW(index, w) {
  21593. this.data.array[index * this.data.stride + this.offset + 3] = w;
  21594. return this;
  21595. },
  21596. getX: function getX(index) {
  21597. return this.data.array[index * this.data.stride + this.offset];
  21598. },
  21599. getY: function getY(index) {
  21600. return this.data.array[index * this.data.stride + this.offset + 1];
  21601. },
  21602. getZ: function getZ(index) {
  21603. return this.data.array[index * this.data.stride + this.offset + 2];
  21604. },
  21605. getW: function getW(index) {
  21606. return this.data.array[index * this.data.stride + this.offset + 3];
  21607. },
  21608. setXY: function setXY(index, x, y) {
  21609. index = index * this.data.stride + this.offset;
  21610. this.data.array[index + 0] = x;
  21611. this.data.array[index + 1] = y;
  21612. return this;
  21613. },
  21614. setXYZ: function setXYZ(index, x, y, z) {
  21615. index = index * this.data.stride + this.offset;
  21616. this.data.array[index + 0] = x;
  21617. this.data.array[index + 1] = y;
  21618. this.data.array[index + 2] = z;
  21619. return this;
  21620. },
  21621. setXYZW: function setXYZW(index, x, y, z, w) {
  21622. index = index * this.data.stride + this.offset;
  21623. this.data.array[index + 0] = x;
  21624. this.data.array[index + 1] = y;
  21625. this.data.array[index + 2] = z;
  21626. this.data.array[index + 3] = w;
  21627. return this;
  21628. },
  21629. clone: function clone(data) {
  21630. if (data === undefined) {
  21631. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  21632. var array = [];
  21633. for (var i = 0; i < this.count; i++) {
  21634. var index = i * this.data.stride + this.offset;
  21635. for (var j = 0; j < this.itemSize; j++) {
  21636. array.push(this.data.array[index + j]);
  21637. }
  21638. }
  21639. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  21640. } else {
  21641. if (data.interleavedBuffers === undefined) {
  21642. data.interleavedBuffers = {};
  21643. }
  21644. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  21645. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  21646. }
  21647. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  21648. }
  21649. },
  21650. toJSON: function toJSON(data) {
  21651. if (data === undefined) {
  21652. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  21653. var array = [];
  21654. for (var i = 0; i < this.count; i++) {
  21655. var index = i * this.data.stride + this.offset;
  21656. for (var j = 0; j < this.itemSize; j++) {
  21657. array.push(this.data.array[index + j]);
  21658. }
  21659. } // deinterleave data and save it as an ordinary buffer attribute for now
  21660. return {
  21661. itemSize: this.itemSize,
  21662. type: this.array.constructor.name,
  21663. array: array,
  21664. normalized: this.normalized
  21665. };
  21666. } else {
  21667. // save as true interlaved attribtue
  21668. if (data.interleavedBuffers === undefined) {
  21669. data.interleavedBuffers = {};
  21670. }
  21671. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  21672. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  21673. }
  21674. return {
  21675. isInterleavedBufferAttribute: true,
  21676. itemSize: this.itemSize,
  21677. data: this.data.uuid,
  21678. offset: this.offset,
  21679. normalized: this.normalized
  21680. };
  21681. }
  21682. }
  21683. });
  21684. /**
  21685. * parameters = {
  21686. * color: <hex>,
  21687. * map: new THREE.Texture( <Image> ),
  21688. * alphaMap: new THREE.Texture( <Image> ),
  21689. * rotation: <float>,
  21690. * sizeAttenuation: <bool>
  21691. * }
  21692. */
  21693. function SpriteMaterial(parameters) {
  21694. Material.call(this);
  21695. this.type = 'SpriteMaterial';
  21696. this.color = new Color(0xffffff);
  21697. this.map = null;
  21698. this.alphaMap = null;
  21699. this.rotation = 0;
  21700. this.sizeAttenuation = true;
  21701. this.transparent = true;
  21702. this.setValues(parameters);
  21703. }
  21704. SpriteMaterial.prototype = Object.create(Material.prototype);
  21705. SpriteMaterial.prototype.constructor = SpriteMaterial;
  21706. SpriteMaterial.prototype.isSpriteMaterial = true;
  21707. SpriteMaterial.prototype.copy = function (source) {
  21708. Material.prototype.copy.call(this, source);
  21709. this.color.copy(source.color);
  21710. this.map = source.map;
  21711. this.alphaMap = source.alphaMap;
  21712. this.rotation = source.rotation;
  21713. this.sizeAttenuation = source.sizeAttenuation;
  21714. return this;
  21715. };
  21716. var _geometry;
  21717. var _intersectPoint = new Vector3();
  21718. var _worldScale = new Vector3();
  21719. var _mvPosition = new Vector3();
  21720. var _alignedPosition = new Vector2();
  21721. var _rotatedPosition = new Vector2();
  21722. var _viewWorldMatrix = new Matrix4();
  21723. var _vA$1 = new Vector3();
  21724. var _vB$1 = new Vector3();
  21725. var _vC$1 = new Vector3();
  21726. var _uvA$1 = new Vector2();
  21727. var _uvB$1 = new Vector2();
  21728. var _uvC$1 = new Vector2();
  21729. function Sprite(material) {
  21730. Object3D.call(this);
  21731. this.type = 'Sprite';
  21732. if (_geometry === undefined) {
  21733. _geometry = new BufferGeometry();
  21734. var float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  21735. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  21736. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  21737. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  21738. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  21739. }
  21740. this.geometry = _geometry;
  21741. this.material = material !== undefined ? material : new SpriteMaterial();
  21742. this.center = new Vector2(0.5, 0.5);
  21743. }
  21744. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  21745. constructor: Sprite,
  21746. isSprite: true,
  21747. raycast: function raycast(raycaster, intersects) {
  21748. if (raycaster.camera === null) {
  21749. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  21750. }
  21751. _worldScale.setFromMatrixScale(this.matrixWorld);
  21752. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  21753. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  21754. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  21755. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  21756. _worldScale.multiplyScalar(-_mvPosition.z);
  21757. }
  21758. var rotation = this.material.rotation;
  21759. var sin, cos;
  21760. if (rotation !== 0) {
  21761. cos = Math.cos(rotation);
  21762. sin = Math.sin(rotation);
  21763. }
  21764. var center = this.center;
  21765. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  21766. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  21767. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  21768. _uvA$1.set(0, 0);
  21769. _uvB$1.set(1, 0);
  21770. _uvC$1.set(1, 1); // check first triangle
  21771. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  21772. if (intersect === null) {
  21773. // check second triangle
  21774. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  21775. _uvB$1.set(0, 1);
  21776. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  21777. if (intersect === null) {
  21778. return;
  21779. }
  21780. }
  21781. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  21782. if (distance < raycaster.near || distance > raycaster.far) return;
  21783. intersects.push({
  21784. distance: distance,
  21785. point: _intersectPoint.clone(),
  21786. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  21787. face: null,
  21788. object: this
  21789. });
  21790. },
  21791. copy: function copy(source) {
  21792. Object3D.prototype.copy.call(this, source);
  21793. if (source.center !== undefined) this.center.copy(source.center);
  21794. this.material = source.material;
  21795. return this;
  21796. }
  21797. });
  21798. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  21799. // compute position in camera space
  21800. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  21801. if (sin !== undefined) {
  21802. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  21803. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  21804. } else {
  21805. _rotatedPosition.copy(_alignedPosition);
  21806. }
  21807. vertexPosition.copy(mvPosition);
  21808. vertexPosition.x += _rotatedPosition.x;
  21809. vertexPosition.y += _rotatedPosition.y; // transform to world space
  21810. vertexPosition.applyMatrix4(_viewWorldMatrix);
  21811. }
  21812. var _v1$4 = new Vector3();
  21813. var _v2$2 = new Vector3();
  21814. function LOD() {
  21815. Object3D.call(this);
  21816. this._currentLevel = 0;
  21817. this.type = 'LOD';
  21818. Object.defineProperties(this, {
  21819. levels: {
  21820. enumerable: true,
  21821. value: []
  21822. }
  21823. });
  21824. this.autoUpdate = true;
  21825. }
  21826. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  21827. constructor: LOD,
  21828. isLOD: true,
  21829. copy: function copy(source) {
  21830. Object3D.prototype.copy.call(this, source, false);
  21831. var levels = source.levels;
  21832. for (var i = 0, l = levels.length; i < l; i++) {
  21833. var level = levels[i];
  21834. this.addLevel(level.object.clone(), level.distance);
  21835. }
  21836. this.autoUpdate = source.autoUpdate;
  21837. return this;
  21838. },
  21839. addLevel: function addLevel(object, distance) {
  21840. if (distance === void 0) {
  21841. distance = 0;
  21842. }
  21843. distance = Math.abs(distance);
  21844. var levels = this.levels;
  21845. var l;
  21846. for (l = 0; l < levels.length; l++) {
  21847. if (distance < levels[l].distance) {
  21848. break;
  21849. }
  21850. }
  21851. levels.splice(l, 0, {
  21852. distance: distance,
  21853. object: object
  21854. });
  21855. this.add(object);
  21856. return this;
  21857. },
  21858. getCurrentLevel: function getCurrentLevel() {
  21859. return this._currentLevel;
  21860. },
  21861. getObjectForDistance: function getObjectForDistance(distance) {
  21862. var levels = this.levels;
  21863. if (levels.length > 0) {
  21864. var i, l;
  21865. for (i = 1, l = levels.length; i < l; i++) {
  21866. if (distance < levels[i].distance) {
  21867. break;
  21868. }
  21869. }
  21870. return levels[i - 1].object;
  21871. }
  21872. return null;
  21873. },
  21874. raycast: function raycast(raycaster, intersects) {
  21875. var levels = this.levels;
  21876. if (levels.length > 0) {
  21877. _v1$4.setFromMatrixPosition(this.matrixWorld);
  21878. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  21879. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  21880. }
  21881. },
  21882. update: function update(camera) {
  21883. var levels = this.levels;
  21884. if (levels.length > 1) {
  21885. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  21886. _v2$2.setFromMatrixPosition(this.matrixWorld);
  21887. var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  21888. levels[0].object.visible = true;
  21889. var i, l;
  21890. for (i = 1, l = levels.length; i < l; i++) {
  21891. if (distance >= levels[i].distance) {
  21892. levels[i - 1].object.visible = false;
  21893. levels[i].object.visible = true;
  21894. } else {
  21895. break;
  21896. }
  21897. }
  21898. this._currentLevel = i - 1;
  21899. for (; i < l; i++) {
  21900. levels[i].object.visible = false;
  21901. }
  21902. }
  21903. },
  21904. toJSON: function toJSON(meta) {
  21905. var data = Object3D.prototype.toJSON.call(this, meta);
  21906. if (this.autoUpdate === false) data.object.autoUpdate = false;
  21907. data.object.levels = [];
  21908. var levels = this.levels;
  21909. for (var i = 0, l = levels.length; i < l; i++) {
  21910. var level = levels[i];
  21911. data.object.levels.push({
  21912. object: level.object.uuid,
  21913. distance: level.distance
  21914. });
  21915. }
  21916. return data;
  21917. }
  21918. });
  21919. function SkinnedMesh(geometry, material) {
  21920. if (geometry && geometry.isGeometry) {
  21921. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  21922. }
  21923. Mesh.call(this, geometry, material);
  21924. this.type = 'SkinnedMesh';
  21925. this.bindMode = 'attached';
  21926. this.bindMatrix = new Matrix4();
  21927. this.bindMatrixInverse = new Matrix4();
  21928. }
  21929. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  21930. constructor: SkinnedMesh,
  21931. isSkinnedMesh: true,
  21932. copy: function copy(source) {
  21933. Mesh.prototype.copy.call(this, source);
  21934. this.bindMode = source.bindMode;
  21935. this.bindMatrix.copy(source.bindMatrix);
  21936. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  21937. this.skeleton = source.skeleton;
  21938. return this;
  21939. },
  21940. bind: function bind(skeleton, bindMatrix) {
  21941. this.skeleton = skeleton;
  21942. if (bindMatrix === undefined) {
  21943. this.updateMatrixWorld(true);
  21944. this.skeleton.calculateInverses();
  21945. bindMatrix = this.matrixWorld;
  21946. }
  21947. this.bindMatrix.copy(bindMatrix);
  21948. this.bindMatrixInverse.copy(bindMatrix).invert();
  21949. },
  21950. pose: function pose() {
  21951. this.skeleton.pose();
  21952. },
  21953. normalizeSkinWeights: function normalizeSkinWeights() {
  21954. var vector = new Vector4();
  21955. var skinWeight = this.geometry.attributes.skinWeight;
  21956. for (var i = 0, l = skinWeight.count; i < l; i++) {
  21957. vector.x = skinWeight.getX(i);
  21958. vector.y = skinWeight.getY(i);
  21959. vector.z = skinWeight.getZ(i);
  21960. vector.w = skinWeight.getW(i);
  21961. var scale = 1.0 / vector.manhattanLength();
  21962. if (scale !== Infinity) {
  21963. vector.multiplyScalar(scale);
  21964. } else {
  21965. vector.set(1, 0, 0, 0); // do something reasonable
  21966. }
  21967. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  21968. }
  21969. },
  21970. updateMatrixWorld: function updateMatrixWorld(force) {
  21971. Mesh.prototype.updateMatrixWorld.call(this, force);
  21972. if (this.bindMode === 'attached') {
  21973. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  21974. } else if (this.bindMode === 'detached') {
  21975. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  21976. } else {
  21977. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  21978. }
  21979. },
  21980. boneTransform: function () {
  21981. var basePosition = new Vector3();
  21982. var skinIndex = new Vector4();
  21983. var skinWeight = new Vector4();
  21984. var vector = new Vector3();
  21985. var matrix = new Matrix4();
  21986. return function (index, target) {
  21987. var skeleton = this.skeleton;
  21988. var geometry = this.geometry;
  21989. skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  21990. skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  21991. basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  21992. target.set(0, 0, 0);
  21993. for (var i = 0; i < 4; i++) {
  21994. var weight = skinWeight.getComponent(i);
  21995. if (weight !== 0) {
  21996. var boneIndex = skinIndex.getComponent(i);
  21997. matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  21998. target.addScaledVector(vector.copy(basePosition).applyMatrix4(matrix), weight);
  21999. }
  22000. }
  22001. return target.applyMatrix4(this.bindMatrixInverse);
  22002. };
  22003. }()
  22004. });
  22005. function Bone() {
  22006. Object3D.call(this);
  22007. this.type = 'Bone';
  22008. }
  22009. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  22010. constructor: Bone,
  22011. isBone: true
  22012. });
  22013. var _offsetMatrix = new Matrix4();
  22014. var _identityMatrix = new Matrix4();
  22015. function Skeleton(bones, boneInverses) {
  22016. if (bones === void 0) {
  22017. bones = [];
  22018. }
  22019. if (boneInverses === void 0) {
  22020. boneInverses = [];
  22021. }
  22022. this.uuid = MathUtils.generateUUID();
  22023. this.bones = bones.slice(0);
  22024. this.boneInverses = boneInverses;
  22025. this.boneMatrices = null;
  22026. this.boneTexture = null;
  22027. this.boneTextureSize = 0;
  22028. this.frame = -1;
  22029. this.init();
  22030. }
  22031. Object.assign(Skeleton.prototype, {
  22032. init: function init() {
  22033. var bones = this.bones;
  22034. var boneInverses = this.boneInverses;
  22035. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  22036. if (boneInverses.length === 0) {
  22037. this.calculateInverses();
  22038. } else {
  22039. // handle special case
  22040. if (bones.length !== boneInverses.length) {
  22041. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  22042. this.boneInverses = [];
  22043. for (var i = 0, il = this.bones.length; i < il; i++) {
  22044. this.boneInverses.push(new Matrix4());
  22045. }
  22046. }
  22047. }
  22048. },
  22049. calculateInverses: function calculateInverses() {
  22050. this.boneInverses.length = 0;
  22051. for (var i = 0, il = this.bones.length; i < il; i++) {
  22052. var inverse = new Matrix4();
  22053. if (this.bones[i]) {
  22054. inverse.copy(this.bones[i].matrixWorld).invert();
  22055. }
  22056. this.boneInverses.push(inverse);
  22057. }
  22058. },
  22059. pose: function pose() {
  22060. // recover the bind-time world matrices
  22061. for (var i = 0, il = this.bones.length; i < il; i++) {
  22062. var bone = this.bones[i];
  22063. if (bone) {
  22064. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  22065. }
  22066. } // compute the local matrices, positions, rotations and scales
  22067. for (var _i = 0, _il = this.bones.length; _i < _il; _i++) {
  22068. var _bone = this.bones[_i];
  22069. if (_bone) {
  22070. if (_bone.parent && _bone.parent.isBone) {
  22071. _bone.matrix.copy(_bone.parent.matrixWorld).invert();
  22072. _bone.matrix.multiply(_bone.matrixWorld);
  22073. } else {
  22074. _bone.matrix.copy(_bone.matrixWorld);
  22075. }
  22076. _bone.matrix.decompose(_bone.position, _bone.quaternion, _bone.scale);
  22077. }
  22078. }
  22079. },
  22080. update: function update() {
  22081. var bones = this.bones;
  22082. var boneInverses = this.boneInverses;
  22083. var boneMatrices = this.boneMatrices;
  22084. var boneTexture = this.boneTexture; // flatten bone matrices to array
  22085. for (var i = 0, il = bones.length; i < il; i++) {
  22086. // compute the offset between the current and the original transform
  22087. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  22088. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  22089. _offsetMatrix.toArray(boneMatrices, i * 16);
  22090. }
  22091. if (boneTexture !== null) {
  22092. boneTexture.needsUpdate = true;
  22093. }
  22094. },
  22095. clone: function clone() {
  22096. return new Skeleton(this.bones, this.boneInverses);
  22097. },
  22098. getBoneByName: function getBoneByName(name) {
  22099. for (var i = 0, il = this.bones.length; i < il; i++) {
  22100. var bone = this.bones[i];
  22101. if (bone.name === name) {
  22102. return bone;
  22103. }
  22104. }
  22105. return undefined;
  22106. },
  22107. dispose: function dispose() {
  22108. if (this.boneTexture !== null) {
  22109. this.boneTexture.dispose();
  22110. this.boneTexture = null;
  22111. }
  22112. },
  22113. fromJSON: function fromJSON(json, bones) {
  22114. this.uuid = json.uuid;
  22115. for (var i = 0, l = json.bones.length; i < l; i++) {
  22116. var uuid = json.bones[i];
  22117. var bone = bones[uuid];
  22118. if (bone === undefined) {
  22119. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  22120. bone = new Bone();
  22121. }
  22122. this.bones.push(bone);
  22123. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  22124. }
  22125. this.init();
  22126. return this;
  22127. },
  22128. toJSON: function toJSON() {
  22129. var data = {
  22130. metadata: {
  22131. version: 4.5,
  22132. type: 'Skeleton',
  22133. generator: 'Skeleton.toJSON'
  22134. },
  22135. bones: [],
  22136. boneInverses: []
  22137. };
  22138. data.uuid = this.uuid;
  22139. var bones = this.bones;
  22140. var boneInverses = this.boneInverses;
  22141. for (var i = 0, l = bones.length; i < l; i++) {
  22142. var bone = bones[i];
  22143. data.bones.push(bone.uuid);
  22144. var boneInverse = boneInverses[i];
  22145. data.boneInverses.push(boneInverse.toArray());
  22146. }
  22147. return data;
  22148. }
  22149. });
  22150. var _instanceLocalMatrix = new Matrix4();
  22151. var _instanceWorldMatrix = new Matrix4();
  22152. var _instanceIntersects = [];
  22153. var _mesh = new Mesh();
  22154. function InstancedMesh(geometry, material, count) {
  22155. Mesh.call(this, geometry, material);
  22156. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  22157. this.instanceColor = null;
  22158. this.count = count;
  22159. this.frustumCulled = false;
  22160. }
  22161. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  22162. constructor: InstancedMesh,
  22163. isInstancedMesh: true,
  22164. copy: function copy(source) {
  22165. Mesh.prototype.copy.call(this, source);
  22166. this.instanceMatrix.copy(source.instanceMatrix);
  22167. this.count = source.count;
  22168. return this;
  22169. },
  22170. getColorAt: function getColorAt(index, color) {
  22171. color.fromArray(this.instanceColor.array, index * 3);
  22172. },
  22173. getMatrixAt: function getMatrixAt(index, matrix) {
  22174. matrix.fromArray(this.instanceMatrix.array, index * 16);
  22175. },
  22176. raycast: function raycast(raycaster, intersects) {
  22177. var matrixWorld = this.matrixWorld;
  22178. var raycastTimes = this.count;
  22179. _mesh.geometry = this.geometry;
  22180. _mesh.material = this.material;
  22181. if (_mesh.material === undefined) return;
  22182. for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
  22183. // calculate the world matrix for each instance
  22184. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  22185. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  22186. _mesh.matrixWorld = _instanceWorldMatrix;
  22187. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  22188. for (var i = 0, l = _instanceIntersects.length; i < l; i++) {
  22189. var intersect = _instanceIntersects[i];
  22190. intersect.instanceId = instanceId;
  22191. intersect.object = this;
  22192. intersects.push(intersect);
  22193. }
  22194. _instanceIntersects.length = 0;
  22195. }
  22196. },
  22197. setColorAt: function setColorAt(index, color) {
  22198. if (this.instanceColor === null) {
  22199. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  22200. }
  22201. color.toArray(this.instanceColor.array, index * 3);
  22202. },
  22203. setMatrixAt: function setMatrixAt(index, matrix) {
  22204. matrix.toArray(this.instanceMatrix.array, index * 16);
  22205. },
  22206. updateMorphTargets: function updateMorphTargets() {}
  22207. });
  22208. /**
  22209. * parameters = {
  22210. * color: <hex>,
  22211. * opacity: <float>,
  22212. *
  22213. * linewidth: <float>,
  22214. * linecap: "round",
  22215. * linejoin: "round"
  22216. * }
  22217. */
  22218. function LineBasicMaterial(parameters) {
  22219. Material.call(this);
  22220. this.type = 'LineBasicMaterial';
  22221. this.color = new Color(0xffffff);
  22222. this.linewidth = 1;
  22223. this.linecap = 'round';
  22224. this.linejoin = 'round';
  22225. this.morphTargets = false;
  22226. this.setValues(parameters);
  22227. }
  22228. LineBasicMaterial.prototype = Object.create(Material.prototype);
  22229. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  22230. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  22231. LineBasicMaterial.prototype.copy = function (source) {
  22232. Material.prototype.copy.call(this, source);
  22233. this.color.copy(source.color);
  22234. this.linewidth = source.linewidth;
  22235. this.linecap = source.linecap;
  22236. this.linejoin = source.linejoin;
  22237. this.morphTargets = source.morphTargets;
  22238. return this;
  22239. };
  22240. var _start = new Vector3();
  22241. var _end = new Vector3();
  22242. var _inverseMatrix$1 = new Matrix4();
  22243. var _ray$1 = new Ray();
  22244. var _sphere$2 = new Sphere();
  22245. function Line(geometry, material, mode) {
  22246. if (mode === 1) {
  22247. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  22248. }
  22249. Object3D.call(this);
  22250. this.type = 'Line';
  22251. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  22252. this.material = material !== undefined ? material : new LineBasicMaterial();
  22253. this.updateMorphTargets();
  22254. }
  22255. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  22256. constructor: Line,
  22257. isLine: true,
  22258. copy: function copy(source) {
  22259. Object3D.prototype.copy.call(this, source);
  22260. this.material = source.material;
  22261. this.geometry = source.geometry;
  22262. return this;
  22263. },
  22264. computeLineDistances: function computeLineDistances() {
  22265. var geometry = this.geometry;
  22266. if (geometry.isBufferGeometry) {
  22267. // we assume non-indexed geometry
  22268. if (geometry.index === null) {
  22269. var positionAttribute = geometry.attributes.position;
  22270. var lineDistances = [0];
  22271. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  22272. _start.fromBufferAttribute(positionAttribute, i - 1);
  22273. _end.fromBufferAttribute(positionAttribute, i);
  22274. lineDistances[i] = lineDistances[i - 1];
  22275. lineDistances[i] += _start.distanceTo(_end);
  22276. }
  22277. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  22278. } else {
  22279. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  22280. }
  22281. } else if (geometry.isGeometry) {
  22282. var vertices = geometry.vertices;
  22283. var _lineDistances = geometry.lineDistances;
  22284. _lineDistances[0] = 0;
  22285. for (var _i = 1, _l = vertices.length; _i < _l; _i++) {
  22286. _lineDistances[_i] = _lineDistances[_i - 1];
  22287. _lineDistances[_i] += vertices[_i - 1].distanceTo(vertices[_i]);
  22288. }
  22289. }
  22290. return this;
  22291. },
  22292. raycast: function raycast(raycaster, intersects) {
  22293. var geometry = this.geometry;
  22294. var matrixWorld = this.matrixWorld;
  22295. var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  22296. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  22297. _sphere$2.copy(geometry.boundingSphere);
  22298. _sphere$2.applyMatrix4(matrixWorld);
  22299. _sphere$2.radius += threshold;
  22300. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  22301. _inverseMatrix$1.copy(matrixWorld).invert();
  22302. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  22303. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  22304. var localThresholdSq = localThreshold * localThreshold;
  22305. var vStart = new Vector3();
  22306. var vEnd = new Vector3();
  22307. var interSegment = new Vector3();
  22308. var interRay = new Vector3();
  22309. var step = this.isLineSegments ? 2 : 1;
  22310. if (geometry.isBufferGeometry) {
  22311. var index = geometry.index;
  22312. var attributes = geometry.attributes;
  22313. var positionAttribute = attributes.position;
  22314. if (index !== null) {
  22315. var indices = index.array;
  22316. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  22317. var a = indices[i];
  22318. var b = indices[i + 1];
  22319. vStart.fromBufferAttribute(positionAttribute, a);
  22320. vEnd.fromBufferAttribute(positionAttribute, b);
  22321. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  22322. if (distSq > localThresholdSq) continue;
  22323. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22324. var distance = raycaster.ray.origin.distanceTo(interRay);
  22325. if (distance < raycaster.near || distance > raycaster.far) continue;
  22326. intersects.push({
  22327. distance: distance,
  22328. // What do we want? intersection point on the ray or on the segment??
  22329. // point: raycaster.ray.at( distance ),
  22330. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22331. index: i,
  22332. face: null,
  22333. faceIndex: null,
  22334. object: this
  22335. });
  22336. }
  22337. } else {
  22338. for (var _i2 = 0, _l2 = positionAttribute.count - 1; _i2 < _l2; _i2 += step) {
  22339. vStart.fromBufferAttribute(positionAttribute, _i2);
  22340. vEnd.fromBufferAttribute(positionAttribute, _i2 + 1);
  22341. var _distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  22342. if (_distSq > localThresholdSq) continue;
  22343. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22344. var _distance = raycaster.ray.origin.distanceTo(interRay);
  22345. if (_distance < raycaster.near || _distance > raycaster.far) continue;
  22346. intersects.push({
  22347. distance: _distance,
  22348. // What do we want? intersection point on the ray or on the segment??
  22349. // point: raycaster.ray.at( distance ),
  22350. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22351. index: _i2,
  22352. face: null,
  22353. faceIndex: null,
  22354. object: this
  22355. });
  22356. }
  22357. }
  22358. } else if (geometry.isGeometry) {
  22359. var vertices = geometry.vertices;
  22360. var nbVertices = vertices.length;
  22361. for (var _i3 = 0; _i3 < nbVertices - 1; _i3 += step) {
  22362. var _distSq2 = _ray$1.distanceSqToSegment(vertices[_i3], vertices[_i3 + 1], interRay, interSegment);
  22363. if (_distSq2 > localThresholdSq) continue;
  22364. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22365. var _distance2 = raycaster.ray.origin.distanceTo(interRay);
  22366. if (_distance2 < raycaster.near || _distance2 > raycaster.far) continue;
  22367. intersects.push({
  22368. distance: _distance2,
  22369. // What do we want? intersection point on the ray or on the segment??
  22370. // point: raycaster.ray.at( distance ),
  22371. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22372. index: _i3,
  22373. face: null,
  22374. faceIndex: null,
  22375. object: this
  22376. });
  22377. }
  22378. }
  22379. },
  22380. updateMorphTargets: function updateMorphTargets() {
  22381. var geometry = this.geometry;
  22382. if (geometry.isBufferGeometry) {
  22383. var morphAttributes = geometry.morphAttributes;
  22384. var keys = Object.keys(morphAttributes);
  22385. if (keys.length > 0) {
  22386. var morphAttribute = morphAttributes[keys[0]];
  22387. if (morphAttribute !== undefined) {
  22388. this.morphTargetInfluences = [];
  22389. this.morphTargetDictionary = {};
  22390. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  22391. var name = morphAttribute[m].name || String(m);
  22392. this.morphTargetInfluences.push(0);
  22393. this.morphTargetDictionary[name] = m;
  22394. }
  22395. }
  22396. }
  22397. } else {
  22398. var morphTargets = geometry.morphTargets;
  22399. if (morphTargets !== undefined && morphTargets.length > 0) {
  22400. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  22401. }
  22402. }
  22403. }
  22404. });
  22405. var _start$1 = new Vector3();
  22406. var _end$1 = new Vector3();
  22407. function LineSegments(geometry, material) {
  22408. Line.call(this, geometry, material);
  22409. this.type = 'LineSegments';
  22410. }
  22411. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  22412. constructor: LineSegments,
  22413. isLineSegments: true,
  22414. computeLineDistances: function computeLineDistances() {
  22415. var geometry = this.geometry;
  22416. if (geometry.isBufferGeometry) {
  22417. // we assume non-indexed geometry
  22418. if (geometry.index === null) {
  22419. var positionAttribute = geometry.attributes.position;
  22420. var lineDistances = [];
  22421. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  22422. _start$1.fromBufferAttribute(positionAttribute, i);
  22423. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  22424. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  22425. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  22426. }
  22427. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  22428. } else {
  22429. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  22430. }
  22431. } else if (geometry.isGeometry) {
  22432. var vertices = geometry.vertices;
  22433. var _lineDistances = geometry.lineDistances;
  22434. for (var _i = 0, _l = vertices.length; _i < _l; _i += 2) {
  22435. _start$1.copy(vertices[_i]);
  22436. _end$1.copy(vertices[_i + 1]);
  22437. _lineDistances[_i] = _i === 0 ? 0 : _lineDistances[_i - 1];
  22438. _lineDistances[_i + 1] = _lineDistances[_i] + _start$1.distanceTo(_end$1);
  22439. }
  22440. }
  22441. return this;
  22442. }
  22443. });
  22444. function LineLoop(geometry, material) {
  22445. Line.call(this, geometry, material);
  22446. this.type = 'LineLoop';
  22447. }
  22448. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  22449. constructor: LineLoop,
  22450. isLineLoop: true
  22451. });
  22452. /**
  22453. * parameters = {
  22454. * color: <hex>,
  22455. * opacity: <float>,
  22456. * map: new THREE.Texture( <Image> ),
  22457. * alphaMap: new THREE.Texture( <Image> ),
  22458. *
  22459. * size: <float>,
  22460. * sizeAttenuation: <bool>
  22461. *
  22462. * morphTargets: <bool>
  22463. * }
  22464. */
  22465. function PointsMaterial(parameters) {
  22466. Material.call(this);
  22467. this.type = 'PointsMaterial';
  22468. this.color = new Color(0xffffff);
  22469. this.map = null;
  22470. this.alphaMap = null;
  22471. this.size = 1;
  22472. this.sizeAttenuation = true;
  22473. this.morphTargets = false;
  22474. this.setValues(parameters);
  22475. }
  22476. PointsMaterial.prototype = Object.create(Material.prototype);
  22477. PointsMaterial.prototype.constructor = PointsMaterial;
  22478. PointsMaterial.prototype.isPointsMaterial = true;
  22479. PointsMaterial.prototype.copy = function (source) {
  22480. Material.prototype.copy.call(this, source);
  22481. this.color.copy(source.color);
  22482. this.map = source.map;
  22483. this.alphaMap = source.alphaMap;
  22484. this.size = source.size;
  22485. this.sizeAttenuation = source.sizeAttenuation;
  22486. this.morphTargets = source.morphTargets;
  22487. return this;
  22488. };
  22489. var _inverseMatrix$2 = new Matrix4();
  22490. var _ray$2 = new Ray();
  22491. var _sphere$3 = new Sphere();
  22492. var _position$1 = new Vector3();
  22493. function Points(geometry, material) {
  22494. Object3D.call(this);
  22495. this.type = 'Points';
  22496. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  22497. this.material = material !== undefined ? material : new PointsMaterial();
  22498. this.updateMorphTargets();
  22499. }
  22500. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  22501. constructor: Points,
  22502. isPoints: true,
  22503. copy: function copy(source) {
  22504. Object3D.prototype.copy.call(this, source);
  22505. this.material = source.material;
  22506. this.geometry = source.geometry;
  22507. return this;
  22508. },
  22509. raycast: function raycast(raycaster, intersects) {
  22510. var geometry = this.geometry;
  22511. var matrixWorld = this.matrixWorld;
  22512. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  22513. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  22514. _sphere$3.copy(geometry.boundingSphere);
  22515. _sphere$3.applyMatrix4(matrixWorld);
  22516. _sphere$3.radius += threshold;
  22517. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  22518. _inverseMatrix$2.copy(matrixWorld).invert();
  22519. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  22520. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  22521. var localThresholdSq = localThreshold * localThreshold;
  22522. if (geometry.isBufferGeometry) {
  22523. var index = geometry.index;
  22524. var attributes = geometry.attributes;
  22525. var positionAttribute = attributes.position;
  22526. if (index !== null) {
  22527. var indices = index.array;
  22528. for (var i = 0, il = indices.length; i < il; i++) {
  22529. var a = indices[i];
  22530. _position$1.fromBufferAttribute(positionAttribute, a);
  22531. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22532. }
  22533. } else {
  22534. for (var _i = 0, l = positionAttribute.count; _i < l; _i++) {
  22535. _position$1.fromBufferAttribute(positionAttribute, _i);
  22536. testPoint(_position$1, _i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22537. }
  22538. }
  22539. } else {
  22540. var vertices = geometry.vertices;
  22541. for (var _i2 = 0, _l = vertices.length; _i2 < _l; _i2++) {
  22542. testPoint(vertices[_i2], _i2, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22543. }
  22544. }
  22545. },
  22546. updateMorphTargets: function updateMorphTargets() {
  22547. var geometry = this.geometry;
  22548. if (geometry.isBufferGeometry) {
  22549. var morphAttributes = geometry.morphAttributes;
  22550. var keys = Object.keys(morphAttributes);
  22551. if (keys.length > 0) {
  22552. var morphAttribute = morphAttributes[keys[0]];
  22553. if (morphAttribute !== undefined) {
  22554. this.morphTargetInfluences = [];
  22555. this.morphTargetDictionary = {};
  22556. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  22557. var name = morphAttribute[m].name || String(m);
  22558. this.morphTargetInfluences.push(0);
  22559. this.morphTargetDictionary[name] = m;
  22560. }
  22561. }
  22562. }
  22563. } else {
  22564. var morphTargets = geometry.morphTargets;
  22565. if (morphTargets !== undefined && morphTargets.length > 0) {
  22566. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  22567. }
  22568. }
  22569. }
  22570. });
  22571. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  22572. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  22573. if (rayPointDistanceSq < localThresholdSq) {
  22574. var intersectPoint = new Vector3();
  22575. _ray$2.closestPointToPoint(point, intersectPoint);
  22576. intersectPoint.applyMatrix4(matrixWorld);
  22577. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  22578. if (distance < raycaster.near || distance > raycaster.far) return;
  22579. intersects.push({
  22580. distance: distance,
  22581. distanceToRay: Math.sqrt(rayPointDistanceSq),
  22582. point: intersectPoint,
  22583. index: index,
  22584. face: null,
  22585. object: object
  22586. });
  22587. }
  22588. }
  22589. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  22590. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  22591. this.format = format !== undefined ? format : RGBFormat;
  22592. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  22593. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  22594. this.generateMipmaps = false;
  22595. var scope = this;
  22596. function updateVideo() {
  22597. scope.needsUpdate = true;
  22598. video.requestVideoFrameCallback(updateVideo);
  22599. }
  22600. if ('requestVideoFrameCallback' in video) {
  22601. video.requestVideoFrameCallback(updateVideo);
  22602. }
  22603. }
  22604. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  22605. constructor: VideoTexture,
  22606. clone: function clone() {
  22607. return new this.constructor(this.image).copy(this);
  22608. },
  22609. isVideoTexture: true,
  22610. update: function update() {
  22611. var video = this.image;
  22612. var hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  22613. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  22614. this.needsUpdate = true;
  22615. }
  22616. }
  22617. });
  22618. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  22619. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  22620. this.image = {
  22621. width: width,
  22622. height: height
  22623. };
  22624. this.mipmaps = mipmaps; // no flipping for cube textures
  22625. // (also flipping doesn't work for compressed textures )
  22626. this.flipY = false; // can't generate mipmaps for compressed textures
  22627. // mips must be embedded in DDS files
  22628. this.generateMipmaps = false;
  22629. }
  22630. CompressedTexture.prototype = Object.create(Texture.prototype);
  22631. CompressedTexture.prototype.constructor = CompressedTexture;
  22632. CompressedTexture.prototype.isCompressedTexture = true;
  22633. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  22634. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  22635. this.needsUpdate = true;
  22636. }
  22637. CanvasTexture.prototype = Object.create(Texture.prototype);
  22638. CanvasTexture.prototype.constructor = CanvasTexture;
  22639. CanvasTexture.prototype.isCanvasTexture = true;
  22640. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  22641. format = format !== undefined ? format : DepthFormat;
  22642. if (format !== DepthFormat && format !== DepthStencilFormat) {
  22643. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  22644. }
  22645. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  22646. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  22647. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  22648. this.image = {
  22649. width: width,
  22650. height: height
  22651. };
  22652. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  22653. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  22654. this.flipY = false;
  22655. this.generateMipmaps = false;
  22656. }
  22657. DepthTexture.prototype = Object.create(Texture.prototype);
  22658. DepthTexture.prototype.constructor = DepthTexture;
  22659. DepthTexture.prototype.isDepthTexture = true;
  22660. var _geometryId = 0; // Geometry uses even numbers as Id
  22661. var _m1$3 = new Matrix4();
  22662. var _obj$1 = new Object3D();
  22663. var _offset$1 = new Vector3();
  22664. function Geometry() {
  22665. Object.defineProperty(this, 'id', {
  22666. value: _geometryId += 2
  22667. });
  22668. this.uuid = MathUtils.generateUUID();
  22669. this.name = '';
  22670. this.type = 'Geometry';
  22671. this.vertices = [];
  22672. this.colors = [];
  22673. this.faces = [];
  22674. this.faceVertexUvs = [[]];
  22675. this.morphTargets = [];
  22676. this.morphNormals = [];
  22677. this.skinWeights = [];
  22678. this.skinIndices = [];
  22679. this.lineDistances = [];
  22680. this.boundingBox = null;
  22681. this.boundingSphere = null; // update flags
  22682. this.elementsNeedUpdate = false;
  22683. this.verticesNeedUpdate = false;
  22684. this.uvsNeedUpdate = false;
  22685. this.normalsNeedUpdate = false;
  22686. this.colorsNeedUpdate = false;
  22687. this.lineDistancesNeedUpdate = false;
  22688. this.groupsNeedUpdate = false;
  22689. }
  22690. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  22691. constructor: Geometry,
  22692. isGeometry: true,
  22693. applyMatrix4: function applyMatrix4(matrix) {
  22694. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  22695. for (var i = 0, il = this.vertices.length; i < il; i++) {
  22696. var vertex = this.vertices[i];
  22697. vertex.applyMatrix4(matrix);
  22698. }
  22699. for (var _i = 0, _il = this.faces.length; _i < _il; _i++) {
  22700. var face = this.faces[_i];
  22701. face.normal.applyMatrix3(normalMatrix).normalize();
  22702. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  22703. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  22704. }
  22705. }
  22706. if (this.boundingBox !== null) {
  22707. this.computeBoundingBox();
  22708. }
  22709. if (this.boundingSphere !== null) {
  22710. this.computeBoundingSphere();
  22711. }
  22712. this.verticesNeedUpdate = true;
  22713. this.normalsNeedUpdate = true;
  22714. return this;
  22715. },
  22716. rotateX: function rotateX(angle) {
  22717. // rotate geometry around world x-axis
  22718. _m1$3.makeRotationX(angle);
  22719. this.applyMatrix4(_m1$3);
  22720. return this;
  22721. },
  22722. rotateY: function rotateY(angle) {
  22723. // rotate geometry around world y-axis
  22724. _m1$3.makeRotationY(angle);
  22725. this.applyMatrix4(_m1$3);
  22726. return this;
  22727. },
  22728. rotateZ: function rotateZ(angle) {
  22729. // rotate geometry around world z-axis
  22730. _m1$3.makeRotationZ(angle);
  22731. this.applyMatrix4(_m1$3);
  22732. return this;
  22733. },
  22734. translate: function translate(x, y, z) {
  22735. // translate geometry
  22736. _m1$3.makeTranslation(x, y, z);
  22737. this.applyMatrix4(_m1$3);
  22738. return this;
  22739. },
  22740. scale: function scale(x, y, z) {
  22741. // scale geometry
  22742. _m1$3.makeScale(x, y, z);
  22743. this.applyMatrix4(_m1$3);
  22744. return this;
  22745. },
  22746. lookAt: function lookAt(vector) {
  22747. _obj$1.lookAt(vector);
  22748. _obj$1.updateMatrix();
  22749. this.applyMatrix4(_obj$1.matrix);
  22750. return this;
  22751. },
  22752. fromBufferGeometry: function fromBufferGeometry(geometry) {
  22753. var scope = this;
  22754. var index = geometry.index !== null ? geometry.index : undefined;
  22755. var attributes = geometry.attributes;
  22756. if (attributes.position === undefined) {
  22757. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  22758. return this;
  22759. }
  22760. var position = attributes.position;
  22761. var normal = attributes.normal;
  22762. var color = attributes.color;
  22763. var uv = attributes.uv;
  22764. var uv2 = attributes.uv2;
  22765. if (uv2 !== undefined) this.faceVertexUvs[1] = [];
  22766. for (var i = 0; i < position.count; i++) {
  22767. scope.vertices.push(new Vector3().fromBufferAttribute(position, i));
  22768. if (color !== undefined) {
  22769. scope.colors.push(new Color().fromBufferAttribute(color, i));
  22770. }
  22771. }
  22772. function addFace(a, b, c, materialIndex) {
  22773. var vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  22774. var vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)];
  22775. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  22776. scope.faces.push(face);
  22777. if (uv !== undefined) {
  22778. scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]);
  22779. }
  22780. if (uv2 !== undefined) {
  22781. scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]);
  22782. }
  22783. }
  22784. var groups = geometry.groups;
  22785. if (groups.length > 0) {
  22786. for (var _i2 = 0; _i2 < groups.length; _i2++) {
  22787. var group = groups[_i2];
  22788. var start = group.start;
  22789. var count = group.count;
  22790. for (var j = start, jl = start + count; j < jl; j += 3) {
  22791. if (index !== undefined) {
  22792. addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex);
  22793. } else {
  22794. addFace(j, j + 1, j + 2, group.materialIndex);
  22795. }
  22796. }
  22797. }
  22798. } else {
  22799. if (index !== undefined) {
  22800. for (var _i3 = 0; _i3 < index.count; _i3 += 3) {
  22801. addFace(index.getX(_i3), index.getX(_i3 + 1), index.getX(_i3 + 2));
  22802. }
  22803. } else {
  22804. for (var _i4 = 0; _i4 < position.count; _i4 += 3) {
  22805. addFace(_i4, _i4 + 1, _i4 + 2);
  22806. }
  22807. }
  22808. }
  22809. this.computeFaceNormals();
  22810. if (geometry.boundingBox !== null) {
  22811. this.boundingBox = geometry.boundingBox.clone();
  22812. }
  22813. if (geometry.boundingSphere !== null) {
  22814. this.boundingSphere = geometry.boundingSphere.clone();
  22815. }
  22816. return this;
  22817. },
  22818. center: function center() {
  22819. this.computeBoundingBox();
  22820. this.boundingBox.getCenter(_offset$1).negate();
  22821. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  22822. return this;
  22823. },
  22824. normalize: function normalize() {
  22825. this.computeBoundingSphere();
  22826. var center = this.boundingSphere.center;
  22827. var radius = this.boundingSphere.radius;
  22828. var s = radius === 0 ? 1 : 1.0 / radius;
  22829. var matrix = new Matrix4();
  22830. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  22831. this.applyMatrix4(matrix);
  22832. return this;
  22833. },
  22834. computeFaceNormals: function computeFaceNormals() {
  22835. var cb = new Vector3(),
  22836. ab = new Vector3();
  22837. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  22838. var face = this.faces[f];
  22839. var vA = this.vertices[face.a];
  22840. var vB = this.vertices[face.b];
  22841. var vC = this.vertices[face.c];
  22842. cb.subVectors(vC, vB);
  22843. ab.subVectors(vA, vB);
  22844. cb.cross(ab);
  22845. cb.normalize();
  22846. face.normal.copy(cb);
  22847. }
  22848. },
  22849. computeVertexNormals: function computeVertexNormals(areaWeighted) {
  22850. if (areaWeighted === void 0) {
  22851. areaWeighted = true;
  22852. }
  22853. var vertices = new Array(this.vertices.length);
  22854. for (var v = 0, vl = this.vertices.length; v < vl; v++) {
  22855. vertices[v] = new Vector3();
  22856. }
  22857. if (areaWeighted) {
  22858. // vertex normals weighted by triangle areas
  22859. // http://www.iquilezles.org/www/articles/normals/normals.htm
  22860. var cb = new Vector3(),
  22861. ab = new Vector3();
  22862. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  22863. var face = this.faces[f];
  22864. var vA = this.vertices[face.a];
  22865. var vB = this.vertices[face.b];
  22866. var vC = this.vertices[face.c];
  22867. cb.subVectors(vC, vB);
  22868. ab.subVectors(vA, vB);
  22869. cb.cross(ab);
  22870. vertices[face.a].add(cb);
  22871. vertices[face.b].add(cb);
  22872. vertices[face.c].add(cb);
  22873. }
  22874. } else {
  22875. this.computeFaceNormals();
  22876. for (var _f = 0, _fl = this.faces.length; _f < _fl; _f++) {
  22877. var _face = this.faces[_f];
  22878. vertices[_face.a].add(_face.normal);
  22879. vertices[_face.b].add(_face.normal);
  22880. vertices[_face.c].add(_face.normal);
  22881. }
  22882. }
  22883. for (var _v = 0, _vl = this.vertices.length; _v < _vl; _v++) {
  22884. vertices[_v].normalize();
  22885. }
  22886. for (var _f2 = 0, _fl2 = this.faces.length; _f2 < _fl2; _f2++) {
  22887. var _face2 = this.faces[_f2];
  22888. var vertexNormals = _face2.vertexNormals;
  22889. if (vertexNormals.length === 3) {
  22890. vertexNormals[0].copy(vertices[_face2.a]);
  22891. vertexNormals[1].copy(vertices[_face2.b]);
  22892. vertexNormals[2].copy(vertices[_face2.c]);
  22893. } else {
  22894. vertexNormals[0] = vertices[_face2.a].clone();
  22895. vertexNormals[1] = vertices[_face2.b].clone();
  22896. vertexNormals[2] = vertices[_face2.c].clone();
  22897. }
  22898. }
  22899. if (this.faces.length > 0) {
  22900. this.normalsNeedUpdate = true;
  22901. }
  22902. },
  22903. computeFlatVertexNormals: function computeFlatVertexNormals() {
  22904. this.computeFaceNormals();
  22905. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  22906. var face = this.faces[f];
  22907. var vertexNormals = face.vertexNormals;
  22908. if (vertexNormals.length === 3) {
  22909. vertexNormals[0].copy(face.normal);
  22910. vertexNormals[1].copy(face.normal);
  22911. vertexNormals[2].copy(face.normal);
  22912. } else {
  22913. vertexNormals[0] = face.normal.clone();
  22914. vertexNormals[1] = face.normal.clone();
  22915. vertexNormals[2] = face.normal.clone();
  22916. }
  22917. }
  22918. if (this.faces.length > 0) {
  22919. this.normalsNeedUpdate = true;
  22920. }
  22921. },
  22922. computeMorphNormals: function computeMorphNormals() {
  22923. // save original normals
  22924. // - create temp variables on first access
  22925. // otherwise just copy (for faster repeated calls)
  22926. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  22927. var face = this.faces[f];
  22928. if (!face.__originalFaceNormal) {
  22929. face.__originalFaceNormal = face.normal.clone();
  22930. } else {
  22931. face.__originalFaceNormal.copy(face.normal);
  22932. }
  22933. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  22934. for (var i = 0, il = face.vertexNormals.length; i < il; i++) {
  22935. if (!face.__originalVertexNormals[i]) {
  22936. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  22937. } else {
  22938. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  22939. }
  22940. }
  22941. } // use temp geometry to compute face and vertex normals for each morph
  22942. var tmpGeo = new Geometry();
  22943. tmpGeo.faces = this.faces;
  22944. for (var _i5 = 0, _il2 = this.morphTargets.length; _i5 < _il2; _i5++) {
  22945. // create on first access
  22946. if (!this.morphNormals[_i5]) {
  22947. this.morphNormals[_i5] = {};
  22948. this.morphNormals[_i5].faceNormals = [];
  22949. this.morphNormals[_i5].vertexNormals = [];
  22950. var dstNormalsFace = this.morphNormals[_i5].faceNormals;
  22951. var dstNormalsVertex = this.morphNormals[_i5].vertexNormals;
  22952. for (var _f3 = 0, _fl3 = this.faces.length; _f3 < _fl3; _f3++) {
  22953. var faceNormal = new Vector3();
  22954. var vertexNormals = {
  22955. a: new Vector3(),
  22956. b: new Vector3(),
  22957. c: new Vector3()
  22958. };
  22959. dstNormalsFace.push(faceNormal);
  22960. dstNormalsVertex.push(vertexNormals);
  22961. }
  22962. }
  22963. var morphNormals = this.morphNormals[_i5]; // set vertices to morph target
  22964. tmpGeo.vertices = this.morphTargets[_i5].vertices; // compute morph normals
  22965. tmpGeo.computeFaceNormals();
  22966. tmpGeo.computeVertexNormals(); // store morph normals
  22967. for (var _f4 = 0, _fl4 = this.faces.length; _f4 < _fl4; _f4++) {
  22968. var _face3 = this.faces[_f4];
  22969. var _faceNormal = morphNormals.faceNormals[_f4];
  22970. var _vertexNormals = morphNormals.vertexNormals[_f4];
  22971. _faceNormal.copy(_face3.normal);
  22972. _vertexNormals.a.copy(_face3.vertexNormals[0]);
  22973. _vertexNormals.b.copy(_face3.vertexNormals[1]);
  22974. _vertexNormals.c.copy(_face3.vertexNormals[2]);
  22975. }
  22976. } // restore original normals
  22977. for (var _f5 = 0, _fl5 = this.faces.length; _f5 < _fl5; _f5++) {
  22978. var _face4 = this.faces[_f5];
  22979. _face4.normal = _face4.__originalFaceNormal;
  22980. _face4.vertexNormals = _face4.__originalVertexNormals;
  22981. }
  22982. },
  22983. computeBoundingBox: function computeBoundingBox() {
  22984. if (this.boundingBox === null) {
  22985. this.boundingBox = new Box3();
  22986. }
  22987. this.boundingBox.setFromPoints(this.vertices);
  22988. },
  22989. computeBoundingSphere: function computeBoundingSphere() {
  22990. if (this.boundingSphere === null) {
  22991. this.boundingSphere = new Sphere();
  22992. }
  22993. this.boundingSphere.setFromPoints(this.vertices);
  22994. },
  22995. merge: function merge(geometry, matrix, materialIndexOffset) {
  22996. if (materialIndexOffset === void 0) {
  22997. materialIndexOffset = 0;
  22998. }
  22999. if (!(geometry && geometry.isGeometry)) {
  23000. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  23001. return;
  23002. }
  23003. var normalMatrix;
  23004. var vertexOffset = this.vertices.length,
  23005. vertices1 = this.vertices,
  23006. vertices2 = geometry.vertices,
  23007. faces1 = this.faces,
  23008. faces2 = geometry.faces,
  23009. colors1 = this.colors,
  23010. colors2 = geometry.colors;
  23011. if (matrix !== undefined) {
  23012. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  23013. } // vertices
  23014. for (var i = 0, il = vertices2.length; i < il; i++) {
  23015. var vertex = vertices2[i];
  23016. var vertexCopy = vertex.clone();
  23017. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  23018. vertices1.push(vertexCopy);
  23019. } // colors
  23020. for (var _i6 = 0, _il3 = colors2.length; _i6 < _il3; _i6++) {
  23021. colors1.push(colors2[_i6].clone());
  23022. } // faces
  23023. for (var _i7 = 0, _il4 = faces2.length; _i7 < _il4; _i7++) {
  23024. var face = faces2[_i7];
  23025. var normal = void 0,
  23026. color = void 0;
  23027. var faceVertexNormals = face.vertexNormals,
  23028. faceVertexColors = face.vertexColors;
  23029. var faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  23030. faceCopy.normal.copy(face.normal);
  23031. if (normalMatrix !== undefined) {
  23032. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  23033. }
  23034. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  23035. normal = faceVertexNormals[j].clone();
  23036. if (normalMatrix !== undefined) {
  23037. normal.applyMatrix3(normalMatrix).normalize();
  23038. }
  23039. faceCopy.vertexNormals.push(normal);
  23040. }
  23041. faceCopy.color.copy(face.color);
  23042. for (var _j = 0, _jl = faceVertexColors.length; _j < _jl; _j++) {
  23043. color = faceVertexColors[_j];
  23044. faceCopy.vertexColors.push(color.clone());
  23045. }
  23046. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  23047. faces1.push(faceCopy);
  23048. } // uvs
  23049. for (var _i8 = 0, _il5 = geometry.faceVertexUvs.length; _i8 < _il5; _i8++) {
  23050. var faceVertexUvs2 = geometry.faceVertexUvs[_i8];
  23051. if (this.faceVertexUvs[_i8] === undefined) this.faceVertexUvs[_i8] = [];
  23052. for (var _j2 = 0, _jl2 = faceVertexUvs2.length; _j2 < _jl2; _j2++) {
  23053. var uvs2 = faceVertexUvs2[_j2],
  23054. uvsCopy = [];
  23055. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  23056. uvsCopy.push(uvs2[k].clone());
  23057. }
  23058. this.faceVertexUvs[_i8].push(uvsCopy);
  23059. }
  23060. }
  23061. },
  23062. mergeMesh: function mergeMesh(mesh) {
  23063. if (!(mesh && mesh.isMesh)) {
  23064. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  23065. return;
  23066. }
  23067. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  23068. this.merge(mesh.geometry, mesh.matrix);
  23069. },
  23070. /*
  23071. * Checks for duplicate vertices with hashmap.
  23072. * Duplicated vertices are removed
  23073. * and faces' vertices are updated.
  23074. */
  23075. mergeVertices: function mergeVertices(precisionPoints) {
  23076. if (precisionPoints === void 0) {
  23077. precisionPoints = 4;
  23078. }
  23079. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  23080. var unique = [],
  23081. changes = [];
  23082. var precision = Math.pow(10, precisionPoints);
  23083. for (var i = 0, il = this.vertices.length; i < il; i++) {
  23084. var v = this.vertices[i];
  23085. var key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  23086. if (verticesMap[key] === undefined) {
  23087. verticesMap[key] = i;
  23088. unique.push(this.vertices[i]);
  23089. changes[i] = unique.length - 1;
  23090. } else {
  23091. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  23092. changes[i] = changes[verticesMap[key]];
  23093. }
  23094. } // if faces are completely degenerate after merging vertices, we
  23095. // have to remove them from the geometry.
  23096. var faceIndicesToRemove = [];
  23097. for (var _i9 = 0, _il6 = this.faces.length; _i9 < _il6; _i9++) {
  23098. var face = this.faces[_i9];
  23099. face.a = changes[face.a];
  23100. face.b = changes[face.b];
  23101. face.c = changes[face.c];
  23102. var indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  23103. // we have to remove the face as nothing can be saved
  23104. for (var n = 0; n < 3; n++) {
  23105. if (indices[n] === indices[(n + 1) % 3]) {
  23106. faceIndicesToRemove.push(_i9);
  23107. break;
  23108. }
  23109. }
  23110. }
  23111. for (var _i10 = faceIndicesToRemove.length - 1; _i10 >= 0; _i10--) {
  23112. var idx = faceIndicesToRemove[_i10];
  23113. this.faces.splice(idx, 1);
  23114. for (var j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  23115. this.faceVertexUvs[j].splice(idx, 1);
  23116. }
  23117. } // Use unique set of vertices
  23118. var diff = this.vertices.length - unique.length;
  23119. this.vertices = unique;
  23120. return diff;
  23121. },
  23122. setFromPoints: function setFromPoints(points) {
  23123. this.vertices = [];
  23124. for (var i = 0, l = points.length; i < l; i++) {
  23125. var point = points[i];
  23126. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  23127. }
  23128. return this;
  23129. },
  23130. sortFacesByMaterialIndex: function sortFacesByMaterialIndex() {
  23131. var faces = this.faces;
  23132. var length = faces.length; // tag faces
  23133. for (var i = 0; i < length; i++) {
  23134. faces[i]._id = i;
  23135. } // sort faces
  23136. function materialIndexSort(a, b) {
  23137. return a.materialIndex - b.materialIndex;
  23138. }
  23139. faces.sort(materialIndexSort); // sort uvs
  23140. var uvs1 = this.faceVertexUvs[0];
  23141. var uvs2 = this.faceVertexUvs[1];
  23142. var newUvs1, newUvs2;
  23143. if (uvs1 && uvs1.length === length) newUvs1 = [];
  23144. if (uvs2 && uvs2.length === length) newUvs2 = [];
  23145. for (var _i11 = 0; _i11 < length; _i11++) {
  23146. var id = faces[_i11]._id;
  23147. if (newUvs1) newUvs1.push(uvs1[id]);
  23148. if (newUvs2) newUvs2.push(uvs2[id]);
  23149. }
  23150. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  23151. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  23152. },
  23153. toJSON: function toJSON() {
  23154. var data = {
  23155. metadata: {
  23156. version: 4.5,
  23157. type: 'Geometry',
  23158. generator: 'Geometry.toJSON'
  23159. }
  23160. }; // standard Geometry serialization
  23161. data.uuid = this.uuid;
  23162. data.type = this.type;
  23163. if (this.name !== '') data.name = this.name;
  23164. if (this.parameters !== undefined) {
  23165. var parameters = this.parameters;
  23166. for (var key in parameters) {
  23167. if (parameters[key] !== undefined) data[key] = parameters[key];
  23168. }
  23169. return data;
  23170. }
  23171. var vertices = [];
  23172. for (var i = 0; i < this.vertices.length; i++) {
  23173. var vertex = this.vertices[i];
  23174. vertices.push(vertex.x, vertex.y, vertex.z);
  23175. }
  23176. var faces = [];
  23177. var normals = [];
  23178. var normalsHash = {};
  23179. var colors = [];
  23180. var colorsHash = {};
  23181. var uvs = [];
  23182. var uvsHash = {};
  23183. for (var _i12 = 0; _i12 < this.faces.length; _i12++) {
  23184. var face = this.faces[_i12];
  23185. var hasMaterial = true;
  23186. var hasFaceUv = false; // deprecated
  23187. var hasFaceVertexUv = this.faceVertexUvs[0][_i12] !== undefined;
  23188. var hasFaceNormal = face.normal.length() > 0;
  23189. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  23190. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  23191. var hasFaceVertexColor = face.vertexColors.length > 0;
  23192. var faceType = 0;
  23193. faceType = setBit(faceType, 0, 0); // isQuad
  23194. faceType = setBit(faceType, 1, hasMaterial);
  23195. faceType = setBit(faceType, 2, hasFaceUv);
  23196. faceType = setBit(faceType, 3, hasFaceVertexUv);
  23197. faceType = setBit(faceType, 4, hasFaceNormal);
  23198. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  23199. faceType = setBit(faceType, 6, hasFaceColor);
  23200. faceType = setBit(faceType, 7, hasFaceVertexColor);
  23201. faces.push(faceType);
  23202. faces.push(face.a, face.b, face.c);
  23203. faces.push(face.materialIndex);
  23204. if (hasFaceVertexUv) {
  23205. var faceVertexUvs = this.faceVertexUvs[0][_i12];
  23206. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  23207. }
  23208. if (hasFaceNormal) {
  23209. faces.push(getNormalIndex(face.normal));
  23210. }
  23211. if (hasFaceVertexNormal) {
  23212. var vertexNormals = face.vertexNormals;
  23213. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  23214. }
  23215. if (hasFaceColor) {
  23216. faces.push(getColorIndex(face.color));
  23217. }
  23218. if (hasFaceVertexColor) {
  23219. var vertexColors = face.vertexColors;
  23220. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  23221. }
  23222. }
  23223. function setBit(value, position, enabled) {
  23224. return enabled ? value | 1 << position : value & ~(1 << position);
  23225. }
  23226. function getNormalIndex(normal) {
  23227. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  23228. if (normalsHash[hash] !== undefined) {
  23229. return normalsHash[hash];
  23230. }
  23231. normalsHash[hash] = normals.length / 3;
  23232. normals.push(normal.x, normal.y, normal.z);
  23233. return normalsHash[hash];
  23234. }
  23235. function getColorIndex(color) {
  23236. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  23237. if (colorsHash[hash] !== undefined) {
  23238. return colorsHash[hash];
  23239. }
  23240. colorsHash[hash] = colors.length;
  23241. colors.push(color.getHex());
  23242. return colorsHash[hash];
  23243. }
  23244. function getUvIndex(uv) {
  23245. var hash = uv.x.toString() + uv.y.toString();
  23246. if (uvsHash[hash] !== undefined) {
  23247. return uvsHash[hash];
  23248. }
  23249. uvsHash[hash] = uvs.length / 2;
  23250. uvs.push(uv.x, uv.y);
  23251. return uvsHash[hash];
  23252. }
  23253. data.data = {};
  23254. data.data.vertices = vertices;
  23255. data.data.normals = normals;
  23256. if (colors.length > 0) data.data.colors = colors;
  23257. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  23258. data.data.faces = faces;
  23259. return data;
  23260. },
  23261. clone: function clone() {
  23262. /*
  23263. // Handle primitives
  23264. const parameters = this.parameters;
  23265. if ( parameters !== undefined ) {
  23266. const values = [];
  23267. for ( const key in parameters ) {
  23268. values.push( parameters[ key ] );
  23269. }
  23270. const geometry = Object.create( this.constructor.prototype );
  23271. this.constructor.apply( geometry, values );
  23272. return geometry;
  23273. }
  23274. return new this.constructor().copy( this );
  23275. */
  23276. return new Geometry().copy(this);
  23277. },
  23278. copy: function copy(source) {
  23279. // reset
  23280. this.vertices = [];
  23281. this.colors = [];
  23282. this.faces = [];
  23283. this.faceVertexUvs = [[]];
  23284. this.morphTargets = [];
  23285. this.morphNormals = [];
  23286. this.skinWeights = [];
  23287. this.skinIndices = [];
  23288. this.lineDistances = [];
  23289. this.boundingBox = null;
  23290. this.boundingSphere = null; // name
  23291. this.name = source.name; // vertices
  23292. var vertices = source.vertices;
  23293. for (var i = 0, il = vertices.length; i < il; i++) {
  23294. this.vertices.push(vertices[i].clone());
  23295. } // colors
  23296. var colors = source.colors;
  23297. for (var _i13 = 0, _il7 = colors.length; _i13 < _il7; _i13++) {
  23298. this.colors.push(colors[_i13].clone());
  23299. } // faces
  23300. var faces = source.faces;
  23301. for (var _i14 = 0, _il8 = faces.length; _i14 < _il8; _i14++) {
  23302. this.faces.push(faces[_i14].clone());
  23303. } // face vertex uvs
  23304. for (var _i15 = 0, _il9 = source.faceVertexUvs.length; _i15 < _il9; _i15++) {
  23305. var faceVertexUvs = source.faceVertexUvs[_i15];
  23306. if (this.faceVertexUvs[_i15] === undefined) {
  23307. this.faceVertexUvs[_i15] = [];
  23308. }
  23309. for (var j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  23310. var uvs = faceVertexUvs[j],
  23311. uvsCopy = [];
  23312. for (var k = 0, kl = uvs.length; k < kl; k++) {
  23313. var uv = uvs[k];
  23314. uvsCopy.push(uv.clone());
  23315. }
  23316. this.faceVertexUvs[_i15].push(uvsCopy);
  23317. }
  23318. } // morph targets
  23319. var morphTargets = source.morphTargets;
  23320. for (var _i16 = 0, _il10 = morphTargets.length; _i16 < _il10; _i16++) {
  23321. var morphTarget = {};
  23322. morphTarget.name = morphTargets[_i16].name; // vertices
  23323. if (morphTargets[_i16].vertices !== undefined) {
  23324. morphTarget.vertices = [];
  23325. for (var _j3 = 0, _jl3 = morphTargets[_i16].vertices.length; _j3 < _jl3; _j3++) {
  23326. morphTarget.vertices.push(morphTargets[_i16].vertices[_j3].clone());
  23327. }
  23328. } // normals
  23329. if (morphTargets[_i16].normals !== undefined) {
  23330. morphTarget.normals = [];
  23331. for (var _j4 = 0, _jl4 = morphTargets[_i16].normals.length; _j4 < _jl4; _j4++) {
  23332. morphTarget.normals.push(morphTargets[_i16].normals[_j4].clone());
  23333. }
  23334. }
  23335. this.morphTargets.push(morphTarget);
  23336. } // morph normals
  23337. var morphNormals = source.morphNormals;
  23338. for (var _i17 = 0, _il11 = morphNormals.length; _i17 < _il11; _i17++) {
  23339. var morphNormal = {}; // vertex normals
  23340. if (morphNormals[_i17].vertexNormals !== undefined) {
  23341. morphNormal.vertexNormals = [];
  23342. for (var _j5 = 0, _jl5 = morphNormals[_i17].vertexNormals.length; _j5 < _jl5; _j5++) {
  23343. var srcVertexNormal = morphNormals[_i17].vertexNormals[_j5];
  23344. var destVertexNormal = {};
  23345. destVertexNormal.a = srcVertexNormal.a.clone();
  23346. destVertexNormal.b = srcVertexNormal.b.clone();
  23347. destVertexNormal.c = srcVertexNormal.c.clone();
  23348. morphNormal.vertexNormals.push(destVertexNormal);
  23349. }
  23350. } // face normals
  23351. if (morphNormals[_i17].faceNormals !== undefined) {
  23352. morphNormal.faceNormals = [];
  23353. for (var _j6 = 0, _jl6 = morphNormals[_i17].faceNormals.length; _j6 < _jl6; _j6++) {
  23354. morphNormal.faceNormals.push(morphNormals[_i17].faceNormals[_j6].clone());
  23355. }
  23356. }
  23357. this.morphNormals.push(morphNormal);
  23358. } // skin weights
  23359. var skinWeights = source.skinWeights;
  23360. for (var _i18 = 0, _il12 = skinWeights.length; _i18 < _il12; _i18++) {
  23361. this.skinWeights.push(skinWeights[_i18].clone());
  23362. } // skin indices
  23363. var skinIndices = source.skinIndices;
  23364. for (var _i19 = 0, _il13 = skinIndices.length; _i19 < _il13; _i19++) {
  23365. this.skinIndices.push(skinIndices[_i19].clone());
  23366. } // line distances
  23367. var lineDistances = source.lineDistances;
  23368. for (var _i20 = 0, _il14 = lineDistances.length; _i20 < _il14; _i20++) {
  23369. this.lineDistances.push(lineDistances[_i20]);
  23370. } // bounding box
  23371. var boundingBox = source.boundingBox;
  23372. if (boundingBox !== null) {
  23373. this.boundingBox = boundingBox.clone();
  23374. } // bounding sphere
  23375. var boundingSphere = source.boundingSphere;
  23376. if (boundingSphere !== null) {
  23377. this.boundingSphere = boundingSphere.clone();
  23378. } // update flags
  23379. this.elementsNeedUpdate = source.elementsNeedUpdate;
  23380. this.verticesNeedUpdate = source.verticesNeedUpdate;
  23381. this.uvsNeedUpdate = source.uvsNeedUpdate;
  23382. this.normalsNeedUpdate = source.normalsNeedUpdate;
  23383. this.colorsNeedUpdate = source.colorsNeedUpdate;
  23384. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  23385. this.groupsNeedUpdate = source.groupsNeedUpdate;
  23386. return this;
  23387. },
  23388. dispose: function dispose() {
  23389. this.dispatchEvent({
  23390. type: 'dispose'
  23391. });
  23392. }
  23393. });
  23394. var BoxGeometry = /*#__PURE__*/function (_Geometry) {
  23395. _inheritsLoose(BoxGeometry, _Geometry);
  23396. function BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
  23397. var _this;
  23398. _this = _Geometry.call(this) || this;
  23399. _this.type = 'BoxGeometry';
  23400. _this.parameters = {
  23401. width: width,
  23402. height: height,
  23403. depth: depth,
  23404. widthSegments: widthSegments,
  23405. heightSegments: heightSegments,
  23406. depthSegments: depthSegments
  23407. };
  23408. _this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  23409. _this.mergeVertices();
  23410. return _this;
  23411. }
  23412. return BoxGeometry;
  23413. }(Geometry);
  23414. var CircleBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23415. _inheritsLoose(CircleBufferGeometry, _BufferGeometry);
  23416. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  23417. var _this;
  23418. if (radius === void 0) {
  23419. radius = 1;
  23420. }
  23421. if (segments === void 0) {
  23422. segments = 8;
  23423. }
  23424. if (thetaStart === void 0) {
  23425. thetaStart = 0;
  23426. }
  23427. if (thetaLength === void 0) {
  23428. thetaLength = Math.PI * 2;
  23429. }
  23430. _this = _BufferGeometry.call(this) || this;
  23431. _this.type = 'CircleBufferGeometry';
  23432. _this.parameters = {
  23433. radius: radius,
  23434. segments: segments,
  23435. thetaStart: thetaStart,
  23436. thetaLength: thetaLength
  23437. };
  23438. segments = Math.max(3, segments); // buffers
  23439. var indices = [];
  23440. var vertices = [];
  23441. var normals = [];
  23442. var uvs = []; // helper variables
  23443. var vertex = new Vector3();
  23444. var uv = new Vector2(); // center point
  23445. vertices.push(0, 0, 0);
  23446. normals.push(0, 0, 1);
  23447. uvs.push(0.5, 0.5);
  23448. for (var s = 0, i = 3; s <= segments; s++, i += 3) {
  23449. var segment = thetaStart + s / segments * thetaLength; // vertex
  23450. vertex.x = radius * Math.cos(segment);
  23451. vertex.y = radius * Math.sin(segment);
  23452. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23453. normals.push(0, 0, 1); // uvs
  23454. uv.x = (vertices[i] / radius + 1) / 2;
  23455. uv.y = (vertices[i + 1] / radius + 1) / 2;
  23456. uvs.push(uv.x, uv.y);
  23457. } // indices
  23458. for (var _i = 1; _i <= segments; _i++) {
  23459. indices.push(_i, _i + 1, 0);
  23460. } // build geometry
  23461. _this.setIndex(indices);
  23462. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23463. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23464. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23465. return _this;
  23466. }
  23467. return CircleBufferGeometry;
  23468. }(BufferGeometry);
  23469. var CircleGeometry = /*#__PURE__*/function (_Geometry) {
  23470. _inheritsLoose(CircleGeometry, _Geometry);
  23471. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  23472. var _this;
  23473. _this = _Geometry.call(this) || this;
  23474. _this.type = 'CircleGeometry';
  23475. _this.parameters = {
  23476. radius: radius,
  23477. segments: segments,
  23478. thetaStart: thetaStart,
  23479. thetaLength: thetaLength
  23480. };
  23481. _this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  23482. _this.mergeVertices();
  23483. return _this;
  23484. }
  23485. return CircleGeometry;
  23486. }(Geometry);
  23487. var CylinderBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23488. _inheritsLoose(CylinderBufferGeometry, _BufferGeometry);
  23489. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23490. var _this;
  23491. if (radiusTop === void 0) {
  23492. radiusTop = 1;
  23493. }
  23494. if (radiusBottom === void 0) {
  23495. radiusBottom = 1;
  23496. }
  23497. if (height === void 0) {
  23498. height = 1;
  23499. }
  23500. if (radialSegments === void 0) {
  23501. radialSegments = 8;
  23502. }
  23503. if (heightSegments === void 0) {
  23504. heightSegments = 1;
  23505. }
  23506. if (openEnded === void 0) {
  23507. openEnded = false;
  23508. }
  23509. if (thetaStart === void 0) {
  23510. thetaStart = 0;
  23511. }
  23512. if (thetaLength === void 0) {
  23513. thetaLength = Math.PI * 2;
  23514. }
  23515. _this = _BufferGeometry.call(this) || this;
  23516. _this.type = 'CylinderBufferGeometry';
  23517. _this.parameters = {
  23518. radiusTop: radiusTop,
  23519. radiusBottom: radiusBottom,
  23520. height: height,
  23521. radialSegments: radialSegments,
  23522. heightSegments: heightSegments,
  23523. openEnded: openEnded,
  23524. thetaStart: thetaStart,
  23525. thetaLength: thetaLength
  23526. };
  23527. var scope = _assertThisInitialized(_this);
  23528. radialSegments = Math.floor(radialSegments);
  23529. heightSegments = Math.floor(heightSegments); // buffers
  23530. var indices = [];
  23531. var vertices = [];
  23532. var normals = [];
  23533. var uvs = []; // helper variables
  23534. var index = 0;
  23535. var indexArray = [];
  23536. var halfHeight = height / 2;
  23537. var groupStart = 0; // generate geometry
  23538. generateTorso();
  23539. if (openEnded === false) {
  23540. if (radiusTop > 0) generateCap(true);
  23541. if (radiusBottom > 0) generateCap(false);
  23542. } // build geometry
  23543. _this.setIndex(indices);
  23544. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23545. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23546. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23547. function generateTorso() {
  23548. var normal = new Vector3();
  23549. var vertex = new Vector3();
  23550. var groupCount = 0; // this will be used to calculate the normal
  23551. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  23552. for (var y = 0; y <= heightSegments; y++) {
  23553. var indexRow = [];
  23554. var v = y / heightSegments; // calculate the radius of the current row
  23555. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  23556. for (var x = 0; x <= radialSegments; x++) {
  23557. var u = x / radialSegments;
  23558. var theta = u * thetaLength + thetaStart;
  23559. var sinTheta = Math.sin(theta);
  23560. var cosTheta = Math.cos(theta); // vertex
  23561. vertex.x = radius * sinTheta;
  23562. vertex.y = -v * height + halfHeight;
  23563. vertex.z = radius * cosTheta;
  23564. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23565. normal.set(sinTheta, slope, cosTheta).normalize();
  23566. normals.push(normal.x, normal.y, normal.z); // uv
  23567. uvs.push(u, 1 - v); // save index of vertex in respective row
  23568. indexRow.push(index++);
  23569. } // now save vertices of the row in our index array
  23570. indexArray.push(indexRow);
  23571. } // generate indices
  23572. for (var _x = 0; _x < radialSegments; _x++) {
  23573. for (var _y = 0; _y < heightSegments; _y++) {
  23574. // we use the index array to access the correct indices
  23575. var a = indexArray[_y][_x];
  23576. var b = indexArray[_y + 1][_x];
  23577. var c = indexArray[_y + 1][_x + 1];
  23578. var d = indexArray[_y][_x + 1]; // faces
  23579. indices.push(a, b, d);
  23580. indices.push(b, c, d); // update group counter
  23581. groupCount += 6;
  23582. }
  23583. } // add a group to the geometry. this will ensure multi material support
  23584. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  23585. groupStart += groupCount;
  23586. }
  23587. function generateCap(top) {
  23588. // save the index of the first center vertex
  23589. var centerIndexStart = index;
  23590. var uv = new Vector2();
  23591. var vertex = new Vector3();
  23592. var groupCount = 0;
  23593. var radius = top === true ? radiusTop : radiusBottom;
  23594. var sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  23595. // because the geometry needs one set of uvs per face,
  23596. // we must generate a center vertex per face/segment
  23597. for (var x = 1; x <= radialSegments; x++) {
  23598. // vertex
  23599. vertices.push(0, halfHeight * sign, 0); // normal
  23600. normals.push(0, sign, 0); // uv
  23601. uvs.push(0.5, 0.5); // increase index
  23602. index++;
  23603. } // save the index of the last center vertex
  23604. var centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  23605. for (var _x2 = 0; _x2 <= radialSegments; _x2++) {
  23606. var u = _x2 / radialSegments;
  23607. var theta = u * thetaLength + thetaStart;
  23608. var cosTheta = Math.cos(theta);
  23609. var sinTheta = Math.sin(theta); // vertex
  23610. vertex.x = radius * sinTheta;
  23611. vertex.y = halfHeight * sign;
  23612. vertex.z = radius * cosTheta;
  23613. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23614. normals.push(0, sign, 0); // uv
  23615. uv.x = cosTheta * 0.5 + 0.5;
  23616. uv.y = sinTheta * 0.5 * sign + 0.5;
  23617. uvs.push(uv.x, uv.y); // increase index
  23618. index++;
  23619. } // generate indices
  23620. for (var _x3 = 0; _x3 < radialSegments; _x3++) {
  23621. var c = centerIndexStart + _x3;
  23622. var i = centerIndexEnd + _x3;
  23623. if (top === true) {
  23624. // face top
  23625. indices.push(i, i + 1, c);
  23626. } else {
  23627. // face bottom
  23628. indices.push(i + 1, i, c);
  23629. }
  23630. groupCount += 3;
  23631. } // add a group to the geometry. this will ensure multi material support
  23632. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  23633. groupStart += groupCount;
  23634. }
  23635. return _this;
  23636. }
  23637. return CylinderBufferGeometry;
  23638. }(BufferGeometry);
  23639. var CylinderGeometry = /*#__PURE__*/function (_Geometry) {
  23640. _inheritsLoose(CylinderGeometry, _Geometry);
  23641. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23642. var _this;
  23643. _this = _Geometry.call(this) || this;
  23644. _this.type = 'CylinderGeometry';
  23645. _this.parameters = {
  23646. radiusTop: radiusTop,
  23647. radiusBottom: radiusBottom,
  23648. height: height,
  23649. radialSegments: radialSegments,
  23650. heightSegments: heightSegments,
  23651. openEnded: openEnded,
  23652. thetaStart: thetaStart,
  23653. thetaLength: thetaLength
  23654. };
  23655. _this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  23656. _this.mergeVertices();
  23657. return _this;
  23658. }
  23659. return CylinderGeometry;
  23660. }(Geometry);
  23661. var ConeGeometry = /*#__PURE__*/function (_CylinderGeometry) {
  23662. _inheritsLoose(ConeGeometry, _CylinderGeometry);
  23663. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23664. var _this;
  23665. _this = _CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
  23666. _this.type = 'ConeGeometry';
  23667. _this.parameters = {
  23668. radius: radius,
  23669. height: height,
  23670. radialSegments: radialSegments,
  23671. heightSegments: heightSegments,
  23672. openEnded: openEnded,
  23673. thetaStart: thetaStart,
  23674. thetaLength: thetaLength
  23675. };
  23676. return _this;
  23677. }
  23678. return ConeGeometry;
  23679. }(CylinderGeometry);
  23680. var ConeBufferGeometry = /*#__PURE__*/function (_CylinderBufferGeomet) {
  23681. _inheritsLoose(ConeBufferGeometry, _CylinderBufferGeomet);
  23682. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23683. var _this;
  23684. if (radius === void 0) {
  23685. radius = 1;
  23686. }
  23687. if (height === void 0) {
  23688. height = 1;
  23689. }
  23690. if (radialSegments === void 0) {
  23691. radialSegments = 8;
  23692. }
  23693. if (heightSegments === void 0) {
  23694. heightSegments = 1;
  23695. }
  23696. if (openEnded === void 0) {
  23697. openEnded = false;
  23698. }
  23699. if (thetaStart === void 0) {
  23700. thetaStart = 0;
  23701. }
  23702. if (thetaLength === void 0) {
  23703. thetaLength = Math.PI * 2;
  23704. }
  23705. _this = _CylinderBufferGeomet.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
  23706. _this.type = 'ConeBufferGeometry';
  23707. _this.parameters = {
  23708. radius: radius,
  23709. height: height,
  23710. radialSegments: radialSegments,
  23711. heightSegments: heightSegments,
  23712. openEnded: openEnded,
  23713. thetaStart: thetaStart,
  23714. thetaLength: thetaLength
  23715. };
  23716. return _this;
  23717. }
  23718. return ConeBufferGeometry;
  23719. }(CylinderBufferGeometry);
  23720. var PolyhedronBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23721. _inheritsLoose(PolyhedronBufferGeometry, _BufferGeometry);
  23722. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  23723. var _this;
  23724. if (radius === void 0) {
  23725. radius = 1;
  23726. }
  23727. if (detail === void 0) {
  23728. detail = 0;
  23729. }
  23730. _this = _BufferGeometry.call(this) || this;
  23731. _this.type = 'PolyhedronBufferGeometry';
  23732. _this.parameters = {
  23733. vertices: vertices,
  23734. indices: indices,
  23735. radius: radius,
  23736. detail: detail
  23737. }; // default buffer data
  23738. var vertexBuffer = [];
  23739. var uvBuffer = []; // the subdivision creates the vertex buffer data
  23740. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  23741. applyRadius(radius); // finally, create the uv data
  23742. generateUVs(); // build non-indexed geometry
  23743. _this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  23744. _this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  23745. _this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  23746. if (detail === 0) {
  23747. _this.computeVertexNormals(); // flat normals
  23748. } else {
  23749. _this.normalizeNormals(); // smooth normals
  23750. } // helper functions
  23751. function subdivide(detail) {
  23752. var a = new Vector3();
  23753. var b = new Vector3();
  23754. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  23755. for (var i = 0; i < indices.length; i += 3) {
  23756. // get the vertices of the face
  23757. getVertexByIndex(indices[i + 0], a);
  23758. getVertexByIndex(indices[i + 1], b);
  23759. getVertexByIndex(indices[i + 2], c); // perform subdivision
  23760. subdivideFace(a, b, c, detail);
  23761. }
  23762. }
  23763. function subdivideFace(a, b, c, detail) {
  23764. var cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  23765. var v = []; // construct all of the vertices for this subdivision
  23766. for (var i = 0; i <= cols; i++) {
  23767. v[i] = [];
  23768. var aj = a.clone().lerp(c, i / cols);
  23769. var bj = b.clone().lerp(c, i / cols);
  23770. var rows = cols - i;
  23771. for (var j = 0; j <= rows; j++) {
  23772. if (j === 0 && i === cols) {
  23773. v[i][j] = aj;
  23774. } else {
  23775. v[i][j] = aj.clone().lerp(bj, j / rows);
  23776. }
  23777. }
  23778. } // construct all of the faces
  23779. for (var _i = 0; _i < cols; _i++) {
  23780. for (var _j = 0; _j < 2 * (cols - _i) - 1; _j++) {
  23781. var k = Math.floor(_j / 2);
  23782. if (_j % 2 === 0) {
  23783. pushVertex(v[_i][k + 1]);
  23784. pushVertex(v[_i + 1][k]);
  23785. pushVertex(v[_i][k]);
  23786. } else {
  23787. pushVertex(v[_i][k + 1]);
  23788. pushVertex(v[_i + 1][k + 1]);
  23789. pushVertex(v[_i + 1][k]);
  23790. }
  23791. }
  23792. }
  23793. }
  23794. function applyRadius(radius) {
  23795. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  23796. for (var i = 0; i < vertexBuffer.length; i += 3) {
  23797. vertex.x = vertexBuffer[i + 0];
  23798. vertex.y = vertexBuffer[i + 1];
  23799. vertex.z = vertexBuffer[i + 2];
  23800. vertex.normalize().multiplyScalar(radius);
  23801. vertexBuffer[i + 0] = vertex.x;
  23802. vertexBuffer[i + 1] = vertex.y;
  23803. vertexBuffer[i + 2] = vertex.z;
  23804. }
  23805. }
  23806. function generateUVs() {
  23807. var vertex = new Vector3();
  23808. for (var i = 0; i < vertexBuffer.length; i += 3) {
  23809. vertex.x = vertexBuffer[i + 0];
  23810. vertex.y = vertexBuffer[i + 1];
  23811. vertex.z = vertexBuffer[i + 2];
  23812. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  23813. var v = inclination(vertex) / Math.PI + 0.5;
  23814. uvBuffer.push(u, 1 - v);
  23815. }
  23816. correctUVs();
  23817. correctSeam();
  23818. }
  23819. function correctSeam() {
  23820. // handle case when face straddles the seam, see #3269
  23821. for (var i = 0; i < uvBuffer.length; i += 6) {
  23822. // uv data of a single face
  23823. var x0 = uvBuffer[i + 0];
  23824. var x1 = uvBuffer[i + 2];
  23825. var x2 = uvBuffer[i + 4];
  23826. var max = Math.max(x0, x1, x2);
  23827. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  23828. if (max > 0.9 && min < 0.1) {
  23829. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  23830. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  23831. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  23832. }
  23833. }
  23834. }
  23835. function pushVertex(vertex) {
  23836. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  23837. }
  23838. function getVertexByIndex(index, vertex) {
  23839. var stride = index * 3;
  23840. vertex.x = vertices[stride + 0];
  23841. vertex.y = vertices[stride + 1];
  23842. vertex.z = vertices[stride + 2];
  23843. }
  23844. function correctUVs() {
  23845. var a = new Vector3();
  23846. var b = new Vector3();
  23847. var c = new Vector3();
  23848. var centroid = new Vector3();
  23849. var uvA = new Vector2();
  23850. var uvB = new Vector2();
  23851. var uvC = new Vector2();
  23852. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  23853. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  23854. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  23855. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  23856. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  23857. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  23858. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  23859. centroid.copy(a).add(b).add(c).divideScalar(3);
  23860. var azi = azimuth(centroid);
  23861. correctUV(uvA, j + 0, a, azi);
  23862. correctUV(uvB, j + 2, b, azi);
  23863. correctUV(uvC, j + 4, c, azi);
  23864. }
  23865. }
  23866. function correctUV(uv, stride, vector, azimuth) {
  23867. if (azimuth < 0 && uv.x === 1) {
  23868. uvBuffer[stride] = uv.x - 1;
  23869. }
  23870. if (vector.x === 0 && vector.z === 0) {
  23871. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  23872. }
  23873. } // Angle around the Y axis, counter-clockwise when looking from above.
  23874. function azimuth(vector) {
  23875. return Math.atan2(vector.z, -vector.x);
  23876. } // Angle above the XZ plane.
  23877. function inclination(vector) {
  23878. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  23879. }
  23880. return _this;
  23881. }
  23882. return PolyhedronBufferGeometry;
  23883. }(BufferGeometry);
  23884. var DodecahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
  23885. _inheritsLoose(DodecahedronBufferGeometry, _PolyhedronBufferGeom);
  23886. function DodecahedronBufferGeometry(radius, detail) {
  23887. var _this;
  23888. if (radius === void 0) {
  23889. radius = 1;
  23890. }
  23891. if (detail === void 0) {
  23892. detail = 0;
  23893. }
  23894. var t = (1 + Math.sqrt(5)) / 2;
  23895. var r = 1 / t;
  23896. var vertices = [// (±1, ±1, ±1)
  23897. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  23898. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  23899. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  23900. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  23901. var indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  23902. _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
  23903. _this.type = 'DodecahedronBufferGeometry';
  23904. _this.parameters = {
  23905. radius: radius,
  23906. detail: detail
  23907. };
  23908. return _this;
  23909. }
  23910. return DodecahedronBufferGeometry;
  23911. }(PolyhedronBufferGeometry);
  23912. var DodecahedronGeometry = /*#__PURE__*/function (_Geometry) {
  23913. _inheritsLoose(DodecahedronGeometry, _Geometry);
  23914. function DodecahedronGeometry(radius, detail) {
  23915. var _this;
  23916. _this = _Geometry.call(this) || this;
  23917. _this.type = 'DodecahedronGeometry';
  23918. _this.parameters = {
  23919. radius: radius,
  23920. detail: detail
  23921. };
  23922. _this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  23923. _this.mergeVertices();
  23924. return _this;
  23925. }
  23926. return DodecahedronGeometry;
  23927. }(Geometry);
  23928. var _v0$2 = new Vector3();
  23929. var _v1$5 = new Vector3();
  23930. var _normal$1 = new Vector3();
  23931. var _triangle = new Triangle();
  23932. var EdgesGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23933. _inheritsLoose(EdgesGeometry, _BufferGeometry);
  23934. function EdgesGeometry(geometry, thresholdAngle) {
  23935. var _this;
  23936. _this = _BufferGeometry.call(this) || this;
  23937. _this.type = 'EdgesGeometry';
  23938. _this.parameters = {
  23939. thresholdAngle: thresholdAngle
  23940. };
  23941. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  23942. if (geometry.isGeometry) {
  23943. geometry = new BufferGeometry().fromGeometry(geometry);
  23944. }
  23945. var precisionPoints = 4;
  23946. var precision = Math.pow(10, precisionPoints);
  23947. var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  23948. var indexAttr = geometry.getIndex();
  23949. var positionAttr = geometry.getAttribute('position');
  23950. var indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23951. var indexArr = [0, 0, 0];
  23952. var vertKeys = ['a', 'b', 'c'];
  23953. var hashes = new Array(3);
  23954. var edgeData = {};
  23955. var vertices = [];
  23956. for (var i = 0; i < indexCount; i += 3) {
  23957. if (indexAttr) {
  23958. indexArr[0] = indexAttr.getX(i);
  23959. indexArr[1] = indexAttr.getX(i + 1);
  23960. indexArr[2] = indexAttr.getX(i + 2);
  23961. } else {
  23962. indexArr[0] = i;
  23963. indexArr[1] = i + 1;
  23964. indexArr[2] = i + 2;
  23965. }
  23966. var a = _triangle.a,
  23967. b = _triangle.b,
  23968. c = _triangle.c;
  23969. a.fromBufferAttribute(positionAttr, indexArr[0]);
  23970. b.fromBufferAttribute(positionAttr, indexArr[1]);
  23971. c.fromBufferAttribute(positionAttr, indexArr[2]);
  23972. _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
  23973. hashes[0] = Math.round(a.x * precision) + "," + Math.round(a.y * precision) + "," + Math.round(a.z * precision);
  23974. hashes[1] = Math.round(b.x * precision) + "," + Math.round(b.y * precision) + "," + Math.round(b.z * precision);
  23975. hashes[2] = Math.round(c.x * precision) + "," + Math.round(c.y * precision) + "," + Math.round(c.z * precision); // skip degenerate triangles
  23976. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  23977. continue;
  23978. } // iterate over every edge
  23979. for (var j = 0; j < 3; j++) {
  23980. // get the first and next vertex making up the edge
  23981. var jNext = (j + 1) % 3;
  23982. var vecHash0 = hashes[j];
  23983. var vecHash1 = hashes[jNext];
  23984. var v0 = _triangle[vertKeys[j]];
  23985. var v1 = _triangle[vertKeys[jNext]];
  23986. var hash = vecHash0 + "_" + vecHash1;
  23987. var reverseHash = vecHash1 + "_" + vecHash0;
  23988. if (reverseHash in edgeData && edgeData[reverseHash]) {
  23989. // if we found a sibling edge add it into the vertex array if
  23990. // it meets the angle threshold and delete the edge from the map.
  23991. if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  23992. vertices.push(v0.x, v0.y, v0.z);
  23993. vertices.push(v1.x, v1.y, v1.z);
  23994. }
  23995. edgeData[reverseHash] = null;
  23996. } else if (!(hash in edgeData)) {
  23997. // if we've already got an edge here then skip adding a new one
  23998. edgeData[hash] = {
  23999. index0: indexArr[j],
  24000. index1: indexArr[jNext],
  24001. normal: _normal$1.clone()
  24002. };
  24003. }
  24004. }
  24005. } // iterate over all remaining, unmatched edges and add them to the vertex array
  24006. for (var key in edgeData) {
  24007. if (edgeData[key]) {
  24008. var _edgeData$key = edgeData[key],
  24009. index0 = _edgeData$key.index0,
  24010. index1 = _edgeData$key.index1;
  24011. _v0$2.fromBufferAttribute(positionAttr, index0);
  24012. _v1$5.fromBufferAttribute(positionAttr, index1);
  24013. vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
  24014. vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
  24015. }
  24016. }
  24017. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24018. return _this;
  24019. }
  24020. return EdgesGeometry;
  24021. }(BufferGeometry);
  24022. /**
  24023. * Port from https://github.com/mapbox/earcut (v2.2.2)
  24024. */
  24025. var Earcut = {
  24026. triangulate: function triangulate(data, holeIndices, dim) {
  24027. dim = dim || 2;
  24028. var hasHoles = holeIndices && holeIndices.length;
  24029. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24030. var outerNode = linkedList(data, 0, outerLen, dim, true);
  24031. var triangles = [];
  24032. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24033. var minX, minY, maxX, maxY, x, y, invSize;
  24034. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24035. if (data.length > 80 * dim) {
  24036. minX = maxX = data[0];
  24037. minY = maxY = data[1];
  24038. for (var i = dim; i < outerLen; i += dim) {
  24039. x = data[i];
  24040. y = data[i + 1];
  24041. if (x < minX) minX = x;
  24042. if (y < minY) minY = y;
  24043. if (x > maxX) maxX = x;
  24044. if (y > maxY) maxY = y;
  24045. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24046. invSize = Math.max(maxX - minX, maxY - minY);
  24047. invSize = invSize !== 0 ? 1 / invSize : 0;
  24048. }
  24049. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  24050. return triangles;
  24051. }
  24052. }; // create a circular doubly linked list from polygon points in the specified winding order
  24053. function linkedList(data, start, end, dim, clockwise) {
  24054. var i, last;
  24055. if (clockwise === signedArea(data, start, end, dim) > 0) {
  24056. for (i = start; i < end; i += dim) {
  24057. last = insertNode(i, data[i], data[i + 1], last);
  24058. }
  24059. } else {
  24060. for (i = end - dim; i >= start; i -= dim) {
  24061. last = insertNode(i, data[i], data[i + 1], last);
  24062. }
  24063. }
  24064. if (last && equals(last, last.next)) {
  24065. removeNode(last);
  24066. last = last.next;
  24067. }
  24068. return last;
  24069. } // eliminate colinear or duplicate points
  24070. function filterPoints(start, end) {
  24071. if (!start) return start;
  24072. if (!end) end = start;
  24073. var p = start,
  24074. again;
  24075. do {
  24076. again = false;
  24077. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24078. removeNode(p);
  24079. p = end = p.prev;
  24080. if (p === p.next) break;
  24081. again = true;
  24082. } else {
  24083. p = p.next;
  24084. }
  24085. } while (again || p !== end);
  24086. return end;
  24087. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  24088. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24089. if (!ear) return; // interlink polygon nodes in z-order
  24090. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24091. var stop = ear,
  24092. prev,
  24093. next; // iterate through ears, slicing them one by one
  24094. while (ear.prev !== ear.next) {
  24095. prev = ear.prev;
  24096. next = ear.next;
  24097. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24098. // cut off the triangle
  24099. triangles.push(prev.i / dim);
  24100. triangles.push(ear.i / dim);
  24101. triangles.push(next.i / dim);
  24102. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  24103. ear = next.next;
  24104. stop = next.next;
  24105. continue;
  24106. }
  24107. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  24108. if (ear === stop) {
  24109. // try filtering points and slicing again
  24110. if (!pass) {
  24111. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  24112. } else if (pass === 1) {
  24113. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  24114. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  24115. } else if (pass === 2) {
  24116. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24117. }
  24118. break;
  24119. }
  24120. }
  24121. } // check whether a polygon node forms a valid ear with adjacent nodes
  24122. function isEar(ear) {
  24123. var a = ear.prev,
  24124. b = ear,
  24125. c = ear.next;
  24126. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24127. // now make sure we don't have other points inside the potential ear
  24128. var p = ear.next.next;
  24129. while (p !== ear.prev) {
  24130. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24131. p = p.next;
  24132. }
  24133. return true;
  24134. }
  24135. function isEarHashed(ear, minX, minY, invSize) {
  24136. var a = ear.prev,
  24137. b = ear,
  24138. c = ear.next;
  24139. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24140. // triangle bbox; min & max are calculated like this for speed
  24141. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  24142. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  24143. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  24144. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  24145. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  24146. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  24147. var p = ear.prevZ,
  24148. n = ear.nextZ; // look for points inside the triangle in both directions
  24149. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24150. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24151. p = p.prevZ;
  24152. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24153. n = n.nextZ;
  24154. } // look for remaining points in decreasing z-order
  24155. while (p && p.z >= minZ) {
  24156. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24157. p = p.prevZ;
  24158. } // look for remaining points in increasing z-order
  24159. while (n && n.z <= maxZ) {
  24160. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24161. n = n.nextZ;
  24162. }
  24163. return true;
  24164. } // go through all polygon nodes and cure small local self-intersections
  24165. function cureLocalIntersections(start, triangles, dim) {
  24166. var p = start;
  24167. do {
  24168. var a = p.prev,
  24169. b = p.next.next;
  24170. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24171. triangles.push(a.i / dim);
  24172. triangles.push(p.i / dim);
  24173. triangles.push(b.i / dim); // remove two nodes involved
  24174. removeNode(p);
  24175. removeNode(p.next);
  24176. p = start = b;
  24177. }
  24178. p = p.next;
  24179. } while (p !== start);
  24180. return filterPoints(p);
  24181. } // try splitting polygon into two and triangulate them independently
  24182. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  24183. // look for a valid diagonal that divides the polygon into two
  24184. var a = start;
  24185. do {
  24186. var b = a.next.next;
  24187. while (b !== a.prev) {
  24188. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24189. // split the polygon in two by the diagonal
  24190. var c = splitPolygon(a, b); // filter colinear points around the cuts
  24191. a = filterPoints(a, a.next);
  24192. c = filterPoints(c, c.next); // run earcut on each half
  24193. earcutLinked(a, triangles, dim, minX, minY, invSize);
  24194. earcutLinked(c, triangles, dim, minX, minY, invSize);
  24195. return;
  24196. }
  24197. b = b.next;
  24198. }
  24199. a = a.next;
  24200. } while (a !== start);
  24201. } // link every hole into the outer loop, producing a single-ring polygon without holes
  24202. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24203. var queue = [];
  24204. var i, len, start, end, list;
  24205. for (i = 0, len = holeIndices.length; i < len; i++) {
  24206. start = holeIndices[i] * dim;
  24207. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24208. list = linkedList(data, start, end, dim, false);
  24209. if (list === list.next) list.steiner = true;
  24210. queue.push(getLeftmost(list));
  24211. }
  24212. queue.sort(compareX); // process holes from left to right
  24213. for (i = 0; i < queue.length; i++) {
  24214. eliminateHole(queue[i], outerNode);
  24215. outerNode = filterPoints(outerNode, outerNode.next);
  24216. }
  24217. return outerNode;
  24218. }
  24219. function compareX(a, b) {
  24220. return a.x - b.x;
  24221. } // find a bridge between vertices that connects hole with an outer ring and and link it
  24222. function eliminateHole(hole, outerNode) {
  24223. outerNode = findHoleBridge(hole, outerNode);
  24224. if (outerNode) {
  24225. var b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  24226. filterPoints(outerNode, outerNode.next);
  24227. filterPoints(b, b.next);
  24228. }
  24229. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24230. function findHoleBridge(hole, outerNode) {
  24231. var p = outerNode;
  24232. var hx = hole.x;
  24233. var hy = hole.y;
  24234. var qx = -Infinity,
  24235. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  24236. // segment's endpoint with lesser x will be potential connection point
  24237. do {
  24238. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  24239. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24240. if (x <= hx && x > qx) {
  24241. qx = x;
  24242. if (x === hx) {
  24243. if (hy === p.y) return p;
  24244. if (hy === p.next.y) return p.next;
  24245. }
  24246. m = p.x < p.next.x ? p : p.next;
  24247. }
  24248. }
  24249. p = p.next;
  24250. } while (p !== outerNode);
  24251. if (!m) return null;
  24252. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  24253. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24254. // if there are no points found, we have a valid connection;
  24255. // otherwise choose the point of the minimum angle with the ray as connection point
  24256. var stop = m,
  24257. mx = m.x,
  24258. my = m.y;
  24259. var tanMin = Infinity,
  24260. tan;
  24261. p = m;
  24262. do {
  24263. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24264. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24265. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  24266. m = p;
  24267. tanMin = tan;
  24268. }
  24269. }
  24270. p = p.next;
  24271. } while (p !== stop);
  24272. return m;
  24273. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  24274. function sectorContainsSector(m, p) {
  24275. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  24276. } // interlink polygon nodes in z-order
  24277. function indexCurve(start, minX, minY, invSize) {
  24278. var p = start;
  24279. do {
  24280. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  24281. p.prevZ = p.prev;
  24282. p.nextZ = p.next;
  24283. p = p.next;
  24284. } while (p !== start);
  24285. p.prevZ.nextZ = null;
  24286. p.prevZ = null;
  24287. sortLinked(p);
  24288. } // Simon Tatham's linked list merge sort algorithm
  24289. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24290. function sortLinked(list) {
  24291. var i,
  24292. p,
  24293. q,
  24294. e,
  24295. tail,
  24296. numMerges,
  24297. pSize,
  24298. qSize,
  24299. inSize = 1;
  24300. do {
  24301. p = list;
  24302. list = null;
  24303. tail = null;
  24304. numMerges = 0;
  24305. while (p) {
  24306. numMerges++;
  24307. q = p;
  24308. pSize = 0;
  24309. for (i = 0; i < inSize; i++) {
  24310. pSize++;
  24311. q = q.nextZ;
  24312. if (!q) break;
  24313. }
  24314. qSize = inSize;
  24315. while (pSize > 0 || qSize > 0 && q) {
  24316. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  24317. e = p;
  24318. p = p.nextZ;
  24319. pSize--;
  24320. } else {
  24321. e = q;
  24322. q = q.nextZ;
  24323. qSize--;
  24324. }
  24325. if (tail) tail.nextZ = e;else list = e;
  24326. e.prevZ = tail;
  24327. tail = e;
  24328. }
  24329. p = q;
  24330. }
  24331. tail.nextZ = null;
  24332. inSize *= 2;
  24333. } while (numMerges > 1);
  24334. return list;
  24335. } // z-order of a point given coords and inverse of the longer side of data bbox
  24336. function zOrder(x, y, minX, minY, invSize) {
  24337. // coords are transformed into non-negative 15-bit integer range
  24338. x = 32767 * (x - minX) * invSize;
  24339. y = 32767 * (y - minY) * invSize;
  24340. x = (x | x << 8) & 0x00FF00FF;
  24341. x = (x | x << 4) & 0x0F0F0F0F;
  24342. x = (x | x << 2) & 0x33333333;
  24343. x = (x | x << 1) & 0x55555555;
  24344. y = (y | y << 8) & 0x00FF00FF;
  24345. y = (y | y << 4) & 0x0F0F0F0F;
  24346. y = (y | y << 2) & 0x33333333;
  24347. y = (y | y << 1) & 0x55555555;
  24348. return x | y << 1;
  24349. } // find the leftmost node of a polygon ring
  24350. function getLeftmost(start) {
  24351. var p = start,
  24352. leftmost = start;
  24353. do {
  24354. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  24355. p = p.next;
  24356. } while (p !== start);
  24357. return leftmost;
  24358. } // check if a point lies within a convex triangle
  24359. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  24360. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  24361. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  24362. function isValidDiagonal(a, b) {
  24363. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  24364. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  24365. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  24366. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  24367. } // signed area of a triangle
  24368. function area(p, q, r) {
  24369. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  24370. } // check if two points are equal
  24371. function equals(p1, p2) {
  24372. return p1.x === p2.x && p1.y === p2.y;
  24373. } // check if two segments intersect
  24374. function intersects(p1, q1, p2, q2) {
  24375. var o1 = sign(area(p1, q1, p2));
  24376. var o2 = sign(area(p1, q1, q2));
  24377. var o3 = sign(area(p2, q2, p1));
  24378. var o4 = sign(area(p2, q2, q1));
  24379. if (o1 !== o2 && o3 !== o4) return true; // general case
  24380. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  24381. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  24382. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  24383. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  24384. return false;
  24385. } // for collinear points p, q, r, check if point q lies on segment pr
  24386. function onSegment(p, q, r) {
  24387. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  24388. }
  24389. function sign(num) {
  24390. return num > 0 ? 1 : num < 0 ? -1 : 0;
  24391. } // check if a polygon diagonal intersects any polygon segments
  24392. function intersectsPolygon(a, b) {
  24393. var p = a;
  24394. do {
  24395. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  24396. p = p.next;
  24397. } while (p !== a);
  24398. return false;
  24399. } // check if a polygon diagonal is locally inside the polygon
  24400. function locallyInside(a, b) {
  24401. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24402. } // check if the middle point of a polygon diagonal is inside the polygon
  24403. function middleInside(a, b) {
  24404. var p = a,
  24405. inside = false;
  24406. var px = (a.x + b.x) / 2,
  24407. py = (a.y + b.y) / 2;
  24408. do {
  24409. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  24410. p = p.next;
  24411. } while (p !== a);
  24412. return inside;
  24413. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24414. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24415. function splitPolygon(a, b) {
  24416. var a2 = new Node(a.i, a.x, a.y),
  24417. b2 = new Node(b.i, b.x, b.y),
  24418. an = a.next,
  24419. bp = b.prev;
  24420. a.next = b;
  24421. b.prev = a;
  24422. a2.next = an;
  24423. an.prev = a2;
  24424. b2.next = a2;
  24425. a2.prev = b2;
  24426. bp.next = b2;
  24427. b2.prev = bp;
  24428. return b2;
  24429. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  24430. function insertNode(i, x, y, last) {
  24431. var p = new Node(i, x, y);
  24432. if (!last) {
  24433. p.prev = p;
  24434. p.next = p;
  24435. } else {
  24436. p.next = last.next;
  24437. p.prev = last;
  24438. last.next.prev = p;
  24439. last.next = p;
  24440. }
  24441. return p;
  24442. }
  24443. function removeNode(p) {
  24444. p.next.prev = p.prev;
  24445. p.prev.next = p.next;
  24446. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24447. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24448. }
  24449. function Node(i, x, y) {
  24450. // vertex index in coordinates array
  24451. this.i = i; // vertex coordinates
  24452. this.x = x;
  24453. this.y = y; // previous and next vertex nodes in a polygon ring
  24454. this.prev = null;
  24455. this.next = null; // z-order curve value
  24456. this.z = null; // previous and next nodes in z-order
  24457. this.prevZ = null;
  24458. this.nextZ = null; // indicates whether this is a steiner point
  24459. this.steiner = false;
  24460. }
  24461. function signedArea(data, start, end, dim) {
  24462. var sum = 0;
  24463. for (var i = start, j = end - dim; i < end; i += dim) {
  24464. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24465. j = i;
  24466. }
  24467. return sum;
  24468. }
  24469. var ShapeUtils = {
  24470. // calculate area of the contour polygon
  24471. area: function area(contour) {
  24472. var n = contour.length;
  24473. var a = 0.0;
  24474. for (var p = n - 1, q = 0; q < n; p = q++) {
  24475. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  24476. }
  24477. return a * 0.5;
  24478. },
  24479. isClockWise: function isClockWise(pts) {
  24480. return ShapeUtils.area(pts) < 0;
  24481. },
  24482. triangulateShape: function triangulateShape(contour, holes) {
  24483. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  24484. var holeIndices = []; // array of hole indices
  24485. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  24486. removeDupEndPts(contour);
  24487. addContour(vertices, contour); //
  24488. var holeIndex = contour.length;
  24489. holes.forEach(removeDupEndPts);
  24490. for (var i = 0; i < holes.length; i++) {
  24491. holeIndices.push(holeIndex);
  24492. holeIndex += holes[i].length;
  24493. addContour(vertices, holes[i]);
  24494. } //
  24495. var triangles = Earcut.triangulate(vertices, holeIndices); //
  24496. for (var _i = 0; _i < triangles.length; _i += 3) {
  24497. faces.push(triangles.slice(_i, _i + 3));
  24498. }
  24499. return faces;
  24500. }
  24501. };
  24502. function removeDupEndPts(points) {
  24503. var l = points.length;
  24504. if (l > 2 && points[l - 1].equals(points[0])) {
  24505. points.pop();
  24506. }
  24507. }
  24508. function addContour(vertices, contour) {
  24509. for (var i = 0; i < contour.length; i++) {
  24510. vertices.push(contour[i].x);
  24511. vertices.push(contour[i].y);
  24512. }
  24513. }
  24514. var ExtrudeBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24515. _inheritsLoose(ExtrudeBufferGeometry, _BufferGeometry);
  24516. function ExtrudeBufferGeometry(shapes, options) {
  24517. var _this;
  24518. _this = _BufferGeometry.call(this) || this;
  24519. _this.type = 'ExtrudeBufferGeometry';
  24520. _this.parameters = {
  24521. shapes: shapes,
  24522. options: options
  24523. };
  24524. shapes = Array.isArray(shapes) ? shapes : [shapes];
  24525. var scope = _assertThisInitialized(_this);
  24526. var verticesArray = [];
  24527. var uvArray = [];
  24528. for (var i = 0, l = shapes.length; i < l; i++) {
  24529. var shape = shapes[i];
  24530. addShape(shape);
  24531. } // build geometry
  24532. _this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  24533. _this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  24534. _this.computeVertexNormals(); // functions
  24535. function addShape(shape) {
  24536. var placeholder = []; // options
  24537. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  24538. var steps = options.steps !== undefined ? options.steps : 1;
  24539. var depth = options.depth !== undefined ? options.depth : 100;
  24540. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  24541. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  24542. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  24543. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  24544. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  24545. var extrudePath = options.extrudePath;
  24546. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  24547. if (options.amount !== undefined) {
  24548. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  24549. depth = options.amount;
  24550. } //
  24551. var extrudePts,
  24552. extrudeByPath = false;
  24553. var splineTube, binormal, normal, position2;
  24554. if (extrudePath) {
  24555. extrudePts = extrudePath.getSpacedPoints(steps);
  24556. extrudeByPath = true;
  24557. bevelEnabled = false; // bevels not supported for path extrusion
  24558. // SETUP TNB variables
  24559. // TODO1 - have a .isClosed in spline?
  24560. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  24561. binormal = new Vector3();
  24562. normal = new Vector3();
  24563. position2 = new Vector3();
  24564. } // Safeguards if bevels are not enabled
  24565. if (!bevelEnabled) {
  24566. bevelSegments = 0;
  24567. bevelThickness = 0;
  24568. bevelSize = 0;
  24569. bevelOffset = 0;
  24570. } // Variables initialization
  24571. var shapePoints = shape.extractPoints(curveSegments);
  24572. var vertices = shapePoints.shape;
  24573. var holes = shapePoints.holes;
  24574. var reverse = !ShapeUtils.isClockWise(vertices);
  24575. if (reverse) {
  24576. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  24577. for (var h = 0, hl = holes.length; h < hl; h++) {
  24578. var ahole = holes[h];
  24579. if (ShapeUtils.isClockWise(ahole)) {
  24580. holes[h] = ahole.reverse();
  24581. }
  24582. }
  24583. }
  24584. var faces = ShapeUtils.triangulateShape(vertices, holes);
  24585. /* Vertices */
  24586. var contour = vertices; // vertices has all points but contour has only points of circumference
  24587. for (var _h = 0, _hl = holes.length; _h < _hl; _h++) {
  24588. var _ahole = holes[_h];
  24589. vertices = vertices.concat(_ahole);
  24590. }
  24591. function scalePt2(pt, vec, size) {
  24592. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  24593. return vec.clone().multiplyScalar(size).add(pt);
  24594. }
  24595. var vlen = vertices.length,
  24596. flen = faces.length; // Find directions for point movement
  24597. function getBevelVec(inPt, inPrev, inNext) {
  24598. // computes for inPt the corresponding point inPt' on a new contour
  24599. // shifted by 1 unit (length of normalized vector) to the left
  24600. // if we walk along contour clockwise, this new contour is outside the old one
  24601. //
  24602. // inPt' is the intersection of the two lines parallel to the two
  24603. // adjacent edges of inPt at a distance of 1 unit on the left side.
  24604. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  24605. // good reading for geometry algorithms (here: line-line intersection)
  24606. // http://geomalgorithms.com/a05-_intersect-1.html
  24607. var v_prev_x = inPt.x - inPrev.x,
  24608. v_prev_y = inPt.y - inPrev.y;
  24609. var v_next_x = inNext.x - inPt.x,
  24610. v_next_y = inNext.y - inPt.y;
  24611. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  24612. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  24613. if (Math.abs(collinear0) > Number.EPSILON) {
  24614. // not collinear
  24615. // length of vectors for normalizing
  24616. var v_prev_len = Math.sqrt(v_prev_lensq);
  24617. var v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  24618. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  24619. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  24620. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  24621. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  24622. var sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  24623. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  24624. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  24625. // but prevent crazy spikes
  24626. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  24627. if (v_trans_lensq <= 2) {
  24628. return new Vector2(v_trans_x, v_trans_y);
  24629. } else {
  24630. shrink_by = Math.sqrt(v_trans_lensq / 2);
  24631. }
  24632. } else {
  24633. // handle special case of collinear edges
  24634. var direction_eq = false; // assumes: opposite
  24635. if (v_prev_x > Number.EPSILON) {
  24636. if (v_next_x > Number.EPSILON) {
  24637. direction_eq = true;
  24638. }
  24639. } else {
  24640. if (v_prev_x < -Number.EPSILON) {
  24641. if (v_next_x < -Number.EPSILON) {
  24642. direction_eq = true;
  24643. }
  24644. } else {
  24645. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  24646. direction_eq = true;
  24647. }
  24648. }
  24649. }
  24650. if (direction_eq) {
  24651. // console.log("Warning: lines are a straight sequence");
  24652. v_trans_x = -v_prev_y;
  24653. v_trans_y = v_prev_x;
  24654. shrink_by = Math.sqrt(v_prev_lensq);
  24655. } else {
  24656. // console.log("Warning: lines are a straight spike");
  24657. v_trans_x = v_prev_x;
  24658. v_trans_y = v_prev_y;
  24659. shrink_by = Math.sqrt(v_prev_lensq / 2);
  24660. }
  24661. }
  24662. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  24663. }
  24664. var contourMovements = [];
  24665. for (var _i = 0, il = contour.length, j = il - 1, k = _i + 1; _i < il; _i++, j++, k++) {
  24666. if (j === il) j = 0;
  24667. if (k === il) k = 0; // (j)---(i)---(k)
  24668. // console.log('i,j,k', i, j , k)
  24669. contourMovements[_i] = getBevelVec(contour[_i], contour[j], contour[k]);
  24670. }
  24671. var holesMovements = [];
  24672. var oneHoleMovements,
  24673. verticesMovements = contourMovements.concat();
  24674. for (var _h2 = 0, _hl2 = holes.length; _h2 < _hl2; _h2++) {
  24675. var _ahole2 = holes[_h2];
  24676. oneHoleMovements = [];
  24677. for (var _i2 = 0, _il = _ahole2.length, _j = _il - 1, _k = _i2 + 1; _i2 < _il; _i2++, _j++, _k++) {
  24678. if (_j === _il) _j = 0;
  24679. if (_k === _il) _k = 0; // (j)---(i)---(k)
  24680. oneHoleMovements[_i2] = getBevelVec(_ahole2[_i2], _ahole2[_j], _ahole2[_k]);
  24681. }
  24682. holesMovements.push(oneHoleMovements);
  24683. verticesMovements = verticesMovements.concat(oneHoleMovements);
  24684. } // Loop bevelSegments, 1 for the front, 1 for the back
  24685. for (var b = 0; b < bevelSegments; b++) {
  24686. //for ( b = bevelSegments; b > 0; b -- ) {
  24687. var t = b / bevelSegments;
  24688. var z = bevelThickness * Math.cos(t * Math.PI / 2);
  24689. var _bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  24690. for (var _i3 = 0, _il2 = contour.length; _i3 < _il2; _i3++) {
  24691. var vert = scalePt2(contour[_i3], contourMovements[_i3], _bs);
  24692. v(vert.x, vert.y, -z);
  24693. } // expand holes
  24694. for (var _h3 = 0, _hl3 = holes.length; _h3 < _hl3; _h3++) {
  24695. var _ahole3 = holes[_h3];
  24696. oneHoleMovements = holesMovements[_h3];
  24697. for (var _i4 = 0, _il3 = _ahole3.length; _i4 < _il3; _i4++) {
  24698. var _vert = scalePt2(_ahole3[_i4], oneHoleMovements[_i4], _bs);
  24699. v(_vert.x, _vert.y, -z);
  24700. }
  24701. }
  24702. }
  24703. var bs = bevelSize + bevelOffset; // Back facing vertices
  24704. for (var _i5 = 0; _i5 < vlen; _i5++) {
  24705. var _vert2 = bevelEnabled ? scalePt2(vertices[_i5], verticesMovements[_i5], bs) : vertices[_i5];
  24706. if (!extrudeByPath) {
  24707. v(_vert2.x, _vert2.y, 0);
  24708. } else {
  24709. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  24710. normal.copy(splineTube.normals[0]).multiplyScalar(_vert2.x);
  24711. binormal.copy(splineTube.binormals[0]).multiplyScalar(_vert2.y);
  24712. position2.copy(extrudePts[0]).add(normal).add(binormal);
  24713. v(position2.x, position2.y, position2.z);
  24714. }
  24715. } // Add stepped vertices...
  24716. // Including front facing vertices
  24717. for (var s = 1; s <= steps; s++) {
  24718. for (var _i6 = 0; _i6 < vlen; _i6++) {
  24719. var _vert3 = bevelEnabled ? scalePt2(vertices[_i6], verticesMovements[_i6], bs) : vertices[_i6];
  24720. if (!extrudeByPath) {
  24721. v(_vert3.x, _vert3.y, depth / steps * s);
  24722. } else {
  24723. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  24724. normal.copy(splineTube.normals[s]).multiplyScalar(_vert3.x);
  24725. binormal.copy(splineTube.binormals[s]).multiplyScalar(_vert3.y);
  24726. position2.copy(extrudePts[s]).add(normal).add(binormal);
  24727. v(position2.x, position2.y, position2.z);
  24728. }
  24729. }
  24730. } // Add bevel segments planes
  24731. //for ( b = 1; b <= bevelSegments; b ++ ) {
  24732. for (var _b = bevelSegments - 1; _b >= 0; _b--) {
  24733. var _t = _b / bevelSegments;
  24734. var _z = bevelThickness * Math.cos(_t * Math.PI / 2);
  24735. var _bs2 = bevelSize * Math.sin(_t * Math.PI / 2) + bevelOffset; // contract shape
  24736. for (var _i7 = 0, _il4 = contour.length; _i7 < _il4; _i7++) {
  24737. var _vert4 = scalePt2(contour[_i7], contourMovements[_i7], _bs2);
  24738. v(_vert4.x, _vert4.y, depth + _z);
  24739. } // expand holes
  24740. for (var _h4 = 0, _hl4 = holes.length; _h4 < _hl4; _h4++) {
  24741. var _ahole4 = holes[_h4];
  24742. oneHoleMovements = holesMovements[_h4];
  24743. for (var _i8 = 0, _il5 = _ahole4.length; _i8 < _il5; _i8++) {
  24744. var _vert5 = scalePt2(_ahole4[_i8], oneHoleMovements[_i8], _bs2);
  24745. if (!extrudeByPath) {
  24746. v(_vert5.x, _vert5.y, depth + _z);
  24747. } else {
  24748. v(_vert5.x, _vert5.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + _z);
  24749. }
  24750. }
  24751. }
  24752. }
  24753. /* Faces */
  24754. // Top and bottom faces
  24755. buildLidFaces(); // Sides faces
  24756. buildSideFaces(); ///// Internal functions
  24757. function buildLidFaces() {
  24758. var start = verticesArray.length / 3;
  24759. if (bevelEnabled) {
  24760. var layer = 0; // steps + 1
  24761. var offset = vlen * layer; // Bottom faces
  24762. for (var _i9 = 0; _i9 < flen; _i9++) {
  24763. var face = faces[_i9];
  24764. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  24765. }
  24766. layer = steps + bevelSegments * 2;
  24767. offset = vlen * layer; // Top faces
  24768. for (var _i10 = 0; _i10 < flen; _i10++) {
  24769. var _face = faces[_i10];
  24770. f3(_face[0] + offset, _face[1] + offset, _face[2] + offset);
  24771. }
  24772. } else {
  24773. // Bottom faces
  24774. for (var _i11 = 0; _i11 < flen; _i11++) {
  24775. var _face2 = faces[_i11];
  24776. f3(_face2[2], _face2[1], _face2[0]);
  24777. } // Top faces
  24778. for (var _i12 = 0; _i12 < flen; _i12++) {
  24779. var _face3 = faces[_i12];
  24780. f3(_face3[0] + vlen * steps, _face3[1] + vlen * steps, _face3[2] + vlen * steps);
  24781. }
  24782. }
  24783. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  24784. } // Create faces for the z-sides of the shape
  24785. function buildSideFaces() {
  24786. var start = verticesArray.length / 3;
  24787. var layeroffset = 0;
  24788. sidewalls(contour, layeroffset);
  24789. layeroffset += contour.length;
  24790. for (var _h5 = 0, _hl5 = holes.length; _h5 < _hl5; _h5++) {
  24791. var _ahole5 = holes[_h5];
  24792. sidewalls(_ahole5, layeroffset); //, true
  24793. layeroffset += _ahole5.length;
  24794. }
  24795. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  24796. }
  24797. function sidewalls(contour, layeroffset) {
  24798. var i = contour.length;
  24799. while (--i >= 0) {
  24800. var _j2 = i;
  24801. var _k2 = i - 1;
  24802. if (_k2 < 0) _k2 = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  24803. for (var _s = 0, sl = steps + bevelSegments * 2; _s < sl; _s++) {
  24804. var slen1 = vlen * _s;
  24805. var slen2 = vlen * (_s + 1);
  24806. var a = layeroffset + _j2 + slen1,
  24807. _b2 = layeroffset + _k2 + slen1,
  24808. c = layeroffset + _k2 + slen2,
  24809. d = layeroffset + _j2 + slen2;
  24810. f4(a, _b2, c, d);
  24811. }
  24812. }
  24813. }
  24814. function v(x, y, z) {
  24815. placeholder.push(x);
  24816. placeholder.push(y);
  24817. placeholder.push(z);
  24818. }
  24819. function f3(a, b, c) {
  24820. addVertex(a);
  24821. addVertex(b);
  24822. addVertex(c);
  24823. var nextIndex = verticesArray.length / 3;
  24824. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  24825. addUV(uvs[0]);
  24826. addUV(uvs[1]);
  24827. addUV(uvs[2]);
  24828. }
  24829. function f4(a, b, c, d) {
  24830. addVertex(a);
  24831. addVertex(b);
  24832. addVertex(d);
  24833. addVertex(b);
  24834. addVertex(c);
  24835. addVertex(d);
  24836. var nextIndex = verticesArray.length / 3;
  24837. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  24838. addUV(uvs[0]);
  24839. addUV(uvs[1]);
  24840. addUV(uvs[3]);
  24841. addUV(uvs[1]);
  24842. addUV(uvs[2]);
  24843. addUV(uvs[3]);
  24844. }
  24845. function addVertex(index) {
  24846. verticesArray.push(placeholder[index * 3 + 0]);
  24847. verticesArray.push(placeholder[index * 3 + 1]);
  24848. verticesArray.push(placeholder[index * 3 + 2]);
  24849. }
  24850. function addUV(vector2) {
  24851. uvArray.push(vector2.x);
  24852. uvArray.push(vector2.y);
  24853. }
  24854. }
  24855. return _this;
  24856. }
  24857. var _proto = ExtrudeBufferGeometry.prototype;
  24858. _proto.toJSON = function toJSON() {
  24859. var data = BufferGeometry.prototype.toJSON.call(this);
  24860. var shapes = this.parameters.shapes;
  24861. var options = this.parameters.options;
  24862. return _toJSON(shapes, options, data);
  24863. };
  24864. return ExtrudeBufferGeometry;
  24865. }(BufferGeometry);
  24866. var WorldUVGenerator = {
  24867. generateTopUV: function generateTopUV(geometry, vertices, indexA, indexB, indexC) {
  24868. var a_x = vertices[indexA * 3];
  24869. var a_y = vertices[indexA * 3 + 1];
  24870. var b_x = vertices[indexB * 3];
  24871. var b_y = vertices[indexB * 3 + 1];
  24872. var c_x = vertices[indexC * 3];
  24873. var c_y = vertices[indexC * 3 + 1];
  24874. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  24875. },
  24876. generateSideWallUV: function generateSideWallUV(geometry, vertices, indexA, indexB, indexC, indexD) {
  24877. var a_x = vertices[indexA * 3];
  24878. var a_y = vertices[indexA * 3 + 1];
  24879. var a_z = vertices[indexA * 3 + 2];
  24880. var b_x = vertices[indexB * 3];
  24881. var b_y = vertices[indexB * 3 + 1];
  24882. var b_z = vertices[indexB * 3 + 2];
  24883. var c_x = vertices[indexC * 3];
  24884. var c_y = vertices[indexC * 3 + 1];
  24885. var c_z = vertices[indexC * 3 + 2];
  24886. var d_x = vertices[indexD * 3];
  24887. var d_y = vertices[indexD * 3 + 1];
  24888. var d_z = vertices[indexD * 3 + 2];
  24889. if (Math.abs(a_y - b_y) < 0.01) {
  24890. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  24891. } else {
  24892. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  24893. }
  24894. }
  24895. };
  24896. function _toJSON(shapes, options, data) {
  24897. data.shapes = [];
  24898. if (Array.isArray(shapes)) {
  24899. for (var i = 0, l = shapes.length; i < l; i++) {
  24900. var shape = shapes[i];
  24901. data.shapes.push(shape.uuid);
  24902. }
  24903. } else {
  24904. data.shapes.push(shapes.uuid);
  24905. }
  24906. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  24907. return data;
  24908. }
  24909. var ExtrudeGeometry = /*#__PURE__*/function (_Geometry) {
  24910. _inheritsLoose(ExtrudeGeometry, _Geometry);
  24911. function ExtrudeGeometry(shapes, options) {
  24912. var _this;
  24913. _this = _Geometry.call(this) || this;
  24914. _this.type = 'ExtrudeGeometry';
  24915. _this.parameters = {
  24916. shapes: shapes,
  24917. options: options
  24918. };
  24919. _this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  24920. _this.mergeVertices();
  24921. return _this;
  24922. }
  24923. var _proto = ExtrudeGeometry.prototype;
  24924. _proto.toJSON = function toJSON() {
  24925. var data = _Geometry.prototype.toJSON.call(this);
  24926. var shapes = this.parameters.shapes;
  24927. var options = this.parameters.options;
  24928. return _toJSON$1(shapes, options, data);
  24929. };
  24930. return ExtrudeGeometry;
  24931. }(Geometry);
  24932. function _toJSON$1(shapes, options, data) {
  24933. data.shapes = [];
  24934. if (Array.isArray(shapes)) {
  24935. for (var i = 0, l = shapes.length; i < l; i++) {
  24936. var shape = shapes[i];
  24937. data.shapes.push(shape.uuid);
  24938. }
  24939. } else {
  24940. data.shapes.push(shapes.uuid);
  24941. }
  24942. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  24943. return data;
  24944. }
  24945. var IcosahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
  24946. _inheritsLoose(IcosahedronBufferGeometry, _PolyhedronBufferGeom);
  24947. function IcosahedronBufferGeometry(radius, detail) {
  24948. var _this;
  24949. if (radius === void 0) {
  24950. radius = 1;
  24951. }
  24952. if (detail === void 0) {
  24953. detail = 0;
  24954. }
  24955. var t = (1 + Math.sqrt(5)) / 2;
  24956. var vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  24957. var indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  24958. _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
  24959. _this.type = 'IcosahedronBufferGeometry';
  24960. _this.parameters = {
  24961. radius: radius,
  24962. detail: detail
  24963. };
  24964. return _this;
  24965. }
  24966. return IcosahedronBufferGeometry;
  24967. }(PolyhedronBufferGeometry);
  24968. var IcosahedronGeometry = /*#__PURE__*/function (_Geometry) {
  24969. _inheritsLoose(IcosahedronGeometry, _Geometry);
  24970. function IcosahedronGeometry(radius, detail) {
  24971. var _this;
  24972. _this = _Geometry.call(this) || this;
  24973. _this.type = 'IcosahedronGeometry';
  24974. _this.parameters = {
  24975. radius: radius,
  24976. detail: detail
  24977. };
  24978. _this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  24979. _this.mergeVertices();
  24980. return _this;
  24981. }
  24982. return IcosahedronGeometry;
  24983. }(Geometry);
  24984. var LatheBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24985. _inheritsLoose(LatheBufferGeometry, _BufferGeometry);
  24986. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  24987. var _this;
  24988. if (segments === void 0) {
  24989. segments = 12;
  24990. }
  24991. if (phiStart === void 0) {
  24992. phiStart = 0;
  24993. }
  24994. if (phiLength === void 0) {
  24995. phiLength = Math.PI * 2;
  24996. }
  24997. _this = _BufferGeometry.call(this) || this;
  24998. _this.type = 'LatheBufferGeometry';
  24999. _this.parameters = {
  25000. points: points,
  25001. segments: segments,
  25002. phiStart: phiStart,
  25003. phiLength: phiLength
  25004. };
  25005. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  25006. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  25007. var indices = [];
  25008. var vertices = [];
  25009. var uvs = []; // helper variables
  25010. var inverseSegments = 1.0 / segments;
  25011. var vertex = new Vector3();
  25012. var uv = new Vector2(); // generate vertices and uvs
  25013. for (var i = 0; i <= segments; i++) {
  25014. var phi = phiStart + i * inverseSegments * phiLength;
  25015. var sin = Math.sin(phi);
  25016. var cos = Math.cos(phi);
  25017. for (var j = 0; j <= points.length - 1; j++) {
  25018. // vertex
  25019. vertex.x = points[j].x * sin;
  25020. vertex.y = points[j].y;
  25021. vertex.z = points[j].x * cos;
  25022. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  25023. uv.x = i / segments;
  25024. uv.y = j / (points.length - 1);
  25025. uvs.push(uv.x, uv.y);
  25026. }
  25027. } // indices
  25028. for (var _i = 0; _i < segments; _i++) {
  25029. for (var _j = 0; _j < points.length - 1; _j++) {
  25030. var base = _j + _i * points.length;
  25031. var a = base;
  25032. var b = base + points.length;
  25033. var c = base + points.length + 1;
  25034. var d = base + 1; // faces
  25035. indices.push(a, b, d);
  25036. indices.push(b, c, d);
  25037. }
  25038. } // build geometry
  25039. _this.setIndex(indices);
  25040. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25041. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  25042. _this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  25043. // because the corresponding vertices are identical (but still have different UVs).
  25044. if (phiLength === Math.PI * 2) {
  25045. var normals = _this.attributes.normal.array;
  25046. var n1 = new Vector3();
  25047. var n2 = new Vector3();
  25048. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  25049. var _base = segments * points.length * 3;
  25050. for (var _i2 = 0, _j2 = 0; _i2 < points.length; _i2++, _j2 += 3) {
  25051. // select the normal of the vertex in the first line
  25052. n1.x = normals[_j2 + 0];
  25053. n1.y = normals[_j2 + 1];
  25054. n1.z = normals[_j2 + 2]; // select the normal of the vertex in the last line
  25055. n2.x = normals[_base + _j2 + 0];
  25056. n2.y = normals[_base + _j2 + 1];
  25057. n2.z = normals[_base + _j2 + 2]; // average normals
  25058. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  25059. normals[_j2 + 0] = normals[_base + _j2 + 0] = n.x;
  25060. normals[_j2 + 1] = normals[_base + _j2 + 1] = n.y;
  25061. normals[_j2 + 2] = normals[_base + _j2 + 2] = n.z;
  25062. }
  25063. }
  25064. return _this;
  25065. }
  25066. return LatheBufferGeometry;
  25067. }(BufferGeometry);
  25068. var LatheGeometry = /*#__PURE__*/function (_Geometry) {
  25069. _inheritsLoose(LatheGeometry, _Geometry);
  25070. function LatheGeometry(points, segments, phiStart, phiLength) {
  25071. var _this;
  25072. _this = _Geometry.call(this) || this;
  25073. _this.type = 'LatheGeometry';
  25074. _this.parameters = {
  25075. points: points,
  25076. segments: segments,
  25077. phiStart: phiStart,
  25078. phiLength: phiLength
  25079. };
  25080. _this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  25081. _this.mergeVertices();
  25082. return _this;
  25083. }
  25084. return LatheGeometry;
  25085. }(Geometry);
  25086. var OctahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
  25087. _inheritsLoose(OctahedronBufferGeometry, _PolyhedronBufferGeom);
  25088. function OctahedronBufferGeometry(radius, detail) {
  25089. var _this;
  25090. if (radius === void 0) {
  25091. radius = 1;
  25092. }
  25093. if (detail === void 0) {
  25094. detail = 0;
  25095. }
  25096. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  25097. var indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  25098. _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
  25099. _this.type = 'OctahedronBufferGeometry';
  25100. _this.parameters = {
  25101. radius: radius,
  25102. detail: detail
  25103. };
  25104. return _this;
  25105. }
  25106. return OctahedronBufferGeometry;
  25107. }(PolyhedronBufferGeometry);
  25108. var OctahedronGeometry = /*#__PURE__*/function (_Geometry) {
  25109. _inheritsLoose(OctahedronGeometry, _Geometry);
  25110. function OctahedronGeometry(radius, detail) {
  25111. var _this;
  25112. _this = _Geometry.call(this) || this;
  25113. _this.type = 'OctahedronGeometry';
  25114. _this.parameters = {
  25115. radius: radius,
  25116. detail: detail
  25117. };
  25118. _this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  25119. _this.mergeVertices();
  25120. return _this;
  25121. }
  25122. return OctahedronGeometry;
  25123. }(Geometry);
  25124. /**
  25125. * Parametric Surfaces Geometry
  25126. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  25127. */
  25128. function ParametricBufferGeometry(func, slices, stacks) {
  25129. BufferGeometry.call(this);
  25130. this.type = 'ParametricBufferGeometry';
  25131. this.parameters = {
  25132. func: func,
  25133. slices: slices,
  25134. stacks: stacks
  25135. }; // buffers
  25136. var indices = [];
  25137. var vertices = [];
  25138. var normals = [];
  25139. var uvs = [];
  25140. var EPS = 0.00001;
  25141. var normal = new Vector3();
  25142. var p0 = new Vector3(),
  25143. p1 = new Vector3();
  25144. var pu = new Vector3(),
  25145. pv = new Vector3();
  25146. if (func.length < 3) {
  25147. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  25148. } // generate vertices, normals and uvs
  25149. var sliceCount = slices + 1;
  25150. for (var i = 0; i <= stacks; i++) {
  25151. var v = i / stacks;
  25152. for (var j = 0; j <= slices; j++) {
  25153. var u = j / slices; // vertex
  25154. func(u, v, p0);
  25155. vertices.push(p0.x, p0.y, p0.z); // normal
  25156. // approximate tangent vectors via finite differences
  25157. if (u - EPS >= 0) {
  25158. func(u - EPS, v, p1);
  25159. pu.subVectors(p0, p1);
  25160. } else {
  25161. func(u + EPS, v, p1);
  25162. pu.subVectors(p1, p0);
  25163. }
  25164. if (v - EPS >= 0) {
  25165. func(u, v - EPS, p1);
  25166. pv.subVectors(p0, p1);
  25167. } else {
  25168. func(u, v + EPS, p1);
  25169. pv.subVectors(p1, p0);
  25170. } // cross product of tangent vectors returns surface normal
  25171. normal.crossVectors(pu, pv).normalize();
  25172. normals.push(normal.x, normal.y, normal.z); // uv
  25173. uvs.push(u, v);
  25174. }
  25175. } // generate indices
  25176. for (var _i = 0; _i < stacks; _i++) {
  25177. for (var _j = 0; _j < slices; _j++) {
  25178. var a = _i * sliceCount + _j;
  25179. var b = _i * sliceCount + _j + 1;
  25180. var c = (_i + 1) * sliceCount + _j + 1;
  25181. var d = (_i + 1) * sliceCount + _j; // faces one and two
  25182. indices.push(a, b, d);
  25183. indices.push(b, c, d);
  25184. }
  25185. } // build geometry
  25186. this.setIndex(indices);
  25187. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25188. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25189. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  25190. }
  25191. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  25192. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  25193. /**
  25194. * Parametric Surfaces Geometry
  25195. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  25196. */
  25197. function ParametricGeometry(func, slices, stacks) {
  25198. Geometry.call(this);
  25199. this.type = 'ParametricGeometry';
  25200. this.parameters = {
  25201. func: func,
  25202. slices: slices,
  25203. stacks: stacks
  25204. };
  25205. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  25206. this.mergeVertices();
  25207. }
  25208. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  25209. ParametricGeometry.prototype.constructor = ParametricGeometry;
  25210. var PlaneGeometry = /*#__PURE__*/function (_Geometry) {
  25211. _inheritsLoose(PlaneGeometry, _Geometry);
  25212. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  25213. var _this;
  25214. _this = _Geometry.call(this) || this;
  25215. _this.type = 'PlaneGeometry';
  25216. _this.parameters = {
  25217. width: width,
  25218. height: height,
  25219. widthSegments: widthSegments,
  25220. heightSegments: heightSegments
  25221. };
  25222. _this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  25223. _this.mergeVertices();
  25224. return _this;
  25225. }
  25226. return PlaneGeometry;
  25227. }(Geometry);
  25228. var PolyhedronGeometry = /*#__PURE__*/function (_Geometry) {
  25229. _inheritsLoose(PolyhedronGeometry, _Geometry);
  25230. function PolyhedronGeometry(vertices, indices, radius, detail) {
  25231. var _this;
  25232. _this = _Geometry.call(this) || this;
  25233. _this.type = 'PolyhedronGeometry';
  25234. _this.parameters = {
  25235. vertices: vertices,
  25236. indices: indices,
  25237. radius: radius,
  25238. detail: detail
  25239. };
  25240. _this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  25241. _this.mergeVertices();
  25242. return _this;
  25243. }
  25244. return PolyhedronGeometry;
  25245. }(Geometry);
  25246. var RingBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25247. _inheritsLoose(RingBufferGeometry, _BufferGeometry);
  25248. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  25249. var _this;
  25250. if (innerRadius === void 0) {
  25251. innerRadius = 0.5;
  25252. }
  25253. if (outerRadius === void 0) {
  25254. outerRadius = 1;
  25255. }
  25256. if (thetaSegments === void 0) {
  25257. thetaSegments = 8;
  25258. }
  25259. if (phiSegments === void 0) {
  25260. phiSegments = 1;
  25261. }
  25262. if (thetaStart === void 0) {
  25263. thetaStart = 0;
  25264. }
  25265. if (thetaLength === void 0) {
  25266. thetaLength = Math.PI * 2;
  25267. }
  25268. _this = _BufferGeometry.call(this) || this;
  25269. _this.type = 'RingBufferGeometry';
  25270. _this.parameters = {
  25271. innerRadius: innerRadius,
  25272. outerRadius: outerRadius,
  25273. thetaSegments: thetaSegments,
  25274. phiSegments: phiSegments,
  25275. thetaStart: thetaStart,
  25276. thetaLength: thetaLength
  25277. };
  25278. thetaSegments = Math.max(3, thetaSegments);
  25279. phiSegments = Math.max(1, phiSegments); // buffers
  25280. var indices = [];
  25281. var vertices = [];
  25282. var normals = [];
  25283. var uvs = []; // some helper variables
  25284. var radius = innerRadius;
  25285. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  25286. var vertex = new Vector3();
  25287. var uv = new Vector2(); // generate vertices, normals and uvs
  25288. for (var j = 0; j <= phiSegments; j++) {
  25289. for (var i = 0; i <= thetaSegments; i++) {
  25290. // values are generate from the inside of the ring to the outside
  25291. var segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  25292. vertex.x = radius * Math.cos(segment);
  25293. vertex.y = radius * Math.sin(segment);
  25294. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  25295. normals.push(0, 0, 1); // uv
  25296. uv.x = (vertex.x / outerRadius + 1) / 2;
  25297. uv.y = (vertex.y / outerRadius + 1) / 2;
  25298. uvs.push(uv.x, uv.y);
  25299. } // increase the radius for next row of vertices
  25300. radius += radiusStep;
  25301. } // indices
  25302. for (var _j = 0; _j < phiSegments; _j++) {
  25303. var thetaSegmentLevel = _j * (thetaSegments + 1);
  25304. for (var _i = 0; _i < thetaSegments; _i++) {
  25305. var _segment = _i + thetaSegmentLevel;
  25306. var a = _segment;
  25307. var b = _segment + thetaSegments + 1;
  25308. var c = _segment + thetaSegments + 2;
  25309. var d = _segment + 1; // faces
  25310. indices.push(a, b, d);
  25311. indices.push(b, c, d);
  25312. }
  25313. } // build geometry
  25314. _this.setIndex(indices);
  25315. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25316. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25317. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  25318. return _this;
  25319. }
  25320. return RingBufferGeometry;
  25321. }(BufferGeometry);
  25322. var RingGeometry = /*#__PURE__*/function (_Geometry) {
  25323. _inheritsLoose(RingGeometry, _Geometry);
  25324. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  25325. var _this;
  25326. _this = _Geometry.call(this) || this;
  25327. _this.type = 'RingGeometry';
  25328. _this.parameters = {
  25329. innerRadius: innerRadius,
  25330. outerRadius: outerRadius,
  25331. thetaSegments: thetaSegments,
  25332. phiSegments: phiSegments,
  25333. thetaStart: thetaStart,
  25334. thetaLength: thetaLength
  25335. };
  25336. _this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  25337. _this.mergeVertices();
  25338. return _this;
  25339. }
  25340. return RingGeometry;
  25341. }(Geometry);
  25342. var ShapeBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25343. _inheritsLoose(ShapeBufferGeometry, _BufferGeometry);
  25344. function ShapeBufferGeometry(shapes, curveSegments) {
  25345. var _this;
  25346. if (curveSegments === void 0) {
  25347. curveSegments = 12;
  25348. }
  25349. _this = _BufferGeometry.call(this) || this;
  25350. _this.type = 'ShapeBufferGeometry';
  25351. _this.parameters = {
  25352. shapes: shapes,
  25353. curveSegments: curveSegments
  25354. }; // buffers
  25355. var indices = [];
  25356. var vertices = [];
  25357. var normals = [];
  25358. var uvs = []; // helper variables
  25359. var groupStart = 0;
  25360. var groupCount = 0; // allow single and array values for "shapes" parameter
  25361. if (Array.isArray(shapes) === false) {
  25362. addShape(shapes);
  25363. } else {
  25364. for (var i = 0; i < shapes.length; i++) {
  25365. addShape(shapes[i]);
  25366. _this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  25367. groupStart += groupCount;
  25368. groupCount = 0;
  25369. }
  25370. } // build geometry
  25371. _this.setIndex(indices);
  25372. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25373. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25374. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  25375. function addShape(shape) {
  25376. var indexOffset = vertices.length / 3;
  25377. var points = shape.extractPoints(curveSegments);
  25378. var shapeVertices = points.shape;
  25379. var shapeHoles = points.holes; // check direction of vertices
  25380. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  25381. shapeVertices = shapeVertices.reverse();
  25382. }
  25383. for (var _i = 0, l = shapeHoles.length; _i < l; _i++) {
  25384. var shapeHole = shapeHoles[_i];
  25385. if (ShapeUtils.isClockWise(shapeHole) === true) {
  25386. shapeHoles[_i] = shapeHole.reverse();
  25387. }
  25388. }
  25389. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  25390. for (var _i2 = 0, _l = shapeHoles.length; _i2 < _l; _i2++) {
  25391. var _shapeHole = shapeHoles[_i2];
  25392. shapeVertices = shapeVertices.concat(_shapeHole);
  25393. } // vertices, normals, uvs
  25394. for (var _i3 = 0, _l2 = shapeVertices.length; _i3 < _l2; _i3++) {
  25395. var vertex = shapeVertices[_i3];
  25396. vertices.push(vertex.x, vertex.y, 0);
  25397. normals.push(0, 0, 1);
  25398. uvs.push(vertex.x, vertex.y); // world uvs
  25399. } // incides
  25400. for (var _i4 = 0, _l3 = faces.length; _i4 < _l3; _i4++) {
  25401. var face = faces[_i4];
  25402. var a = face[0] + indexOffset;
  25403. var b = face[1] + indexOffset;
  25404. var c = face[2] + indexOffset;
  25405. indices.push(a, b, c);
  25406. groupCount += 3;
  25407. }
  25408. }
  25409. return _this;
  25410. }
  25411. var _proto = ShapeBufferGeometry.prototype;
  25412. _proto.toJSON = function toJSON() {
  25413. var data = BufferGeometry.prototype.toJSON.call(this);
  25414. var shapes = this.parameters.shapes;
  25415. return _toJSON$2(shapes, data);
  25416. };
  25417. return ShapeBufferGeometry;
  25418. }(BufferGeometry);
  25419. function _toJSON$2(shapes, data) {
  25420. data.shapes = [];
  25421. if (Array.isArray(shapes)) {
  25422. for (var i = 0, l = shapes.length; i < l; i++) {
  25423. var shape = shapes[i];
  25424. data.shapes.push(shape.uuid);
  25425. }
  25426. } else {
  25427. data.shapes.push(shapes.uuid);
  25428. }
  25429. return data;
  25430. }
  25431. var ShapeGeometry = /*#__PURE__*/function (_Geometry) {
  25432. _inheritsLoose(ShapeGeometry, _Geometry);
  25433. function ShapeGeometry(shapes, curveSegments) {
  25434. var _this;
  25435. _this = _Geometry.call(this) || this;
  25436. _this.type = 'ShapeGeometry';
  25437. if (typeof curveSegments === 'object') {
  25438. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  25439. curveSegments = curveSegments.curveSegments;
  25440. }
  25441. _this.parameters = {
  25442. shapes: shapes,
  25443. curveSegments: curveSegments
  25444. };
  25445. _this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  25446. _this.mergeVertices();
  25447. return _this;
  25448. }
  25449. var _proto = ShapeGeometry.prototype;
  25450. _proto.toJSON = function toJSON() {
  25451. var data = Geometry.prototype.toJSON.call(this);
  25452. var shapes = this.parameters.shapes;
  25453. return _toJSON$3(shapes, data);
  25454. };
  25455. return ShapeGeometry;
  25456. }(Geometry);
  25457. function _toJSON$3(shapes, data) {
  25458. data.shapes = [];
  25459. if (Array.isArray(shapes)) {
  25460. for (var i = 0, l = shapes.length; i < l; i++) {
  25461. var shape = shapes[i];
  25462. data.shapes.push(shape.uuid);
  25463. }
  25464. } else {
  25465. data.shapes.push(shapes.uuid);
  25466. }
  25467. return data;
  25468. }
  25469. var SphereBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25470. _inheritsLoose(SphereBufferGeometry, _BufferGeometry);
  25471. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  25472. var _this;
  25473. if (radius === void 0) {
  25474. radius = 1;
  25475. }
  25476. if (widthSegments === void 0) {
  25477. widthSegments = 8;
  25478. }
  25479. if (heightSegments === void 0) {
  25480. heightSegments = 6;
  25481. }
  25482. if (phiStart === void 0) {
  25483. phiStart = 0;
  25484. }
  25485. if (phiLength === void 0) {
  25486. phiLength = Math.PI * 2;
  25487. }
  25488. if (thetaStart === void 0) {
  25489. thetaStart = 0;
  25490. }
  25491. if (thetaLength === void 0) {
  25492. thetaLength = Math.PI;
  25493. }
  25494. _this = _BufferGeometry.call(this) || this;
  25495. _this.type = 'SphereBufferGeometry';
  25496. _this.parameters = {
  25497. radius: radius,
  25498. widthSegments: widthSegments,
  25499. heightSegments: heightSegments,
  25500. phiStart: phiStart,
  25501. phiLength: phiLength,
  25502. thetaStart: thetaStart,
  25503. thetaLength: thetaLength
  25504. };
  25505. widthSegments = Math.max(3, Math.floor(widthSegments));
  25506. heightSegments = Math.max(2, Math.floor(heightSegments));
  25507. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  25508. var index = 0;
  25509. var grid = [];
  25510. var vertex = new Vector3();
  25511. var normal = new Vector3(); // buffers
  25512. var indices = [];
  25513. var vertices = [];
  25514. var normals = [];
  25515. var uvs = []; // generate vertices, normals and uvs
  25516. for (var iy = 0; iy <= heightSegments; iy++) {
  25517. var verticesRow = [];
  25518. var v = iy / heightSegments; // special case for the poles
  25519. var uOffset = 0;
  25520. if (iy == 0 && thetaStart == 0) {
  25521. uOffset = 0.5 / widthSegments;
  25522. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  25523. uOffset = -0.5 / widthSegments;
  25524. }
  25525. for (var ix = 0; ix <= widthSegments; ix++) {
  25526. var u = ix / widthSegments; // vertex
  25527. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  25528. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  25529. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  25530. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  25531. normal.copy(vertex).normalize();
  25532. normals.push(normal.x, normal.y, normal.z); // uv
  25533. uvs.push(u + uOffset, 1 - v);
  25534. verticesRow.push(index++);
  25535. }
  25536. grid.push(verticesRow);
  25537. } // indices
  25538. for (var _iy = 0; _iy < heightSegments; _iy++) {
  25539. for (var _ix = 0; _ix < widthSegments; _ix++) {
  25540. var a = grid[_iy][_ix + 1];
  25541. var b = grid[_iy][_ix];
  25542. var c = grid[_iy + 1][_ix];
  25543. var d = grid[_iy + 1][_ix + 1];
  25544. if (_iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  25545. if (_iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  25546. }
  25547. } // build geometry
  25548. _this.setIndex(indices);
  25549. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25550. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25551. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  25552. return _this;
  25553. }
  25554. return SphereBufferGeometry;
  25555. }(BufferGeometry);
  25556. var SphereGeometry = /*#__PURE__*/function (_Geometry) {
  25557. _inheritsLoose(SphereGeometry, _Geometry);
  25558. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  25559. var _this;
  25560. _this = _Geometry.call(this) || this;
  25561. _this.type = 'SphereGeometry';
  25562. _this.parameters = {
  25563. radius: radius,
  25564. widthSegments: widthSegments,
  25565. heightSegments: heightSegments,
  25566. phiStart: phiStart,
  25567. phiLength: phiLength,
  25568. thetaStart: thetaStart,
  25569. thetaLength: thetaLength
  25570. };
  25571. _this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  25572. _this.mergeVertices();
  25573. return _this;
  25574. }
  25575. return SphereGeometry;
  25576. }(Geometry);
  25577. var TetrahedronBufferGeometry = /*#__PURE__*/function (_PolyhedronBufferGeom) {
  25578. _inheritsLoose(TetrahedronBufferGeometry, _PolyhedronBufferGeom);
  25579. function TetrahedronBufferGeometry(radius, detail) {
  25580. var _this;
  25581. if (radius === void 0) {
  25582. radius = 1;
  25583. }
  25584. if (detail === void 0) {
  25585. detail = 0;
  25586. }
  25587. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  25588. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  25589. _this = _PolyhedronBufferGeom.call(this, vertices, indices, radius, detail) || this;
  25590. _this.type = 'TetrahedronBufferGeometry';
  25591. _this.parameters = {
  25592. radius: radius,
  25593. detail: detail
  25594. };
  25595. return _this;
  25596. }
  25597. return TetrahedronBufferGeometry;
  25598. }(PolyhedronBufferGeometry);
  25599. var TetrahedronGeometry = /*#__PURE__*/function (_Geometry) {
  25600. _inheritsLoose(TetrahedronGeometry, _Geometry);
  25601. function TetrahedronGeometry(radius, detail) {
  25602. var _this;
  25603. _this = _Geometry.call(this) || this;
  25604. _this.type = 'TetrahedronGeometry';
  25605. _this.parameters = {
  25606. radius: radius,
  25607. detail: detail
  25608. };
  25609. _this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  25610. _this.mergeVertices();
  25611. return _this;
  25612. }
  25613. return TetrahedronGeometry;
  25614. }(Geometry);
  25615. var TextBufferGeometry = /*#__PURE__*/function (_ExtrudeBufferGeometr) {
  25616. _inheritsLoose(TextBufferGeometry, _ExtrudeBufferGeometr);
  25617. function TextBufferGeometry(text, parameters) {
  25618. var _this;
  25619. if (parameters === void 0) {
  25620. parameters = {};
  25621. }
  25622. var font = parameters.font;
  25623. if (!(font && font.isFont)) {
  25624. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  25625. return new BufferGeometry() || _assertThisInitialized(_this);
  25626. }
  25627. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  25628. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  25629. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  25630. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  25631. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  25632. _this = _ExtrudeBufferGeometr.call(this, shapes, parameters) || this;
  25633. _this.type = 'TextBufferGeometry';
  25634. return _this;
  25635. }
  25636. return TextBufferGeometry;
  25637. }(ExtrudeBufferGeometry);
  25638. var TextGeometry = /*#__PURE__*/function (_Geometry) {
  25639. _inheritsLoose(TextGeometry, _Geometry);
  25640. function TextGeometry(text, parameters) {
  25641. var _this;
  25642. _this = _Geometry.call(this) || this;
  25643. _this.type = 'TextGeometry';
  25644. _this.parameters = {
  25645. text: text,
  25646. parameters: parameters
  25647. };
  25648. _this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  25649. _this.mergeVertices();
  25650. return _this;
  25651. }
  25652. return TextGeometry;
  25653. }(Geometry);
  25654. var TorusBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25655. _inheritsLoose(TorusBufferGeometry, _BufferGeometry);
  25656. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  25657. var _this;
  25658. if (radius === void 0) {
  25659. radius = 1;
  25660. }
  25661. if (tube === void 0) {
  25662. tube = 0.4;
  25663. }
  25664. if (radialSegments === void 0) {
  25665. radialSegments = 8;
  25666. }
  25667. if (tubularSegments === void 0) {
  25668. tubularSegments = 6;
  25669. }
  25670. if (arc === void 0) {
  25671. arc = Math.PI * 2;
  25672. }
  25673. _this = _BufferGeometry.call(this) || this;
  25674. _this.type = 'TorusBufferGeometry';
  25675. _this.parameters = {
  25676. radius: radius,
  25677. tube: tube,
  25678. radialSegments: radialSegments,
  25679. tubularSegments: tubularSegments,
  25680. arc: arc
  25681. };
  25682. radialSegments = Math.floor(radialSegments);
  25683. tubularSegments = Math.floor(tubularSegments); // buffers
  25684. var indices = [];
  25685. var vertices = [];
  25686. var normals = [];
  25687. var uvs = []; // helper variables
  25688. var center = new Vector3();
  25689. var vertex = new Vector3();
  25690. var normal = new Vector3(); // generate vertices, normals and uvs
  25691. for (var j = 0; j <= radialSegments; j++) {
  25692. for (var i = 0; i <= tubularSegments; i++) {
  25693. var u = i / tubularSegments * arc;
  25694. var v = j / radialSegments * Math.PI * 2; // vertex
  25695. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  25696. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  25697. vertex.z = tube * Math.sin(v);
  25698. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  25699. center.x = radius * Math.cos(u);
  25700. center.y = radius * Math.sin(u);
  25701. normal.subVectors(vertex, center).normalize();
  25702. normals.push(normal.x, normal.y, normal.z); // uv
  25703. uvs.push(i / tubularSegments);
  25704. uvs.push(j / radialSegments);
  25705. }
  25706. } // generate indices
  25707. for (var _j = 1; _j <= radialSegments; _j++) {
  25708. for (var _i = 1; _i <= tubularSegments; _i++) {
  25709. // indices
  25710. var a = (tubularSegments + 1) * _j + _i - 1;
  25711. var b = (tubularSegments + 1) * (_j - 1) + _i - 1;
  25712. var c = (tubularSegments + 1) * (_j - 1) + _i;
  25713. var d = (tubularSegments + 1) * _j + _i; // faces
  25714. indices.push(a, b, d);
  25715. indices.push(b, c, d);
  25716. }
  25717. } // build geometry
  25718. _this.setIndex(indices);
  25719. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25720. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25721. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  25722. return _this;
  25723. }
  25724. return TorusBufferGeometry;
  25725. }(BufferGeometry);
  25726. var TorusGeometry = /*#__PURE__*/function (_Geometry) {
  25727. _inheritsLoose(TorusGeometry, _Geometry);
  25728. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  25729. var _this;
  25730. _this = _Geometry.call(this) || this;
  25731. _this.type = 'TorusGeometry';
  25732. _this.parameters = {
  25733. radius: radius,
  25734. tube: tube,
  25735. radialSegments: radialSegments,
  25736. tubularSegments: tubularSegments,
  25737. arc: arc
  25738. };
  25739. _this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  25740. _this.mergeVertices();
  25741. return _this;
  25742. }
  25743. return TorusGeometry;
  25744. }(Geometry);
  25745. var TorusKnotBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25746. _inheritsLoose(TorusKnotBufferGeometry, _BufferGeometry);
  25747. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  25748. var _this;
  25749. if (radius === void 0) {
  25750. radius = 1;
  25751. }
  25752. if (tube === void 0) {
  25753. tube = 0.4;
  25754. }
  25755. if (tubularSegments === void 0) {
  25756. tubularSegments = 64;
  25757. }
  25758. if (radialSegments === void 0) {
  25759. radialSegments = 8;
  25760. }
  25761. if (p === void 0) {
  25762. p = 2;
  25763. }
  25764. if (q === void 0) {
  25765. q = 3;
  25766. }
  25767. _this = _BufferGeometry.call(this) || this;
  25768. _this.type = 'TorusKnotBufferGeometry';
  25769. _this.parameters = {
  25770. radius: radius,
  25771. tube: tube,
  25772. tubularSegments: tubularSegments,
  25773. radialSegments: radialSegments,
  25774. p: p,
  25775. q: q
  25776. };
  25777. tubularSegments = Math.floor(tubularSegments);
  25778. radialSegments = Math.floor(radialSegments); // buffers
  25779. var indices = [];
  25780. var vertices = [];
  25781. var normals = [];
  25782. var uvs = []; // helper variables
  25783. var vertex = new Vector3();
  25784. var normal = new Vector3();
  25785. var P1 = new Vector3();
  25786. var P2 = new Vector3();
  25787. var B = new Vector3();
  25788. var T = new Vector3();
  25789. var N = new Vector3(); // generate vertices, normals and uvs
  25790. for (var i = 0; i <= tubularSegments; ++i) {
  25791. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  25792. var u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  25793. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  25794. calculatePositionOnCurve(u, p, q, radius, P1);
  25795. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  25796. T.subVectors(P2, P1);
  25797. N.addVectors(P2, P1);
  25798. B.crossVectors(T, N);
  25799. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  25800. B.normalize();
  25801. N.normalize();
  25802. for (var j = 0; j <= radialSegments; ++j) {
  25803. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  25804. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  25805. var v = j / radialSegments * Math.PI * 2;
  25806. var cx = -tube * Math.cos(v);
  25807. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  25808. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  25809. vertex.x = P1.x + (cx * N.x + cy * B.x);
  25810. vertex.y = P1.y + (cx * N.y + cy * B.y);
  25811. vertex.z = P1.z + (cx * N.z + cy * B.z);
  25812. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  25813. normal.subVectors(vertex, P1).normalize();
  25814. normals.push(normal.x, normal.y, normal.z); // uv
  25815. uvs.push(i / tubularSegments);
  25816. uvs.push(j / radialSegments);
  25817. }
  25818. } // generate indices
  25819. for (var _j = 1; _j <= tubularSegments; _j++) {
  25820. for (var _i = 1; _i <= radialSegments; _i++) {
  25821. // indices
  25822. var a = (radialSegments + 1) * (_j - 1) + (_i - 1);
  25823. var b = (radialSegments + 1) * _j + (_i - 1);
  25824. var c = (radialSegments + 1) * _j + _i;
  25825. var d = (radialSegments + 1) * (_j - 1) + _i; // faces
  25826. indices.push(a, b, d);
  25827. indices.push(b, c, d);
  25828. }
  25829. } // build geometry
  25830. _this.setIndex(indices);
  25831. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25832. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25833. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  25834. function calculatePositionOnCurve(u, p, q, radius, position) {
  25835. var cu = Math.cos(u);
  25836. var su = Math.sin(u);
  25837. var quOverP = q / p * u;
  25838. var cs = Math.cos(quOverP);
  25839. position.x = radius * (2 + cs) * 0.5 * cu;
  25840. position.y = radius * (2 + cs) * su * 0.5;
  25841. position.z = radius * Math.sin(quOverP) * 0.5;
  25842. }
  25843. return _this;
  25844. }
  25845. return TorusKnotBufferGeometry;
  25846. }(BufferGeometry);
  25847. var TorusKnotGeometry = /*#__PURE__*/function (_Geometry) {
  25848. _inheritsLoose(TorusKnotGeometry, _Geometry);
  25849. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  25850. var _this;
  25851. _this = _Geometry.call(this) || this;
  25852. _this.type = 'TorusKnotGeometry';
  25853. _this.parameters = {
  25854. radius: radius,
  25855. tube: tube,
  25856. tubularSegments: tubularSegments,
  25857. radialSegments: radialSegments,
  25858. p: p,
  25859. q: q
  25860. };
  25861. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  25862. _this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  25863. _this.mergeVertices();
  25864. return _this;
  25865. }
  25866. return TorusKnotGeometry;
  25867. }(Geometry);
  25868. var TubeBufferGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25869. _inheritsLoose(TubeBufferGeometry, _BufferGeometry);
  25870. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  25871. var _this;
  25872. if (tubularSegments === void 0) {
  25873. tubularSegments = 64;
  25874. }
  25875. if (radius === void 0) {
  25876. radius = 1;
  25877. }
  25878. if (radialSegments === void 0) {
  25879. radialSegments = 8;
  25880. }
  25881. if (closed === void 0) {
  25882. closed = false;
  25883. }
  25884. _this = _BufferGeometry.call(this) || this;
  25885. _this.type = 'TubeBufferGeometry';
  25886. _this.parameters = {
  25887. path: path,
  25888. tubularSegments: tubularSegments,
  25889. radius: radius,
  25890. radialSegments: radialSegments,
  25891. closed: closed
  25892. };
  25893. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  25894. _this.tangents = frames.tangents;
  25895. _this.normals = frames.normals;
  25896. _this.binormals = frames.binormals; // helper variables
  25897. var vertex = new Vector3();
  25898. var normal = new Vector3();
  25899. var uv = new Vector2();
  25900. var P = new Vector3(); // buffer
  25901. var vertices = [];
  25902. var normals = [];
  25903. var uvs = [];
  25904. var indices = []; // create buffer data
  25905. generateBufferData(); // build geometry
  25906. _this.setIndex(indices);
  25907. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25908. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25909. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  25910. function generateBufferData() {
  25911. for (var i = 0; i < tubularSegments; i++) {
  25912. generateSegment(i);
  25913. } // if the geometry is not closed, generate the last row of vertices and normals
  25914. // at the regular position on the given path
  25915. //
  25916. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  25917. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  25918. // this makes it easy compute correct values for closed geometries
  25919. generateUVs(); // finally create faces
  25920. generateIndices();
  25921. }
  25922. function generateSegment(i) {
  25923. // we use getPointAt to sample evenly distributed points from the given path
  25924. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  25925. var N = frames.normals[i];
  25926. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  25927. for (var j = 0; j <= radialSegments; j++) {
  25928. var v = j / radialSegments * Math.PI * 2;
  25929. var sin = Math.sin(v);
  25930. var cos = -Math.cos(v); // normal
  25931. normal.x = cos * N.x + sin * B.x;
  25932. normal.y = cos * N.y + sin * B.y;
  25933. normal.z = cos * N.z + sin * B.z;
  25934. normal.normalize();
  25935. normals.push(normal.x, normal.y, normal.z); // vertex
  25936. vertex.x = P.x + radius * normal.x;
  25937. vertex.y = P.y + radius * normal.y;
  25938. vertex.z = P.z + radius * normal.z;
  25939. vertices.push(vertex.x, vertex.y, vertex.z);
  25940. }
  25941. }
  25942. function generateIndices() {
  25943. for (var j = 1; j <= tubularSegments; j++) {
  25944. for (var i = 1; i <= radialSegments; i++) {
  25945. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  25946. var b = (radialSegments + 1) * j + (i - 1);
  25947. var c = (radialSegments + 1) * j + i;
  25948. var d = (radialSegments + 1) * (j - 1) + i; // faces
  25949. indices.push(a, b, d);
  25950. indices.push(b, c, d);
  25951. }
  25952. }
  25953. }
  25954. function generateUVs() {
  25955. for (var i = 0; i <= tubularSegments; i++) {
  25956. for (var j = 0; j <= radialSegments; j++) {
  25957. uv.x = i / tubularSegments;
  25958. uv.y = j / radialSegments;
  25959. uvs.push(uv.x, uv.y);
  25960. }
  25961. }
  25962. }
  25963. return _this;
  25964. }
  25965. var _proto = TubeBufferGeometry.prototype;
  25966. _proto.toJSON = function toJSON() {
  25967. var data = BufferGeometry.prototype.toJSON.call(this);
  25968. data.path = this.parameters.path.toJSON();
  25969. return data;
  25970. };
  25971. return TubeBufferGeometry;
  25972. }(BufferGeometry);
  25973. var TubeGeometry = /*#__PURE__*/function (_Geometry) {
  25974. _inheritsLoose(TubeGeometry, _Geometry);
  25975. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  25976. var _this;
  25977. _this = _Geometry.call(this) || this;
  25978. _this.type = 'TubeGeometry';
  25979. _this.parameters = {
  25980. path: path,
  25981. tubularSegments: tubularSegments,
  25982. radius: radius,
  25983. radialSegments: radialSegments,
  25984. closed: closed
  25985. };
  25986. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  25987. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  25988. _this.tangents = bufferGeometry.tangents;
  25989. _this.normals = bufferGeometry.normals;
  25990. _this.binormals = bufferGeometry.binormals; // create geometry
  25991. _this.fromBufferGeometry(bufferGeometry);
  25992. _this.mergeVertices();
  25993. return _this;
  25994. }
  25995. return TubeGeometry;
  25996. }(Geometry);
  25997. var WireframeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25998. _inheritsLoose(WireframeGeometry, _BufferGeometry);
  25999. function WireframeGeometry(geometry) {
  26000. var _this;
  26001. _this = _BufferGeometry.call(this) || this;
  26002. _this.type = 'WireframeGeometry'; // buffer
  26003. var vertices = []; // helper variables
  26004. var edge = [0, 0],
  26005. edges = {};
  26006. var keys = ['a', 'b', 'c']; // different logic for Geometry and BufferGeometry
  26007. if (geometry && geometry.isGeometry) {
  26008. // create a data structure that contains all edges without duplicates
  26009. var faces = geometry.faces;
  26010. for (var i = 0, l = faces.length; i < l; i++) {
  26011. var face = faces[i];
  26012. for (var j = 0; j < 3; j++) {
  26013. var edge1 = face[keys[j]];
  26014. var edge2 = face[keys[(j + 1) % 3]];
  26015. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  26016. edge[1] = Math.max(edge1, edge2);
  26017. var key = edge[0] + ',' + edge[1];
  26018. if (edges[key] === undefined) {
  26019. edges[key] = {
  26020. index1: edge[0],
  26021. index2: edge[1]
  26022. };
  26023. }
  26024. }
  26025. } // generate vertices
  26026. for (var _key in edges) {
  26027. var e = edges[_key];
  26028. var vertex = geometry.vertices[e.index1];
  26029. vertices.push(vertex.x, vertex.y, vertex.z);
  26030. vertex = geometry.vertices[e.index2];
  26031. vertices.push(vertex.x, vertex.y, vertex.z);
  26032. }
  26033. } else if (geometry && geometry.isBufferGeometry) {
  26034. var _vertex = new Vector3();
  26035. if (geometry.index !== null) {
  26036. // indexed BufferGeometry
  26037. var position = geometry.attributes.position;
  26038. var indices = geometry.index;
  26039. var groups = geometry.groups;
  26040. if (groups.length === 0) {
  26041. groups = [{
  26042. start: 0,
  26043. count: indices.count,
  26044. materialIndex: 0
  26045. }];
  26046. } // create a data structure that contains all eges without duplicates
  26047. for (var o = 0, ol = groups.length; o < ol; ++o) {
  26048. var group = groups[o];
  26049. var start = group.start;
  26050. var count = group.count;
  26051. for (var _i = start, _l = start + count; _i < _l; _i += 3) {
  26052. for (var _j = 0; _j < 3; _j++) {
  26053. var _edge = indices.getX(_i + _j);
  26054. var _edge2 = indices.getX(_i + (_j + 1) % 3);
  26055. edge[0] = Math.min(_edge, _edge2); // sorting prevents duplicates
  26056. edge[1] = Math.max(_edge, _edge2);
  26057. var _key2 = edge[0] + ',' + edge[1];
  26058. if (edges[_key2] === undefined) {
  26059. edges[_key2] = {
  26060. index1: edge[0],
  26061. index2: edge[1]
  26062. };
  26063. }
  26064. }
  26065. }
  26066. } // generate vertices
  26067. for (var _key3 in edges) {
  26068. var _e = edges[_key3];
  26069. _vertex.fromBufferAttribute(position, _e.index1);
  26070. vertices.push(_vertex.x, _vertex.y, _vertex.z);
  26071. _vertex.fromBufferAttribute(position, _e.index2);
  26072. vertices.push(_vertex.x, _vertex.y, _vertex.z);
  26073. }
  26074. } else {
  26075. // non-indexed BufferGeometry
  26076. var _position = geometry.attributes.position;
  26077. for (var _i2 = 0, _l2 = _position.count / 3; _i2 < _l2; _i2++) {
  26078. for (var _j2 = 0; _j2 < 3; _j2++) {
  26079. // three edges per triangle, an edge is represented as (index1, index2)
  26080. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26081. var index1 = 3 * _i2 + _j2;
  26082. _vertex.fromBufferAttribute(_position, index1);
  26083. vertices.push(_vertex.x, _vertex.y, _vertex.z);
  26084. var index2 = 3 * _i2 + (_j2 + 1) % 3;
  26085. _vertex.fromBufferAttribute(_position, index2);
  26086. vertices.push(_vertex.x, _vertex.y, _vertex.z);
  26087. }
  26088. }
  26089. }
  26090. } // build geometry
  26091. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26092. return _this;
  26093. }
  26094. return WireframeGeometry;
  26095. }(BufferGeometry);
  26096. var Geometries = /*#__PURE__*/Object.freeze({
  26097. __proto__: null,
  26098. BoxGeometry: BoxGeometry,
  26099. BoxBufferGeometry: BoxBufferGeometry,
  26100. CircleGeometry: CircleGeometry,
  26101. CircleBufferGeometry: CircleBufferGeometry,
  26102. ConeGeometry: ConeGeometry,
  26103. ConeBufferGeometry: ConeBufferGeometry,
  26104. CylinderGeometry: CylinderGeometry,
  26105. CylinderBufferGeometry: CylinderBufferGeometry,
  26106. DodecahedronGeometry: DodecahedronGeometry,
  26107. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  26108. EdgesGeometry: EdgesGeometry,
  26109. ExtrudeGeometry: ExtrudeGeometry,
  26110. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  26111. IcosahedronGeometry: IcosahedronGeometry,
  26112. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  26113. LatheGeometry: LatheGeometry,
  26114. LatheBufferGeometry: LatheBufferGeometry,
  26115. OctahedronGeometry: OctahedronGeometry,
  26116. OctahedronBufferGeometry: OctahedronBufferGeometry,
  26117. ParametricGeometry: ParametricGeometry,
  26118. ParametricBufferGeometry: ParametricBufferGeometry,
  26119. PlaneGeometry: PlaneGeometry,
  26120. PlaneBufferGeometry: PlaneBufferGeometry,
  26121. PolyhedronGeometry: PolyhedronGeometry,
  26122. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  26123. RingGeometry: RingGeometry,
  26124. RingBufferGeometry: RingBufferGeometry,
  26125. ShapeGeometry: ShapeGeometry,
  26126. ShapeBufferGeometry: ShapeBufferGeometry,
  26127. SphereGeometry: SphereGeometry,
  26128. SphereBufferGeometry: SphereBufferGeometry,
  26129. TetrahedronGeometry: TetrahedronGeometry,
  26130. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  26131. TextGeometry: TextGeometry,
  26132. TextBufferGeometry: TextBufferGeometry,
  26133. TorusGeometry: TorusGeometry,
  26134. TorusBufferGeometry: TorusBufferGeometry,
  26135. TorusKnotGeometry: TorusKnotGeometry,
  26136. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  26137. TubeGeometry: TubeGeometry,
  26138. TubeBufferGeometry: TubeBufferGeometry,
  26139. WireframeGeometry: WireframeGeometry
  26140. });
  26141. /**
  26142. * parameters = {
  26143. * color: <THREE.Color>
  26144. * }
  26145. */
  26146. function ShadowMaterial(parameters) {
  26147. Material.call(this);
  26148. this.type = 'ShadowMaterial';
  26149. this.color = new Color(0x000000);
  26150. this.transparent = true;
  26151. this.setValues(parameters);
  26152. }
  26153. ShadowMaterial.prototype = Object.create(Material.prototype);
  26154. ShadowMaterial.prototype.constructor = ShadowMaterial;
  26155. ShadowMaterial.prototype.isShadowMaterial = true;
  26156. ShadowMaterial.prototype.copy = function (source) {
  26157. Material.prototype.copy.call(this, source);
  26158. this.color.copy(source.color);
  26159. return this;
  26160. };
  26161. function RawShaderMaterial(parameters) {
  26162. ShaderMaterial.call(this, parameters);
  26163. this.type = 'RawShaderMaterial';
  26164. }
  26165. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  26166. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  26167. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  26168. /**
  26169. * parameters = {
  26170. * color: <hex>,
  26171. * roughness: <float>,
  26172. * metalness: <float>,
  26173. * opacity: <float>,
  26174. *
  26175. * map: new THREE.Texture( <Image> ),
  26176. *
  26177. * lightMap: new THREE.Texture( <Image> ),
  26178. * lightMapIntensity: <float>
  26179. *
  26180. * aoMap: new THREE.Texture( <Image> ),
  26181. * aoMapIntensity: <float>
  26182. *
  26183. * emissive: <hex>,
  26184. * emissiveIntensity: <float>
  26185. * emissiveMap: new THREE.Texture( <Image> ),
  26186. *
  26187. * bumpMap: new THREE.Texture( <Image> ),
  26188. * bumpScale: <float>,
  26189. *
  26190. * normalMap: new THREE.Texture( <Image> ),
  26191. * normalMapType: THREE.TangentSpaceNormalMap,
  26192. * normalScale: <Vector2>,
  26193. *
  26194. * displacementMap: new THREE.Texture( <Image> ),
  26195. * displacementScale: <float>,
  26196. * displacementBias: <float>,
  26197. *
  26198. * roughnessMap: new THREE.Texture( <Image> ),
  26199. *
  26200. * metalnessMap: new THREE.Texture( <Image> ),
  26201. *
  26202. * alphaMap: new THREE.Texture( <Image> ),
  26203. *
  26204. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  26205. * envMapIntensity: <float>
  26206. *
  26207. * refractionRatio: <float>,
  26208. *
  26209. * wireframe: <boolean>,
  26210. * wireframeLinewidth: <float>,
  26211. *
  26212. * skinning: <bool>,
  26213. * morphTargets: <bool>,
  26214. * morphNormals: <bool>
  26215. * }
  26216. */
  26217. function MeshStandardMaterial(parameters) {
  26218. Material.call(this);
  26219. this.defines = {
  26220. 'STANDARD': ''
  26221. };
  26222. this.type = 'MeshStandardMaterial';
  26223. this.color = new Color(0xffffff); // diffuse
  26224. this.roughness = 1.0;
  26225. this.metalness = 0.0;
  26226. this.map = null;
  26227. this.lightMap = null;
  26228. this.lightMapIntensity = 1.0;
  26229. this.aoMap = null;
  26230. this.aoMapIntensity = 1.0;
  26231. this.emissive = new Color(0x000000);
  26232. this.emissiveIntensity = 1.0;
  26233. this.emissiveMap = null;
  26234. this.bumpMap = null;
  26235. this.bumpScale = 1;
  26236. this.normalMap = null;
  26237. this.normalMapType = TangentSpaceNormalMap;
  26238. this.normalScale = new Vector2(1, 1);
  26239. this.displacementMap = null;
  26240. this.displacementScale = 1;
  26241. this.displacementBias = 0;
  26242. this.roughnessMap = null;
  26243. this.metalnessMap = null;
  26244. this.alphaMap = null;
  26245. this.envMap = null;
  26246. this.envMapIntensity = 1.0;
  26247. this.refractionRatio = 0.98;
  26248. this.wireframe = false;
  26249. this.wireframeLinewidth = 1;
  26250. this.wireframeLinecap = 'round';
  26251. this.wireframeLinejoin = 'round';
  26252. this.skinning = false;
  26253. this.morphTargets = false;
  26254. this.morphNormals = false;
  26255. this.vertexTangents = false;
  26256. this.setValues(parameters);
  26257. }
  26258. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  26259. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  26260. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  26261. MeshStandardMaterial.prototype.copy = function (source) {
  26262. Material.prototype.copy.call(this, source);
  26263. this.defines = {
  26264. 'STANDARD': ''
  26265. };
  26266. this.color.copy(source.color);
  26267. this.roughness = source.roughness;
  26268. this.metalness = source.metalness;
  26269. this.map = source.map;
  26270. this.lightMap = source.lightMap;
  26271. this.lightMapIntensity = source.lightMapIntensity;
  26272. this.aoMap = source.aoMap;
  26273. this.aoMapIntensity = source.aoMapIntensity;
  26274. this.emissive.copy(source.emissive);
  26275. this.emissiveMap = source.emissiveMap;
  26276. this.emissiveIntensity = source.emissiveIntensity;
  26277. this.bumpMap = source.bumpMap;
  26278. this.bumpScale = source.bumpScale;
  26279. this.normalMap = source.normalMap;
  26280. this.normalMapType = source.normalMapType;
  26281. this.normalScale.copy(source.normalScale);
  26282. this.displacementMap = source.displacementMap;
  26283. this.displacementScale = source.displacementScale;
  26284. this.displacementBias = source.displacementBias;
  26285. this.roughnessMap = source.roughnessMap;
  26286. this.metalnessMap = source.metalnessMap;
  26287. this.alphaMap = source.alphaMap;
  26288. this.envMap = source.envMap;
  26289. this.envMapIntensity = source.envMapIntensity;
  26290. this.refractionRatio = source.refractionRatio;
  26291. this.wireframe = source.wireframe;
  26292. this.wireframeLinewidth = source.wireframeLinewidth;
  26293. this.wireframeLinecap = source.wireframeLinecap;
  26294. this.wireframeLinejoin = source.wireframeLinejoin;
  26295. this.skinning = source.skinning;
  26296. this.morphTargets = source.morphTargets;
  26297. this.morphNormals = source.morphNormals;
  26298. this.vertexTangents = source.vertexTangents;
  26299. return this;
  26300. };
  26301. /**
  26302. * parameters = {
  26303. * clearcoat: <float>,
  26304. * clearcoatMap: new THREE.Texture( <Image> ),
  26305. * clearcoatRoughness: <float>,
  26306. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  26307. * clearcoatNormalScale: <Vector2>,
  26308. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  26309. *
  26310. * reflectivity: <float>,
  26311. * ior: <float>,
  26312. *
  26313. * sheen: <Color>,
  26314. *
  26315. * transmission: <float>,
  26316. * transmissionMap: new THREE.Texture( <Image> )
  26317. * }
  26318. */
  26319. function MeshPhysicalMaterial(parameters) {
  26320. MeshStandardMaterial.call(this);
  26321. this.defines = {
  26322. 'STANDARD': '',
  26323. 'PHYSICAL': ''
  26324. };
  26325. this.type = 'MeshPhysicalMaterial';
  26326. this.clearcoat = 0.0;
  26327. this.clearcoatMap = null;
  26328. this.clearcoatRoughness = 0.0;
  26329. this.clearcoatRoughnessMap = null;
  26330. this.clearcoatNormalScale = new Vector2(1, 1);
  26331. this.clearcoatNormalMap = null;
  26332. this.reflectivity = 0.5; // maps to F0 = 0.04
  26333. Object.defineProperty(this, 'ior', {
  26334. get: function get() {
  26335. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  26336. },
  26337. set: function set(ior) {
  26338. this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  26339. }
  26340. });
  26341. this.sheen = null; // null will disable sheen bsdf
  26342. this.transmission = 0.0;
  26343. this.transmissionMap = null;
  26344. this.setValues(parameters);
  26345. }
  26346. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  26347. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  26348. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  26349. MeshPhysicalMaterial.prototype.copy = function (source) {
  26350. MeshStandardMaterial.prototype.copy.call(this, source);
  26351. this.defines = {
  26352. 'STANDARD': '',
  26353. 'PHYSICAL': ''
  26354. };
  26355. this.clearcoat = source.clearcoat;
  26356. this.clearcoatMap = source.clearcoatMap;
  26357. this.clearcoatRoughness = source.clearcoatRoughness;
  26358. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  26359. this.clearcoatNormalMap = source.clearcoatNormalMap;
  26360. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  26361. this.reflectivity = source.reflectivity;
  26362. if (source.sheen) {
  26363. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  26364. } else {
  26365. this.sheen = null;
  26366. }
  26367. this.transmission = source.transmission;
  26368. this.transmissionMap = source.transmissionMap;
  26369. return this;
  26370. };
  26371. /**
  26372. * parameters = {
  26373. * color: <hex>,
  26374. * specular: <hex>,
  26375. * shininess: <float>,
  26376. * opacity: <float>,
  26377. *
  26378. * map: new THREE.Texture( <Image> ),
  26379. *
  26380. * lightMap: new THREE.Texture( <Image> ),
  26381. * lightMapIntensity: <float>
  26382. *
  26383. * aoMap: new THREE.Texture( <Image> ),
  26384. * aoMapIntensity: <float>
  26385. *
  26386. * emissive: <hex>,
  26387. * emissiveIntensity: <float>
  26388. * emissiveMap: new THREE.Texture( <Image> ),
  26389. *
  26390. * bumpMap: new THREE.Texture( <Image> ),
  26391. * bumpScale: <float>,
  26392. *
  26393. * normalMap: new THREE.Texture( <Image> ),
  26394. * normalMapType: THREE.TangentSpaceNormalMap,
  26395. * normalScale: <Vector2>,
  26396. *
  26397. * displacementMap: new THREE.Texture( <Image> ),
  26398. * displacementScale: <float>,
  26399. * displacementBias: <float>,
  26400. *
  26401. * specularMap: new THREE.Texture( <Image> ),
  26402. *
  26403. * alphaMap: new THREE.Texture( <Image> ),
  26404. *
  26405. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  26406. * combine: THREE.MultiplyOperation,
  26407. * reflectivity: <float>,
  26408. * refractionRatio: <float>,
  26409. *
  26410. * wireframe: <boolean>,
  26411. * wireframeLinewidth: <float>,
  26412. *
  26413. * skinning: <bool>,
  26414. * morphTargets: <bool>,
  26415. * morphNormals: <bool>
  26416. * }
  26417. */
  26418. function MeshPhongMaterial(parameters) {
  26419. Material.call(this);
  26420. this.type = 'MeshPhongMaterial';
  26421. this.color = new Color(0xffffff); // diffuse
  26422. this.specular = new Color(0x111111);
  26423. this.shininess = 30;
  26424. this.map = null;
  26425. this.lightMap = null;
  26426. this.lightMapIntensity = 1.0;
  26427. this.aoMap = null;
  26428. this.aoMapIntensity = 1.0;
  26429. this.emissive = new Color(0x000000);
  26430. this.emissiveIntensity = 1.0;
  26431. this.emissiveMap = null;
  26432. this.bumpMap = null;
  26433. this.bumpScale = 1;
  26434. this.normalMap = null;
  26435. this.normalMapType = TangentSpaceNormalMap;
  26436. this.normalScale = new Vector2(1, 1);
  26437. this.displacementMap = null;
  26438. this.displacementScale = 1;
  26439. this.displacementBias = 0;
  26440. this.specularMap = null;
  26441. this.alphaMap = null;
  26442. this.envMap = null;
  26443. this.combine = MultiplyOperation;
  26444. this.reflectivity = 1;
  26445. this.refractionRatio = 0.98;
  26446. this.wireframe = false;
  26447. this.wireframeLinewidth = 1;
  26448. this.wireframeLinecap = 'round';
  26449. this.wireframeLinejoin = 'round';
  26450. this.skinning = false;
  26451. this.morphTargets = false;
  26452. this.morphNormals = false;
  26453. this.setValues(parameters);
  26454. }
  26455. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  26456. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  26457. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  26458. MeshPhongMaterial.prototype.copy = function (source) {
  26459. Material.prototype.copy.call(this, source);
  26460. this.color.copy(source.color);
  26461. this.specular.copy(source.specular);
  26462. this.shininess = source.shininess;
  26463. this.map = source.map;
  26464. this.lightMap = source.lightMap;
  26465. this.lightMapIntensity = source.lightMapIntensity;
  26466. this.aoMap = source.aoMap;
  26467. this.aoMapIntensity = source.aoMapIntensity;
  26468. this.emissive.copy(source.emissive);
  26469. this.emissiveMap = source.emissiveMap;
  26470. this.emissiveIntensity = source.emissiveIntensity;
  26471. this.bumpMap = source.bumpMap;
  26472. this.bumpScale = source.bumpScale;
  26473. this.normalMap = source.normalMap;
  26474. this.normalMapType = source.normalMapType;
  26475. this.normalScale.copy(source.normalScale);
  26476. this.displacementMap = source.displacementMap;
  26477. this.displacementScale = source.displacementScale;
  26478. this.displacementBias = source.displacementBias;
  26479. this.specularMap = source.specularMap;
  26480. this.alphaMap = source.alphaMap;
  26481. this.envMap = source.envMap;
  26482. this.combine = source.combine;
  26483. this.reflectivity = source.reflectivity;
  26484. this.refractionRatio = source.refractionRatio;
  26485. this.wireframe = source.wireframe;
  26486. this.wireframeLinewidth = source.wireframeLinewidth;
  26487. this.wireframeLinecap = source.wireframeLinecap;
  26488. this.wireframeLinejoin = source.wireframeLinejoin;
  26489. this.skinning = source.skinning;
  26490. this.morphTargets = source.morphTargets;
  26491. this.morphNormals = source.morphNormals;
  26492. return this;
  26493. };
  26494. /**
  26495. * parameters = {
  26496. * color: <hex>,
  26497. *
  26498. * map: new THREE.Texture( <Image> ),
  26499. * gradientMap: new THREE.Texture( <Image> ),
  26500. *
  26501. * lightMap: new THREE.Texture( <Image> ),
  26502. * lightMapIntensity: <float>
  26503. *
  26504. * aoMap: new THREE.Texture( <Image> ),
  26505. * aoMapIntensity: <float>
  26506. *
  26507. * emissive: <hex>,
  26508. * emissiveIntensity: <float>
  26509. * emissiveMap: new THREE.Texture( <Image> ),
  26510. *
  26511. * bumpMap: new THREE.Texture( <Image> ),
  26512. * bumpScale: <float>,
  26513. *
  26514. * normalMap: new THREE.Texture( <Image> ),
  26515. * normalMapType: THREE.TangentSpaceNormalMap,
  26516. * normalScale: <Vector2>,
  26517. *
  26518. * displacementMap: new THREE.Texture( <Image> ),
  26519. * displacementScale: <float>,
  26520. * displacementBias: <float>,
  26521. *
  26522. * alphaMap: new THREE.Texture( <Image> ),
  26523. *
  26524. * wireframe: <boolean>,
  26525. * wireframeLinewidth: <float>,
  26526. *
  26527. * skinning: <bool>,
  26528. * morphTargets: <bool>,
  26529. * morphNormals: <bool>
  26530. * }
  26531. */
  26532. function MeshToonMaterial(parameters) {
  26533. Material.call(this);
  26534. this.defines = {
  26535. 'TOON': ''
  26536. };
  26537. this.type = 'MeshToonMaterial';
  26538. this.color = new Color(0xffffff);
  26539. this.map = null;
  26540. this.gradientMap = null;
  26541. this.lightMap = null;
  26542. this.lightMapIntensity = 1.0;
  26543. this.aoMap = null;
  26544. this.aoMapIntensity = 1.0;
  26545. this.emissive = new Color(0x000000);
  26546. this.emissiveIntensity = 1.0;
  26547. this.emissiveMap = null;
  26548. this.bumpMap = null;
  26549. this.bumpScale = 1;
  26550. this.normalMap = null;
  26551. this.normalMapType = TangentSpaceNormalMap;
  26552. this.normalScale = new Vector2(1, 1);
  26553. this.displacementMap = null;
  26554. this.displacementScale = 1;
  26555. this.displacementBias = 0;
  26556. this.alphaMap = null;
  26557. this.wireframe = false;
  26558. this.wireframeLinewidth = 1;
  26559. this.wireframeLinecap = 'round';
  26560. this.wireframeLinejoin = 'round';
  26561. this.skinning = false;
  26562. this.morphTargets = false;
  26563. this.morphNormals = false;
  26564. this.setValues(parameters);
  26565. }
  26566. MeshToonMaterial.prototype = Object.create(Material.prototype);
  26567. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  26568. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  26569. MeshToonMaterial.prototype.copy = function (source) {
  26570. Material.prototype.copy.call(this, source);
  26571. this.color.copy(source.color);
  26572. this.map = source.map;
  26573. this.gradientMap = source.gradientMap;
  26574. this.lightMap = source.lightMap;
  26575. this.lightMapIntensity = source.lightMapIntensity;
  26576. this.aoMap = source.aoMap;
  26577. this.aoMapIntensity = source.aoMapIntensity;
  26578. this.emissive.copy(source.emissive);
  26579. this.emissiveMap = source.emissiveMap;
  26580. this.emissiveIntensity = source.emissiveIntensity;
  26581. this.bumpMap = source.bumpMap;
  26582. this.bumpScale = source.bumpScale;
  26583. this.normalMap = source.normalMap;
  26584. this.normalMapType = source.normalMapType;
  26585. this.normalScale.copy(source.normalScale);
  26586. this.displacementMap = source.displacementMap;
  26587. this.displacementScale = source.displacementScale;
  26588. this.displacementBias = source.displacementBias;
  26589. this.alphaMap = source.alphaMap;
  26590. this.wireframe = source.wireframe;
  26591. this.wireframeLinewidth = source.wireframeLinewidth;
  26592. this.wireframeLinecap = source.wireframeLinecap;
  26593. this.wireframeLinejoin = source.wireframeLinejoin;
  26594. this.skinning = source.skinning;
  26595. this.morphTargets = source.morphTargets;
  26596. this.morphNormals = source.morphNormals;
  26597. return this;
  26598. };
  26599. /**
  26600. * parameters = {
  26601. * opacity: <float>,
  26602. *
  26603. * bumpMap: new THREE.Texture( <Image> ),
  26604. * bumpScale: <float>,
  26605. *
  26606. * normalMap: new THREE.Texture( <Image> ),
  26607. * normalMapType: THREE.TangentSpaceNormalMap,
  26608. * normalScale: <Vector2>,
  26609. *
  26610. * displacementMap: new THREE.Texture( <Image> ),
  26611. * displacementScale: <float>,
  26612. * displacementBias: <float>,
  26613. *
  26614. * wireframe: <boolean>,
  26615. * wireframeLinewidth: <float>
  26616. *
  26617. * skinning: <bool>,
  26618. * morphTargets: <bool>,
  26619. * morphNormals: <bool>
  26620. * }
  26621. */
  26622. function MeshNormalMaterial(parameters) {
  26623. Material.call(this);
  26624. this.type = 'MeshNormalMaterial';
  26625. this.bumpMap = null;
  26626. this.bumpScale = 1;
  26627. this.normalMap = null;
  26628. this.normalMapType = TangentSpaceNormalMap;
  26629. this.normalScale = new Vector2(1, 1);
  26630. this.displacementMap = null;
  26631. this.displacementScale = 1;
  26632. this.displacementBias = 0;
  26633. this.wireframe = false;
  26634. this.wireframeLinewidth = 1;
  26635. this.fog = false;
  26636. this.skinning = false;
  26637. this.morphTargets = false;
  26638. this.morphNormals = false;
  26639. this.setValues(parameters);
  26640. }
  26641. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  26642. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  26643. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  26644. MeshNormalMaterial.prototype.copy = function (source) {
  26645. Material.prototype.copy.call(this, source);
  26646. this.bumpMap = source.bumpMap;
  26647. this.bumpScale = source.bumpScale;
  26648. this.normalMap = source.normalMap;
  26649. this.normalMapType = source.normalMapType;
  26650. this.normalScale.copy(source.normalScale);
  26651. this.displacementMap = source.displacementMap;
  26652. this.displacementScale = source.displacementScale;
  26653. this.displacementBias = source.displacementBias;
  26654. this.wireframe = source.wireframe;
  26655. this.wireframeLinewidth = source.wireframeLinewidth;
  26656. this.skinning = source.skinning;
  26657. this.morphTargets = source.morphTargets;
  26658. this.morphNormals = source.morphNormals;
  26659. return this;
  26660. };
  26661. /**
  26662. * parameters = {
  26663. * color: <hex>,
  26664. * opacity: <float>,
  26665. *
  26666. * map: new THREE.Texture( <Image> ),
  26667. *
  26668. * lightMap: new THREE.Texture( <Image> ),
  26669. * lightMapIntensity: <float>
  26670. *
  26671. * aoMap: new THREE.Texture( <Image> ),
  26672. * aoMapIntensity: <float>
  26673. *
  26674. * emissive: <hex>,
  26675. * emissiveIntensity: <float>
  26676. * emissiveMap: new THREE.Texture( <Image> ),
  26677. *
  26678. * specularMap: new THREE.Texture( <Image> ),
  26679. *
  26680. * alphaMap: new THREE.Texture( <Image> ),
  26681. *
  26682. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  26683. * combine: THREE.Multiply,
  26684. * reflectivity: <float>,
  26685. * refractionRatio: <float>,
  26686. *
  26687. * wireframe: <boolean>,
  26688. * wireframeLinewidth: <float>,
  26689. *
  26690. * skinning: <bool>,
  26691. * morphTargets: <bool>,
  26692. * morphNormals: <bool>
  26693. * }
  26694. */
  26695. function MeshLambertMaterial(parameters) {
  26696. Material.call(this);
  26697. this.type = 'MeshLambertMaterial';
  26698. this.color = new Color(0xffffff); // diffuse
  26699. this.map = null;
  26700. this.lightMap = null;
  26701. this.lightMapIntensity = 1.0;
  26702. this.aoMap = null;
  26703. this.aoMapIntensity = 1.0;
  26704. this.emissive = new Color(0x000000);
  26705. this.emissiveIntensity = 1.0;
  26706. this.emissiveMap = null;
  26707. this.specularMap = null;
  26708. this.alphaMap = null;
  26709. this.envMap = null;
  26710. this.combine = MultiplyOperation;
  26711. this.reflectivity = 1;
  26712. this.refractionRatio = 0.98;
  26713. this.wireframe = false;
  26714. this.wireframeLinewidth = 1;
  26715. this.wireframeLinecap = 'round';
  26716. this.wireframeLinejoin = 'round';
  26717. this.skinning = false;
  26718. this.morphTargets = false;
  26719. this.morphNormals = false;
  26720. this.setValues(parameters);
  26721. }
  26722. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  26723. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  26724. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  26725. MeshLambertMaterial.prototype.copy = function (source) {
  26726. Material.prototype.copy.call(this, source);
  26727. this.color.copy(source.color);
  26728. this.map = source.map;
  26729. this.lightMap = source.lightMap;
  26730. this.lightMapIntensity = source.lightMapIntensity;
  26731. this.aoMap = source.aoMap;
  26732. this.aoMapIntensity = source.aoMapIntensity;
  26733. this.emissive.copy(source.emissive);
  26734. this.emissiveMap = source.emissiveMap;
  26735. this.emissiveIntensity = source.emissiveIntensity;
  26736. this.specularMap = source.specularMap;
  26737. this.alphaMap = source.alphaMap;
  26738. this.envMap = source.envMap;
  26739. this.combine = source.combine;
  26740. this.reflectivity = source.reflectivity;
  26741. this.refractionRatio = source.refractionRatio;
  26742. this.wireframe = source.wireframe;
  26743. this.wireframeLinewidth = source.wireframeLinewidth;
  26744. this.wireframeLinecap = source.wireframeLinecap;
  26745. this.wireframeLinejoin = source.wireframeLinejoin;
  26746. this.skinning = source.skinning;
  26747. this.morphTargets = source.morphTargets;
  26748. this.morphNormals = source.morphNormals;
  26749. return this;
  26750. };
  26751. /**
  26752. * parameters = {
  26753. * color: <hex>,
  26754. * opacity: <float>,
  26755. *
  26756. * matcap: new THREE.Texture( <Image> ),
  26757. *
  26758. * map: new THREE.Texture( <Image> ),
  26759. *
  26760. * bumpMap: new THREE.Texture( <Image> ),
  26761. * bumpScale: <float>,
  26762. *
  26763. * normalMap: new THREE.Texture( <Image> ),
  26764. * normalMapType: THREE.TangentSpaceNormalMap,
  26765. * normalScale: <Vector2>,
  26766. *
  26767. * displacementMap: new THREE.Texture( <Image> ),
  26768. * displacementScale: <float>,
  26769. * displacementBias: <float>,
  26770. *
  26771. * alphaMap: new THREE.Texture( <Image> ),
  26772. *
  26773. * skinning: <bool>,
  26774. * morphTargets: <bool>,
  26775. * morphNormals: <bool>
  26776. * }
  26777. */
  26778. function MeshMatcapMaterial(parameters) {
  26779. Material.call(this);
  26780. this.defines = {
  26781. 'MATCAP': ''
  26782. };
  26783. this.type = 'MeshMatcapMaterial';
  26784. this.color = new Color(0xffffff); // diffuse
  26785. this.matcap = null;
  26786. this.map = null;
  26787. this.bumpMap = null;
  26788. this.bumpScale = 1;
  26789. this.normalMap = null;
  26790. this.normalMapType = TangentSpaceNormalMap;
  26791. this.normalScale = new Vector2(1, 1);
  26792. this.displacementMap = null;
  26793. this.displacementScale = 1;
  26794. this.displacementBias = 0;
  26795. this.alphaMap = null;
  26796. this.skinning = false;
  26797. this.morphTargets = false;
  26798. this.morphNormals = false;
  26799. this.setValues(parameters);
  26800. }
  26801. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  26802. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  26803. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  26804. MeshMatcapMaterial.prototype.copy = function (source) {
  26805. Material.prototype.copy.call(this, source);
  26806. this.defines = {
  26807. 'MATCAP': ''
  26808. };
  26809. this.color.copy(source.color);
  26810. this.matcap = source.matcap;
  26811. this.map = source.map;
  26812. this.bumpMap = source.bumpMap;
  26813. this.bumpScale = source.bumpScale;
  26814. this.normalMap = source.normalMap;
  26815. this.normalMapType = source.normalMapType;
  26816. this.normalScale.copy(source.normalScale);
  26817. this.displacementMap = source.displacementMap;
  26818. this.displacementScale = source.displacementScale;
  26819. this.displacementBias = source.displacementBias;
  26820. this.alphaMap = source.alphaMap;
  26821. this.skinning = source.skinning;
  26822. this.morphTargets = source.morphTargets;
  26823. this.morphNormals = source.morphNormals;
  26824. return this;
  26825. };
  26826. /**
  26827. * parameters = {
  26828. * color: <hex>,
  26829. * opacity: <float>,
  26830. *
  26831. * linewidth: <float>,
  26832. *
  26833. * scale: <float>,
  26834. * dashSize: <float>,
  26835. * gapSize: <float>
  26836. * }
  26837. */
  26838. function LineDashedMaterial(parameters) {
  26839. LineBasicMaterial.call(this);
  26840. this.type = 'LineDashedMaterial';
  26841. this.scale = 1;
  26842. this.dashSize = 3;
  26843. this.gapSize = 1;
  26844. this.setValues(parameters);
  26845. }
  26846. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  26847. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  26848. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  26849. LineDashedMaterial.prototype.copy = function (source) {
  26850. LineBasicMaterial.prototype.copy.call(this, source);
  26851. this.scale = source.scale;
  26852. this.dashSize = source.dashSize;
  26853. this.gapSize = source.gapSize;
  26854. return this;
  26855. };
  26856. var Materials = /*#__PURE__*/Object.freeze({
  26857. __proto__: null,
  26858. ShadowMaterial: ShadowMaterial,
  26859. SpriteMaterial: SpriteMaterial,
  26860. RawShaderMaterial: RawShaderMaterial,
  26861. ShaderMaterial: ShaderMaterial,
  26862. PointsMaterial: PointsMaterial,
  26863. MeshPhysicalMaterial: MeshPhysicalMaterial,
  26864. MeshStandardMaterial: MeshStandardMaterial,
  26865. MeshPhongMaterial: MeshPhongMaterial,
  26866. MeshToonMaterial: MeshToonMaterial,
  26867. MeshNormalMaterial: MeshNormalMaterial,
  26868. MeshLambertMaterial: MeshLambertMaterial,
  26869. MeshDepthMaterial: MeshDepthMaterial,
  26870. MeshDistanceMaterial: MeshDistanceMaterial,
  26871. MeshBasicMaterial: MeshBasicMaterial,
  26872. MeshMatcapMaterial: MeshMatcapMaterial,
  26873. LineDashedMaterial: LineDashedMaterial,
  26874. LineBasicMaterial: LineBasicMaterial,
  26875. Material: Material
  26876. });
  26877. var AnimationUtils = {
  26878. // same as Array.prototype.slice, but also works on typed arrays
  26879. arraySlice: function arraySlice(array, from, to) {
  26880. if (AnimationUtils.isTypedArray(array)) {
  26881. // in ios9 array.subarray(from, undefined) will return empty array
  26882. // but array.subarray(from) or array.subarray(from, len) is correct
  26883. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  26884. }
  26885. return array.slice(from, to);
  26886. },
  26887. // converts an array to a specific type
  26888. convertArray: function convertArray(array, type, forceClone) {
  26889. if (!array || // let 'undefined' and 'null' pass
  26890. !forceClone && array.constructor === type) return array;
  26891. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  26892. return new type(array); // create typed array
  26893. }
  26894. return Array.prototype.slice.call(array); // create Array
  26895. },
  26896. isTypedArray: function isTypedArray(object) {
  26897. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  26898. },
  26899. // returns an array by which times and values can be sorted
  26900. getKeyframeOrder: function getKeyframeOrder(times) {
  26901. function compareTime(i, j) {
  26902. return times[i] - times[j];
  26903. }
  26904. var n = times.length;
  26905. var result = new Array(n);
  26906. for (var i = 0; i !== n; ++i) {
  26907. result[i] = i;
  26908. }
  26909. result.sort(compareTime);
  26910. return result;
  26911. },
  26912. // uses the array previously returned by 'getKeyframeOrder' to sort data
  26913. sortedArray: function sortedArray(values, stride, order) {
  26914. var nValues = values.length;
  26915. var result = new values.constructor(nValues);
  26916. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  26917. var srcOffset = order[i] * stride;
  26918. for (var j = 0; j !== stride; ++j) {
  26919. result[dstOffset++] = values[srcOffset + j];
  26920. }
  26921. }
  26922. return result;
  26923. },
  26924. // function for parsing AOS keyframe formats
  26925. flattenJSON: function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  26926. var i = 1,
  26927. key = jsonKeys[0];
  26928. while (key !== undefined && key[valuePropertyName] === undefined) {
  26929. key = jsonKeys[i++];
  26930. }
  26931. if (key === undefined) return; // no data
  26932. var value = key[valuePropertyName];
  26933. if (value === undefined) return; // no data
  26934. if (Array.isArray(value)) {
  26935. do {
  26936. value = key[valuePropertyName];
  26937. if (value !== undefined) {
  26938. times.push(key.time);
  26939. values.push.apply(values, value); // push all elements
  26940. }
  26941. key = jsonKeys[i++];
  26942. } while (key !== undefined);
  26943. } else if (value.toArray !== undefined) {
  26944. // ...assume THREE.Math-ish
  26945. do {
  26946. value = key[valuePropertyName];
  26947. if (value !== undefined) {
  26948. times.push(key.time);
  26949. value.toArray(values, values.length);
  26950. }
  26951. key = jsonKeys[i++];
  26952. } while (key !== undefined);
  26953. } else {
  26954. // otherwise push as-is
  26955. do {
  26956. value = key[valuePropertyName];
  26957. if (value !== undefined) {
  26958. times.push(key.time);
  26959. values.push(value);
  26960. }
  26961. key = jsonKeys[i++];
  26962. } while (key !== undefined);
  26963. }
  26964. },
  26965. subclip: function subclip(sourceClip, name, startFrame, endFrame, fps) {
  26966. if (fps === void 0) {
  26967. fps = 30;
  26968. }
  26969. var clip = sourceClip.clone();
  26970. clip.name = name;
  26971. var tracks = [];
  26972. for (var i = 0; i < clip.tracks.length; ++i) {
  26973. var track = clip.tracks[i];
  26974. var valueSize = track.getValueSize();
  26975. var times = [];
  26976. var values = [];
  26977. for (var j = 0; j < track.times.length; ++j) {
  26978. var frame = track.times[j] * fps;
  26979. if (frame < startFrame || frame >= endFrame) continue;
  26980. times.push(track.times[j]);
  26981. for (var k = 0; k < valueSize; ++k) {
  26982. values.push(track.values[j * valueSize + k]);
  26983. }
  26984. }
  26985. if (times.length === 0) continue;
  26986. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  26987. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  26988. tracks.push(track);
  26989. }
  26990. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  26991. var minStartTime = Infinity;
  26992. for (var _i = 0; _i < clip.tracks.length; ++_i) {
  26993. if (minStartTime > clip.tracks[_i].times[0]) {
  26994. minStartTime = clip.tracks[_i].times[0];
  26995. }
  26996. } // shift all tracks such that clip begins at t=0
  26997. for (var _i2 = 0; _i2 < clip.tracks.length; ++_i2) {
  26998. clip.tracks[_i2].shift(-1 * minStartTime);
  26999. }
  27000. clip.resetDuration();
  27001. return clip;
  27002. },
  27003. makeClipAdditive: function makeClipAdditive(targetClip, referenceFrame, referenceClip, fps) {
  27004. if (referenceFrame === void 0) {
  27005. referenceFrame = 0;
  27006. }
  27007. if (referenceClip === void 0) {
  27008. referenceClip = targetClip;
  27009. }
  27010. if (fps === void 0) {
  27011. fps = 30;
  27012. }
  27013. if (fps <= 0) fps = 30;
  27014. var numTracks = referenceClip.tracks.length;
  27015. var referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  27016. var _loop = function _loop(i) {
  27017. var referenceTrack = referenceClip.tracks[i];
  27018. var referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  27019. if (referenceTrackType === 'bool' || referenceTrackType === 'string') return "continue"; // Find the track in the target clip whose name and type matches the reference track
  27020. var targetTrack = targetClip.tracks.find(function (track) {
  27021. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  27022. });
  27023. if (targetTrack === undefined) return "continue";
  27024. var referenceOffset = 0;
  27025. var referenceValueSize = referenceTrack.getValueSize();
  27026. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  27027. referenceOffset = referenceValueSize / 3;
  27028. }
  27029. var targetOffset = 0;
  27030. var targetValueSize = targetTrack.getValueSize();
  27031. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  27032. targetOffset = targetValueSize / 3;
  27033. }
  27034. var lastIndex = referenceTrack.times.length - 1;
  27035. var referenceValue = void 0; // Find the value to subtract out of the track
  27036. if (referenceTime <= referenceTrack.times[0]) {
  27037. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  27038. var startIndex = referenceOffset;
  27039. var endIndex = referenceValueSize - referenceOffset;
  27040. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  27041. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  27042. // Reference frame is after the last keyframe, so just use the last keyframe
  27043. var _startIndex = lastIndex * referenceValueSize + referenceOffset;
  27044. var _endIndex = _startIndex + referenceValueSize - referenceOffset;
  27045. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, _startIndex, _endIndex);
  27046. } else {
  27047. // Interpolate to the reference value
  27048. var interpolant = referenceTrack.createInterpolant();
  27049. var _startIndex2 = referenceOffset;
  27050. var _endIndex2 = referenceValueSize - referenceOffset;
  27051. interpolant.evaluate(referenceTime);
  27052. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, _startIndex2, _endIndex2);
  27053. } // Conjugate the quaternion
  27054. if (referenceTrackType === 'quaternion') {
  27055. var referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  27056. referenceQuat.toArray(referenceValue);
  27057. } // Subtract the reference value from all of the track values
  27058. var numTimes = targetTrack.times.length;
  27059. for (var j = 0; j < numTimes; ++j) {
  27060. var valueStart = j * targetValueSize + targetOffset;
  27061. if (referenceTrackType === 'quaternion') {
  27062. // Multiply the conjugate for quaternion track types
  27063. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  27064. } else {
  27065. var valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  27066. for (var k = 0; k < valueEnd; ++k) {
  27067. targetTrack.values[valueStart + k] -= referenceValue[k];
  27068. }
  27069. }
  27070. }
  27071. };
  27072. for (var i = 0; i < numTracks; ++i) {
  27073. var _ret = _loop(i);
  27074. if (_ret === "continue") continue;
  27075. }
  27076. targetClip.blendMode = AdditiveAnimationBlendMode;
  27077. return targetClip;
  27078. }
  27079. };
  27080. /**
  27081. * Abstract base class of interpolants over parametric samples.
  27082. *
  27083. * The parameter domain is one dimensional, typically the time or a path
  27084. * along a curve defined by the data.
  27085. *
  27086. * The sample values can have any dimensionality and derived classes may
  27087. * apply special interpretations to the data.
  27088. *
  27089. * This class provides the interval seek in a Template Method, deferring
  27090. * the actual interpolation to derived classes.
  27091. *
  27092. * Time complexity is O(1) for linear access crossing at most two points
  27093. * and O(log N) for random access, where N is the number of positions.
  27094. *
  27095. * References:
  27096. *
  27097. * http://www.oodesign.com/template-method-pattern.html
  27098. *
  27099. */
  27100. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27101. this.parameterPositions = parameterPositions;
  27102. this._cachedIndex = 0;
  27103. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  27104. this.sampleValues = sampleValues;
  27105. this.valueSize = sampleSize;
  27106. }
  27107. Object.assign(Interpolant.prototype, {
  27108. evaluate: function evaluate(t) {
  27109. var pp = this.parameterPositions;
  27110. var i1 = this._cachedIndex,
  27111. t1 = pp[i1],
  27112. t0 = pp[i1 - 1];
  27113. validate_interval: {
  27114. seek: {
  27115. var right;
  27116. linear_scan: {
  27117. //- See http://jsperf.com/comparison-to-undefined/3
  27118. //- slower code:
  27119. //-
  27120. //- if ( t >= t1 || t1 === undefined ) {
  27121. forward_scan: if (!(t < t1)) {
  27122. for (var giveUpAt = i1 + 2;;) {
  27123. if (t1 === undefined) {
  27124. if (t < t0) break forward_scan; // after end
  27125. i1 = pp.length;
  27126. this._cachedIndex = i1;
  27127. return this.afterEnd_(i1 - 1, t, t0);
  27128. }
  27129. if (i1 === giveUpAt) break; // this loop
  27130. t0 = t1;
  27131. t1 = pp[++i1];
  27132. if (t < t1) {
  27133. // we have arrived at the sought interval
  27134. break seek;
  27135. }
  27136. } // prepare binary search on the right side of the index
  27137. right = pp.length;
  27138. break linear_scan;
  27139. } //- slower code:
  27140. //- if ( t < t0 || t0 === undefined ) {
  27141. if (!(t >= t0)) {
  27142. // looping?
  27143. var t1global = pp[1];
  27144. if (t < t1global) {
  27145. i1 = 2; // + 1, using the scan for the details
  27146. t0 = t1global;
  27147. } // linear reverse scan
  27148. for (var _giveUpAt = i1 - 2;;) {
  27149. if (t0 === undefined) {
  27150. // before start
  27151. this._cachedIndex = 0;
  27152. return this.beforeStart_(0, t, t1);
  27153. }
  27154. if (i1 === _giveUpAt) break; // this loop
  27155. t1 = t0;
  27156. t0 = pp[--i1 - 1];
  27157. if (t >= t0) {
  27158. // we have arrived at the sought interval
  27159. break seek;
  27160. }
  27161. } // prepare binary search on the left side of the index
  27162. right = i1;
  27163. i1 = 0;
  27164. break linear_scan;
  27165. } // the interval is valid
  27166. break validate_interval;
  27167. } // linear scan
  27168. // binary search
  27169. while (i1 < right) {
  27170. var mid = i1 + right >>> 1;
  27171. if (t < pp[mid]) {
  27172. right = mid;
  27173. } else {
  27174. i1 = mid + 1;
  27175. }
  27176. }
  27177. t1 = pp[i1];
  27178. t0 = pp[i1 - 1]; // check boundary cases, again
  27179. if (t0 === undefined) {
  27180. this._cachedIndex = 0;
  27181. return this.beforeStart_(0, t, t1);
  27182. }
  27183. if (t1 === undefined) {
  27184. i1 = pp.length;
  27185. this._cachedIndex = i1;
  27186. return this.afterEnd_(i1 - 1, t0, t);
  27187. }
  27188. } // seek
  27189. this._cachedIndex = i1;
  27190. this.intervalChanged_(i1, t0, t1);
  27191. } // validate_interval
  27192. return this.interpolate_(i1, t0, t, t1);
  27193. },
  27194. settings: null,
  27195. // optional, subclass-specific settings structure
  27196. // Note: The indirection allows central control of many interpolants.
  27197. // --- Protected interface
  27198. DefaultSettings_: {},
  27199. getSettings_: function getSettings_() {
  27200. return this.settings || this.DefaultSettings_;
  27201. },
  27202. copySampleValue_: function copySampleValue_(index) {
  27203. // copies a sample value to the result buffer
  27204. var result = this.resultBuffer,
  27205. values = this.sampleValues,
  27206. stride = this.valueSize,
  27207. offset = index * stride;
  27208. for (var i = 0; i !== stride; ++i) {
  27209. result[i] = values[offset + i];
  27210. }
  27211. return result;
  27212. },
  27213. // Template methods for derived classes:
  27214. interpolate_: function interpolate_()
  27215. /* i1, t0, t, t1 */
  27216. {
  27217. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  27218. },
  27219. intervalChanged_: function intervalChanged_()
  27220. /* i1, t0, t1 */
  27221. {// empty
  27222. }
  27223. }); // DECLARE ALIAS AFTER assign prototype
  27224. Object.assign(Interpolant.prototype, {
  27225. //( 0, t, t0 ), returns this.resultBuffer
  27226. beforeStart_: Interpolant.prototype.copySampleValue_,
  27227. //( N-1, tN-1, t ), returns this.resultBuffer
  27228. afterEnd_: Interpolant.prototype.copySampleValue_
  27229. });
  27230. /**
  27231. * Fast and simple cubic spline interpolant.
  27232. *
  27233. * It was derived from a Hermitian construction setting the first derivative
  27234. * at each sample position to the linear slope between neighboring positions
  27235. * over their parameter interval.
  27236. */
  27237. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27238. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  27239. this._weightPrev = -0;
  27240. this._offsetPrev = -0;
  27241. this._weightNext = -0;
  27242. this._offsetNext = -0;
  27243. }
  27244. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  27245. constructor: CubicInterpolant,
  27246. DefaultSettings_: {
  27247. endingStart: ZeroCurvatureEnding,
  27248. endingEnd: ZeroCurvatureEnding
  27249. },
  27250. intervalChanged_: function intervalChanged_(i1, t0, t1) {
  27251. var pp = this.parameterPositions;
  27252. var iPrev = i1 - 2,
  27253. iNext = i1 + 1,
  27254. tPrev = pp[iPrev],
  27255. tNext = pp[iNext];
  27256. if (tPrev === undefined) {
  27257. switch (this.getSettings_().endingStart) {
  27258. case ZeroSlopeEnding:
  27259. // f'(t0) = 0
  27260. iPrev = i1;
  27261. tPrev = 2 * t0 - t1;
  27262. break;
  27263. case WrapAroundEnding:
  27264. // use the other end of the curve
  27265. iPrev = pp.length - 2;
  27266. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  27267. break;
  27268. default:
  27269. // ZeroCurvatureEnding
  27270. // f''(t0) = 0 a.k.a. Natural Spline
  27271. iPrev = i1;
  27272. tPrev = t1;
  27273. }
  27274. }
  27275. if (tNext === undefined) {
  27276. switch (this.getSettings_().endingEnd) {
  27277. case ZeroSlopeEnding:
  27278. // f'(tN) = 0
  27279. iNext = i1;
  27280. tNext = 2 * t1 - t0;
  27281. break;
  27282. case WrapAroundEnding:
  27283. // use the other end of the curve
  27284. iNext = 1;
  27285. tNext = t1 + pp[1] - pp[0];
  27286. break;
  27287. default:
  27288. // ZeroCurvatureEnding
  27289. // f''(tN) = 0, a.k.a. Natural Spline
  27290. iNext = i1 - 1;
  27291. tNext = t0;
  27292. }
  27293. }
  27294. var halfDt = (t1 - t0) * 0.5,
  27295. stride = this.valueSize;
  27296. this._weightPrev = halfDt / (t0 - tPrev);
  27297. this._weightNext = halfDt / (tNext - t1);
  27298. this._offsetPrev = iPrev * stride;
  27299. this._offsetNext = iNext * stride;
  27300. },
  27301. interpolate_: function interpolate_(i1, t0, t, t1) {
  27302. var result = this.resultBuffer,
  27303. values = this.sampleValues,
  27304. stride = this.valueSize,
  27305. o1 = i1 * stride,
  27306. o0 = o1 - stride,
  27307. oP = this._offsetPrev,
  27308. oN = this._offsetNext,
  27309. wP = this._weightPrev,
  27310. wN = this._weightNext,
  27311. p = (t - t0) / (t1 - t0),
  27312. pp = p * p,
  27313. ppp = pp * p; // evaluate polynomials
  27314. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  27315. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  27316. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  27317. var sN = wN * ppp - wN * pp; // combine data linearly
  27318. for (var i = 0; i !== stride; ++i) {
  27319. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  27320. }
  27321. return result;
  27322. }
  27323. });
  27324. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27325. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  27326. }
  27327. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  27328. constructor: LinearInterpolant,
  27329. interpolate_: function interpolate_(i1, t0, t, t1) {
  27330. var result = this.resultBuffer,
  27331. values = this.sampleValues,
  27332. stride = this.valueSize,
  27333. offset1 = i1 * stride,
  27334. offset0 = offset1 - stride,
  27335. weight1 = (t - t0) / (t1 - t0),
  27336. weight0 = 1 - weight1;
  27337. for (var i = 0; i !== stride; ++i) {
  27338. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  27339. }
  27340. return result;
  27341. }
  27342. });
  27343. /**
  27344. *
  27345. * Interpolant that evaluates to the sample value at the position preceeding
  27346. * the parameter.
  27347. */
  27348. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27349. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  27350. }
  27351. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  27352. constructor: DiscreteInterpolant,
  27353. interpolate_: function interpolate_(i1
  27354. /*, t0, t, t1 */
  27355. ) {
  27356. return this.copySampleValue_(i1 - 1);
  27357. }
  27358. });
  27359. function KeyframeTrack(name, times, values, interpolation) {
  27360. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  27361. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  27362. this.name = name;
  27363. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  27364. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  27365. this.setInterpolation(interpolation || this.DefaultInterpolation);
  27366. } // Static methods
  27367. Object.assign(KeyframeTrack, {
  27368. // Serialization (in static context, because of constructor invocation
  27369. // and automatic invocation of .toJSON):
  27370. toJSON: function toJSON(track) {
  27371. var trackType = track.constructor;
  27372. var json; // derived classes can define a static toJSON method
  27373. if (trackType.toJSON !== undefined) {
  27374. json = trackType.toJSON(track);
  27375. } else {
  27376. // by default, we assume the data can be serialized as-is
  27377. json = {
  27378. 'name': track.name,
  27379. 'times': AnimationUtils.convertArray(track.times, Array),
  27380. 'values': AnimationUtils.convertArray(track.values, Array)
  27381. };
  27382. var interpolation = track.getInterpolation();
  27383. if (interpolation !== track.DefaultInterpolation) {
  27384. json.interpolation = interpolation;
  27385. }
  27386. }
  27387. json.type = track.ValueTypeName; // mandatory
  27388. return json;
  27389. }
  27390. });
  27391. Object.assign(KeyframeTrack.prototype, {
  27392. constructor: KeyframeTrack,
  27393. TimeBufferType: Float32Array,
  27394. ValueBufferType: Float32Array,
  27395. DefaultInterpolation: InterpolateLinear,
  27396. InterpolantFactoryMethodDiscrete: function InterpolantFactoryMethodDiscrete(result) {
  27397. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  27398. },
  27399. InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
  27400. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  27401. },
  27402. InterpolantFactoryMethodSmooth: function InterpolantFactoryMethodSmooth(result) {
  27403. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  27404. },
  27405. setInterpolation: function setInterpolation(interpolation) {
  27406. var factoryMethod;
  27407. switch (interpolation) {
  27408. case InterpolateDiscrete:
  27409. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  27410. break;
  27411. case InterpolateLinear:
  27412. factoryMethod = this.InterpolantFactoryMethodLinear;
  27413. break;
  27414. case InterpolateSmooth:
  27415. factoryMethod = this.InterpolantFactoryMethodSmooth;
  27416. break;
  27417. }
  27418. if (factoryMethod === undefined) {
  27419. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  27420. if (this.createInterpolant === undefined) {
  27421. // fall back to default, unless the default itself is messed up
  27422. if (interpolation !== this.DefaultInterpolation) {
  27423. this.setInterpolation(this.DefaultInterpolation);
  27424. } else {
  27425. throw new Error(message); // fatal, in this case
  27426. }
  27427. }
  27428. console.warn('THREE.KeyframeTrack:', message);
  27429. return this;
  27430. }
  27431. this.createInterpolant = factoryMethod;
  27432. return this;
  27433. },
  27434. getInterpolation: function getInterpolation() {
  27435. switch (this.createInterpolant) {
  27436. case this.InterpolantFactoryMethodDiscrete:
  27437. return InterpolateDiscrete;
  27438. case this.InterpolantFactoryMethodLinear:
  27439. return InterpolateLinear;
  27440. case this.InterpolantFactoryMethodSmooth:
  27441. return InterpolateSmooth;
  27442. }
  27443. },
  27444. getValueSize: function getValueSize() {
  27445. return this.values.length / this.times.length;
  27446. },
  27447. // move all keyframes either forwards or backwards in time
  27448. shift: function shift(timeOffset) {
  27449. if (timeOffset !== 0.0) {
  27450. var times = this.times;
  27451. for (var i = 0, n = times.length; i !== n; ++i) {
  27452. times[i] += timeOffset;
  27453. }
  27454. }
  27455. return this;
  27456. },
  27457. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  27458. scale: function scale(timeScale) {
  27459. if (timeScale !== 1.0) {
  27460. var times = this.times;
  27461. for (var i = 0, n = times.length; i !== n; ++i) {
  27462. times[i] *= timeScale;
  27463. }
  27464. }
  27465. return this;
  27466. },
  27467. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  27468. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  27469. trim: function trim(startTime, endTime) {
  27470. var times = this.times,
  27471. nKeys = times.length;
  27472. var from = 0,
  27473. to = nKeys - 1;
  27474. while (from !== nKeys && times[from] < startTime) {
  27475. ++from;
  27476. }
  27477. while (to !== -1 && times[to] > endTime) {
  27478. --to;
  27479. }
  27480. ++to; // inclusive -> exclusive bound
  27481. if (from !== 0 || to !== nKeys) {
  27482. // empty tracks are forbidden, so keep at least one keyframe
  27483. if (from >= to) {
  27484. to = Math.max(to, 1);
  27485. from = to - 1;
  27486. }
  27487. var stride = this.getValueSize();
  27488. this.times = AnimationUtils.arraySlice(times, from, to);
  27489. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  27490. }
  27491. return this;
  27492. },
  27493. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  27494. validate: function validate() {
  27495. var valid = true;
  27496. var valueSize = this.getValueSize();
  27497. if (valueSize - Math.floor(valueSize) !== 0) {
  27498. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  27499. valid = false;
  27500. }
  27501. var times = this.times,
  27502. values = this.values,
  27503. nKeys = times.length;
  27504. if (nKeys === 0) {
  27505. console.error('THREE.KeyframeTrack: Track is empty.', this);
  27506. valid = false;
  27507. }
  27508. var prevTime = null;
  27509. for (var i = 0; i !== nKeys; i++) {
  27510. var currTime = times[i];
  27511. if (typeof currTime === 'number' && isNaN(currTime)) {
  27512. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  27513. valid = false;
  27514. break;
  27515. }
  27516. if (prevTime !== null && prevTime > currTime) {
  27517. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  27518. valid = false;
  27519. break;
  27520. }
  27521. prevTime = currTime;
  27522. }
  27523. if (values !== undefined) {
  27524. if (AnimationUtils.isTypedArray(values)) {
  27525. for (var _i = 0, n = values.length; _i !== n; ++_i) {
  27526. var value = values[_i];
  27527. if (isNaN(value)) {
  27528. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, _i, value);
  27529. valid = false;
  27530. break;
  27531. }
  27532. }
  27533. }
  27534. }
  27535. return valid;
  27536. },
  27537. // removes equivalent sequential keys as common in morph target sequences
  27538. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  27539. optimize: function optimize() {
  27540. // times or values may be shared with other tracks, so overwriting is unsafe
  27541. var times = AnimationUtils.arraySlice(this.times),
  27542. values = AnimationUtils.arraySlice(this.values),
  27543. stride = this.getValueSize(),
  27544. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  27545. lastIndex = times.length - 1;
  27546. var writeIndex = 1;
  27547. for (var i = 1; i < lastIndex; ++i) {
  27548. var keep = false;
  27549. var time = times[i];
  27550. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  27551. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  27552. if (!smoothInterpolation) {
  27553. // remove unnecessary keyframes same as their neighbors
  27554. var offset = i * stride,
  27555. offsetP = offset - stride,
  27556. offsetN = offset + stride;
  27557. for (var j = 0; j !== stride; ++j) {
  27558. var value = values[offset + j];
  27559. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  27560. keep = true;
  27561. break;
  27562. }
  27563. }
  27564. } else {
  27565. keep = true;
  27566. }
  27567. } // in-place compaction
  27568. if (keep) {
  27569. if (i !== writeIndex) {
  27570. times[writeIndex] = times[i];
  27571. var readOffset = i * stride,
  27572. writeOffset = writeIndex * stride;
  27573. for (var _j = 0; _j !== stride; ++_j) {
  27574. values[writeOffset + _j] = values[readOffset + _j];
  27575. }
  27576. }
  27577. ++writeIndex;
  27578. }
  27579. } // flush last keyframe (compaction looks ahead)
  27580. if (lastIndex > 0) {
  27581. times[writeIndex] = times[lastIndex];
  27582. for (var _readOffset = lastIndex * stride, _writeOffset = writeIndex * stride, _j2 = 0; _j2 !== stride; ++_j2) {
  27583. values[_writeOffset + _j2] = values[_readOffset + _j2];
  27584. }
  27585. ++writeIndex;
  27586. }
  27587. if (writeIndex !== times.length) {
  27588. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  27589. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  27590. } else {
  27591. this.times = times;
  27592. this.values = values;
  27593. }
  27594. return this;
  27595. },
  27596. clone: function clone() {
  27597. var times = AnimationUtils.arraySlice(this.times, 0);
  27598. var values = AnimationUtils.arraySlice(this.values, 0);
  27599. var TypedKeyframeTrack = this.constructor;
  27600. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  27601. track.createInterpolant = this.createInterpolant;
  27602. return track;
  27603. }
  27604. });
  27605. /**
  27606. * A Track of Boolean keyframe values.
  27607. */
  27608. function BooleanKeyframeTrack(name, times, values) {
  27609. KeyframeTrack.call(this, name, times, values);
  27610. }
  27611. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  27612. constructor: BooleanKeyframeTrack,
  27613. ValueTypeName: 'bool',
  27614. ValueBufferType: Array,
  27615. DefaultInterpolation: InterpolateDiscrete,
  27616. InterpolantFactoryMethodLinear: undefined,
  27617. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  27618. // representation of a single value and a custom interpolant that
  27619. // computes "firstValue ^ isOdd( index )".
  27620. });
  27621. /**
  27622. * A Track of keyframe values that represent color.
  27623. */
  27624. function ColorKeyframeTrack(name, times, values, interpolation) {
  27625. KeyframeTrack.call(this, name, times, values, interpolation);
  27626. }
  27627. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  27628. constructor: ColorKeyframeTrack,
  27629. ValueTypeName: 'color' // ValueBufferType is inherited
  27630. // DefaultInterpolation is inherited
  27631. // Note: Very basic implementation and nothing special yet.
  27632. // However, this is the place for color space parameterization.
  27633. });
  27634. /**
  27635. * A Track of numeric keyframe values.
  27636. */
  27637. function NumberKeyframeTrack(name, times, values, interpolation) {
  27638. KeyframeTrack.call(this, name, times, values, interpolation);
  27639. }
  27640. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  27641. constructor: NumberKeyframeTrack,
  27642. ValueTypeName: 'number' // ValueBufferType is inherited
  27643. // DefaultInterpolation is inherited
  27644. });
  27645. /**
  27646. * Spherical linear unit quaternion interpolant.
  27647. */
  27648. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27649. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  27650. }
  27651. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  27652. constructor: QuaternionLinearInterpolant,
  27653. interpolate_: function interpolate_(i1, t0, t, t1) {
  27654. var result = this.resultBuffer,
  27655. values = this.sampleValues,
  27656. stride = this.valueSize,
  27657. alpha = (t - t0) / (t1 - t0);
  27658. var offset = i1 * stride;
  27659. for (var end = offset + stride; offset !== end; offset += 4) {
  27660. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  27661. }
  27662. return result;
  27663. }
  27664. });
  27665. /**
  27666. * A Track of quaternion keyframe values.
  27667. */
  27668. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  27669. KeyframeTrack.call(this, name, times, values, interpolation);
  27670. }
  27671. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  27672. constructor: QuaternionKeyframeTrack,
  27673. ValueTypeName: 'quaternion',
  27674. // ValueBufferType is inherited
  27675. DefaultInterpolation: InterpolateLinear,
  27676. InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
  27677. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  27678. },
  27679. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  27680. });
  27681. /**
  27682. * A Track that interpolates Strings
  27683. */
  27684. function StringKeyframeTrack(name, times, values, interpolation) {
  27685. KeyframeTrack.call(this, name, times, values, interpolation);
  27686. }
  27687. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  27688. constructor: StringKeyframeTrack,
  27689. ValueTypeName: 'string',
  27690. ValueBufferType: Array,
  27691. DefaultInterpolation: InterpolateDiscrete,
  27692. InterpolantFactoryMethodLinear: undefined,
  27693. InterpolantFactoryMethodSmooth: undefined
  27694. });
  27695. /**
  27696. * A Track of vectored keyframe values.
  27697. */
  27698. function VectorKeyframeTrack(name, times, values, interpolation) {
  27699. KeyframeTrack.call(this, name, times, values, interpolation);
  27700. }
  27701. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  27702. constructor: VectorKeyframeTrack,
  27703. ValueTypeName: 'vector' // ValueBufferType is inherited
  27704. // DefaultInterpolation is inherited
  27705. });
  27706. function AnimationClip(name, duration, tracks, blendMode) {
  27707. this.name = name;
  27708. this.tracks = tracks;
  27709. this.duration = duration !== undefined ? duration : -1;
  27710. this.blendMode = blendMode !== undefined ? blendMode : NormalAnimationBlendMode;
  27711. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  27712. if (this.duration < 0) {
  27713. this.resetDuration();
  27714. }
  27715. }
  27716. function getTrackTypeForValueTypeName(typeName) {
  27717. switch (typeName.toLowerCase()) {
  27718. case 'scalar':
  27719. case 'double':
  27720. case 'float':
  27721. case 'number':
  27722. case 'integer':
  27723. return NumberKeyframeTrack;
  27724. case 'vector':
  27725. case 'vector2':
  27726. case 'vector3':
  27727. case 'vector4':
  27728. return VectorKeyframeTrack;
  27729. case 'color':
  27730. return ColorKeyframeTrack;
  27731. case 'quaternion':
  27732. return QuaternionKeyframeTrack;
  27733. case 'bool':
  27734. case 'boolean':
  27735. return BooleanKeyframeTrack;
  27736. case 'string':
  27737. return StringKeyframeTrack;
  27738. }
  27739. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  27740. }
  27741. function parseKeyframeTrack(json) {
  27742. if (json.type === undefined) {
  27743. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  27744. }
  27745. var trackType = getTrackTypeForValueTypeName(json.type);
  27746. if (json.times === undefined) {
  27747. var times = [],
  27748. values = [];
  27749. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  27750. json.times = times;
  27751. json.values = values;
  27752. } // derived classes can define a static parse method
  27753. if (trackType.parse !== undefined) {
  27754. return trackType.parse(json);
  27755. } else {
  27756. // by default, we assume a constructor compatible with the base
  27757. return new trackType(json.name, json.times, json.values, json.interpolation);
  27758. }
  27759. }
  27760. Object.assign(AnimationClip, {
  27761. parse: function parse(json) {
  27762. var tracks = [],
  27763. jsonTracks = json.tracks,
  27764. frameTime = 1.0 / (json.fps || 1.0);
  27765. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  27766. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  27767. }
  27768. var clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
  27769. clip.uuid = json.uuid;
  27770. return clip;
  27771. },
  27772. toJSON: function toJSON(clip) {
  27773. var tracks = [],
  27774. clipTracks = clip.tracks;
  27775. var json = {
  27776. 'name': clip.name,
  27777. 'duration': clip.duration,
  27778. 'tracks': tracks,
  27779. 'uuid': clip.uuid,
  27780. 'blendMode': clip.blendMode
  27781. };
  27782. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  27783. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  27784. }
  27785. return json;
  27786. },
  27787. CreateFromMorphTargetSequence: function CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  27788. var numMorphTargets = morphTargetSequence.length;
  27789. var tracks = [];
  27790. for (var i = 0; i < numMorphTargets; i++) {
  27791. var times = [];
  27792. var values = [];
  27793. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  27794. values.push(0, 1, 0);
  27795. var order = AnimationUtils.getKeyframeOrder(times);
  27796. times = AnimationUtils.sortedArray(times, 1, order);
  27797. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  27798. // last frame as well for perfect loop.
  27799. if (!noLoop && times[0] === 0) {
  27800. times.push(numMorphTargets);
  27801. values.push(values[0]);
  27802. }
  27803. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  27804. }
  27805. return new AnimationClip(name, -1, tracks);
  27806. },
  27807. findByName: function findByName(objectOrClipArray, name) {
  27808. var clipArray = objectOrClipArray;
  27809. if (!Array.isArray(objectOrClipArray)) {
  27810. var o = objectOrClipArray;
  27811. clipArray = o.geometry && o.geometry.animations || o.animations;
  27812. }
  27813. for (var i = 0; i < clipArray.length; i++) {
  27814. if (clipArray[i].name === name) {
  27815. return clipArray[i];
  27816. }
  27817. }
  27818. return null;
  27819. },
  27820. CreateClipsFromMorphTargetSequences: function CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  27821. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  27822. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  27823. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  27824. // patterns like Walk_001, Walk_002, Run_001, Run_002
  27825. for (var i = 0, il = morphTargets.length; i < il; i++) {
  27826. var morphTarget = morphTargets[i];
  27827. var parts = morphTarget.name.match(pattern);
  27828. if (parts && parts.length > 1) {
  27829. var name = parts[1];
  27830. var animationMorphTargets = animationToMorphTargets[name];
  27831. if (!animationMorphTargets) {
  27832. animationToMorphTargets[name] = animationMorphTargets = [];
  27833. }
  27834. animationMorphTargets.push(morphTarget);
  27835. }
  27836. }
  27837. var clips = [];
  27838. for (var _name in animationToMorphTargets) {
  27839. clips.push(AnimationClip.CreateFromMorphTargetSequence(_name, animationToMorphTargets[_name], fps, noLoop));
  27840. }
  27841. return clips;
  27842. },
  27843. // parse the animation.hierarchy format
  27844. parseAnimation: function parseAnimation(animation, bones) {
  27845. if (!animation) {
  27846. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  27847. return null;
  27848. }
  27849. var addNonemptyTrack = function addNonemptyTrack(trackType, trackName, animationKeys, propertyName, destTracks) {
  27850. // only return track if there are actually keys.
  27851. if (animationKeys.length !== 0) {
  27852. var times = [];
  27853. var values = [];
  27854. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  27855. if (times.length !== 0) {
  27856. destTracks.push(new trackType(trackName, times, values));
  27857. }
  27858. }
  27859. };
  27860. var tracks = [];
  27861. var clipName = animation.name || 'default';
  27862. var fps = animation.fps || 30;
  27863. var blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  27864. var duration = animation.length || -1;
  27865. var hierarchyTracks = animation.hierarchy || [];
  27866. for (var h = 0; h < hierarchyTracks.length; h++) {
  27867. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  27868. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  27869. if (animationKeys[0].morphTargets) {
  27870. // figure out all morph targets used in this track
  27871. var morphTargetNames = {};
  27872. var k = void 0;
  27873. for (k = 0; k < animationKeys.length; k++) {
  27874. if (animationKeys[k].morphTargets) {
  27875. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  27876. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  27877. }
  27878. }
  27879. } // create a track for each morph target with all zero
  27880. // morphTargetInfluences except for the keys in which
  27881. // the morphTarget is named.
  27882. for (var morphTargetName in morphTargetNames) {
  27883. var times = [];
  27884. var values = [];
  27885. for (var _m = 0; _m !== animationKeys[k].morphTargets.length; ++_m) {
  27886. var animationKey = animationKeys[k];
  27887. times.push(animationKey.time);
  27888. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  27889. }
  27890. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  27891. }
  27892. duration = morphTargetNames.length * (fps || 1.0);
  27893. } else {
  27894. // ...assume skeletal animation
  27895. var boneName = '.bones[' + bones[h].name + ']';
  27896. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  27897. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  27898. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  27899. }
  27900. }
  27901. if (tracks.length === 0) {
  27902. return null;
  27903. }
  27904. var clip = new AnimationClip(clipName, duration, tracks, blendMode);
  27905. return clip;
  27906. }
  27907. });
  27908. Object.assign(AnimationClip.prototype, {
  27909. resetDuration: function resetDuration() {
  27910. var tracks = this.tracks;
  27911. var duration = 0;
  27912. for (var i = 0, n = tracks.length; i !== n; ++i) {
  27913. var track = this.tracks[i];
  27914. duration = Math.max(duration, track.times[track.times.length - 1]);
  27915. }
  27916. this.duration = duration;
  27917. return this;
  27918. },
  27919. trim: function trim() {
  27920. for (var i = 0; i < this.tracks.length; i++) {
  27921. this.tracks[i].trim(0, this.duration);
  27922. }
  27923. return this;
  27924. },
  27925. validate: function validate() {
  27926. var valid = true;
  27927. for (var i = 0; i < this.tracks.length; i++) {
  27928. valid = valid && this.tracks[i].validate();
  27929. }
  27930. return valid;
  27931. },
  27932. optimize: function optimize() {
  27933. for (var i = 0; i < this.tracks.length; i++) {
  27934. this.tracks[i].optimize();
  27935. }
  27936. return this;
  27937. },
  27938. clone: function clone() {
  27939. var tracks = [];
  27940. for (var i = 0; i < this.tracks.length; i++) {
  27941. tracks.push(this.tracks[i].clone());
  27942. }
  27943. return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
  27944. },
  27945. toJSON: function toJSON() {
  27946. return AnimationClip.toJSON(this);
  27947. }
  27948. });
  27949. var Cache = {
  27950. enabled: false,
  27951. files: {},
  27952. add: function add(key, file) {
  27953. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  27954. this.files[key] = file;
  27955. },
  27956. get: function get(key) {
  27957. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  27958. return this.files[key];
  27959. },
  27960. remove: function remove(key) {
  27961. delete this.files[key];
  27962. },
  27963. clear: function clear() {
  27964. this.files = {};
  27965. }
  27966. };
  27967. function LoadingManager(onLoad, onProgress, onError) {
  27968. var scope = this;
  27969. var isLoading = false;
  27970. var itemsLoaded = 0;
  27971. var itemsTotal = 0;
  27972. var urlModifier = undefined;
  27973. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  27974. // in the constructor
  27975. this.onStart = undefined;
  27976. this.onLoad = onLoad;
  27977. this.onProgress = onProgress;
  27978. this.onError = onError;
  27979. this.itemStart = function (url) {
  27980. itemsTotal++;
  27981. if (isLoading === false) {
  27982. if (scope.onStart !== undefined) {
  27983. scope.onStart(url, itemsLoaded, itemsTotal);
  27984. }
  27985. }
  27986. isLoading = true;
  27987. };
  27988. this.itemEnd = function (url) {
  27989. itemsLoaded++;
  27990. if (scope.onProgress !== undefined) {
  27991. scope.onProgress(url, itemsLoaded, itemsTotal);
  27992. }
  27993. if (itemsLoaded === itemsTotal) {
  27994. isLoading = false;
  27995. if (scope.onLoad !== undefined) {
  27996. scope.onLoad();
  27997. }
  27998. }
  27999. };
  28000. this.itemError = function (url) {
  28001. if (scope.onError !== undefined) {
  28002. scope.onError(url);
  28003. }
  28004. };
  28005. this.resolveURL = function (url) {
  28006. if (urlModifier) {
  28007. return urlModifier(url);
  28008. }
  28009. return url;
  28010. };
  28011. this.setURLModifier = function (transform) {
  28012. urlModifier = transform;
  28013. return this;
  28014. };
  28015. this.addHandler = function (regex, loader) {
  28016. handlers.push(regex, loader);
  28017. return this;
  28018. };
  28019. this.removeHandler = function (regex) {
  28020. var index = handlers.indexOf(regex);
  28021. if (index !== -1) {
  28022. handlers.splice(index, 2);
  28023. }
  28024. return this;
  28025. };
  28026. this.getHandler = function (file) {
  28027. for (var i = 0, l = handlers.length; i < l; i += 2) {
  28028. var regex = handlers[i];
  28029. var loader = handlers[i + 1];
  28030. if (regex.global) regex.lastIndex = 0; // see #17920
  28031. if (regex.test(file)) {
  28032. return loader;
  28033. }
  28034. }
  28035. return null;
  28036. };
  28037. }
  28038. var DefaultLoadingManager = new LoadingManager();
  28039. function Loader(manager) {
  28040. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  28041. this.crossOrigin = 'anonymous';
  28042. this.withCredentials = false;
  28043. this.path = '';
  28044. this.resourcePath = '';
  28045. this.requestHeader = {};
  28046. }
  28047. Object.assign(Loader.prototype, {
  28048. load: function load()
  28049. /* url, onLoad, onProgress, onError */
  28050. {},
  28051. loadAsync: function loadAsync(url, onProgress) {
  28052. var scope = this;
  28053. return new Promise(function (resolve, reject) {
  28054. scope.load(url, resolve, onProgress, reject);
  28055. });
  28056. },
  28057. parse: function parse()
  28058. /* data */
  28059. {},
  28060. setCrossOrigin: function setCrossOrigin(crossOrigin) {
  28061. this.crossOrigin = crossOrigin;
  28062. return this;
  28063. },
  28064. setWithCredentials: function setWithCredentials(value) {
  28065. this.withCredentials = value;
  28066. return this;
  28067. },
  28068. setPath: function setPath(path) {
  28069. this.path = path;
  28070. return this;
  28071. },
  28072. setResourcePath: function setResourcePath(resourcePath) {
  28073. this.resourcePath = resourcePath;
  28074. return this;
  28075. },
  28076. setRequestHeader: function setRequestHeader(requestHeader) {
  28077. this.requestHeader = requestHeader;
  28078. return this;
  28079. }
  28080. });
  28081. var loading = {};
  28082. function FileLoader(manager) {
  28083. Loader.call(this, manager);
  28084. }
  28085. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28086. constructor: FileLoader,
  28087. load: function load(url, onLoad, onProgress, onError) {
  28088. if (url === undefined) url = '';
  28089. if (this.path !== undefined) url = this.path + url;
  28090. url = this.manager.resolveURL(url);
  28091. var scope = this;
  28092. var cached = Cache.get(url);
  28093. if (cached !== undefined) {
  28094. scope.manager.itemStart(url);
  28095. setTimeout(function () {
  28096. if (onLoad) onLoad(cached);
  28097. scope.manager.itemEnd(url);
  28098. }, 0);
  28099. return cached;
  28100. } // Check if request is duplicate
  28101. if (loading[url] !== undefined) {
  28102. loading[url].push({
  28103. onLoad: onLoad,
  28104. onProgress: onProgress,
  28105. onError: onError
  28106. });
  28107. return;
  28108. } // Check for data: URI
  28109. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  28110. var dataUriRegexResult = url.match(dataUriRegex);
  28111. var request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  28112. if (dataUriRegexResult) {
  28113. var mimeType = dataUriRegexResult[1];
  28114. var isBase64 = !!dataUriRegexResult[2];
  28115. var data = dataUriRegexResult[3];
  28116. data = decodeURIComponent(data);
  28117. if (isBase64) data = atob(data);
  28118. try {
  28119. var response;
  28120. var responseType = (this.responseType || '').toLowerCase();
  28121. switch (responseType) {
  28122. case 'arraybuffer':
  28123. case 'blob':
  28124. var view = new Uint8Array(data.length);
  28125. for (var i = 0; i < data.length; i++) {
  28126. view[i] = data.charCodeAt(i);
  28127. }
  28128. if (responseType === 'blob') {
  28129. response = new Blob([view.buffer], {
  28130. type: mimeType
  28131. });
  28132. } else {
  28133. response = view.buffer;
  28134. }
  28135. break;
  28136. case 'document':
  28137. var parser = new DOMParser();
  28138. response = parser.parseFromString(data, mimeType);
  28139. break;
  28140. case 'json':
  28141. response = JSON.parse(data);
  28142. break;
  28143. default:
  28144. // 'text' or other
  28145. response = data;
  28146. break;
  28147. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  28148. setTimeout(function () {
  28149. if (onLoad) onLoad(response);
  28150. scope.manager.itemEnd(url);
  28151. }, 0);
  28152. } catch (error) {
  28153. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  28154. setTimeout(function () {
  28155. if (onError) onError(error);
  28156. scope.manager.itemError(url);
  28157. scope.manager.itemEnd(url);
  28158. }, 0);
  28159. }
  28160. } else {
  28161. // Initialise array for duplicate requests
  28162. loading[url] = [];
  28163. loading[url].push({
  28164. onLoad: onLoad,
  28165. onProgress: onProgress,
  28166. onError: onError
  28167. });
  28168. request = new XMLHttpRequest();
  28169. request.open('GET', url, true);
  28170. request.addEventListener('load', function (event) {
  28171. var response = this.response;
  28172. var callbacks = loading[url];
  28173. delete loading[url];
  28174. if (this.status === 200 || this.status === 0) {
  28175. // Some browsers return HTTP Status 0 when using non-http protocol
  28176. // e.g. 'file://' or 'data://'. Handle as success.
  28177. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  28178. // error response bodies as proper responses to requests.
  28179. Cache.add(url, response);
  28180. for (var _i = 0, il = callbacks.length; _i < il; _i++) {
  28181. var callback = callbacks[_i];
  28182. if (callback.onLoad) callback.onLoad(response);
  28183. }
  28184. scope.manager.itemEnd(url);
  28185. } else {
  28186. for (var _i2 = 0, _il = callbacks.length; _i2 < _il; _i2++) {
  28187. var _callback = callbacks[_i2];
  28188. if (_callback.onError) _callback.onError(event);
  28189. }
  28190. scope.manager.itemError(url);
  28191. scope.manager.itemEnd(url);
  28192. }
  28193. }, false);
  28194. request.addEventListener('progress', function (event) {
  28195. var callbacks = loading[url];
  28196. for (var _i3 = 0, il = callbacks.length; _i3 < il; _i3++) {
  28197. var callback = callbacks[_i3];
  28198. if (callback.onProgress) callback.onProgress(event);
  28199. }
  28200. }, false);
  28201. request.addEventListener('error', function (event) {
  28202. var callbacks = loading[url];
  28203. delete loading[url];
  28204. for (var _i4 = 0, il = callbacks.length; _i4 < il; _i4++) {
  28205. var callback = callbacks[_i4];
  28206. if (callback.onError) callback.onError(event);
  28207. }
  28208. scope.manager.itemError(url);
  28209. scope.manager.itemEnd(url);
  28210. }, false);
  28211. request.addEventListener('abort', function (event) {
  28212. var callbacks = loading[url];
  28213. delete loading[url];
  28214. for (var _i5 = 0, il = callbacks.length; _i5 < il; _i5++) {
  28215. var callback = callbacks[_i5];
  28216. if (callback.onError) callback.onError(event);
  28217. }
  28218. scope.manager.itemError(url);
  28219. scope.manager.itemEnd(url);
  28220. }, false);
  28221. if (this.responseType !== undefined) request.responseType = this.responseType;
  28222. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  28223. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  28224. for (var header in this.requestHeader) {
  28225. request.setRequestHeader(header, this.requestHeader[header]);
  28226. }
  28227. request.send(null);
  28228. }
  28229. scope.manager.itemStart(url);
  28230. return request;
  28231. },
  28232. setResponseType: function setResponseType(value) {
  28233. this.responseType = value;
  28234. return this;
  28235. },
  28236. setMimeType: function setMimeType(value) {
  28237. this.mimeType = value;
  28238. return this;
  28239. }
  28240. });
  28241. function AnimationLoader(manager) {
  28242. Loader.call(this, manager);
  28243. }
  28244. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28245. constructor: AnimationLoader,
  28246. load: function load(url, onLoad, onProgress, onError) {
  28247. var scope = this;
  28248. var loader = new FileLoader(scope.manager);
  28249. loader.setPath(scope.path);
  28250. loader.setRequestHeader(scope.requestHeader);
  28251. loader.setWithCredentials(scope.withCredentials);
  28252. loader.load(url, function (text) {
  28253. try {
  28254. onLoad(scope.parse(JSON.parse(text)));
  28255. } catch (e) {
  28256. if (onError) {
  28257. onError(e);
  28258. } else {
  28259. console.error(e);
  28260. }
  28261. scope.manager.itemError(url);
  28262. }
  28263. }, onProgress, onError);
  28264. },
  28265. parse: function parse(json) {
  28266. var animations = [];
  28267. for (var i = 0; i < json.length; i++) {
  28268. var clip = AnimationClip.parse(json[i]);
  28269. animations.push(clip);
  28270. }
  28271. return animations;
  28272. }
  28273. });
  28274. /**
  28275. * Abstract Base class to block based textures loader (dds, pvr, ...)
  28276. *
  28277. * Sub classes have to implement the parse() method which will be used in load().
  28278. */
  28279. function CompressedTextureLoader(manager) {
  28280. Loader.call(this, manager);
  28281. }
  28282. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28283. constructor: CompressedTextureLoader,
  28284. load: function load(url, onLoad, onProgress, onError) {
  28285. var scope = this;
  28286. var images = [];
  28287. var texture = new CompressedTexture();
  28288. texture.image = images;
  28289. var loader = new FileLoader(this.manager);
  28290. loader.setPath(this.path);
  28291. loader.setResponseType('arraybuffer');
  28292. loader.setRequestHeader(this.requestHeader);
  28293. loader.setWithCredentials(scope.withCredentials);
  28294. var loaded = 0;
  28295. function loadTexture(i) {
  28296. loader.load(url[i], function (buffer) {
  28297. var texDatas = scope.parse(buffer, true);
  28298. images[i] = {
  28299. width: texDatas.width,
  28300. height: texDatas.height,
  28301. format: texDatas.format,
  28302. mipmaps: texDatas.mipmaps
  28303. };
  28304. loaded += 1;
  28305. if (loaded === 6) {
  28306. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  28307. texture.format = texDatas.format;
  28308. texture.needsUpdate = true;
  28309. if (onLoad) onLoad(texture);
  28310. }
  28311. }, onProgress, onError);
  28312. }
  28313. if (Array.isArray(url)) {
  28314. for (var i = 0, il = url.length; i < il; ++i) {
  28315. loadTexture(i);
  28316. }
  28317. } else {
  28318. // compressed cubemap texture stored in a single DDS file
  28319. loader.load(url, function (buffer) {
  28320. var texDatas = scope.parse(buffer, true);
  28321. if (texDatas.isCubemap) {
  28322. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  28323. for (var f = 0; f < faces; f++) {
  28324. images[f] = {
  28325. mipmaps: []
  28326. };
  28327. for (var _i = 0; _i < texDatas.mipmapCount; _i++) {
  28328. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + _i]);
  28329. images[f].format = texDatas.format;
  28330. images[f].width = texDatas.width;
  28331. images[f].height = texDatas.height;
  28332. }
  28333. }
  28334. } else {
  28335. texture.image.width = texDatas.width;
  28336. texture.image.height = texDatas.height;
  28337. texture.mipmaps = texDatas.mipmaps;
  28338. }
  28339. if (texDatas.mipmapCount === 1) {
  28340. texture.minFilter = LinearFilter;
  28341. }
  28342. texture.format = texDatas.format;
  28343. texture.needsUpdate = true;
  28344. if (onLoad) onLoad(texture);
  28345. }, onProgress, onError);
  28346. }
  28347. return texture;
  28348. }
  28349. });
  28350. function ImageLoader(manager) {
  28351. Loader.call(this, manager);
  28352. }
  28353. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28354. constructor: ImageLoader,
  28355. load: function load(url, onLoad, onProgress, onError) {
  28356. if (this.path !== undefined) url = this.path + url;
  28357. url = this.manager.resolveURL(url);
  28358. var scope = this;
  28359. var cached = Cache.get(url);
  28360. if (cached !== undefined) {
  28361. scope.manager.itemStart(url);
  28362. setTimeout(function () {
  28363. if (onLoad) onLoad(cached);
  28364. scope.manager.itemEnd(url);
  28365. }, 0);
  28366. return cached;
  28367. }
  28368. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  28369. function onImageLoad() {
  28370. image.removeEventListener('load', onImageLoad, false);
  28371. image.removeEventListener('error', onImageError, false);
  28372. Cache.add(url, this);
  28373. if (onLoad) onLoad(this);
  28374. scope.manager.itemEnd(url);
  28375. }
  28376. function onImageError(event) {
  28377. image.removeEventListener('load', onImageLoad, false);
  28378. image.removeEventListener('error', onImageError, false);
  28379. if (onError) onError(event);
  28380. scope.manager.itemError(url);
  28381. scope.manager.itemEnd(url);
  28382. }
  28383. image.addEventListener('load', onImageLoad, false);
  28384. image.addEventListener('error', onImageError, false);
  28385. if (url.substr(0, 5) !== 'data:') {
  28386. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  28387. }
  28388. scope.manager.itemStart(url);
  28389. image.src = url;
  28390. return image;
  28391. }
  28392. });
  28393. function CubeTextureLoader(manager) {
  28394. Loader.call(this, manager);
  28395. }
  28396. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28397. constructor: CubeTextureLoader,
  28398. load: function load(urls, onLoad, onProgress, onError) {
  28399. var texture = new CubeTexture();
  28400. var loader = new ImageLoader(this.manager);
  28401. loader.setCrossOrigin(this.crossOrigin);
  28402. loader.setPath(this.path);
  28403. var loaded = 0;
  28404. function loadTexture(i) {
  28405. loader.load(urls[i], function (image) {
  28406. texture.images[i] = image;
  28407. loaded++;
  28408. if (loaded === 6) {
  28409. texture.needsUpdate = true;
  28410. if (onLoad) onLoad(texture);
  28411. }
  28412. }, undefined, onError);
  28413. }
  28414. for (var i = 0; i < urls.length; ++i) {
  28415. loadTexture(i);
  28416. }
  28417. return texture;
  28418. }
  28419. });
  28420. /**
  28421. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  28422. *
  28423. * Sub classes have to implement the parse() method which will be used in load().
  28424. */
  28425. function DataTextureLoader(manager) {
  28426. Loader.call(this, manager);
  28427. }
  28428. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28429. constructor: DataTextureLoader,
  28430. load: function load(url, onLoad, onProgress, onError) {
  28431. var scope = this;
  28432. var texture = new DataTexture();
  28433. var loader = new FileLoader(this.manager);
  28434. loader.setResponseType('arraybuffer');
  28435. loader.setRequestHeader(this.requestHeader);
  28436. loader.setPath(this.path);
  28437. loader.setWithCredentials(scope.withCredentials);
  28438. loader.load(url, function (buffer) {
  28439. var texData = scope.parse(buffer);
  28440. if (!texData) return;
  28441. if (texData.image !== undefined) {
  28442. texture.image = texData.image;
  28443. } else if (texData.data !== undefined) {
  28444. texture.image.width = texData.width;
  28445. texture.image.height = texData.height;
  28446. texture.image.data = texData.data;
  28447. }
  28448. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  28449. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  28450. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  28451. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  28452. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  28453. if (texData.format !== undefined) {
  28454. texture.format = texData.format;
  28455. }
  28456. if (texData.type !== undefined) {
  28457. texture.type = texData.type;
  28458. }
  28459. if (texData.mipmaps !== undefined) {
  28460. texture.mipmaps = texData.mipmaps;
  28461. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  28462. }
  28463. if (texData.mipmapCount === 1) {
  28464. texture.minFilter = LinearFilter;
  28465. }
  28466. texture.needsUpdate = true;
  28467. if (onLoad) onLoad(texture, texData);
  28468. }, onProgress, onError);
  28469. return texture;
  28470. }
  28471. });
  28472. function TextureLoader(manager) {
  28473. Loader.call(this, manager);
  28474. }
  28475. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  28476. constructor: TextureLoader,
  28477. load: function load(url, onLoad, onProgress, onError) {
  28478. var texture = new Texture();
  28479. var loader = new ImageLoader(this.manager);
  28480. loader.setCrossOrigin(this.crossOrigin);
  28481. loader.setPath(this.path);
  28482. loader.load(url, function (image) {
  28483. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  28484. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  28485. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  28486. texture.needsUpdate = true;
  28487. if (onLoad !== undefined) {
  28488. onLoad(texture);
  28489. }
  28490. }, onProgress, onError);
  28491. return texture;
  28492. }
  28493. });
  28494. /**
  28495. * Extensible curve object.
  28496. *
  28497. * Some common of curve methods:
  28498. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  28499. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  28500. * .getPoints(), .getSpacedPoints()
  28501. * .getLength()
  28502. * .updateArcLengths()
  28503. *
  28504. * This following curves inherit from THREE.Curve:
  28505. *
  28506. * -- 2D curves --
  28507. * THREE.ArcCurve
  28508. * THREE.CubicBezierCurve
  28509. * THREE.EllipseCurve
  28510. * THREE.LineCurve
  28511. * THREE.QuadraticBezierCurve
  28512. * THREE.SplineCurve
  28513. *
  28514. * -- 3D curves --
  28515. * THREE.CatmullRomCurve3
  28516. * THREE.CubicBezierCurve3
  28517. * THREE.LineCurve3
  28518. * THREE.QuadraticBezierCurve3
  28519. *
  28520. * A series of curves can be represented as a THREE.CurvePath.
  28521. *
  28522. **/
  28523. function Curve() {
  28524. this.type = 'Curve';
  28525. this.arcLengthDivisions = 200;
  28526. }
  28527. Object.assign(Curve.prototype, {
  28528. // Virtual base class method to overwrite and implement in subclasses
  28529. // - t [0 .. 1]
  28530. getPoint: function getPoint()
  28531. /* t, optionalTarget */
  28532. {
  28533. console.warn('THREE.Curve: .getPoint() not implemented.');
  28534. return null;
  28535. },
  28536. // Get point at relative position in curve according to arc length
  28537. // - u [0 .. 1]
  28538. getPointAt: function getPointAt(u, optionalTarget) {
  28539. var t = this.getUtoTmapping(u);
  28540. return this.getPoint(t, optionalTarget);
  28541. },
  28542. // Get sequence of points using getPoint( t )
  28543. getPoints: function getPoints(divisions) {
  28544. if (divisions === void 0) {
  28545. divisions = 5;
  28546. }
  28547. var points = [];
  28548. for (var d = 0; d <= divisions; d++) {
  28549. points.push(this.getPoint(d / divisions));
  28550. }
  28551. return points;
  28552. },
  28553. // Get sequence of points using getPointAt( u )
  28554. getSpacedPoints: function getSpacedPoints(divisions) {
  28555. if (divisions === void 0) {
  28556. divisions = 5;
  28557. }
  28558. var points = [];
  28559. for (var d = 0; d <= divisions; d++) {
  28560. points.push(this.getPointAt(d / divisions));
  28561. }
  28562. return points;
  28563. },
  28564. // Get total curve arc length
  28565. getLength: function getLength() {
  28566. var lengths = this.getLengths();
  28567. return lengths[lengths.length - 1];
  28568. },
  28569. // Get list of cumulative segment lengths
  28570. getLengths: function getLengths(divisions) {
  28571. if (divisions === undefined) divisions = this.arcLengthDivisions;
  28572. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  28573. return this.cacheArcLengths;
  28574. }
  28575. this.needsUpdate = false;
  28576. var cache = [];
  28577. var current,
  28578. last = this.getPoint(0);
  28579. var sum = 0;
  28580. cache.push(0);
  28581. for (var p = 1; p <= divisions; p++) {
  28582. current = this.getPoint(p / divisions);
  28583. sum += current.distanceTo(last);
  28584. cache.push(sum);
  28585. last = current;
  28586. }
  28587. this.cacheArcLengths = cache;
  28588. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  28589. },
  28590. updateArcLengths: function updateArcLengths() {
  28591. this.needsUpdate = true;
  28592. this.getLengths();
  28593. },
  28594. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  28595. getUtoTmapping: function getUtoTmapping(u, distance) {
  28596. var arcLengths = this.getLengths();
  28597. var i = 0;
  28598. var il = arcLengths.length;
  28599. var targetArcLength; // The targeted u distance value to get
  28600. if (distance) {
  28601. targetArcLength = distance;
  28602. } else {
  28603. targetArcLength = u * arcLengths[il - 1];
  28604. } // binary search for the index with largest value smaller than target u distance
  28605. var low = 0,
  28606. high = il - 1,
  28607. comparison;
  28608. while (low <= high) {
  28609. i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  28610. comparison = arcLengths[i] - targetArcLength;
  28611. if (comparison < 0) {
  28612. low = i + 1;
  28613. } else if (comparison > 0) {
  28614. high = i - 1;
  28615. } else {
  28616. high = i;
  28617. break; // DONE
  28618. }
  28619. }
  28620. i = high;
  28621. if (arcLengths[i] === targetArcLength) {
  28622. return i / (il - 1);
  28623. } // we could get finer grain at lengths, or use simple interpolation between two points
  28624. var lengthBefore = arcLengths[i];
  28625. var lengthAfter = arcLengths[i + 1];
  28626. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  28627. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  28628. var t = (i + segmentFraction) / (il - 1);
  28629. return t;
  28630. },
  28631. // Returns a unit vector tangent at t
  28632. // In case any sub curve does not implement its tangent derivation,
  28633. // 2 points a small delta apart will be used to find its gradient
  28634. // which seems to give a reasonable approximation
  28635. getTangent: function getTangent(t, optionalTarget) {
  28636. var delta = 0.0001;
  28637. var t1 = t - delta;
  28638. var t2 = t + delta; // Capping in case of danger
  28639. if (t1 < 0) t1 = 0;
  28640. if (t2 > 1) t2 = 1;
  28641. var pt1 = this.getPoint(t1);
  28642. var pt2 = this.getPoint(t2);
  28643. var tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  28644. tangent.copy(pt2).sub(pt1).normalize();
  28645. return tangent;
  28646. },
  28647. getTangentAt: function getTangentAt(u, optionalTarget) {
  28648. var t = this.getUtoTmapping(u);
  28649. return this.getTangent(t, optionalTarget);
  28650. },
  28651. computeFrenetFrames: function computeFrenetFrames(segments, closed) {
  28652. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  28653. var normal = new Vector3();
  28654. var tangents = [];
  28655. var normals = [];
  28656. var binormals = [];
  28657. var vec = new Vector3();
  28658. var mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  28659. for (var i = 0; i <= segments; i++) {
  28660. var u = i / segments;
  28661. tangents[i] = this.getTangentAt(u, new Vector3());
  28662. tangents[i].normalize();
  28663. } // select an initial normal vector perpendicular to the first tangent vector,
  28664. // and in the direction of the minimum tangent xyz component
  28665. normals[0] = new Vector3();
  28666. binormals[0] = new Vector3();
  28667. var min = Number.MAX_VALUE;
  28668. var tx = Math.abs(tangents[0].x);
  28669. var ty = Math.abs(tangents[0].y);
  28670. var tz = Math.abs(tangents[0].z);
  28671. if (tx <= min) {
  28672. min = tx;
  28673. normal.set(1, 0, 0);
  28674. }
  28675. if (ty <= min) {
  28676. min = ty;
  28677. normal.set(0, 1, 0);
  28678. }
  28679. if (tz <= min) {
  28680. normal.set(0, 0, 1);
  28681. }
  28682. vec.crossVectors(tangents[0], normal).normalize();
  28683. normals[0].crossVectors(tangents[0], vec);
  28684. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  28685. for (var _i = 1; _i <= segments; _i++) {
  28686. normals[_i] = normals[_i - 1].clone();
  28687. binormals[_i] = binormals[_i - 1].clone();
  28688. vec.crossVectors(tangents[_i - 1], tangents[_i]);
  28689. if (vec.length() > Number.EPSILON) {
  28690. vec.normalize();
  28691. var theta = Math.acos(MathUtils.clamp(tangents[_i - 1].dot(tangents[_i]), -1, 1)); // clamp for floating pt errors
  28692. normals[_i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  28693. }
  28694. binormals[_i].crossVectors(tangents[_i], normals[_i]);
  28695. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  28696. if (closed === true) {
  28697. var _theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  28698. _theta /= segments;
  28699. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  28700. _theta = -_theta;
  28701. }
  28702. for (var _i2 = 1; _i2 <= segments; _i2++) {
  28703. // twist a little...
  28704. normals[_i2].applyMatrix4(mat.makeRotationAxis(tangents[_i2], _theta * _i2));
  28705. binormals[_i2].crossVectors(tangents[_i2], normals[_i2]);
  28706. }
  28707. }
  28708. return {
  28709. tangents: tangents,
  28710. normals: normals,
  28711. binormals: binormals
  28712. };
  28713. },
  28714. clone: function clone() {
  28715. return new this.constructor().copy(this);
  28716. },
  28717. copy: function copy(source) {
  28718. this.arcLengthDivisions = source.arcLengthDivisions;
  28719. return this;
  28720. },
  28721. toJSON: function toJSON() {
  28722. var data = {
  28723. metadata: {
  28724. version: 4.5,
  28725. type: 'Curve',
  28726. generator: 'Curve.toJSON'
  28727. }
  28728. };
  28729. data.arcLengthDivisions = this.arcLengthDivisions;
  28730. data.type = this.type;
  28731. return data;
  28732. },
  28733. fromJSON: function fromJSON(json) {
  28734. this.arcLengthDivisions = json.arcLengthDivisions;
  28735. return this;
  28736. }
  28737. });
  28738. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28739. Curve.call(this);
  28740. this.type = 'EllipseCurve';
  28741. this.aX = aX || 0;
  28742. this.aY = aY || 0;
  28743. this.xRadius = xRadius || 1;
  28744. this.yRadius = yRadius || 1;
  28745. this.aStartAngle = aStartAngle || 0;
  28746. this.aEndAngle = aEndAngle || 2 * Math.PI;
  28747. this.aClockwise = aClockwise || false;
  28748. this.aRotation = aRotation || 0;
  28749. }
  28750. EllipseCurve.prototype = Object.create(Curve.prototype);
  28751. EllipseCurve.prototype.constructor = EllipseCurve;
  28752. EllipseCurve.prototype.isEllipseCurve = true;
  28753. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  28754. var point = optionalTarget || new Vector2();
  28755. var twoPi = Math.PI * 2;
  28756. var deltaAngle = this.aEndAngle - this.aStartAngle;
  28757. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  28758. while (deltaAngle < 0) {
  28759. deltaAngle += twoPi;
  28760. }
  28761. while (deltaAngle > twoPi) {
  28762. deltaAngle -= twoPi;
  28763. }
  28764. if (deltaAngle < Number.EPSILON) {
  28765. if (samePoints) {
  28766. deltaAngle = 0;
  28767. } else {
  28768. deltaAngle = twoPi;
  28769. }
  28770. }
  28771. if (this.aClockwise === true && !samePoints) {
  28772. if (deltaAngle === twoPi) {
  28773. deltaAngle = -twoPi;
  28774. } else {
  28775. deltaAngle = deltaAngle - twoPi;
  28776. }
  28777. }
  28778. var angle = this.aStartAngle + t * deltaAngle;
  28779. var x = this.aX + this.xRadius * Math.cos(angle);
  28780. var y = this.aY + this.yRadius * Math.sin(angle);
  28781. if (this.aRotation !== 0) {
  28782. var cos = Math.cos(this.aRotation);
  28783. var sin = Math.sin(this.aRotation);
  28784. var tx = x - this.aX;
  28785. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  28786. x = tx * cos - ty * sin + this.aX;
  28787. y = tx * sin + ty * cos + this.aY;
  28788. }
  28789. return point.set(x, y);
  28790. };
  28791. EllipseCurve.prototype.copy = function (source) {
  28792. Curve.prototype.copy.call(this, source);
  28793. this.aX = source.aX;
  28794. this.aY = source.aY;
  28795. this.xRadius = source.xRadius;
  28796. this.yRadius = source.yRadius;
  28797. this.aStartAngle = source.aStartAngle;
  28798. this.aEndAngle = source.aEndAngle;
  28799. this.aClockwise = source.aClockwise;
  28800. this.aRotation = source.aRotation;
  28801. return this;
  28802. };
  28803. EllipseCurve.prototype.toJSON = function () {
  28804. var data = Curve.prototype.toJSON.call(this);
  28805. data.aX = this.aX;
  28806. data.aY = this.aY;
  28807. data.xRadius = this.xRadius;
  28808. data.yRadius = this.yRadius;
  28809. data.aStartAngle = this.aStartAngle;
  28810. data.aEndAngle = this.aEndAngle;
  28811. data.aClockwise = this.aClockwise;
  28812. data.aRotation = this.aRotation;
  28813. return data;
  28814. };
  28815. EllipseCurve.prototype.fromJSON = function (json) {
  28816. Curve.prototype.fromJSON.call(this, json);
  28817. this.aX = json.aX;
  28818. this.aY = json.aY;
  28819. this.xRadius = json.xRadius;
  28820. this.yRadius = json.yRadius;
  28821. this.aStartAngle = json.aStartAngle;
  28822. this.aEndAngle = json.aEndAngle;
  28823. this.aClockwise = json.aClockwise;
  28824. this.aRotation = json.aRotation;
  28825. return this;
  28826. };
  28827. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28828. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  28829. this.type = 'ArcCurve';
  28830. }
  28831. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  28832. ArcCurve.prototype.constructor = ArcCurve;
  28833. ArcCurve.prototype.isArcCurve = true;
  28834. /**
  28835. * Centripetal CatmullRom Curve - which is useful for avoiding
  28836. * cusps and self-intersections in non-uniform catmull rom curves.
  28837. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  28838. *
  28839. * curve.type accepts centripetal(default), chordal and catmullrom
  28840. * curve.tension is used for catmullrom which defaults to 0.5
  28841. */
  28842. /*
  28843. Based on an optimized c++ solution in
  28844. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  28845. - http://ideone.com/NoEbVM
  28846. This CubicPoly class could be used for reusing some variables and calculations,
  28847. but for three.js curve use, it could be possible inlined and flatten into a single function call
  28848. which can be placed in CurveUtils.
  28849. */
  28850. function CubicPoly() {
  28851. var c0 = 0,
  28852. c1 = 0,
  28853. c2 = 0,
  28854. c3 = 0;
  28855. /*
  28856. * Compute coefficients for a cubic polynomial
  28857. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  28858. * such that
  28859. * p(0) = x0, p(1) = x1
  28860. * and
  28861. * p'(0) = t0, p'(1) = t1.
  28862. */
  28863. function init(x0, x1, t0, t1) {
  28864. c0 = x0;
  28865. c1 = t0;
  28866. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  28867. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  28868. }
  28869. return {
  28870. initCatmullRom: function initCatmullRom(x0, x1, x2, x3, tension) {
  28871. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  28872. },
  28873. initNonuniformCatmullRom: function initNonuniformCatmullRom(x0, x1, x2, x3, dt0, dt1, dt2) {
  28874. // compute tangents when parameterized in [t1,t2]
  28875. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  28876. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  28877. t1 *= dt1;
  28878. t2 *= dt1;
  28879. init(x1, x2, t1, t2);
  28880. },
  28881. calc: function calc(t) {
  28882. var t2 = t * t;
  28883. var t3 = t2 * t;
  28884. return c0 + c1 * t + c2 * t2 + c3 * t3;
  28885. }
  28886. };
  28887. } //
  28888. var tmp = new Vector3();
  28889. var px = new CubicPoly(),
  28890. py = new CubicPoly(),
  28891. pz = new CubicPoly();
  28892. function CatmullRomCurve3(points, closed, curveType, tension) {
  28893. if (points === void 0) {
  28894. points = [];
  28895. }
  28896. if (closed === void 0) {
  28897. closed = false;
  28898. }
  28899. if (curveType === void 0) {
  28900. curveType = 'centripetal';
  28901. }
  28902. if (tension === void 0) {
  28903. tension = 0.5;
  28904. }
  28905. Curve.call(this);
  28906. this.type = 'CatmullRomCurve3';
  28907. this.points = points;
  28908. this.closed = closed;
  28909. this.curveType = curveType;
  28910. this.tension = tension;
  28911. }
  28912. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  28913. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  28914. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  28915. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  28916. if (optionalTarget === void 0) {
  28917. optionalTarget = new Vector3();
  28918. }
  28919. var point = optionalTarget;
  28920. var points = this.points;
  28921. var l = points.length;
  28922. var p = (l - (this.closed ? 0 : 1)) * t;
  28923. var intPoint = Math.floor(p);
  28924. var weight = p - intPoint;
  28925. if (this.closed) {
  28926. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  28927. } else if (weight === 0 && intPoint === l - 1) {
  28928. intPoint = l - 2;
  28929. weight = 1;
  28930. }
  28931. var p0, p3; // 4 points (p1 & p2 defined below)
  28932. if (this.closed || intPoint > 0) {
  28933. p0 = points[(intPoint - 1) % l];
  28934. } else {
  28935. // extrapolate first point
  28936. tmp.subVectors(points[0], points[1]).add(points[0]);
  28937. p0 = tmp;
  28938. }
  28939. var p1 = points[intPoint % l];
  28940. var p2 = points[(intPoint + 1) % l];
  28941. if (this.closed || intPoint + 2 < l) {
  28942. p3 = points[(intPoint + 2) % l];
  28943. } else {
  28944. // extrapolate last point
  28945. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  28946. p3 = tmp;
  28947. }
  28948. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  28949. // init Centripetal / Chordal Catmull-Rom
  28950. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  28951. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  28952. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  28953. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  28954. if (dt1 < 1e-4) dt1 = 1.0;
  28955. if (dt0 < 1e-4) dt0 = dt1;
  28956. if (dt2 < 1e-4) dt2 = dt1;
  28957. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  28958. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  28959. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  28960. } else if (this.curveType === 'catmullrom') {
  28961. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  28962. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  28963. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  28964. }
  28965. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  28966. return point;
  28967. };
  28968. CatmullRomCurve3.prototype.copy = function (source) {
  28969. Curve.prototype.copy.call(this, source);
  28970. this.points = [];
  28971. for (var i = 0, l = source.points.length; i < l; i++) {
  28972. var point = source.points[i];
  28973. this.points.push(point.clone());
  28974. }
  28975. this.closed = source.closed;
  28976. this.curveType = source.curveType;
  28977. this.tension = source.tension;
  28978. return this;
  28979. };
  28980. CatmullRomCurve3.prototype.toJSON = function () {
  28981. var data = Curve.prototype.toJSON.call(this);
  28982. data.points = [];
  28983. for (var i = 0, l = this.points.length; i < l; i++) {
  28984. var point = this.points[i];
  28985. data.points.push(point.toArray());
  28986. }
  28987. data.closed = this.closed;
  28988. data.curveType = this.curveType;
  28989. data.tension = this.tension;
  28990. return data;
  28991. };
  28992. CatmullRomCurve3.prototype.fromJSON = function (json) {
  28993. Curve.prototype.fromJSON.call(this, json);
  28994. this.points = [];
  28995. for (var i = 0, l = json.points.length; i < l; i++) {
  28996. var point = json.points[i];
  28997. this.points.push(new Vector3().fromArray(point));
  28998. }
  28999. this.closed = json.closed;
  29000. this.curveType = json.curveType;
  29001. this.tension = json.tension;
  29002. return this;
  29003. };
  29004. /**
  29005. * Bezier Curves formulas obtained from
  29006. * http://en.wikipedia.org/wiki/Bézier_curve
  29007. */
  29008. function CatmullRom(t, p0, p1, p2, p3) {
  29009. var v0 = (p2 - p0) * 0.5;
  29010. var v1 = (p3 - p1) * 0.5;
  29011. var t2 = t * t;
  29012. var t3 = t * t2;
  29013. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  29014. } //
  29015. function QuadraticBezierP0(t, p) {
  29016. var k = 1 - t;
  29017. return k * k * p;
  29018. }
  29019. function QuadraticBezierP1(t, p) {
  29020. return 2 * (1 - t) * t * p;
  29021. }
  29022. function QuadraticBezierP2(t, p) {
  29023. return t * t * p;
  29024. }
  29025. function QuadraticBezier(t, p0, p1, p2) {
  29026. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  29027. } //
  29028. function CubicBezierP0(t, p) {
  29029. var k = 1 - t;
  29030. return k * k * k * p;
  29031. }
  29032. function CubicBezierP1(t, p) {
  29033. var k = 1 - t;
  29034. return 3 * k * k * t * p;
  29035. }
  29036. function CubicBezierP2(t, p) {
  29037. return 3 * (1 - t) * t * t * p;
  29038. }
  29039. function CubicBezierP3(t, p) {
  29040. return t * t * t * p;
  29041. }
  29042. function CubicBezier(t, p0, p1, p2, p3) {
  29043. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  29044. }
  29045. function CubicBezierCurve(v0, v1, v2, v3) {
  29046. if (v0 === void 0) {
  29047. v0 = new Vector2();
  29048. }
  29049. if (v1 === void 0) {
  29050. v1 = new Vector2();
  29051. }
  29052. if (v2 === void 0) {
  29053. v2 = new Vector2();
  29054. }
  29055. if (v3 === void 0) {
  29056. v3 = new Vector2();
  29057. }
  29058. Curve.call(this);
  29059. this.type = 'CubicBezierCurve';
  29060. this.v0 = v0;
  29061. this.v1 = v1;
  29062. this.v2 = v2;
  29063. this.v3 = v3;
  29064. }
  29065. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  29066. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  29067. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  29068. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  29069. if (optionalTarget === void 0) {
  29070. optionalTarget = new Vector2();
  29071. }
  29072. var point = optionalTarget;
  29073. var v0 = this.v0,
  29074. v1 = this.v1,
  29075. v2 = this.v2,
  29076. v3 = this.v3;
  29077. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  29078. return point;
  29079. };
  29080. CubicBezierCurve.prototype.copy = function (source) {
  29081. Curve.prototype.copy.call(this, source);
  29082. this.v0.copy(source.v0);
  29083. this.v1.copy(source.v1);
  29084. this.v2.copy(source.v2);
  29085. this.v3.copy(source.v3);
  29086. return this;
  29087. };
  29088. CubicBezierCurve.prototype.toJSON = function () {
  29089. var data = Curve.prototype.toJSON.call(this);
  29090. data.v0 = this.v0.toArray();
  29091. data.v1 = this.v1.toArray();
  29092. data.v2 = this.v2.toArray();
  29093. data.v3 = this.v3.toArray();
  29094. return data;
  29095. };
  29096. CubicBezierCurve.prototype.fromJSON = function (json) {
  29097. Curve.prototype.fromJSON.call(this, json);
  29098. this.v0.fromArray(json.v0);
  29099. this.v1.fromArray(json.v1);
  29100. this.v2.fromArray(json.v2);
  29101. this.v3.fromArray(json.v3);
  29102. return this;
  29103. };
  29104. function CubicBezierCurve3(v0, v1, v2, v3) {
  29105. if (v0 === void 0) {
  29106. v0 = new Vector3();
  29107. }
  29108. if (v1 === void 0) {
  29109. v1 = new Vector3();
  29110. }
  29111. if (v2 === void 0) {
  29112. v2 = new Vector3();
  29113. }
  29114. if (v3 === void 0) {
  29115. v3 = new Vector3();
  29116. }
  29117. Curve.call(this);
  29118. this.type = 'CubicBezierCurve3';
  29119. this.v0 = v0;
  29120. this.v1 = v1;
  29121. this.v2 = v2;
  29122. this.v3 = v3;
  29123. }
  29124. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  29125. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  29126. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  29127. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  29128. if (optionalTarget === void 0) {
  29129. optionalTarget = new Vector3();
  29130. }
  29131. var point = optionalTarget;
  29132. var v0 = this.v0,
  29133. v1 = this.v1,
  29134. v2 = this.v2,
  29135. v3 = this.v3;
  29136. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  29137. return point;
  29138. };
  29139. CubicBezierCurve3.prototype.copy = function (source) {
  29140. Curve.prototype.copy.call(this, source);
  29141. this.v0.copy(source.v0);
  29142. this.v1.copy(source.v1);
  29143. this.v2.copy(source.v2);
  29144. this.v3.copy(source.v3);
  29145. return this;
  29146. };
  29147. CubicBezierCurve3.prototype.toJSON = function () {
  29148. var data = Curve.prototype.toJSON.call(this);
  29149. data.v0 = this.v0.toArray();
  29150. data.v1 = this.v1.toArray();
  29151. data.v2 = this.v2.toArray();
  29152. data.v3 = this.v3.toArray();
  29153. return data;
  29154. };
  29155. CubicBezierCurve3.prototype.fromJSON = function (json) {
  29156. Curve.prototype.fromJSON.call(this, json);
  29157. this.v0.fromArray(json.v0);
  29158. this.v1.fromArray(json.v1);
  29159. this.v2.fromArray(json.v2);
  29160. this.v3.fromArray(json.v3);
  29161. return this;
  29162. };
  29163. function LineCurve(v1, v2) {
  29164. if (v1 === void 0) {
  29165. v1 = new Vector2();
  29166. }
  29167. if (v2 === void 0) {
  29168. v2 = new Vector2();
  29169. }
  29170. Curve.call(this);
  29171. this.type = 'LineCurve';
  29172. this.v1 = v1;
  29173. this.v2 = v2;
  29174. }
  29175. LineCurve.prototype = Object.create(Curve.prototype);
  29176. LineCurve.prototype.constructor = LineCurve;
  29177. LineCurve.prototype.isLineCurve = true;
  29178. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  29179. if (optionalTarget === void 0) {
  29180. optionalTarget = new Vector2();
  29181. }
  29182. var point = optionalTarget;
  29183. if (t === 1) {
  29184. point.copy(this.v2);
  29185. } else {
  29186. point.copy(this.v2).sub(this.v1);
  29187. point.multiplyScalar(t).add(this.v1);
  29188. }
  29189. return point;
  29190. }; // Line curve is linear, so we can overwrite default getPointAt
  29191. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  29192. return this.getPoint(u, optionalTarget);
  29193. };
  29194. LineCurve.prototype.getTangent = function (t, optionalTarget) {
  29195. var tangent = optionalTarget || new Vector2();
  29196. tangent.copy(this.v2).sub(this.v1).normalize();
  29197. return tangent;
  29198. };
  29199. LineCurve.prototype.copy = function (source) {
  29200. Curve.prototype.copy.call(this, source);
  29201. this.v1.copy(source.v1);
  29202. this.v2.copy(source.v2);
  29203. return this;
  29204. };
  29205. LineCurve.prototype.toJSON = function () {
  29206. var data = Curve.prototype.toJSON.call(this);
  29207. data.v1 = this.v1.toArray();
  29208. data.v2 = this.v2.toArray();
  29209. return data;
  29210. };
  29211. LineCurve.prototype.fromJSON = function (json) {
  29212. Curve.prototype.fromJSON.call(this, json);
  29213. this.v1.fromArray(json.v1);
  29214. this.v2.fromArray(json.v2);
  29215. return this;
  29216. };
  29217. function LineCurve3(v1, v2) {
  29218. if (v1 === void 0) {
  29219. v1 = new Vector3();
  29220. }
  29221. if (v2 === void 0) {
  29222. v2 = new Vector3();
  29223. }
  29224. Curve.call(this);
  29225. this.type = 'LineCurve3';
  29226. this.v1 = v1;
  29227. this.v2 = v2;
  29228. }
  29229. LineCurve3.prototype = Object.create(Curve.prototype);
  29230. LineCurve3.prototype.constructor = LineCurve3;
  29231. LineCurve3.prototype.isLineCurve3 = true;
  29232. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  29233. if (optionalTarget === void 0) {
  29234. optionalTarget = new Vector3();
  29235. }
  29236. var point = optionalTarget;
  29237. if (t === 1) {
  29238. point.copy(this.v2);
  29239. } else {
  29240. point.copy(this.v2).sub(this.v1);
  29241. point.multiplyScalar(t).add(this.v1);
  29242. }
  29243. return point;
  29244. }; // Line curve is linear, so we can overwrite default getPointAt
  29245. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  29246. return this.getPoint(u, optionalTarget);
  29247. };
  29248. LineCurve3.prototype.copy = function (source) {
  29249. Curve.prototype.copy.call(this, source);
  29250. this.v1.copy(source.v1);
  29251. this.v2.copy(source.v2);
  29252. return this;
  29253. };
  29254. LineCurve3.prototype.toJSON = function () {
  29255. var data = Curve.prototype.toJSON.call(this);
  29256. data.v1 = this.v1.toArray();
  29257. data.v2 = this.v2.toArray();
  29258. return data;
  29259. };
  29260. LineCurve3.prototype.fromJSON = function (json) {
  29261. Curve.prototype.fromJSON.call(this, json);
  29262. this.v1.fromArray(json.v1);
  29263. this.v2.fromArray(json.v2);
  29264. return this;
  29265. };
  29266. function QuadraticBezierCurve(v0, v1, v2) {
  29267. if (v0 === void 0) {
  29268. v0 = new Vector2();
  29269. }
  29270. if (v1 === void 0) {
  29271. v1 = new Vector2();
  29272. }
  29273. if (v2 === void 0) {
  29274. v2 = new Vector2();
  29275. }
  29276. Curve.call(this);
  29277. this.type = 'QuadraticBezierCurve';
  29278. this.v0 = v0;
  29279. this.v1 = v1;
  29280. this.v2 = v2;
  29281. }
  29282. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  29283. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  29284. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  29285. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  29286. if (optionalTarget === void 0) {
  29287. optionalTarget = new Vector2();
  29288. }
  29289. var point = optionalTarget;
  29290. var v0 = this.v0,
  29291. v1 = this.v1,
  29292. v2 = this.v2;
  29293. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  29294. return point;
  29295. };
  29296. QuadraticBezierCurve.prototype.copy = function (source) {
  29297. Curve.prototype.copy.call(this, source);
  29298. this.v0.copy(source.v0);
  29299. this.v1.copy(source.v1);
  29300. this.v2.copy(source.v2);
  29301. return this;
  29302. };
  29303. QuadraticBezierCurve.prototype.toJSON = function () {
  29304. var data = Curve.prototype.toJSON.call(this);
  29305. data.v0 = this.v0.toArray();
  29306. data.v1 = this.v1.toArray();
  29307. data.v2 = this.v2.toArray();
  29308. return data;
  29309. };
  29310. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  29311. Curve.prototype.fromJSON.call(this, json);
  29312. this.v0.fromArray(json.v0);
  29313. this.v1.fromArray(json.v1);
  29314. this.v2.fromArray(json.v2);
  29315. return this;
  29316. };
  29317. function QuadraticBezierCurve3(v0, v1, v2) {
  29318. if (v0 === void 0) {
  29319. v0 = new Vector3();
  29320. }
  29321. if (v1 === void 0) {
  29322. v1 = new Vector3();
  29323. }
  29324. if (v2 === void 0) {
  29325. v2 = new Vector3();
  29326. }
  29327. Curve.call(this);
  29328. this.type = 'QuadraticBezierCurve3';
  29329. this.v0 = v0;
  29330. this.v1 = v1;
  29331. this.v2 = v2;
  29332. }
  29333. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  29334. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  29335. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  29336. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  29337. if (optionalTarget === void 0) {
  29338. optionalTarget = new Vector3();
  29339. }
  29340. var point = optionalTarget;
  29341. var v0 = this.v0,
  29342. v1 = this.v1,
  29343. v2 = this.v2;
  29344. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  29345. return point;
  29346. };
  29347. QuadraticBezierCurve3.prototype.copy = function (source) {
  29348. Curve.prototype.copy.call(this, source);
  29349. this.v0.copy(source.v0);
  29350. this.v1.copy(source.v1);
  29351. this.v2.copy(source.v2);
  29352. return this;
  29353. };
  29354. QuadraticBezierCurve3.prototype.toJSON = function () {
  29355. var data = Curve.prototype.toJSON.call(this);
  29356. data.v0 = this.v0.toArray();
  29357. data.v1 = this.v1.toArray();
  29358. data.v2 = this.v2.toArray();
  29359. return data;
  29360. };
  29361. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  29362. Curve.prototype.fromJSON.call(this, json);
  29363. this.v0.fromArray(json.v0);
  29364. this.v1.fromArray(json.v1);
  29365. this.v2.fromArray(json.v2);
  29366. return this;
  29367. };
  29368. function SplineCurve(points) {
  29369. if (points === void 0) {
  29370. points = [];
  29371. }
  29372. Curve.call(this);
  29373. this.type = 'SplineCurve';
  29374. this.points = points;
  29375. }
  29376. SplineCurve.prototype = Object.create(Curve.prototype);
  29377. SplineCurve.prototype.constructor = SplineCurve;
  29378. SplineCurve.prototype.isSplineCurve = true;
  29379. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  29380. if (optionalTarget === void 0) {
  29381. optionalTarget = new Vector2();
  29382. }
  29383. var point = optionalTarget;
  29384. var points = this.points;
  29385. var p = (points.length - 1) * t;
  29386. var intPoint = Math.floor(p);
  29387. var weight = p - intPoint;
  29388. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  29389. var p1 = points[intPoint];
  29390. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  29391. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  29392. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  29393. return point;
  29394. };
  29395. SplineCurve.prototype.copy = function (source) {
  29396. Curve.prototype.copy.call(this, source);
  29397. this.points = [];
  29398. for (var i = 0, l = source.points.length; i < l; i++) {
  29399. var point = source.points[i];
  29400. this.points.push(point.clone());
  29401. }
  29402. return this;
  29403. };
  29404. SplineCurve.prototype.toJSON = function () {
  29405. var data = Curve.prototype.toJSON.call(this);
  29406. data.points = [];
  29407. for (var i = 0, l = this.points.length; i < l; i++) {
  29408. var point = this.points[i];
  29409. data.points.push(point.toArray());
  29410. }
  29411. return data;
  29412. };
  29413. SplineCurve.prototype.fromJSON = function (json) {
  29414. Curve.prototype.fromJSON.call(this, json);
  29415. this.points = [];
  29416. for (var i = 0, l = json.points.length; i < l; i++) {
  29417. var point = json.points[i];
  29418. this.points.push(new Vector2().fromArray(point));
  29419. }
  29420. return this;
  29421. };
  29422. var Curves = /*#__PURE__*/Object.freeze({
  29423. __proto__: null,
  29424. ArcCurve: ArcCurve,
  29425. CatmullRomCurve3: CatmullRomCurve3,
  29426. CubicBezierCurve: CubicBezierCurve,
  29427. CubicBezierCurve3: CubicBezierCurve3,
  29428. EllipseCurve: EllipseCurve,
  29429. LineCurve: LineCurve,
  29430. LineCurve3: LineCurve3,
  29431. QuadraticBezierCurve: QuadraticBezierCurve,
  29432. QuadraticBezierCurve3: QuadraticBezierCurve3,
  29433. SplineCurve: SplineCurve
  29434. });
  29435. /**************************************************************
  29436. * Curved Path - a curve path is simply a array of connected
  29437. * curves, but retains the api of a curve
  29438. **************************************************************/
  29439. function CurvePath() {
  29440. Curve.call(this);
  29441. this.type = 'CurvePath';
  29442. this.curves = [];
  29443. this.autoClose = false; // Automatically closes the path
  29444. }
  29445. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  29446. constructor: CurvePath,
  29447. add: function add(curve) {
  29448. this.curves.push(curve);
  29449. },
  29450. closePath: function closePath() {
  29451. // Add a line curve if start and end of lines are not connected
  29452. var startPoint = this.curves[0].getPoint(0);
  29453. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  29454. if (!startPoint.equals(endPoint)) {
  29455. this.curves.push(new LineCurve(endPoint, startPoint));
  29456. }
  29457. },
  29458. // To get accurate point with reference to
  29459. // entire path distance at time t,
  29460. // following has to be done:
  29461. // 1. Length of each sub path have to be known
  29462. // 2. Locate and identify type of curve
  29463. // 3. Get t for the curve
  29464. // 4. Return curve.getPointAt(t')
  29465. getPoint: function getPoint(t) {
  29466. var d = t * this.getLength();
  29467. var curveLengths = this.getCurveLengths();
  29468. var i = 0; // To think about boundaries points.
  29469. while (i < curveLengths.length) {
  29470. if (curveLengths[i] >= d) {
  29471. var diff = curveLengths[i] - d;
  29472. var curve = this.curves[i];
  29473. var segmentLength = curve.getLength();
  29474. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  29475. return curve.getPointAt(u);
  29476. }
  29477. i++;
  29478. }
  29479. return null; // loop where sum != 0, sum > d , sum+1 <d
  29480. },
  29481. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  29482. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  29483. // getPoint() depends on getLength
  29484. getLength: function getLength() {
  29485. var lens = this.getCurveLengths();
  29486. return lens[lens.length - 1];
  29487. },
  29488. // cacheLengths must be recalculated.
  29489. updateArcLengths: function updateArcLengths() {
  29490. this.needsUpdate = true;
  29491. this.cacheLengths = null;
  29492. this.getCurveLengths();
  29493. },
  29494. // Compute lengths and cache them
  29495. // We cannot overwrite getLengths() because UtoT mapping uses it.
  29496. getCurveLengths: function getCurveLengths() {
  29497. // We use cache values if curves and cache array are same length
  29498. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  29499. return this.cacheLengths;
  29500. } // Get length of sub-curve
  29501. // Push sums into cached array
  29502. var lengths = [];
  29503. var sums = 0;
  29504. for (var i = 0, l = this.curves.length; i < l; i++) {
  29505. sums += this.curves[i].getLength();
  29506. lengths.push(sums);
  29507. }
  29508. this.cacheLengths = lengths;
  29509. return lengths;
  29510. },
  29511. getSpacedPoints: function getSpacedPoints(divisions) {
  29512. if (divisions === void 0) {
  29513. divisions = 40;
  29514. }
  29515. var points = [];
  29516. for (var i = 0; i <= divisions; i++) {
  29517. points.push(this.getPoint(i / divisions));
  29518. }
  29519. if (this.autoClose) {
  29520. points.push(points[0]);
  29521. }
  29522. return points;
  29523. },
  29524. getPoints: function getPoints(divisions) {
  29525. if (divisions === void 0) {
  29526. divisions = 12;
  29527. }
  29528. var points = [];
  29529. var last;
  29530. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  29531. var curve = curves[i];
  29532. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  29533. var pts = curve.getPoints(resolution);
  29534. for (var j = 0; j < pts.length; j++) {
  29535. var point = pts[j];
  29536. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  29537. points.push(point);
  29538. last = point;
  29539. }
  29540. }
  29541. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  29542. points.push(points[0]);
  29543. }
  29544. return points;
  29545. },
  29546. copy: function copy(source) {
  29547. Curve.prototype.copy.call(this, source);
  29548. this.curves = [];
  29549. for (var i = 0, l = source.curves.length; i < l; i++) {
  29550. var curve = source.curves[i];
  29551. this.curves.push(curve.clone());
  29552. }
  29553. this.autoClose = source.autoClose;
  29554. return this;
  29555. },
  29556. toJSON: function toJSON() {
  29557. var data = Curve.prototype.toJSON.call(this);
  29558. data.autoClose = this.autoClose;
  29559. data.curves = [];
  29560. for (var i = 0, l = this.curves.length; i < l; i++) {
  29561. var curve = this.curves[i];
  29562. data.curves.push(curve.toJSON());
  29563. }
  29564. return data;
  29565. },
  29566. fromJSON: function fromJSON(json) {
  29567. Curve.prototype.fromJSON.call(this, json);
  29568. this.autoClose = json.autoClose;
  29569. this.curves = [];
  29570. for (var i = 0, l = json.curves.length; i < l; i++) {
  29571. var curve = json.curves[i];
  29572. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  29573. }
  29574. return this;
  29575. }
  29576. });
  29577. function Path(points) {
  29578. CurvePath.call(this);
  29579. this.type = 'Path';
  29580. this.currentPoint = new Vector2();
  29581. if (points) {
  29582. this.setFromPoints(points);
  29583. }
  29584. }
  29585. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  29586. constructor: Path,
  29587. setFromPoints: function setFromPoints(points) {
  29588. this.moveTo(points[0].x, points[0].y);
  29589. for (var i = 1, l = points.length; i < l; i++) {
  29590. this.lineTo(points[i].x, points[i].y);
  29591. }
  29592. return this;
  29593. },
  29594. moveTo: function moveTo(x, y) {
  29595. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  29596. return this;
  29597. },
  29598. lineTo: function lineTo(x, y) {
  29599. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  29600. this.curves.push(curve);
  29601. this.currentPoint.set(x, y);
  29602. return this;
  29603. },
  29604. quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
  29605. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  29606. this.curves.push(curve);
  29607. this.currentPoint.set(aX, aY);
  29608. return this;
  29609. },
  29610. bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  29611. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  29612. this.curves.push(curve);
  29613. this.currentPoint.set(aX, aY);
  29614. return this;
  29615. },
  29616. splineThru: function splineThru(pts
  29617. /*Array of Vector*/
  29618. ) {
  29619. var npts = [this.currentPoint.clone()].concat(pts);
  29620. var curve = new SplineCurve(npts);
  29621. this.curves.push(curve);
  29622. this.currentPoint.copy(pts[pts.length - 1]);
  29623. return this;
  29624. },
  29625. arc: function arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  29626. var x0 = this.currentPoint.x;
  29627. var y0 = this.currentPoint.y;
  29628. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  29629. return this;
  29630. },
  29631. absarc: function absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  29632. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  29633. return this;
  29634. },
  29635. ellipse: function ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  29636. var x0 = this.currentPoint.x;
  29637. var y0 = this.currentPoint.y;
  29638. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  29639. return this;
  29640. },
  29641. absellipse: function absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  29642. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  29643. if (this.curves.length > 0) {
  29644. // if a previous curve is present, attempt to join
  29645. var firstPoint = curve.getPoint(0);
  29646. if (!firstPoint.equals(this.currentPoint)) {
  29647. this.lineTo(firstPoint.x, firstPoint.y);
  29648. }
  29649. }
  29650. this.curves.push(curve);
  29651. var lastPoint = curve.getPoint(1);
  29652. this.currentPoint.copy(lastPoint);
  29653. return this;
  29654. },
  29655. copy: function copy(source) {
  29656. CurvePath.prototype.copy.call(this, source);
  29657. this.currentPoint.copy(source.currentPoint);
  29658. return this;
  29659. },
  29660. toJSON: function toJSON() {
  29661. var data = CurvePath.prototype.toJSON.call(this);
  29662. data.currentPoint = this.currentPoint.toArray();
  29663. return data;
  29664. },
  29665. fromJSON: function fromJSON(json) {
  29666. CurvePath.prototype.fromJSON.call(this, json);
  29667. this.currentPoint.fromArray(json.currentPoint);
  29668. return this;
  29669. }
  29670. });
  29671. function Shape(points) {
  29672. Path.call(this, points);
  29673. this.uuid = MathUtils.generateUUID();
  29674. this.type = 'Shape';
  29675. this.holes = [];
  29676. }
  29677. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  29678. constructor: Shape,
  29679. getPointsHoles: function getPointsHoles(divisions) {
  29680. var holesPts = [];
  29681. for (var i = 0, l = this.holes.length; i < l; i++) {
  29682. holesPts[i] = this.holes[i].getPoints(divisions);
  29683. }
  29684. return holesPts;
  29685. },
  29686. // get points of shape and holes (keypoints based on segments parameter)
  29687. extractPoints: function extractPoints(divisions) {
  29688. return {
  29689. shape: this.getPoints(divisions),
  29690. holes: this.getPointsHoles(divisions)
  29691. };
  29692. },
  29693. copy: function copy(source) {
  29694. Path.prototype.copy.call(this, source);
  29695. this.holes = [];
  29696. for (var i = 0, l = source.holes.length; i < l; i++) {
  29697. var hole = source.holes[i];
  29698. this.holes.push(hole.clone());
  29699. }
  29700. return this;
  29701. },
  29702. toJSON: function toJSON() {
  29703. var data = Path.prototype.toJSON.call(this);
  29704. data.uuid = this.uuid;
  29705. data.holes = [];
  29706. for (var i = 0, l = this.holes.length; i < l; i++) {
  29707. var hole = this.holes[i];
  29708. data.holes.push(hole.toJSON());
  29709. }
  29710. return data;
  29711. },
  29712. fromJSON: function fromJSON(json) {
  29713. Path.prototype.fromJSON.call(this, json);
  29714. this.uuid = json.uuid;
  29715. this.holes = [];
  29716. for (var i = 0, l = json.holes.length; i < l; i++) {
  29717. var hole = json.holes[i];
  29718. this.holes.push(new Path().fromJSON(hole));
  29719. }
  29720. return this;
  29721. }
  29722. });
  29723. function Light(color, intensity) {
  29724. if (intensity === void 0) {
  29725. intensity = 1;
  29726. }
  29727. Object3D.call(this);
  29728. this.type = 'Light';
  29729. this.color = new Color(color);
  29730. this.intensity = intensity;
  29731. }
  29732. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  29733. constructor: Light,
  29734. isLight: true,
  29735. copy: function copy(source) {
  29736. Object3D.prototype.copy.call(this, source);
  29737. this.color.copy(source.color);
  29738. this.intensity = source.intensity;
  29739. return this;
  29740. },
  29741. toJSON: function toJSON(meta) {
  29742. var data = Object3D.prototype.toJSON.call(this, meta);
  29743. data.object.color = this.color.getHex();
  29744. data.object.intensity = this.intensity;
  29745. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  29746. if (this.distance !== undefined) data.object.distance = this.distance;
  29747. if (this.angle !== undefined) data.object.angle = this.angle;
  29748. if (this.decay !== undefined) data.object.decay = this.decay;
  29749. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  29750. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  29751. return data;
  29752. }
  29753. });
  29754. function HemisphereLight(skyColor, groundColor, intensity) {
  29755. Light.call(this, skyColor, intensity);
  29756. this.type = 'HemisphereLight';
  29757. this.position.copy(Object3D.DefaultUp);
  29758. this.updateMatrix();
  29759. this.groundColor = new Color(groundColor);
  29760. }
  29761. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  29762. constructor: HemisphereLight,
  29763. isHemisphereLight: true,
  29764. copy: function copy(source) {
  29765. Light.prototype.copy.call(this, source);
  29766. this.groundColor.copy(source.groundColor);
  29767. return this;
  29768. }
  29769. });
  29770. function LightShadow(camera) {
  29771. this.camera = camera;
  29772. this.bias = 0;
  29773. this.normalBias = 0;
  29774. this.radius = 1;
  29775. this.mapSize = new Vector2(512, 512);
  29776. this.map = null;
  29777. this.mapPass = null;
  29778. this.matrix = new Matrix4();
  29779. this.autoUpdate = true;
  29780. this.needsUpdate = false;
  29781. this._frustum = new Frustum();
  29782. this._frameExtents = new Vector2(1, 1);
  29783. this._viewportCount = 1;
  29784. this._viewports = [new Vector4(0, 0, 1, 1)];
  29785. }
  29786. Object.assign(LightShadow.prototype, {
  29787. _projScreenMatrix: new Matrix4(),
  29788. _lightPositionWorld: new Vector3(),
  29789. _lookTarget: new Vector3(),
  29790. getViewportCount: function getViewportCount() {
  29791. return this._viewportCount;
  29792. },
  29793. getFrustum: function getFrustum() {
  29794. return this._frustum;
  29795. },
  29796. updateMatrices: function updateMatrices(light) {
  29797. var shadowCamera = this.camera,
  29798. shadowMatrix = this.matrix,
  29799. projScreenMatrix = this._projScreenMatrix,
  29800. lookTarget = this._lookTarget,
  29801. lightPositionWorld = this._lightPositionWorld;
  29802. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29803. shadowCamera.position.copy(lightPositionWorld);
  29804. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  29805. shadowCamera.lookAt(lookTarget);
  29806. shadowCamera.updateMatrixWorld();
  29807. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  29808. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  29809. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  29810. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  29811. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  29812. },
  29813. getViewport: function getViewport(viewportIndex) {
  29814. return this._viewports[viewportIndex];
  29815. },
  29816. getFrameExtents: function getFrameExtents() {
  29817. return this._frameExtents;
  29818. },
  29819. copy: function copy(source) {
  29820. this.camera = source.camera.clone();
  29821. this.bias = source.bias;
  29822. this.radius = source.radius;
  29823. this.mapSize.copy(source.mapSize);
  29824. return this;
  29825. },
  29826. clone: function clone() {
  29827. return new this.constructor().copy(this);
  29828. },
  29829. toJSON: function toJSON() {
  29830. var object = {};
  29831. if (this.bias !== 0) object.bias = this.bias;
  29832. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  29833. if (this.radius !== 1) object.radius = this.radius;
  29834. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  29835. object.camera = this.camera.toJSON(false).object;
  29836. delete object.camera.matrix;
  29837. return object;
  29838. }
  29839. });
  29840. function SpotLightShadow() {
  29841. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  29842. this.focus = 1;
  29843. }
  29844. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29845. constructor: SpotLightShadow,
  29846. isSpotLightShadow: true,
  29847. updateMatrices: function updateMatrices(light) {
  29848. var camera = this.camera;
  29849. var fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  29850. var aspect = this.mapSize.width / this.mapSize.height;
  29851. var far = light.distance || camera.far;
  29852. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  29853. camera.fov = fov;
  29854. camera.aspect = aspect;
  29855. camera.far = far;
  29856. camera.updateProjectionMatrix();
  29857. }
  29858. LightShadow.prototype.updateMatrices.call(this, light);
  29859. }
  29860. });
  29861. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  29862. Light.call(this, color, intensity);
  29863. this.type = 'SpotLight';
  29864. this.position.copy(Object3D.DefaultUp);
  29865. this.updateMatrix();
  29866. this.target = new Object3D();
  29867. Object.defineProperty(this, 'power', {
  29868. get: function get() {
  29869. // intensity = power per solid angle.
  29870. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29871. return this.intensity * Math.PI;
  29872. },
  29873. set: function set(power) {
  29874. // intensity = power per solid angle.
  29875. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29876. this.intensity = power / Math.PI;
  29877. }
  29878. });
  29879. this.distance = distance !== undefined ? distance : 0;
  29880. this.angle = angle !== undefined ? angle : Math.PI / 3;
  29881. this.penumbra = penumbra !== undefined ? penumbra : 0;
  29882. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  29883. this.shadow = new SpotLightShadow();
  29884. }
  29885. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  29886. constructor: SpotLight,
  29887. isSpotLight: true,
  29888. copy: function copy(source) {
  29889. Light.prototype.copy.call(this, source);
  29890. this.distance = source.distance;
  29891. this.angle = source.angle;
  29892. this.penumbra = source.penumbra;
  29893. this.decay = source.decay;
  29894. this.target = source.target.clone();
  29895. this.shadow = source.shadow.clone();
  29896. return this;
  29897. }
  29898. });
  29899. function PointLightShadow() {
  29900. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  29901. this._frameExtents = new Vector2(4, 2);
  29902. this._viewportCount = 6;
  29903. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  29904. // following orientation:
  29905. //
  29906. // xzXZ
  29907. // y Y
  29908. //
  29909. // X - Positive x direction
  29910. // x - Negative x direction
  29911. // Y - Positive y direction
  29912. // y - Negative y direction
  29913. // Z - Positive z direction
  29914. // z - Negative z direction
  29915. // positive X
  29916. new Vector4(2, 1, 1, 1), // negative X
  29917. new Vector4(0, 1, 1, 1), // positive Z
  29918. new Vector4(3, 1, 1, 1), // negative Z
  29919. new Vector4(1, 1, 1, 1), // positive Y
  29920. new Vector4(3, 0, 1, 1), // negative Y
  29921. new Vector4(1, 0, 1, 1)];
  29922. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  29923. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  29924. }
  29925. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29926. constructor: PointLightShadow,
  29927. isPointLightShadow: true,
  29928. updateMatrices: function updateMatrices(light, viewportIndex) {
  29929. if (viewportIndex === void 0) {
  29930. viewportIndex = 0;
  29931. }
  29932. var camera = this.camera,
  29933. shadowMatrix = this.matrix,
  29934. lightPositionWorld = this._lightPositionWorld,
  29935. lookTarget = this._lookTarget,
  29936. projScreenMatrix = this._projScreenMatrix;
  29937. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29938. camera.position.copy(lightPositionWorld);
  29939. lookTarget.copy(camera.position);
  29940. lookTarget.add(this._cubeDirections[viewportIndex]);
  29941. camera.up.copy(this._cubeUps[viewportIndex]);
  29942. camera.lookAt(lookTarget);
  29943. camera.updateMatrixWorld();
  29944. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  29945. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  29946. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  29947. }
  29948. });
  29949. function PointLight(color, intensity, distance, decay) {
  29950. Light.call(this, color, intensity);
  29951. this.type = 'PointLight';
  29952. Object.defineProperty(this, 'power', {
  29953. get: function get() {
  29954. // intensity = power per solid angle.
  29955. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29956. return this.intensity * 4 * Math.PI;
  29957. },
  29958. set: function set(power) {
  29959. // intensity = power per solid angle.
  29960. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29961. this.intensity = power / (4 * Math.PI);
  29962. }
  29963. });
  29964. this.distance = distance !== undefined ? distance : 0;
  29965. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  29966. this.shadow = new PointLightShadow();
  29967. }
  29968. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  29969. constructor: PointLight,
  29970. isPointLight: true,
  29971. copy: function copy(source) {
  29972. Light.prototype.copy.call(this, source);
  29973. this.distance = source.distance;
  29974. this.decay = source.decay;
  29975. this.shadow = source.shadow.clone();
  29976. return this;
  29977. }
  29978. });
  29979. function OrthographicCamera(left, right, top, bottom, near, far) {
  29980. Camera.call(this);
  29981. this.type = 'OrthographicCamera';
  29982. this.zoom = 1;
  29983. this.view = null;
  29984. this.left = left !== undefined ? left : -1;
  29985. this.right = right !== undefined ? right : 1;
  29986. this.top = top !== undefined ? top : 1;
  29987. this.bottom = bottom !== undefined ? bottom : -1;
  29988. this.near = near !== undefined ? near : 0.1;
  29989. this.far = far !== undefined ? far : 2000;
  29990. this.updateProjectionMatrix();
  29991. }
  29992. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  29993. constructor: OrthographicCamera,
  29994. isOrthographicCamera: true,
  29995. copy: function copy(source, recursive) {
  29996. Camera.prototype.copy.call(this, source, recursive);
  29997. this.left = source.left;
  29998. this.right = source.right;
  29999. this.top = source.top;
  30000. this.bottom = source.bottom;
  30001. this.near = source.near;
  30002. this.far = source.far;
  30003. this.zoom = source.zoom;
  30004. this.view = source.view === null ? null : Object.assign({}, source.view);
  30005. return this;
  30006. },
  30007. setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  30008. if (this.view === null) {
  30009. this.view = {
  30010. enabled: true,
  30011. fullWidth: 1,
  30012. fullHeight: 1,
  30013. offsetX: 0,
  30014. offsetY: 0,
  30015. width: 1,
  30016. height: 1
  30017. };
  30018. }
  30019. this.view.enabled = true;
  30020. this.view.fullWidth = fullWidth;
  30021. this.view.fullHeight = fullHeight;
  30022. this.view.offsetX = x;
  30023. this.view.offsetY = y;
  30024. this.view.width = width;
  30025. this.view.height = height;
  30026. this.updateProjectionMatrix();
  30027. },
  30028. clearViewOffset: function clearViewOffset() {
  30029. if (this.view !== null) {
  30030. this.view.enabled = false;
  30031. }
  30032. this.updateProjectionMatrix();
  30033. },
  30034. updateProjectionMatrix: function updateProjectionMatrix() {
  30035. var dx = (this.right - this.left) / (2 * this.zoom);
  30036. var dy = (this.top - this.bottom) / (2 * this.zoom);
  30037. var cx = (this.right + this.left) / 2;
  30038. var cy = (this.top + this.bottom) / 2;
  30039. var left = cx - dx;
  30040. var right = cx + dx;
  30041. var top = cy + dy;
  30042. var bottom = cy - dy;
  30043. if (this.view !== null && this.view.enabled) {
  30044. var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  30045. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  30046. left += scaleW * this.view.offsetX;
  30047. right = left + scaleW * this.view.width;
  30048. top -= scaleH * this.view.offsetY;
  30049. bottom = top - scaleH * this.view.height;
  30050. }
  30051. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  30052. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  30053. },
  30054. toJSON: function toJSON(meta) {
  30055. var data = Object3D.prototype.toJSON.call(this, meta);
  30056. data.object.zoom = this.zoom;
  30057. data.object.left = this.left;
  30058. data.object.right = this.right;
  30059. data.object.top = this.top;
  30060. data.object.bottom = this.bottom;
  30061. data.object.near = this.near;
  30062. data.object.far = this.far;
  30063. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  30064. return data;
  30065. }
  30066. });
  30067. function DirectionalLightShadow() {
  30068. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  30069. }
  30070. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  30071. constructor: DirectionalLightShadow,
  30072. isDirectionalLightShadow: true,
  30073. updateMatrices: function updateMatrices(light) {
  30074. LightShadow.prototype.updateMatrices.call(this, light);
  30075. }
  30076. });
  30077. function DirectionalLight(color, intensity) {
  30078. Light.call(this, color, intensity);
  30079. this.type = 'DirectionalLight';
  30080. this.position.copy(Object3D.DefaultUp);
  30081. this.updateMatrix();
  30082. this.target = new Object3D();
  30083. this.shadow = new DirectionalLightShadow();
  30084. }
  30085. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  30086. constructor: DirectionalLight,
  30087. isDirectionalLight: true,
  30088. copy: function copy(source) {
  30089. Light.prototype.copy.call(this, source);
  30090. this.target = source.target.clone();
  30091. this.shadow = source.shadow.clone();
  30092. return this;
  30093. }
  30094. });
  30095. function AmbientLight(color, intensity) {
  30096. Light.call(this, color, intensity);
  30097. this.type = 'AmbientLight';
  30098. }
  30099. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  30100. constructor: AmbientLight,
  30101. isAmbientLight: true
  30102. });
  30103. function RectAreaLight(color, intensity, width, height) {
  30104. Light.call(this, color, intensity);
  30105. this.type = 'RectAreaLight';
  30106. this.width = width !== undefined ? width : 10;
  30107. this.height = height !== undefined ? height : 10;
  30108. }
  30109. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  30110. constructor: RectAreaLight,
  30111. isRectAreaLight: true,
  30112. copy: function copy(source) {
  30113. Light.prototype.copy.call(this, source);
  30114. this.width = source.width;
  30115. this.height = source.height;
  30116. return this;
  30117. },
  30118. toJSON: function toJSON(meta) {
  30119. var data = Light.prototype.toJSON.call(this, meta);
  30120. data.object.width = this.width;
  30121. data.object.height = this.height;
  30122. return data;
  30123. }
  30124. });
  30125. /**
  30126. * Primary reference:
  30127. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  30128. *
  30129. * Secondary reference:
  30130. * https://www.ppsloan.org/publications/StupidSH36.pdf
  30131. */
  30132. // 3-band SH defined by 9 coefficients
  30133. var SphericalHarmonics3 = /*#__PURE__*/function () {
  30134. function SphericalHarmonics3() {
  30135. Object.defineProperty(this, 'isSphericalHarmonics3', {
  30136. value: true
  30137. });
  30138. this.coefficients = [];
  30139. for (var i = 0; i < 9; i++) {
  30140. this.coefficients.push(new Vector3());
  30141. }
  30142. }
  30143. var _proto = SphericalHarmonics3.prototype;
  30144. _proto.set = function set(coefficients) {
  30145. for (var i = 0; i < 9; i++) {
  30146. this.coefficients[i].copy(coefficients[i]);
  30147. }
  30148. return this;
  30149. };
  30150. _proto.zero = function zero() {
  30151. for (var i = 0; i < 9; i++) {
  30152. this.coefficients[i].set(0, 0, 0);
  30153. }
  30154. return this;
  30155. } // get the radiance in the direction of the normal
  30156. // target is a Vector3
  30157. ;
  30158. _proto.getAt = function getAt(normal, target) {
  30159. // normal is assumed to be unit length
  30160. var x = normal.x,
  30161. y = normal.y,
  30162. z = normal.z;
  30163. var coeff = this.coefficients; // band 0
  30164. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  30165. target.addScaledVector(coeff[1], 0.488603 * y);
  30166. target.addScaledVector(coeff[2], 0.488603 * z);
  30167. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  30168. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  30169. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  30170. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  30171. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  30172. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  30173. return target;
  30174. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  30175. // target is a Vector3
  30176. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  30177. ;
  30178. _proto.getIrradianceAt = function getIrradianceAt(normal, target) {
  30179. // normal is assumed to be unit length
  30180. var x = normal.x,
  30181. y = normal.y,
  30182. z = normal.z;
  30183. var coeff = this.coefficients; // band 0
  30184. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  30185. // band 1
  30186. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  30187. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  30188. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  30189. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  30190. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  30191. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  30192. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  30193. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  30194. return target;
  30195. };
  30196. _proto.add = function add(sh) {
  30197. for (var i = 0; i < 9; i++) {
  30198. this.coefficients[i].add(sh.coefficients[i]);
  30199. }
  30200. return this;
  30201. };
  30202. _proto.addScaledSH = function addScaledSH(sh, s) {
  30203. for (var i = 0; i < 9; i++) {
  30204. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  30205. }
  30206. return this;
  30207. };
  30208. _proto.scale = function scale(s) {
  30209. for (var i = 0; i < 9; i++) {
  30210. this.coefficients[i].multiplyScalar(s);
  30211. }
  30212. return this;
  30213. };
  30214. _proto.lerp = function lerp(sh, alpha) {
  30215. for (var i = 0; i < 9; i++) {
  30216. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  30217. }
  30218. return this;
  30219. };
  30220. _proto.equals = function equals(sh) {
  30221. for (var i = 0; i < 9; i++) {
  30222. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  30223. return false;
  30224. }
  30225. }
  30226. return true;
  30227. };
  30228. _proto.copy = function copy(sh) {
  30229. return this.set(sh.coefficients);
  30230. };
  30231. _proto.clone = function clone() {
  30232. return new this.constructor().copy(this);
  30233. };
  30234. _proto.fromArray = function fromArray(array, offset) {
  30235. if (offset === void 0) {
  30236. offset = 0;
  30237. }
  30238. var coefficients = this.coefficients;
  30239. for (var i = 0; i < 9; i++) {
  30240. coefficients[i].fromArray(array, offset + i * 3);
  30241. }
  30242. return this;
  30243. };
  30244. _proto.toArray = function toArray(array, offset) {
  30245. if (array === void 0) {
  30246. array = [];
  30247. }
  30248. if (offset === void 0) {
  30249. offset = 0;
  30250. }
  30251. var coefficients = this.coefficients;
  30252. for (var i = 0; i < 9; i++) {
  30253. coefficients[i].toArray(array, offset + i * 3);
  30254. }
  30255. return array;
  30256. } // evaluate the basis functions
  30257. // shBasis is an Array[ 9 ]
  30258. ;
  30259. SphericalHarmonics3.getBasisAt = function getBasisAt(normal, shBasis) {
  30260. // normal is assumed to be unit length
  30261. var x = normal.x,
  30262. y = normal.y,
  30263. z = normal.z; // band 0
  30264. shBasis[0] = 0.282095; // band 1
  30265. shBasis[1] = 0.488603 * y;
  30266. shBasis[2] = 0.488603 * z;
  30267. shBasis[3] = 0.488603 * x; // band 2
  30268. shBasis[4] = 1.092548 * x * y;
  30269. shBasis[5] = 1.092548 * y * z;
  30270. shBasis[6] = 0.315392 * (3 * z * z - 1);
  30271. shBasis[7] = 1.092548 * x * z;
  30272. shBasis[8] = 0.546274 * (x * x - y * y);
  30273. };
  30274. return SphericalHarmonics3;
  30275. }();
  30276. function LightProbe(sh, intensity) {
  30277. Light.call(this, undefined, intensity);
  30278. this.type = 'LightProbe';
  30279. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  30280. }
  30281. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  30282. constructor: LightProbe,
  30283. isLightProbe: true,
  30284. copy: function copy(source) {
  30285. Light.prototype.copy.call(this, source);
  30286. this.sh.copy(source.sh);
  30287. return this;
  30288. },
  30289. fromJSON: function fromJSON(json) {
  30290. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  30291. this.sh.fromArray(json.sh);
  30292. return this;
  30293. },
  30294. toJSON: function toJSON(meta) {
  30295. var data = Light.prototype.toJSON.call(this, meta);
  30296. data.object.sh = this.sh.toArray();
  30297. return data;
  30298. }
  30299. });
  30300. function MaterialLoader(manager) {
  30301. Loader.call(this, manager);
  30302. this.textures = {};
  30303. }
  30304. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30305. constructor: MaterialLoader,
  30306. load: function load(url, onLoad, onProgress, onError) {
  30307. var scope = this;
  30308. var loader = new FileLoader(scope.manager);
  30309. loader.setPath(scope.path);
  30310. loader.setRequestHeader(scope.requestHeader);
  30311. loader.setWithCredentials(scope.withCredentials);
  30312. loader.load(url, function (text) {
  30313. try {
  30314. onLoad(scope.parse(JSON.parse(text)));
  30315. } catch (e) {
  30316. if (onError) {
  30317. onError(e);
  30318. } else {
  30319. console.error(e);
  30320. }
  30321. scope.manager.itemError(url);
  30322. }
  30323. }, onProgress, onError);
  30324. },
  30325. parse: function parse(json) {
  30326. var textures = this.textures;
  30327. function getTexture(name) {
  30328. if (textures[name] === undefined) {
  30329. console.warn('THREE.MaterialLoader: Undefined texture', name);
  30330. }
  30331. return textures[name];
  30332. }
  30333. var material = new Materials[json.type]();
  30334. if (json.uuid !== undefined) material.uuid = json.uuid;
  30335. if (json.name !== undefined) material.name = json.name;
  30336. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  30337. if (json.roughness !== undefined) material.roughness = json.roughness;
  30338. if (json.metalness !== undefined) material.metalness = json.metalness;
  30339. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  30340. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  30341. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  30342. if (json.shininess !== undefined) material.shininess = json.shininess;
  30343. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  30344. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  30345. if (json.fog !== undefined) material.fog = json.fog;
  30346. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  30347. if (json.blending !== undefined) material.blending = json.blending;
  30348. if (json.combine !== undefined) material.combine = json.combine;
  30349. if (json.side !== undefined) material.side = json.side;
  30350. if (json.opacity !== undefined) material.opacity = json.opacity;
  30351. if (json.transparent !== undefined) material.transparent = json.transparent;
  30352. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  30353. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  30354. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  30355. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  30356. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  30357. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  30358. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  30359. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  30360. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  30361. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  30362. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  30363. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  30364. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  30365. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  30366. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  30367. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  30368. if (json.rotation !== undefined) material.rotation = json.rotation;
  30369. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  30370. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  30371. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  30372. if (json.scale !== undefined) material.scale = json.scale;
  30373. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  30374. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  30375. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  30376. if (json.skinning !== undefined) material.skinning = json.skinning;
  30377. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  30378. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  30379. if (json.dithering !== undefined) material.dithering = json.dithering;
  30380. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  30381. if (json.visible !== undefined) material.visible = json.visible;
  30382. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  30383. if (json.userData !== undefined) material.userData = json.userData;
  30384. if (json.vertexColors !== undefined) {
  30385. if (typeof json.vertexColors === 'number') {
  30386. material.vertexColors = json.vertexColors > 0 ? true : false;
  30387. } else {
  30388. material.vertexColors = json.vertexColors;
  30389. }
  30390. } // Shader Material
  30391. if (json.uniforms !== undefined) {
  30392. for (var name in json.uniforms) {
  30393. var uniform = json.uniforms[name];
  30394. material.uniforms[name] = {};
  30395. switch (uniform.type) {
  30396. case 't':
  30397. material.uniforms[name].value = getTexture(uniform.value);
  30398. break;
  30399. case 'c':
  30400. material.uniforms[name].value = new Color().setHex(uniform.value);
  30401. break;
  30402. case 'v2':
  30403. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  30404. break;
  30405. case 'v3':
  30406. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  30407. break;
  30408. case 'v4':
  30409. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  30410. break;
  30411. case 'm3':
  30412. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  30413. break;
  30414. case 'm4':
  30415. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  30416. break;
  30417. default:
  30418. material.uniforms[name].value = uniform.value;
  30419. }
  30420. }
  30421. }
  30422. if (json.defines !== undefined) material.defines = json.defines;
  30423. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  30424. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  30425. if (json.extensions !== undefined) {
  30426. for (var key in json.extensions) {
  30427. material.extensions[key] = json.extensions[key];
  30428. }
  30429. } // Deprecated
  30430. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  30431. // for PointsMaterial
  30432. if (json.size !== undefined) material.size = json.size;
  30433. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  30434. if (json.map !== undefined) material.map = getTexture(json.map);
  30435. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  30436. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  30437. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  30438. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  30439. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  30440. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  30441. if (json.normalScale !== undefined) {
  30442. var normalScale = json.normalScale;
  30443. if (Array.isArray(normalScale) === false) {
  30444. // Blender exporter used to export a scalar. See #7459
  30445. normalScale = [normalScale, normalScale];
  30446. }
  30447. material.normalScale = new Vector2().fromArray(normalScale);
  30448. }
  30449. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  30450. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  30451. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  30452. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  30453. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  30454. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  30455. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  30456. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  30457. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  30458. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  30459. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  30460. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  30461. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  30462. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  30463. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  30464. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  30465. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  30466. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  30467. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  30468. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  30469. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  30470. if (json.transmission !== undefined) material.transmission = json.transmission;
  30471. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  30472. return material;
  30473. },
  30474. setTextures: function setTextures(value) {
  30475. this.textures = value;
  30476. return this;
  30477. }
  30478. });
  30479. var LoaderUtils = {
  30480. decodeText: function decodeText(array) {
  30481. if (typeof TextDecoder !== 'undefined') {
  30482. return new TextDecoder().decode(array);
  30483. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  30484. // throws a "maximum call stack size exceeded" error for large arrays.
  30485. var s = '';
  30486. for (var i = 0, il = array.length; i < il; i++) {
  30487. // Implicitly assumes little-endian.
  30488. s += String.fromCharCode(array[i]);
  30489. }
  30490. try {
  30491. // merges multi-byte utf-8 characters.
  30492. return decodeURIComponent(escape(s));
  30493. } catch (e) {
  30494. // see #16358
  30495. return s;
  30496. }
  30497. },
  30498. extractUrlBase: function extractUrlBase(url) {
  30499. var index = url.lastIndexOf('/');
  30500. if (index === -1) return './';
  30501. return url.substr(0, index + 1);
  30502. }
  30503. };
  30504. function InstancedBufferGeometry() {
  30505. BufferGeometry.call(this);
  30506. this.type = 'InstancedBufferGeometry';
  30507. this.instanceCount = Infinity;
  30508. }
  30509. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  30510. constructor: InstancedBufferGeometry,
  30511. isInstancedBufferGeometry: true,
  30512. copy: function copy(source) {
  30513. BufferGeometry.prototype.copy.call(this, source);
  30514. this.instanceCount = source.instanceCount;
  30515. return this;
  30516. },
  30517. clone: function clone() {
  30518. return new this.constructor().copy(this);
  30519. },
  30520. toJSON: function toJSON() {
  30521. var data = BufferGeometry.prototype.toJSON.call(this);
  30522. data.instanceCount = this.instanceCount;
  30523. data.isInstancedBufferGeometry = true;
  30524. return data;
  30525. }
  30526. });
  30527. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  30528. if (typeof normalized === 'number') {
  30529. meshPerAttribute = normalized;
  30530. normalized = false;
  30531. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  30532. }
  30533. BufferAttribute.call(this, array, itemSize, normalized);
  30534. this.meshPerAttribute = meshPerAttribute || 1;
  30535. }
  30536. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  30537. constructor: InstancedBufferAttribute,
  30538. isInstancedBufferAttribute: true,
  30539. copy: function copy(source) {
  30540. BufferAttribute.prototype.copy.call(this, source);
  30541. this.meshPerAttribute = source.meshPerAttribute;
  30542. return this;
  30543. },
  30544. toJSON: function toJSON() {
  30545. var data = BufferAttribute.prototype.toJSON.call(this);
  30546. data.meshPerAttribute = this.meshPerAttribute;
  30547. data.isInstancedBufferAttribute = true;
  30548. return data;
  30549. }
  30550. });
  30551. function BufferGeometryLoader(manager) {
  30552. Loader.call(this, manager);
  30553. }
  30554. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30555. constructor: BufferGeometryLoader,
  30556. load: function load(url, onLoad, onProgress, onError) {
  30557. var scope = this;
  30558. var loader = new FileLoader(scope.manager);
  30559. loader.setPath(scope.path);
  30560. loader.setRequestHeader(scope.requestHeader);
  30561. loader.setWithCredentials(scope.withCredentials);
  30562. loader.load(url, function (text) {
  30563. try {
  30564. onLoad(scope.parse(JSON.parse(text)));
  30565. } catch (e) {
  30566. if (onError) {
  30567. onError(e);
  30568. } else {
  30569. console.error(e);
  30570. }
  30571. scope.manager.itemError(url);
  30572. }
  30573. }, onProgress, onError);
  30574. },
  30575. parse: function parse(json) {
  30576. var interleavedBufferMap = {};
  30577. var arrayBufferMap = {};
  30578. function getInterleavedBuffer(json, uuid) {
  30579. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  30580. var interleavedBuffers = json.interleavedBuffers;
  30581. var interleavedBuffer = interleavedBuffers[uuid];
  30582. var buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  30583. var array = getTypedArray(interleavedBuffer.type, buffer);
  30584. var ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  30585. ib.uuid = interleavedBuffer.uuid;
  30586. interleavedBufferMap[uuid] = ib;
  30587. return ib;
  30588. }
  30589. function getArrayBuffer(json, uuid) {
  30590. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  30591. var arrayBuffers = json.arrayBuffers;
  30592. var arrayBuffer = arrayBuffers[uuid];
  30593. var ab = new Uint32Array(arrayBuffer).buffer;
  30594. arrayBufferMap[uuid] = ab;
  30595. return ab;
  30596. }
  30597. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  30598. var index = json.data.index;
  30599. if (index !== undefined) {
  30600. var typedArray = getTypedArray(index.type, index.array);
  30601. geometry.setIndex(new BufferAttribute(typedArray, 1));
  30602. }
  30603. var attributes = json.data.attributes;
  30604. for (var key in attributes) {
  30605. var attribute = attributes[key];
  30606. var bufferAttribute = void 0;
  30607. if (attribute.isInterleavedBufferAttribute) {
  30608. var interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  30609. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  30610. } else {
  30611. var _typedArray = getTypedArray(attribute.type, attribute.array);
  30612. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  30613. bufferAttribute = new bufferAttributeConstr(_typedArray, attribute.itemSize, attribute.normalized);
  30614. }
  30615. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  30616. geometry.setAttribute(key, bufferAttribute);
  30617. }
  30618. var morphAttributes = json.data.morphAttributes;
  30619. if (morphAttributes) {
  30620. for (var _key in morphAttributes) {
  30621. var attributeArray = morphAttributes[_key];
  30622. var array = [];
  30623. for (var i = 0, il = attributeArray.length; i < il; i++) {
  30624. var _attribute = attributeArray[i];
  30625. var _bufferAttribute = void 0;
  30626. if (_attribute.isInterleavedBufferAttribute) {
  30627. var _interleavedBuffer = getInterleavedBuffer(json.data, _attribute.data);
  30628. _bufferAttribute = new InterleavedBufferAttribute(_interleavedBuffer, _attribute.itemSize, _attribute.offset, _attribute.normalized);
  30629. } else {
  30630. var _typedArray2 = getTypedArray(_attribute.type, _attribute.array);
  30631. _bufferAttribute = new BufferAttribute(_typedArray2, _attribute.itemSize, _attribute.normalized);
  30632. }
  30633. if (_attribute.name !== undefined) _bufferAttribute.name = _attribute.name;
  30634. array.push(_bufferAttribute);
  30635. }
  30636. geometry.morphAttributes[_key] = array;
  30637. }
  30638. }
  30639. var morphTargetsRelative = json.data.morphTargetsRelative;
  30640. if (morphTargetsRelative) {
  30641. geometry.morphTargetsRelative = true;
  30642. }
  30643. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  30644. if (groups !== undefined) {
  30645. for (var _i = 0, n = groups.length; _i !== n; ++_i) {
  30646. var group = groups[_i];
  30647. geometry.addGroup(group.start, group.count, group.materialIndex);
  30648. }
  30649. }
  30650. var boundingSphere = json.data.boundingSphere;
  30651. if (boundingSphere !== undefined) {
  30652. var center = new Vector3();
  30653. if (boundingSphere.center !== undefined) {
  30654. center.fromArray(boundingSphere.center);
  30655. }
  30656. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  30657. }
  30658. if (json.name) geometry.name = json.name;
  30659. if (json.userData) geometry.userData = json.userData;
  30660. return geometry;
  30661. }
  30662. });
  30663. var ObjectLoader = /*#__PURE__*/function (_Loader) {
  30664. _inheritsLoose(ObjectLoader, _Loader);
  30665. function ObjectLoader(manager) {
  30666. return _Loader.call(this, manager) || this;
  30667. }
  30668. var _proto = ObjectLoader.prototype;
  30669. _proto.load = function load(url, onLoad, onProgress, onError) {
  30670. var scope = this;
  30671. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  30672. this.resourcePath = this.resourcePath || path;
  30673. var loader = new FileLoader(this.manager);
  30674. loader.setPath(this.path);
  30675. loader.setRequestHeader(this.requestHeader);
  30676. loader.setWithCredentials(this.withCredentials);
  30677. loader.load(url, function (text) {
  30678. var json = null;
  30679. try {
  30680. json = JSON.parse(text);
  30681. } catch (error) {
  30682. if (onError !== undefined) onError(error);
  30683. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  30684. return;
  30685. }
  30686. var metadata = json.metadata;
  30687. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  30688. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  30689. return;
  30690. }
  30691. scope.parse(json, onLoad);
  30692. }, onProgress, onError);
  30693. };
  30694. _proto.parse = function parse(json, onLoad) {
  30695. var animations = this.parseAnimations(json.animations);
  30696. var shapes = this.parseShapes(json.shapes);
  30697. var geometries = this.parseGeometries(json.geometries, shapes);
  30698. var images = this.parseImages(json.images, function () {
  30699. if (onLoad !== undefined) onLoad(object);
  30700. });
  30701. var textures = this.parseTextures(json.textures, images);
  30702. var materials = this.parseMaterials(json.materials, textures);
  30703. var object = this.parseObject(json.object, geometries, materials, animations);
  30704. var skeletons = this.parseSkeletons(json.skeletons, object);
  30705. this.bindSkeletons(object, skeletons); //
  30706. if (onLoad !== undefined) {
  30707. var hasImages = false;
  30708. for (var uuid in images) {
  30709. if (images[uuid] instanceof HTMLImageElement) {
  30710. hasImages = true;
  30711. break;
  30712. }
  30713. }
  30714. if (hasImages === false) onLoad(object);
  30715. }
  30716. return object;
  30717. };
  30718. _proto.parseShapes = function parseShapes(json) {
  30719. var shapes = {};
  30720. if (json !== undefined) {
  30721. for (var i = 0, l = json.length; i < l; i++) {
  30722. var shape = new Shape().fromJSON(json[i]);
  30723. shapes[shape.uuid] = shape;
  30724. }
  30725. }
  30726. return shapes;
  30727. };
  30728. _proto.parseSkeletons = function parseSkeletons(json, object) {
  30729. var skeletons = {};
  30730. var bones = {}; // generate bone lookup table
  30731. object.traverse(function (child) {
  30732. if (child.isBone) bones[child.uuid] = child;
  30733. }); // create skeletons
  30734. if (json !== undefined) {
  30735. for (var i = 0, l = json.length; i < l; i++) {
  30736. var skeleton = new Skeleton().fromJSON(json[i], bones);
  30737. skeletons[skeleton.uuid] = skeleton;
  30738. }
  30739. }
  30740. return skeletons;
  30741. };
  30742. _proto.parseGeometries = function parseGeometries(json, shapes) {
  30743. var geometries = {};
  30744. var geometryShapes;
  30745. if (json !== undefined) {
  30746. var bufferGeometryLoader = new BufferGeometryLoader();
  30747. for (var i = 0, l = json.length; i < l; i++) {
  30748. var geometry = void 0;
  30749. var data = json[i];
  30750. switch (data.type) {
  30751. case 'PlaneGeometry':
  30752. case 'PlaneBufferGeometry':
  30753. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  30754. break;
  30755. case 'BoxGeometry':
  30756. case 'BoxBufferGeometry':
  30757. case 'CubeGeometry':
  30758. // backwards compatible
  30759. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  30760. break;
  30761. case 'CircleGeometry':
  30762. case 'CircleBufferGeometry':
  30763. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  30764. break;
  30765. case 'CylinderGeometry':
  30766. case 'CylinderBufferGeometry':
  30767. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  30768. break;
  30769. case 'ConeGeometry':
  30770. case 'ConeBufferGeometry':
  30771. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  30772. break;
  30773. case 'SphereGeometry':
  30774. case 'SphereBufferGeometry':
  30775. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  30776. break;
  30777. case 'DodecahedronGeometry':
  30778. case 'DodecahedronBufferGeometry':
  30779. case 'IcosahedronGeometry':
  30780. case 'IcosahedronBufferGeometry':
  30781. case 'OctahedronGeometry':
  30782. case 'OctahedronBufferGeometry':
  30783. case 'TetrahedronGeometry':
  30784. case 'TetrahedronBufferGeometry':
  30785. geometry = new Geometries[data.type](data.radius, data.detail);
  30786. break;
  30787. case 'RingGeometry':
  30788. case 'RingBufferGeometry':
  30789. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  30790. break;
  30791. case 'TorusGeometry':
  30792. case 'TorusBufferGeometry':
  30793. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  30794. break;
  30795. case 'TorusKnotGeometry':
  30796. case 'TorusKnotBufferGeometry':
  30797. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  30798. break;
  30799. case 'TubeGeometry':
  30800. case 'TubeBufferGeometry':
  30801. // This only works for built-in curves (e.g. CatmullRomCurve3).
  30802. // User defined curves or instances of CurvePath will not be deserialized.
  30803. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  30804. break;
  30805. case 'LatheGeometry':
  30806. case 'LatheBufferGeometry':
  30807. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  30808. break;
  30809. case 'PolyhedronGeometry':
  30810. case 'PolyhedronBufferGeometry':
  30811. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  30812. break;
  30813. case 'ShapeGeometry':
  30814. case 'ShapeBufferGeometry':
  30815. geometryShapes = [];
  30816. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  30817. var shape = shapes[data.shapes[j]];
  30818. geometryShapes.push(shape);
  30819. }
  30820. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  30821. break;
  30822. case 'ExtrudeGeometry':
  30823. case 'ExtrudeBufferGeometry':
  30824. geometryShapes = [];
  30825. for (var _j = 0, _jl = data.shapes.length; _j < _jl; _j++) {
  30826. var _shape = shapes[data.shapes[_j]];
  30827. geometryShapes.push(_shape);
  30828. }
  30829. var extrudePath = data.options.extrudePath;
  30830. if (extrudePath !== undefined) {
  30831. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  30832. }
  30833. geometry = new Geometries[data.type](geometryShapes, data.options);
  30834. break;
  30835. case 'BufferGeometry':
  30836. case 'InstancedBufferGeometry':
  30837. geometry = bufferGeometryLoader.parse(data);
  30838. break;
  30839. case 'Geometry':
  30840. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  30841. var geometryLoader = new THREE.LegacyJSONLoader();
  30842. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  30843. } else {
  30844. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  30845. }
  30846. break;
  30847. default:
  30848. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  30849. continue;
  30850. }
  30851. geometry.uuid = data.uuid;
  30852. if (data.name !== undefined) geometry.name = data.name;
  30853. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  30854. geometries[data.uuid] = geometry;
  30855. }
  30856. }
  30857. return geometries;
  30858. };
  30859. _proto.parseMaterials = function parseMaterials(json, textures) {
  30860. var cache = {}; // MultiMaterial
  30861. var materials = {};
  30862. if (json !== undefined) {
  30863. var loader = new MaterialLoader();
  30864. loader.setTextures(textures);
  30865. for (var i = 0, l = json.length; i < l; i++) {
  30866. var data = json[i];
  30867. if (data.type === 'MultiMaterial') {
  30868. // Deprecated
  30869. var array = [];
  30870. for (var j = 0; j < data.materials.length; j++) {
  30871. var material = data.materials[j];
  30872. if (cache[material.uuid] === undefined) {
  30873. cache[material.uuid] = loader.parse(material);
  30874. }
  30875. array.push(cache[material.uuid]);
  30876. }
  30877. materials[data.uuid] = array;
  30878. } else {
  30879. if (cache[data.uuid] === undefined) {
  30880. cache[data.uuid] = loader.parse(data);
  30881. }
  30882. materials[data.uuid] = cache[data.uuid];
  30883. }
  30884. }
  30885. }
  30886. return materials;
  30887. };
  30888. _proto.parseAnimations = function parseAnimations(json) {
  30889. var animations = {};
  30890. if (json !== undefined) {
  30891. for (var i = 0; i < json.length; i++) {
  30892. var data = json[i];
  30893. var clip = AnimationClip.parse(data);
  30894. animations[clip.uuid] = clip;
  30895. }
  30896. }
  30897. return animations;
  30898. };
  30899. _proto.parseImages = function parseImages(json, onLoad) {
  30900. var scope = this;
  30901. var images = {};
  30902. var loader;
  30903. function loadImage(url) {
  30904. scope.manager.itemStart(url);
  30905. return loader.load(url, function () {
  30906. scope.manager.itemEnd(url);
  30907. }, undefined, function () {
  30908. scope.manager.itemError(url);
  30909. scope.manager.itemEnd(url);
  30910. });
  30911. }
  30912. function deserializeImage(image) {
  30913. if (typeof image === 'string') {
  30914. var url = image;
  30915. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  30916. return loadImage(path);
  30917. } else {
  30918. if (image.data) {
  30919. return {
  30920. data: getTypedArray(image.type, image.data),
  30921. width: image.width,
  30922. height: image.height
  30923. };
  30924. } else {
  30925. return null;
  30926. }
  30927. }
  30928. }
  30929. if (json !== undefined && json.length > 0) {
  30930. var manager = new LoadingManager(onLoad);
  30931. loader = new ImageLoader(manager);
  30932. loader.setCrossOrigin(this.crossOrigin);
  30933. for (var i = 0, il = json.length; i < il; i++) {
  30934. var image = json[i];
  30935. var url = image.url;
  30936. if (Array.isArray(url)) {
  30937. // load array of images e.g CubeTexture
  30938. images[image.uuid] = [];
  30939. for (var j = 0, jl = url.length; j < jl; j++) {
  30940. var currentUrl = url[j];
  30941. var deserializedImage = deserializeImage(currentUrl);
  30942. if (deserializedImage !== null) {
  30943. if (deserializedImage instanceof HTMLImageElement) {
  30944. images[image.uuid].push(deserializedImage);
  30945. } else {
  30946. // special case: handle array of data textures for cube textures
  30947. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  30948. }
  30949. }
  30950. }
  30951. } else {
  30952. // load single image
  30953. var _deserializedImage = deserializeImage(image.url);
  30954. if (_deserializedImage !== null) {
  30955. images[image.uuid] = _deserializedImage;
  30956. }
  30957. }
  30958. }
  30959. }
  30960. return images;
  30961. };
  30962. _proto.parseTextures = function parseTextures(json, images) {
  30963. function parseConstant(value, type) {
  30964. if (typeof value === 'number') return value;
  30965. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  30966. return type[value];
  30967. }
  30968. var textures = {};
  30969. if (json !== undefined) {
  30970. for (var i = 0, l = json.length; i < l; i++) {
  30971. var data = json[i];
  30972. if (data.image === undefined) {
  30973. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  30974. }
  30975. if (images[data.image] === undefined) {
  30976. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  30977. }
  30978. var texture = void 0;
  30979. var image = images[data.image];
  30980. if (Array.isArray(image)) {
  30981. texture = new CubeTexture(image);
  30982. if (image.length === 6) texture.needsUpdate = true;
  30983. } else {
  30984. if (image && image.data) {
  30985. texture = new DataTexture(image.data, image.width, image.height);
  30986. } else {
  30987. texture = new Texture(image);
  30988. }
  30989. if (image) texture.needsUpdate = true; // textures can have undefined image data
  30990. }
  30991. texture.uuid = data.uuid;
  30992. if (data.name !== undefined) texture.name = data.name;
  30993. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  30994. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  30995. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  30996. if (data.center !== undefined) texture.center.fromArray(data.center);
  30997. if (data.rotation !== undefined) texture.rotation = data.rotation;
  30998. if (data.wrap !== undefined) {
  30999. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  31000. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  31001. }
  31002. if (data.format !== undefined) texture.format = data.format;
  31003. if (data.type !== undefined) texture.type = data.type;
  31004. if (data.encoding !== undefined) texture.encoding = data.encoding;
  31005. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  31006. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  31007. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  31008. if (data.flipY !== undefined) texture.flipY = data.flipY;
  31009. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  31010. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  31011. textures[data.uuid] = texture;
  31012. }
  31013. }
  31014. return textures;
  31015. };
  31016. _proto.parseObject = function parseObject(data, geometries, materials, animations) {
  31017. var object;
  31018. function getGeometry(name) {
  31019. if (geometries[name] === undefined) {
  31020. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  31021. }
  31022. return geometries[name];
  31023. }
  31024. function getMaterial(name) {
  31025. if (name === undefined) return undefined;
  31026. if (Array.isArray(name)) {
  31027. var array = [];
  31028. for (var i = 0, l = name.length; i < l; i++) {
  31029. var uuid = name[i];
  31030. if (materials[uuid] === undefined) {
  31031. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  31032. }
  31033. array.push(materials[uuid]);
  31034. }
  31035. return array;
  31036. }
  31037. if (materials[name] === undefined) {
  31038. console.warn('THREE.ObjectLoader: Undefined material', name);
  31039. }
  31040. return materials[name];
  31041. }
  31042. var geometry, material;
  31043. switch (data.type) {
  31044. case 'Scene':
  31045. object = new Scene();
  31046. if (data.background !== undefined) {
  31047. if (Number.isInteger(data.background)) {
  31048. object.background = new Color(data.background);
  31049. }
  31050. }
  31051. if (data.fog !== undefined) {
  31052. if (data.fog.type === 'Fog') {
  31053. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  31054. } else if (data.fog.type === 'FogExp2') {
  31055. object.fog = new FogExp2(data.fog.color, data.fog.density);
  31056. }
  31057. }
  31058. break;
  31059. case 'PerspectiveCamera':
  31060. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  31061. if (data.focus !== undefined) object.focus = data.focus;
  31062. if (data.zoom !== undefined) object.zoom = data.zoom;
  31063. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  31064. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  31065. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  31066. break;
  31067. case 'OrthographicCamera':
  31068. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  31069. if (data.zoom !== undefined) object.zoom = data.zoom;
  31070. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  31071. break;
  31072. case 'AmbientLight':
  31073. object = new AmbientLight(data.color, data.intensity);
  31074. break;
  31075. case 'DirectionalLight':
  31076. object = new DirectionalLight(data.color, data.intensity);
  31077. break;
  31078. case 'PointLight':
  31079. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  31080. break;
  31081. case 'RectAreaLight':
  31082. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  31083. break;
  31084. case 'SpotLight':
  31085. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  31086. break;
  31087. case 'HemisphereLight':
  31088. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  31089. break;
  31090. case 'LightProbe':
  31091. object = new LightProbe().fromJSON(data);
  31092. break;
  31093. case 'SkinnedMesh':
  31094. geometry = getGeometry(data.geometry);
  31095. material = getMaterial(data.material);
  31096. object = new SkinnedMesh(geometry, material);
  31097. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  31098. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  31099. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  31100. break;
  31101. case 'Mesh':
  31102. geometry = getGeometry(data.geometry);
  31103. material = getMaterial(data.material);
  31104. object = new Mesh(geometry, material);
  31105. break;
  31106. case 'InstancedMesh':
  31107. geometry = getGeometry(data.geometry);
  31108. material = getMaterial(data.material);
  31109. var count = data.count;
  31110. var instanceMatrix = data.instanceMatrix;
  31111. object = new InstancedMesh(geometry, material, count);
  31112. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  31113. break;
  31114. case 'LOD':
  31115. object = new LOD();
  31116. break;
  31117. case 'Line':
  31118. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  31119. break;
  31120. case 'LineLoop':
  31121. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  31122. break;
  31123. case 'LineSegments':
  31124. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  31125. break;
  31126. case 'PointCloud':
  31127. case 'Points':
  31128. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  31129. break;
  31130. case 'Sprite':
  31131. object = new Sprite(getMaterial(data.material));
  31132. break;
  31133. case 'Group':
  31134. object = new Group();
  31135. break;
  31136. case 'Bone':
  31137. object = new Bone();
  31138. break;
  31139. default:
  31140. object = new Object3D();
  31141. }
  31142. object.uuid = data.uuid;
  31143. if (data.name !== undefined) object.name = data.name;
  31144. if (data.matrix !== undefined) {
  31145. object.matrix.fromArray(data.matrix);
  31146. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  31147. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  31148. } else {
  31149. if (data.position !== undefined) object.position.fromArray(data.position);
  31150. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  31151. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  31152. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  31153. }
  31154. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  31155. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  31156. if (data.shadow) {
  31157. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  31158. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  31159. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  31160. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  31161. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  31162. }
  31163. if (data.visible !== undefined) object.visible = data.visible;
  31164. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  31165. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  31166. if (data.userData !== undefined) object.userData = data.userData;
  31167. if (data.layers !== undefined) object.layers.mask = data.layers;
  31168. if (data.children !== undefined) {
  31169. var children = data.children;
  31170. for (var i = 0; i < children.length; i++) {
  31171. object.add(this.parseObject(children[i], geometries, materials, animations));
  31172. }
  31173. }
  31174. if (data.animations !== undefined) {
  31175. var objectAnimations = data.animations;
  31176. for (var _i = 0; _i < objectAnimations.length; _i++) {
  31177. var uuid = objectAnimations[_i];
  31178. object.animations.push(animations[uuid]);
  31179. }
  31180. }
  31181. if (data.type === 'LOD') {
  31182. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  31183. var levels = data.levels;
  31184. for (var l = 0; l < levels.length; l++) {
  31185. var level = levels[l];
  31186. var child = object.getObjectByProperty('uuid', level.object);
  31187. if (child !== undefined) {
  31188. object.addLevel(child, level.distance);
  31189. }
  31190. }
  31191. }
  31192. return object;
  31193. };
  31194. _proto.bindSkeletons = function bindSkeletons(object, skeletons) {
  31195. if (Object.keys(skeletons).length === 0) return;
  31196. object.traverse(function (child) {
  31197. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  31198. var skeleton = skeletons[child.skeleton];
  31199. if (skeleton === undefined) {
  31200. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  31201. } else {
  31202. child.bind(skeleton, child.bindMatrix);
  31203. }
  31204. }
  31205. });
  31206. }
  31207. /* DEPRECATED */
  31208. ;
  31209. _proto.setTexturePath = function setTexturePath(value) {
  31210. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  31211. return this.setResourcePath(value);
  31212. };
  31213. return ObjectLoader;
  31214. }(Loader);
  31215. var TEXTURE_MAPPING = {
  31216. UVMapping: UVMapping,
  31217. CubeReflectionMapping: CubeReflectionMapping,
  31218. CubeRefractionMapping: CubeRefractionMapping,
  31219. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  31220. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  31221. CubeUVReflectionMapping: CubeUVReflectionMapping,
  31222. CubeUVRefractionMapping: CubeUVRefractionMapping
  31223. };
  31224. var TEXTURE_WRAPPING = {
  31225. RepeatWrapping: RepeatWrapping,
  31226. ClampToEdgeWrapping: ClampToEdgeWrapping,
  31227. MirroredRepeatWrapping: MirroredRepeatWrapping
  31228. };
  31229. var TEXTURE_FILTER = {
  31230. NearestFilter: NearestFilter,
  31231. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  31232. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  31233. LinearFilter: LinearFilter,
  31234. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  31235. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  31236. };
  31237. function ImageBitmapLoader(manager) {
  31238. if (typeof createImageBitmap === 'undefined') {
  31239. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  31240. }
  31241. if (typeof fetch === 'undefined') {
  31242. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  31243. }
  31244. Loader.call(this, manager);
  31245. this.options = {
  31246. premultiplyAlpha: 'none'
  31247. };
  31248. }
  31249. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  31250. constructor: ImageBitmapLoader,
  31251. isImageBitmapLoader: true,
  31252. setOptions: function setOptions(options) {
  31253. this.options = options;
  31254. return this;
  31255. },
  31256. load: function load(url, onLoad, onProgress, onError) {
  31257. if (url === undefined) url = '';
  31258. if (this.path !== undefined) url = this.path + url;
  31259. url = this.manager.resolveURL(url);
  31260. var scope = this;
  31261. var cached = Cache.get(url);
  31262. if (cached !== undefined) {
  31263. scope.manager.itemStart(url);
  31264. setTimeout(function () {
  31265. if (onLoad) onLoad(cached);
  31266. scope.manager.itemEnd(url);
  31267. }, 0);
  31268. return cached;
  31269. }
  31270. var fetchOptions = {};
  31271. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  31272. fetch(url, fetchOptions).then(function (res) {
  31273. return res.blob();
  31274. }).then(function (blob) {
  31275. return createImageBitmap(blob, scope.options);
  31276. }).then(function (imageBitmap) {
  31277. Cache.add(url, imageBitmap);
  31278. if (onLoad) onLoad(imageBitmap);
  31279. scope.manager.itemEnd(url);
  31280. }).catch(function (e) {
  31281. if (onError) onError(e);
  31282. scope.manager.itemError(url);
  31283. scope.manager.itemEnd(url);
  31284. });
  31285. scope.manager.itemStart(url);
  31286. }
  31287. });
  31288. function ShapePath() {
  31289. this.type = 'ShapePath';
  31290. this.color = new Color();
  31291. this.subPaths = [];
  31292. this.currentPath = null;
  31293. }
  31294. Object.assign(ShapePath.prototype, {
  31295. moveTo: function moveTo(x, y) {
  31296. this.currentPath = new Path();
  31297. this.subPaths.push(this.currentPath);
  31298. this.currentPath.moveTo(x, y);
  31299. return this;
  31300. },
  31301. lineTo: function lineTo(x, y) {
  31302. this.currentPath.lineTo(x, y);
  31303. return this;
  31304. },
  31305. quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
  31306. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  31307. return this;
  31308. },
  31309. bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  31310. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  31311. return this;
  31312. },
  31313. splineThru: function splineThru(pts) {
  31314. this.currentPath.splineThru(pts);
  31315. return this;
  31316. },
  31317. toShapes: function toShapes(isCCW, noHoles) {
  31318. function toShapesNoHoles(inSubpaths) {
  31319. var shapes = [];
  31320. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  31321. var _tmpPath = inSubpaths[i];
  31322. var _tmpShape = new Shape();
  31323. _tmpShape.curves = _tmpPath.curves;
  31324. shapes.push(_tmpShape);
  31325. }
  31326. return shapes;
  31327. }
  31328. function isPointInsidePolygon(inPt, inPolygon) {
  31329. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  31330. // toggling of inside/outside at every single! intersection point of an edge
  31331. // with the horizontal line through inPt, left of inPt
  31332. // not counting lowerY endpoints of edges and whole edges on that line
  31333. var inside = false;
  31334. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  31335. var edgeLowPt = inPolygon[p];
  31336. var edgeHighPt = inPolygon[q];
  31337. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  31338. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  31339. if (Math.abs(edgeDy) > Number.EPSILON) {
  31340. // not parallel
  31341. if (edgeDy < 0) {
  31342. edgeLowPt = inPolygon[q];
  31343. edgeDx = -edgeDx;
  31344. edgeHighPt = inPolygon[p];
  31345. edgeDy = -edgeDy;
  31346. }
  31347. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  31348. if (inPt.y === edgeLowPt.y) {
  31349. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  31350. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31351. } else {
  31352. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  31353. if (perpEdge === 0) return true; // inPt is on contour ?
  31354. if (perpEdge < 0) continue;
  31355. inside = !inside; // true intersection left of inPt
  31356. }
  31357. } else {
  31358. // parallel or collinear
  31359. if (inPt.y !== edgeLowPt.y) continue; // parallel
  31360. // edge lies on the same horizontal line as inPt
  31361. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  31362. // continue;
  31363. }
  31364. }
  31365. return inside;
  31366. }
  31367. var isClockWise = ShapeUtils.isClockWise;
  31368. var subPaths = this.subPaths;
  31369. if (subPaths.length === 0) return [];
  31370. if (noHoles === true) return toShapesNoHoles(subPaths);
  31371. var solid, tmpPath, tmpShape;
  31372. var shapes = [];
  31373. if (subPaths.length === 1) {
  31374. tmpPath = subPaths[0];
  31375. tmpShape = new Shape();
  31376. tmpShape.curves = tmpPath.curves;
  31377. shapes.push(tmpShape);
  31378. return shapes;
  31379. }
  31380. var holesFirst = !isClockWise(subPaths[0].getPoints());
  31381. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  31382. var betterShapeHoles = [];
  31383. var newShapes = [];
  31384. var newShapeHoles = [];
  31385. var mainIdx = 0;
  31386. var tmpPoints;
  31387. newShapes[mainIdx] = undefined;
  31388. newShapeHoles[mainIdx] = [];
  31389. for (var i = 0, l = subPaths.length; i < l; i++) {
  31390. tmpPath = subPaths[i];
  31391. tmpPoints = tmpPath.getPoints();
  31392. solid = isClockWise(tmpPoints);
  31393. solid = isCCW ? !solid : solid;
  31394. if (solid) {
  31395. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  31396. newShapes[mainIdx] = {
  31397. s: new Shape(),
  31398. p: tmpPoints
  31399. };
  31400. newShapes[mainIdx].s.curves = tmpPath.curves;
  31401. if (holesFirst) mainIdx++;
  31402. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  31403. } else {
  31404. newShapeHoles[mainIdx].push({
  31405. h: tmpPath,
  31406. p: tmpPoints[0]
  31407. }); //console.log('ccw', i);
  31408. }
  31409. } // only Holes? -> probably all Shapes with wrong orientation
  31410. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  31411. if (newShapes.length > 1) {
  31412. var ambiguous = false;
  31413. var toChange = [];
  31414. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  31415. betterShapeHoles[sIdx] = [];
  31416. }
  31417. for (var _sIdx = 0, _sLen = newShapes.length; _sIdx < _sLen; _sIdx++) {
  31418. var sho = newShapeHoles[_sIdx];
  31419. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  31420. var ho = sho[hIdx];
  31421. var hole_unassigned = true;
  31422. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  31423. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  31424. if (_sIdx !== s2Idx) toChange.push({
  31425. froms: _sIdx,
  31426. tos: s2Idx,
  31427. hole: hIdx
  31428. });
  31429. if (hole_unassigned) {
  31430. hole_unassigned = false;
  31431. betterShapeHoles[s2Idx].push(ho);
  31432. } else {
  31433. ambiguous = true;
  31434. }
  31435. }
  31436. }
  31437. if (hole_unassigned) {
  31438. betterShapeHoles[_sIdx].push(ho);
  31439. }
  31440. }
  31441. } // console.log("ambiguous: ", ambiguous);
  31442. if (toChange.length > 0) {
  31443. // console.log("to change: ", toChange);
  31444. if (!ambiguous) newShapeHoles = betterShapeHoles;
  31445. }
  31446. }
  31447. var tmpHoles;
  31448. for (var _i = 0, il = newShapes.length; _i < il; _i++) {
  31449. tmpShape = newShapes[_i].s;
  31450. shapes.push(tmpShape);
  31451. tmpHoles = newShapeHoles[_i];
  31452. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  31453. tmpShape.holes.push(tmpHoles[j].h);
  31454. }
  31455. } //console.log("shape", shapes);
  31456. return shapes;
  31457. }
  31458. });
  31459. function Font(data) {
  31460. this.type = 'Font';
  31461. this.data = data;
  31462. }
  31463. Object.assign(Font.prototype, {
  31464. isFont: true,
  31465. generateShapes: function generateShapes(text, size) {
  31466. if (size === void 0) {
  31467. size = 100;
  31468. }
  31469. var shapes = [];
  31470. var paths = createPaths(text, size, this.data);
  31471. for (var p = 0, pl = paths.length; p < pl; p++) {
  31472. Array.prototype.push.apply(shapes, paths[p].toShapes());
  31473. }
  31474. return shapes;
  31475. }
  31476. });
  31477. function createPaths(text, size, data) {
  31478. var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  31479. var scale = size / data.resolution;
  31480. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  31481. var paths = [];
  31482. var offsetX = 0,
  31483. offsetY = 0;
  31484. for (var i = 0; i < chars.length; i++) {
  31485. var char = chars[i];
  31486. if (char === '\n') {
  31487. offsetX = 0;
  31488. offsetY -= line_height;
  31489. } else {
  31490. var ret = createPath(char, scale, offsetX, offsetY, data);
  31491. offsetX += ret.offsetX;
  31492. paths.push(ret.path);
  31493. }
  31494. }
  31495. return paths;
  31496. }
  31497. function createPath(char, scale, offsetX, offsetY, data) {
  31498. var glyph = data.glyphs[char] || data.glyphs['?'];
  31499. if (!glyph) {
  31500. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  31501. return;
  31502. }
  31503. var path = new ShapePath();
  31504. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  31505. if (glyph.o) {
  31506. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  31507. for (var i = 0, l = outline.length; i < l;) {
  31508. var action = outline[i++];
  31509. switch (action) {
  31510. case 'm':
  31511. // moveTo
  31512. x = outline[i++] * scale + offsetX;
  31513. y = outline[i++] * scale + offsetY;
  31514. path.moveTo(x, y);
  31515. break;
  31516. case 'l':
  31517. // lineTo
  31518. x = outline[i++] * scale + offsetX;
  31519. y = outline[i++] * scale + offsetY;
  31520. path.lineTo(x, y);
  31521. break;
  31522. case 'q':
  31523. // quadraticCurveTo
  31524. cpx = outline[i++] * scale + offsetX;
  31525. cpy = outline[i++] * scale + offsetY;
  31526. cpx1 = outline[i++] * scale + offsetX;
  31527. cpy1 = outline[i++] * scale + offsetY;
  31528. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  31529. break;
  31530. case 'b':
  31531. // bezierCurveTo
  31532. cpx = outline[i++] * scale + offsetX;
  31533. cpy = outline[i++] * scale + offsetY;
  31534. cpx1 = outline[i++] * scale + offsetX;
  31535. cpy1 = outline[i++] * scale + offsetY;
  31536. cpx2 = outline[i++] * scale + offsetX;
  31537. cpy2 = outline[i++] * scale + offsetY;
  31538. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  31539. break;
  31540. }
  31541. }
  31542. }
  31543. return {
  31544. offsetX: glyph.ha * scale,
  31545. path: path
  31546. };
  31547. }
  31548. function FontLoader(manager) {
  31549. Loader.call(this, manager);
  31550. }
  31551. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  31552. constructor: FontLoader,
  31553. load: function load(url, onLoad, onProgress, onError) {
  31554. var scope = this;
  31555. var loader = new FileLoader(this.manager);
  31556. loader.setPath(this.path);
  31557. loader.setRequestHeader(this.requestHeader);
  31558. loader.setWithCredentials(scope.withCredentials);
  31559. loader.load(url, function (text) {
  31560. var json;
  31561. try {
  31562. json = JSON.parse(text);
  31563. } catch (e) {
  31564. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  31565. json = JSON.parse(text.substring(65, text.length - 2));
  31566. }
  31567. var font = scope.parse(json);
  31568. if (onLoad) onLoad(font);
  31569. }, onProgress, onError);
  31570. },
  31571. parse: function parse(json) {
  31572. return new Font(json);
  31573. }
  31574. });
  31575. var _context;
  31576. var AudioContext = {
  31577. getContext: function getContext() {
  31578. if (_context === undefined) {
  31579. _context = new (window.AudioContext || window.webkitAudioContext)();
  31580. }
  31581. return _context;
  31582. },
  31583. setContext: function setContext(value) {
  31584. _context = value;
  31585. }
  31586. };
  31587. function AudioLoader(manager) {
  31588. Loader.call(this, manager);
  31589. }
  31590. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  31591. constructor: AudioLoader,
  31592. load: function load(url, onLoad, onProgress, onError) {
  31593. var scope = this;
  31594. var loader = new FileLoader(scope.manager);
  31595. loader.setResponseType('arraybuffer');
  31596. loader.setPath(scope.path);
  31597. loader.setRequestHeader(scope.requestHeader);
  31598. loader.setWithCredentials(scope.withCredentials);
  31599. loader.load(url, function (buffer) {
  31600. try {
  31601. // Create a copy of the buffer. The `decodeAudioData` method
  31602. // detaches the buffer when complete, preventing reuse.
  31603. var bufferCopy = buffer.slice(0);
  31604. var context = AudioContext.getContext();
  31605. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  31606. onLoad(audioBuffer);
  31607. });
  31608. } catch (e) {
  31609. if (onError) {
  31610. onError(e);
  31611. } else {
  31612. console.error(e);
  31613. }
  31614. scope.manager.itemError(url);
  31615. }
  31616. }, onProgress, onError);
  31617. }
  31618. });
  31619. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  31620. LightProbe.call(this, undefined, intensity);
  31621. var color1 = new Color().set(skyColor);
  31622. var color2 = new Color().set(groundColor);
  31623. var sky = new Vector3(color1.r, color1.g, color1.b);
  31624. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  31625. var c0 = Math.sqrt(Math.PI);
  31626. var c1 = c0 * Math.sqrt(0.75);
  31627. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  31628. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  31629. }
  31630. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  31631. constructor: HemisphereLightProbe,
  31632. isHemisphereLightProbe: true,
  31633. copy: function copy(source) {
  31634. // modifying colors not currently supported
  31635. LightProbe.prototype.copy.call(this, source);
  31636. return this;
  31637. },
  31638. toJSON: function toJSON(meta) {
  31639. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  31640. return data;
  31641. }
  31642. });
  31643. function AmbientLightProbe(color, intensity) {
  31644. LightProbe.call(this, undefined, intensity);
  31645. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  31646. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  31647. }
  31648. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  31649. constructor: AmbientLightProbe,
  31650. isAmbientLightProbe: true,
  31651. copy: function copy(source) {
  31652. // modifying color not currently supported
  31653. LightProbe.prototype.copy.call(this, source);
  31654. return this;
  31655. },
  31656. toJSON: function toJSON(meta) {
  31657. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  31658. return data;
  31659. }
  31660. });
  31661. var _eyeRight = new Matrix4();
  31662. var _eyeLeft = new Matrix4();
  31663. function StereoCamera() {
  31664. this.type = 'StereoCamera';
  31665. this.aspect = 1;
  31666. this.eyeSep = 0.064;
  31667. this.cameraL = new PerspectiveCamera();
  31668. this.cameraL.layers.enable(1);
  31669. this.cameraL.matrixAutoUpdate = false;
  31670. this.cameraR = new PerspectiveCamera();
  31671. this.cameraR.layers.enable(2);
  31672. this.cameraR.matrixAutoUpdate = false;
  31673. this._cache = {
  31674. focus: null,
  31675. fov: null,
  31676. aspect: null,
  31677. near: null,
  31678. far: null,
  31679. zoom: null,
  31680. eyeSep: null
  31681. };
  31682. }
  31683. Object.assign(StereoCamera.prototype, {
  31684. update: function update(camera) {
  31685. var cache = this._cache;
  31686. var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  31687. if (needsUpdate) {
  31688. cache.focus = camera.focus;
  31689. cache.fov = camera.fov;
  31690. cache.aspect = camera.aspect * this.aspect;
  31691. cache.near = camera.near;
  31692. cache.far = camera.far;
  31693. cache.zoom = camera.zoom;
  31694. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  31695. // http://paulbourke.net/stereographics/stereorender/
  31696. var projectionMatrix = camera.projectionMatrix.clone();
  31697. var eyeSepHalf = cache.eyeSep / 2;
  31698. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  31699. var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  31700. var xmin, xmax; // translate xOffset
  31701. _eyeLeft.elements[12] = -eyeSepHalf;
  31702. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  31703. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  31704. xmax = ymax * cache.aspect + eyeSepOnProjection;
  31705. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  31706. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  31707. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  31708. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  31709. xmax = ymax * cache.aspect - eyeSepOnProjection;
  31710. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  31711. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  31712. this.cameraR.projectionMatrix.copy(projectionMatrix);
  31713. }
  31714. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  31715. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  31716. }
  31717. });
  31718. var Clock = /*#__PURE__*/function () {
  31719. function Clock(autoStart) {
  31720. this.autoStart = autoStart !== undefined ? autoStart : true;
  31721. this.startTime = 0;
  31722. this.oldTime = 0;
  31723. this.elapsedTime = 0;
  31724. this.running = false;
  31725. }
  31726. var _proto = Clock.prototype;
  31727. _proto.start = function start() {
  31728. this.startTime = now();
  31729. this.oldTime = this.startTime;
  31730. this.elapsedTime = 0;
  31731. this.running = true;
  31732. };
  31733. _proto.stop = function stop() {
  31734. this.getElapsedTime();
  31735. this.running = false;
  31736. this.autoStart = false;
  31737. };
  31738. _proto.getElapsedTime = function getElapsedTime() {
  31739. this.getDelta();
  31740. return this.elapsedTime;
  31741. };
  31742. _proto.getDelta = function getDelta() {
  31743. var diff = 0;
  31744. if (this.autoStart && !this.running) {
  31745. this.start();
  31746. return 0;
  31747. }
  31748. if (this.running) {
  31749. var newTime = now();
  31750. diff = (newTime - this.oldTime) / 1000;
  31751. this.oldTime = newTime;
  31752. this.elapsedTime += diff;
  31753. }
  31754. return diff;
  31755. };
  31756. return Clock;
  31757. }();
  31758. function now() {
  31759. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  31760. }
  31761. var _position$2 = /*@__PURE__*/new Vector3();
  31762. var _quaternion$3 = /*@__PURE__*/new Quaternion();
  31763. var _scale$1 = /*@__PURE__*/new Vector3();
  31764. var _orientation = /*@__PURE__*/new Vector3();
  31765. var AudioListener = /*#__PURE__*/function (_Object3D) {
  31766. _inheritsLoose(AudioListener, _Object3D);
  31767. function AudioListener() {
  31768. var _this;
  31769. _this = _Object3D.call(this) || this;
  31770. _this.type = 'AudioListener';
  31771. _this.context = AudioContext.getContext();
  31772. _this.gain = _this.context.createGain();
  31773. _this.gain.connect(_this.context.destination);
  31774. _this.filter = null;
  31775. _this.timeDelta = 0; // private
  31776. _this._clock = new Clock();
  31777. return _this;
  31778. }
  31779. var _proto = AudioListener.prototype;
  31780. _proto.getInput = function getInput() {
  31781. return this.gain;
  31782. };
  31783. _proto.removeFilter = function removeFilter() {
  31784. if (this.filter !== null) {
  31785. this.gain.disconnect(this.filter);
  31786. this.filter.disconnect(this.context.destination);
  31787. this.gain.connect(this.context.destination);
  31788. this.filter = null;
  31789. }
  31790. return this;
  31791. };
  31792. _proto.getFilter = function getFilter() {
  31793. return this.filter;
  31794. };
  31795. _proto.setFilter = function setFilter(value) {
  31796. if (this.filter !== null) {
  31797. this.gain.disconnect(this.filter);
  31798. this.filter.disconnect(this.context.destination);
  31799. } else {
  31800. this.gain.disconnect(this.context.destination);
  31801. }
  31802. this.filter = value;
  31803. this.gain.connect(this.filter);
  31804. this.filter.connect(this.context.destination);
  31805. return this;
  31806. };
  31807. _proto.getMasterVolume = function getMasterVolume() {
  31808. return this.gain.gain.value;
  31809. };
  31810. _proto.setMasterVolume = function setMasterVolume(value) {
  31811. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  31812. return this;
  31813. };
  31814. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  31815. _Object3D.prototype.updateMatrixWorld.call(this, force);
  31816. var listener = this.context.listener;
  31817. var up = this.up;
  31818. this.timeDelta = this._clock.getDelta();
  31819. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  31820. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  31821. if (listener.positionX) {
  31822. // code path for Chrome (see #14393)
  31823. var endTime = this.context.currentTime + this.timeDelta;
  31824. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  31825. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  31826. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  31827. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  31828. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  31829. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  31830. listener.upX.linearRampToValueAtTime(up.x, endTime);
  31831. listener.upY.linearRampToValueAtTime(up.y, endTime);
  31832. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  31833. } else {
  31834. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  31835. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  31836. }
  31837. };
  31838. return AudioListener;
  31839. }(Object3D);
  31840. var Audio = /*#__PURE__*/function (_Object3D) {
  31841. _inheritsLoose(Audio, _Object3D);
  31842. function Audio(listener) {
  31843. var _this;
  31844. _this = _Object3D.call(this) || this;
  31845. _this.type = 'Audio';
  31846. _this.listener = listener;
  31847. _this.context = listener.context;
  31848. _this.gain = _this.context.createGain();
  31849. _this.gain.connect(listener.getInput());
  31850. _this.autoplay = false;
  31851. _this.buffer = null;
  31852. _this.detune = 0;
  31853. _this.loop = false;
  31854. _this.loopStart = 0;
  31855. _this.loopEnd = 0;
  31856. _this.offset = 0;
  31857. _this.duration = undefined;
  31858. _this.playbackRate = 1;
  31859. _this.isPlaying = false;
  31860. _this.hasPlaybackControl = true;
  31861. _this.source = null;
  31862. _this.sourceType = 'empty';
  31863. _this._startedAt = 0;
  31864. _this._progress = 0;
  31865. _this._connected = false;
  31866. _this.filters = [];
  31867. return _this;
  31868. }
  31869. var _proto = Audio.prototype;
  31870. _proto.getOutput = function getOutput() {
  31871. return this.gain;
  31872. };
  31873. _proto.setNodeSource = function setNodeSource(audioNode) {
  31874. this.hasPlaybackControl = false;
  31875. this.sourceType = 'audioNode';
  31876. this.source = audioNode;
  31877. this.connect();
  31878. return this;
  31879. };
  31880. _proto.setMediaElementSource = function setMediaElementSource(mediaElement) {
  31881. this.hasPlaybackControl = false;
  31882. this.sourceType = 'mediaNode';
  31883. this.source = this.context.createMediaElementSource(mediaElement);
  31884. this.connect();
  31885. return this;
  31886. };
  31887. _proto.setMediaStreamSource = function setMediaStreamSource(mediaStream) {
  31888. this.hasPlaybackControl = false;
  31889. this.sourceType = 'mediaStreamNode';
  31890. this.source = this.context.createMediaStreamSource(mediaStream);
  31891. this.connect();
  31892. return this;
  31893. };
  31894. _proto.setBuffer = function setBuffer(audioBuffer) {
  31895. this.buffer = audioBuffer;
  31896. this.sourceType = 'buffer';
  31897. if (this.autoplay) this.play();
  31898. return this;
  31899. };
  31900. _proto.play = function play(delay) {
  31901. if (delay === void 0) {
  31902. delay = 0;
  31903. }
  31904. if (this.isPlaying === true) {
  31905. console.warn('THREE.Audio: Audio is already playing.');
  31906. return;
  31907. }
  31908. if (this.hasPlaybackControl === false) {
  31909. console.warn('THREE.Audio: this Audio has no playback control.');
  31910. return;
  31911. }
  31912. this._startedAt = this.context.currentTime + delay;
  31913. var source = this.context.createBufferSource();
  31914. source.buffer = this.buffer;
  31915. source.loop = this.loop;
  31916. source.loopStart = this.loopStart;
  31917. source.loopEnd = this.loopEnd;
  31918. source.onended = this.onEnded.bind(this);
  31919. source.start(this._startedAt, this._progress + this.offset, this.duration);
  31920. this.isPlaying = true;
  31921. this.source = source;
  31922. this.setDetune(this.detune);
  31923. this.setPlaybackRate(this.playbackRate);
  31924. return this.connect();
  31925. };
  31926. _proto.pause = function pause() {
  31927. if (this.hasPlaybackControl === false) {
  31928. console.warn('THREE.Audio: this Audio has no playback control.');
  31929. return;
  31930. }
  31931. if (this.isPlaying === true) {
  31932. // update current progress
  31933. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  31934. if (this.loop === true) {
  31935. // ensure _progress does not exceed duration with looped audios
  31936. this._progress = this._progress % (this.duration || this.buffer.duration);
  31937. }
  31938. this.source.stop();
  31939. this.source.onended = null;
  31940. this.isPlaying = false;
  31941. }
  31942. return this;
  31943. };
  31944. _proto.stop = function stop() {
  31945. if (this.hasPlaybackControl === false) {
  31946. console.warn('THREE.Audio: this Audio has no playback control.');
  31947. return;
  31948. }
  31949. this._progress = 0;
  31950. this.source.stop();
  31951. this.source.onended = null;
  31952. this.isPlaying = false;
  31953. return this;
  31954. };
  31955. _proto.connect = function connect() {
  31956. if (this.filters.length > 0) {
  31957. this.source.connect(this.filters[0]);
  31958. for (var i = 1, l = this.filters.length; i < l; i++) {
  31959. this.filters[i - 1].connect(this.filters[i]);
  31960. }
  31961. this.filters[this.filters.length - 1].connect(this.getOutput());
  31962. } else {
  31963. this.source.connect(this.getOutput());
  31964. }
  31965. this._connected = true;
  31966. return this;
  31967. };
  31968. _proto.disconnect = function disconnect() {
  31969. if (this.filters.length > 0) {
  31970. this.source.disconnect(this.filters[0]);
  31971. for (var i = 1, l = this.filters.length; i < l; i++) {
  31972. this.filters[i - 1].disconnect(this.filters[i]);
  31973. }
  31974. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  31975. } else {
  31976. this.source.disconnect(this.getOutput());
  31977. }
  31978. this._connected = false;
  31979. return this;
  31980. };
  31981. _proto.getFilters = function getFilters() {
  31982. return this.filters;
  31983. };
  31984. _proto.setFilters = function setFilters(value) {
  31985. if (!value) value = [];
  31986. if (this._connected === true) {
  31987. this.disconnect();
  31988. this.filters = value.slice();
  31989. this.connect();
  31990. } else {
  31991. this.filters = value.slice();
  31992. }
  31993. return this;
  31994. };
  31995. _proto.setDetune = function setDetune(value) {
  31996. this.detune = value;
  31997. if (this.source.detune === undefined) return; // only set detune when available
  31998. if (this.isPlaying === true) {
  31999. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  32000. }
  32001. return this;
  32002. };
  32003. _proto.getDetune = function getDetune() {
  32004. return this.detune;
  32005. };
  32006. _proto.getFilter = function getFilter() {
  32007. return this.getFilters()[0];
  32008. };
  32009. _proto.setFilter = function setFilter(filter) {
  32010. return this.setFilters(filter ? [filter] : []);
  32011. };
  32012. _proto.setPlaybackRate = function setPlaybackRate(value) {
  32013. if (this.hasPlaybackControl === false) {
  32014. console.warn('THREE.Audio: this Audio has no playback control.');
  32015. return;
  32016. }
  32017. this.playbackRate = value;
  32018. if (this.isPlaying === true) {
  32019. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  32020. }
  32021. return this;
  32022. };
  32023. _proto.getPlaybackRate = function getPlaybackRate() {
  32024. return this.playbackRate;
  32025. };
  32026. _proto.onEnded = function onEnded() {
  32027. this.isPlaying = false;
  32028. };
  32029. _proto.getLoop = function getLoop() {
  32030. if (this.hasPlaybackControl === false) {
  32031. console.warn('THREE.Audio: this Audio has no playback control.');
  32032. return false;
  32033. }
  32034. return this.loop;
  32035. };
  32036. _proto.setLoop = function setLoop(value) {
  32037. if (this.hasPlaybackControl === false) {
  32038. console.warn('THREE.Audio: this Audio has no playback control.');
  32039. return;
  32040. }
  32041. this.loop = value;
  32042. if (this.isPlaying === true) {
  32043. this.source.loop = this.loop;
  32044. }
  32045. return this;
  32046. };
  32047. _proto.setLoopStart = function setLoopStart(value) {
  32048. this.loopStart = value;
  32049. return this;
  32050. };
  32051. _proto.setLoopEnd = function setLoopEnd(value) {
  32052. this.loopEnd = value;
  32053. return this;
  32054. };
  32055. _proto.getVolume = function getVolume() {
  32056. return this.gain.gain.value;
  32057. };
  32058. _proto.setVolume = function setVolume(value) {
  32059. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  32060. return this;
  32061. };
  32062. return Audio;
  32063. }(Object3D);
  32064. var _position$3 = /*@__PURE__*/new Vector3();
  32065. var _quaternion$4 = /*@__PURE__*/new Quaternion();
  32066. var _scale$2 = /*@__PURE__*/new Vector3();
  32067. var _orientation$1 = /*@__PURE__*/new Vector3();
  32068. var PositionalAudio = /*#__PURE__*/function (_Audio) {
  32069. _inheritsLoose(PositionalAudio, _Audio);
  32070. function PositionalAudio(listener) {
  32071. var _this;
  32072. _this = _Audio.call(this, listener) || this;
  32073. _this.panner = _this.context.createPanner();
  32074. _this.panner.panningModel = 'HRTF';
  32075. _this.panner.connect(_this.gain);
  32076. return _this;
  32077. }
  32078. var _proto = PositionalAudio.prototype;
  32079. _proto.getOutput = function getOutput() {
  32080. return this.panner;
  32081. };
  32082. _proto.getRefDistance = function getRefDistance() {
  32083. return this.panner.refDistance;
  32084. };
  32085. _proto.setRefDistance = function setRefDistance(value) {
  32086. this.panner.refDistance = value;
  32087. return this;
  32088. };
  32089. _proto.getRolloffFactor = function getRolloffFactor() {
  32090. return this.panner.rolloffFactor;
  32091. };
  32092. _proto.setRolloffFactor = function setRolloffFactor(value) {
  32093. this.panner.rolloffFactor = value;
  32094. return this;
  32095. };
  32096. _proto.getDistanceModel = function getDistanceModel() {
  32097. return this.panner.distanceModel;
  32098. };
  32099. _proto.setDistanceModel = function setDistanceModel(value) {
  32100. this.panner.distanceModel = value;
  32101. return this;
  32102. };
  32103. _proto.getMaxDistance = function getMaxDistance() {
  32104. return this.panner.maxDistance;
  32105. };
  32106. _proto.setMaxDistance = function setMaxDistance(value) {
  32107. this.panner.maxDistance = value;
  32108. return this;
  32109. };
  32110. _proto.setDirectionalCone = function setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  32111. this.panner.coneInnerAngle = coneInnerAngle;
  32112. this.panner.coneOuterAngle = coneOuterAngle;
  32113. this.panner.coneOuterGain = coneOuterGain;
  32114. return this;
  32115. };
  32116. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  32117. _Audio.prototype.updateMatrixWorld.call(this, force);
  32118. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  32119. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  32120. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  32121. var panner = this.panner;
  32122. if (panner.positionX) {
  32123. // code path for Chrome and Firefox (see #14393)
  32124. var endTime = this.context.currentTime + this.listener.timeDelta;
  32125. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  32126. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  32127. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  32128. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  32129. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  32130. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  32131. } else {
  32132. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  32133. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  32134. }
  32135. };
  32136. return PositionalAudio;
  32137. }(Audio);
  32138. var AudioAnalyser = /*#__PURE__*/function () {
  32139. function AudioAnalyser(audio, fftSize) {
  32140. if (fftSize === void 0) {
  32141. fftSize = 2048;
  32142. }
  32143. this.analyser = audio.context.createAnalyser();
  32144. this.analyser.fftSize = fftSize;
  32145. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  32146. audio.getOutput().connect(this.analyser);
  32147. }
  32148. var _proto = AudioAnalyser.prototype;
  32149. _proto.getFrequencyData = function getFrequencyData() {
  32150. this.analyser.getByteFrequencyData(this.data);
  32151. return this.data;
  32152. };
  32153. _proto.getAverageFrequency = function getAverageFrequency() {
  32154. var value = 0;
  32155. var data = this.getFrequencyData();
  32156. for (var i = 0; i < data.length; i++) {
  32157. value += data[i];
  32158. }
  32159. return value / data.length;
  32160. };
  32161. return AudioAnalyser;
  32162. }();
  32163. function PropertyMixer(binding, typeName, valueSize) {
  32164. this.binding = binding;
  32165. this.valueSize = valueSize;
  32166. var mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  32167. //
  32168. // interpolators can use .buffer as their .result
  32169. // the data then goes to 'incoming'
  32170. //
  32171. // 'accu0' and 'accu1' are used frame-interleaved for
  32172. // the cumulative result and are compared to detect
  32173. // changes
  32174. //
  32175. // 'orig' stores the original state of the property
  32176. //
  32177. // 'add' is used for additive cumulative results
  32178. //
  32179. // 'work' is optional and is only present for quaternion types. It is used
  32180. // to store intermediate quaternion multiplication results
  32181. switch (typeName) {
  32182. case 'quaternion':
  32183. mixFunction = this._slerp;
  32184. mixFunctionAdditive = this._slerpAdditive;
  32185. setIdentity = this._setAdditiveIdentityQuaternion;
  32186. this.buffer = new Float64Array(valueSize * 6);
  32187. this._workIndex = 5;
  32188. break;
  32189. case 'string':
  32190. case 'bool':
  32191. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  32192. // additive is not relevant for non-numeric types
  32193. mixFunctionAdditive = this._select;
  32194. setIdentity = this._setAdditiveIdentityOther;
  32195. this.buffer = new Array(valueSize * 5);
  32196. break;
  32197. default:
  32198. mixFunction = this._lerp;
  32199. mixFunctionAdditive = this._lerpAdditive;
  32200. setIdentity = this._setAdditiveIdentityNumeric;
  32201. this.buffer = new Float64Array(valueSize * 5);
  32202. }
  32203. this._mixBufferRegion = mixFunction;
  32204. this._mixBufferRegionAdditive = mixFunctionAdditive;
  32205. this._setIdentity = setIdentity;
  32206. this._origIndex = 3;
  32207. this._addIndex = 4;
  32208. this.cumulativeWeight = 0;
  32209. this.cumulativeWeightAdditive = 0;
  32210. this.useCount = 0;
  32211. this.referenceCount = 0;
  32212. }
  32213. Object.assign(PropertyMixer.prototype, {
  32214. // accumulate data in the 'incoming' region into 'accu<i>'
  32215. accumulate: function accumulate(accuIndex, weight) {
  32216. // note: happily accumulating nothing when weight = 0, the caller knows
  32217. // the weight and shouldn't have made the call in the first place
  32218. var buffer = this.buffer,
  32219. stride = this.valueSize,
  32220. offset = accuIndex * stride + stride;
  32221. var currentWeight = this.cumulativeWeight;
  32222. if (currentWeight === 0) {
  32223. // accuN := incoming * weight
  32224. for (var i = 0; i !== stride; ++i) {
  32225. buffer[offset + i] = buffer[i];
  32226. }
  32227. currentWeight = weight;
  32228. } else {
  32229. // accuN := accuN + incoming * weight
  32230. currentWeight += weight;
  32231. var mix = weight / currentWeight;
  32232. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  32233. }
  32234. this.cumulativeWeight = currentWeight;
  32235. },
  32236. // accumulate data in the 'incoming' region into 'add'
  32237. accumulateAdditive: function accumulateAdditive(weight) {
  32238. var buffer = this.buffer,
  32239. stride = this.valueSize,
  32240. offset = stride * this._addIndex;
  32241. if (this.cumulativeWeightAdditive === 0) {
  32242. // add = identity
  32243. this._setIdentity();
  32244. } // add := add + incoming * weight
  32245. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  32246. this.cumulativeWeightAdditive += weight;
  32247. },
  32248. // apply the state of 'accu<i>' to the binding when accus differ
  32249. apply: function apply(accuIndex) {
  32250. var stride = this.valueSize,
  32251. buffer = this.buffer,
  32252. offset = accuIndex * stride + stride,
  32253. weight = this.cumulativeWeight,
  32254. weightAdditive = this.cumulativeWeightAdditive,
  32255. binding = this.binding;
  32256. this.cumulativeWeight = 0;
  32257. this.cumulativeWeightAdditive = 0;
  32258. if (weight < 1) {
  32259. // accuN := accuN + original * ( 1 - cumulativeWeight )
  32260. var originalValueOffset = stride * this._origIndex;
  32261. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  32262. }
  32263. if (weightAdditive > 0) {
  32264. // accuN := accuN + additive accuN
  32265. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  32266. }
  32267. for (var i = stride, e = stride + stride; i !== e; ++i) {
  32268. if (buffer[i] !== buffer[i + stride]) {
  32269. // value has changed -> update scene graph
  32270. binding.setValue(buffer, offset);
  32271. break;
  32272. }
  32273. }
  32274. },
  32275. // remember the state of the bound property and copy it to both accus
  32276. saveOriginalState: function saveOriginalState() {
  32277. var binding = this.binding;
  32278. var buffer = this.buffer,
  32279. stride = this.valueSize,
  32280. originalValueOffset = stride * this._origIndex;
  32281. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  32282. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  32283. buffer[i] = buffer[originalValueOffset + i % stride];
  32284. } // Add to identity for additive
  32285. this._setIdentity();
  32286. this.cumulativeWeight = 0;
  32287. this.cumulativeWeightAdditive = 0;
  32288. },
  32289. // apply the state previously taken via 'saveOriginalState' to the binding
  32290. restoreOriginalState: function restoreOriginalState() {
  32291. var originalValueOffset = this.valueSize * 3;
  32292. this.binding.setValue(this.buffer, originalValueOffset);
  32293. },
  32294. _setAdditiveIdentityNumeric: function _setAdditiveIdentityNumeric() {
  32295. var startIndex = this._addIndex * this.valueSize;
  32296. var endIndex = startIndex + this.valueSize;
  32297. for (var i = startIndex; i < endIndex; i++) {
  32298. this.buffer[i] = 0;
  32299. }
  32300. },
  32301. _setAdditiveIdentityQuaternion: function _setAdditiveIdentityQuaternion() {
  32302. this._setAdditiveIdentityNumeric();
  32303. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  32304. },
  32305. _setAdditiveIdentityOther: function _setAdditiveIdentityOther() {
  32306. var startIndex = this._origIndex * this.valueSize;
  32307. var targetIndex = this._addIndex * this.valueSize;
  32308. for (var i = 0; i < this.valueSize; i++) {
  32309. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  32310. }
  32311. },
  32312. // mix functions
  32313. _select: function _select(buffer, dstOffset, srcOffset, t, stride) {
  32314. if (t >= 0.5) {
  32315. for (var i = 0; i !== stride; ++i) {
  32316. buffer[dstOffset + i] = buffer[srcOffset + i];
  32317. }
  32318. }
  32319. },
  32320. _slerp: function _slerp(buffer, dstOffset, srcOffset, t) {
  32321. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  32322. },
  32323. _slerpAdditive: function _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  32324. var workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  32325. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  32326. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  32327. },
  32328. _lerp: function _lerp(buffer, dstOffset, srcOffset, t, stride) {
  32329. var s = 1 - t;
  32330. for (var i = 0; i !== stride; ++i) {
  32331. var j = dstOffset + i;
  32332. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  32333. }
  32334. },
  32335. _lerpAdditive: function _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  32336. for (var i = 0; i !== stride; ++i) {
  32337. var j = dstOffset + i;
  32338. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  32339. }
  32340. }
  32341. });
  32342. // Characters [].:/ are reserved for track binding syntax.
  32343. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  32344. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  32345. // only latin characters, and the unicode \p{L} is not yet supported. So
  32346. // instead, we exclude reserved characters and match everything else.
  32347. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  32348. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  32349. // be matched to parse the rest of the track name.
  32350. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  32351. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  32352. // characters. Accessor may contain any character except closing bracket.
  32353. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  32354. // contain any non-bracket characters.
  32355. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  32356. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  32357. var _supportedObjectNames = ['material', 'materials', 'bones'];
  32358. function Composite(targetGroup, path, optionalParsedPath) {
  32359. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  32360. this._targetGroup = targetGroup;
  32361. this._bindings = targetGroup.subscribe_(path, parsedPath);
  32362. }
  32363. Object.assign(Composite.prototype, {
  32364. getValue: function getValue(array, offset) {
  32365. this.bind(); // bind all binding
  32366. var firstValidIndex = this._targetGroup.nCachedObjects_,
  32367. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  32368. if (binding !== undefined) binding.getValue(array, offset);
  32369. },
  32370. setValue: function setValue(array, offset) {
  32371. var bindings = this._bindings;
  32372. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  32373. bindings[i].setValue(array, offset);
  32374. }
  32375. },
  32376. bind: function bind() {
  32377. var bindings = this._bindings;
  32378. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  32379. bindings[i].bind();
  32380. }
  32381. },
  32382. unbind: function unbind() {
  32383. var bindings = this._bindings;
  32384. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  32385. bindings[i].unbind();
  32386. }
  32387. }
  32388. });
  32389. function PropertyBinding(rootNode, path, parsedPath) {
  32390. this.path = path;
  32391. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  32392. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  32393. this.rootNode = rootNode;
  32394. }
  32395. Object.assign(PropertyBinding, {
  32396. Composite: Composite,
  32397. create: function create(root, path, parsedPath) {
  32398. if (!(root && root.isAnimationObjectGroup)) {
  32399. return new PropertyBinding(root, path, parsedPath);
  32400. } else {
  32401. return new PropertyBinding.Composite(root, path, parsedPath);
  32402. }
  32403. },
  32404. /**
  32405. * Replaces spaces with underscores and removes unsupported characters from
  32406. * node names, to ensure compatibility with parseTrackName().
  32407. *
  32408. * @param {string} name Node name to be sanitized.
  32409. * @return {string}
  32410. */
  32411. sanitizeNodeName: function sanitizeNodeName(name) {
  32412. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  32413. },
  32414. parseTrackName: function parseTrackName(trackName) {
  32415. var matches = _trackRe.exec(trackName);
  32416. if (!matches) {
  32417. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  32418. }
  32419. var results = {
  32420. // directoryName: matches[ 1 ], // (tschw) currently unused
  32421. nodeName: matches[2],
  32422. objectName: matches[3],
  32423. objectIndex: matches[4],
  32424. propertyName: matches[5],
  32425. // required
  32426. propertyIndex: matches[6]
  32427. };
  32428. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  32429. if (lastDot !== undefined && lastDot !== -1) {
  32430. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  32431. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  32432. // 'bar' could be the objectName, or part of a nodeName (which can
  32433. // include '.' characters).
  32434. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  32435. results.nodeName = results.nodeName.substring(0, lastDot);
  32436. results.objectName = objectName;
  32437. }
  32438. }
  32439. if (results.propertyName === null || results.propertyName.length === 0) {
  32440. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  32441. }
  32442. return results;
  32443. },
  32444. findNode: function findNode(root, nodeName) {
  32445. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  32446. return root;
  32447. } // search into skeleton bones.
  32448. if (root.skeleton) {
  32449. var bone = root.skeleton.getBoneByName(nodeName);
  32450. if (bone !== undefined) {
  32451. return bone;
  32452. }
  32453. } // search into node subtree.
  32454. if (root.children) {
  32455. var searchNodeSubtree = function searchNodeSubtree(children) {
  32456. for (var i = 0; i < children.length; i++) {
  32457. var childNode = children[i];
  32458. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  32459. return childNode;
  32460. }
  32461. var result = searchNodeSubtree(childNode.children);
  32462. if (result) return result;
  32463. }
  32464. return null;
  32465. };
  32466. var subTreeNode = searchNodeSubtree(root.children);
  32467. if (subTreeNode) {
  32468. return subTreeNode;
  32469. }
  32470. }
  32471. return null;
  32472. }
  32473. });
  32474. Object.assign(PropertyBinding.prototype, {
  32475. // prototype, continued
  32476. // these are used to "bind" a nonexistent property
  32477. _getValue_unavailable: function _getValue_unavailable() {},
  32478. _setValue_unavailable: function _setValue_unavailable() {},
  32479. BindingType: {
  32480. Direct: 0,
  32481. EntireArray: 1,
  32482. ArrayElement: 2,
  32483. HasFromToArray: 3
  32484. },
  32485. Versioning: {
  32486. None: 0,
  32487. NeedsUpdate: 1,
  32488. MatrixWorldNeedsUpdate: 2
  32489. },
  32490. GetterByBindingType: [function getValue_direct(buffer, offset) {
  32491. buffer[offset] = this.node[this.propertyName];
  32492. }, function getValue_array(buffer, offset) {
  32493. var source = this.resolvedProperty;
  32494. for (var i = 0, n = source.length; i !== n; ++i) {
  32495. buffer[offset++] = source[i];
  32496. }
  32497. }, function getValue_arrayElement(buffer, offset) {
  32498. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  32499. }, function getValue_toArray(buffer, offset) {
  32500. this.resolvedProperty.toArray(buffer, offset);
  32501. }],
  32502. SetterByBindingTypeAndVersioning: [[// Direct
  32503. function setValue_direct(buffer, offset) {
  32504. this.targetObject[this.propertyName] = buffer[offset];
  32505. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  32506. this.targetObject[this.propertyName] = buffer[offset];
  32507. this.targetObject.needsUpdate = true;
  32508. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  32509. this.targetObject[this.propertyName] = buffer[offset];
  32510. this.targetObject.matrixWorldNeedsUpdate = true;
  32511. }], [// EntireArray
  32512. function setValue_array(buffer, offset) {
  32513. var dest = this.resolvedProperty;
  32514. for (var i = 0, n = dest.length; i !== n; ++i) {
  32515. dest[i] = buffer[offset++];
  32516. }
  32517. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  32518. var dest = this.resolvedProperty;
  32519. for (var i = 0, n = dest.length; i !== n; ++i) {
  32520. dest[i] = buffer[offset++];
  32521. }
  32522. this.targetObject.needsUpdate = true;
  32523. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  32524. var dest = this.resolvedProperty;
  32525. for (var i = 0, n = dest.length; i !== n; ++i) {
  32526. dest[i] = buffer[offset++];
  32527. }
  32528. this.targetObject.matrixWorldNeedsUpdate = true;
  32529. }], [// ArrayElement
  32530. function setValue_arrayElement(buffer, offset) {
  32531. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  32532. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  32533. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  32534. this.targetObject.needsUpdate = true;
  32535. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  32536. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  32537. this.targetObject.matrixWorldNeedsUpdate = true;
  32538. }], [// HasToFromArray
  32539. function setValue_fromArray(buffer, offset) {
  32540. this.resolvedProperty.fromArray(buffer, offset);
  32541. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  32542. this.resolvedProperty.fromArray(buffer, offset);
  32543. this.targetObject.needsUpdate = true;
  32544. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  32545. this.resolvedProperty.fromArray(buffer, offset);
  32546. this.targetObject.matrixWorldNeedsUpdate = true;
  32547. }]],
  32548. getValue: function getValue_unbound(targetArray, offset) {
  32549. this.bind();
  32550. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  32551. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  32552. // prototype version of these methods with one that represents
  32553. // the bound state. When the property is not found, the methods
  32554. // become no-ops.
  32555. },
  32556. setValue: function getValue_unbound(sourceArray, offset) {
  32557. this.bind();
  32558. this.setValue(sourceArray, offset);
  32559. },
  32560. // create getter / setter pair for a property in the scene graph
  32561. bind: function bind() {
  32562. var targetObject = this.node;
  32563. var parsedPath = this.parsedPath;
  32564. var objectName = parsedPath.objectName;
  32565. var propertyName = parsedPath.propertyName;
  32566. var propertyIndex = parsedPath.propertyIndex;
  32567. if (!targetObject) {
  32568. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  32569. this.node = targetObject;
  32570. } // set fail state so we can just 'return' on error
  32571. this.getValue = this._getValue_unavailable;
  32572. this.setValue = this._setValue_unavailable; // ensure there is a value node
  32573. if (!targetObject) {
  32574. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  32575. return;
  32576. }
  32577. if (objectName) {
  32578. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  32579. switch (objectName) {
  32580. case 'materials':
  32581. if (!targetObject.material) {
  32582. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  32583. return;
  32584. }
  32585. if (!targetObject.material.materials) {
  32586. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  32587. return;
  32588. }
  32589. targetObject = targetObject.material.materials;
  32590. break;
  32591. case 'bones':
  32592. if (!targetObject.skeleton) {
  32593. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  32594. return;
  32595. } // potential future optimization: skip this if propertyIndex is already an integer
  32596. // and convert the integer string to a true integer.
  32597. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  32598. for (var i = 0; i < targetObject.length; i++) {
  32599. if (targetObject[i].name === objectIndex) {
  32600. objectIndex = i;
  32601. break;
  32602. }
  32603. }
  32604. break;
  32605. default:
  32606. if (targetObject[objectName] === undefined) {
  32607. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  32608. return;
  32609. }
  32610. targetObject = targetObject[objectName];
  32611. }
  32612. if (objectIndex !== undefined) {
  32613. if (targetObject[objectIndex] === undefined) {
  32614. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  32615. return;
  32616. }
  32617. targetObject = targetObject[objectIndex];
  32618. }
  32619. } // resolve property
  32620. var nodeProperty = targetObject[propertyName];
  32621. if (nodeProperty === undefined) {
  32622. var nodeName = parsedPath.nodeName;
  32623. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  32624. return;
  32625. } // determine versioning scheme
  32626. var versioning = this.Versioning.None;
  32627. this.targetObject = targetObject;
  32628. if (targetObject.needsUpdate !== undefined) {
  32629. // material
  32630. versioning = this.Versioning.NeedsUpdate;
  32631. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  32632. // node transform
  32633. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  32634. } // determine how the property gets bound
  32635. var bindingType = this.BindingType.Direct;
  32636. if (propertyIndex !== undefined) {
  32637. // access a sub element of the property array (only primitives are supported right now)
  32638. if (propertyName === "morphTargetInfluences") {
  32639. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  32640. // support resolving morphTarget names into indices.
  32641. if (!targetObject.geometry) {
  32642. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  32643. return;
  32644. }
  32645. if (targetObject.geometry.isBufferGeometry) {
  32646. if (!targetObject.geometry.morphAttributes) {
  32647. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  32648. return;
  32649. }
  32650. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  32651. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  32652. }
  32653. } else {
  32654. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  32655. return;
  32656. }
  32657. }
  32658. bindingType = this.BindingType.ArrayElement;
  32659. this.resolvedProperty = nodeProperty;
  32660. this.propertyIndex = propertyIndex;
  32661. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  32662. // must use copy for Object3D.Euler/Quaternion
  32663. bindingType = this.BindingType.HasFromToArray;
  32664. this.resolvedProperty = nodeProperty;
  32665. } else if (Array.isArray(nodeProperty)) {
  32666. bindingType = this.BindingType.EntireArray;
  32667. this.resolvedProperty = nodeProperty;
  32668. } else {
  32669. this.propertyName = propertyName;
  32670. } // select getter / setter
  32671. this.getValue = this.GetterByBindingType[bindingType];
  32672. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  32673. },
  32674. unbind: function unbind() {
  32675. this.node = null; // back to the prototype version of getValue / setValue
  32676. // note: avoiding to mutate the shape of 'this' via 'delete'
  32677. this.getValue = this._getValue_unbound;
  32678. this.setValue = this._setValue_unbound;
  32679. }
  32680. }); // DECLARE ALIAS AFTER assign prototype
  32681. Object.assign(PropertyBinding.prototype, {
  32682. // initial state of these methods that calls 'bind'
  32683. _getValue_unbound: PropertyBinding.prototype.getValue,
  32684. _setValue_unbound: PropertyBinding.prototype.setValue
  32685. });
  32686. /**
  32687. *
  32688. * A group of objects that receives a shared animation state.
  32689. *
  32690. * Usage:
  32691. *
  32692. * - Add objects you would otherwise pass as 'root' to the
  32693. * constructor or the .clipAction method of AnimationMixer.
  32694. *
  32695. * - Instead pass this object as 'root'.
  32696. *
  32697. * - You can also add and remove objects later when the mixer
  32698. * is running.
  32699. *
  32700. * Note:
  32701. *
  32702. * Objects of this class appear as one object to the mixer,
  32703. * so cache control of the individual objects must be done
  32704. * on the group.
  32705. *
  32706. * Limitation:
  32707. *
  32708. * - The animated properties must be compatible among the
  32709. * all objects in the group.
  32710. *
  32711. * - A single property can either be controlled through a
  32712. * target group or directly, but not both.
  32713. */
  32714. function AnimationObjectGroup() {
  32715. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  32716. this._objects = Array.prototype.slice.call(arguments);
  32717. this.nCachedObjects_ = 0; // threshold
  32718. // note: read by PropertyBinding.Composite
  32719. var indices = {};
  32720. this._indicesByUUID = indices; // for bookkeeping
  32721. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32722. indices[arguments[i].uuid] = i;
  32723. }
  32724. this._paths = []; // inside: string
  32725. this._parsedPaths = []; // inside: { we don't care, here }
  32726. this._bindings = []; // inside: Array< PropertyBinding >
  32727. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  32728. var scope = this;
  32729. this.stats = {
  32730. objects: {
  32731. get total() {
  32732. return scope._objects.length;
  32733. },
  32734. get inUse() {
  32735. return this.total - scope.nCachedObjects_;
  32736. }
  32737. },
  32738. get bindingsPerObject() {
  32739. return scope._bindings.length;
  32740. }
  32741. };
  32742. }
  32743. Object.assign(AnimationObjectGroup.prototype, {
  32744. isAnimationObjectGroup: true,
  32745. add: function add() {
  32746. var objects = this._objects,
  32747. indicesByUUID = this._indicesByUUID,
  32748. paths = this._paths,
  32749. parsedPaths = this._parsedPaths,
  32750. bindings = this._bindings,
  32751. nBindings = bindings.length;
  32752. var knownObject = undefined,
  32753. nObjects = objects.length,
  32754. nCachedObjects = this.nCachedObjects_;
  32755. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32756. var object = arguments[i],
  32757. uuid = object.uuid;
  32758. var index = indicesByUUID[uuid];
  32759. if (index === undefined) {
  32760. // unknown object -> add it to the ACTIVE region
  32761. index = nObjects++;
  32762. indicesByUUID[uuid] = index;
  32763. objects.push(object); // accounting is done, now do the same for all bindings
  32764. for (var j = 0, m = nBindings; j !== m; ++j) {
  32765. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  32766. }
  32767. } else if (index < nCachedObjects) {
  32768. knownObject = objects[index]; // move existing object to the ACTIVE region
  32769. var firstActiveIndex = --nCachedObjects,
  32770. lastCachedObject = objects[firstActiveIndex];
  32771. indicesByUUID[lastCachedObject.uuid] = index;
  32772. objects[index] = lastCachedObject;
  32773. indicesByUUID[uuid] = firstActiveIndex;
  32774. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  32775. for (var _j = 0, _m = nBindings; _j !== _m; ++_j) {
  32776. var bindingsForPath = bindings[_j],
  32777. lastCached = bindingsForPath[firstActiveIndex];
  32778. var binding = bindingsForPath[index];
  32779. bindingsForPath[index] = lastCached;
  32780. if (binding === undefined) {
  32781. // since we do not bother to create new bindings
  32782. // for objects that are cached, the binding may
  32783. // or may not exist
  32784. binding = new PropertyBinding(object, paths[_j], parsedPaths[_j]);
  32785. }
  32786. bindingsForPath[firstActiveIndex] = binding;
  32787. }
  32788. } else if (objects[index] !== knownObject) {
  32789. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  32790. } // else the object is already where we want it to be
  32791. } // for arguments
  32792. this.nCachedObjects_ = nCachedObjects;
  32793. },
  32794. remove: function remove() {
  32795. var objects = this._objects,
  32796. indicesByUUID = this._indicesByUUID,
  32797. bindings = this._bindings,
  32798. nBindings = bindings.length;
  32799. var nCachedObjects = this.nCachedObjects_;
  32800. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32801. var object = arguments[i],
  32802. uuid = object.uuid,
  32803. index = indicesByUUID[uuid];
  32804. if (index !== undefined && index >= nCachedObjects) {
  32805. // move existing object into the CACHED region
  32806. var lastCachedIndex = nCachedObjects++,
  32807. firstActiveObject = objects[lastCachedIndex];
  32808. indicesByUUID[firstActiveObject.uuid] = index;
  32809. objects[index] = firstActiveObject;
  32810. indicesByUUID[uuid] = lastCachedIndex;
  32811. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  32812. for (var j = 0, m = nBindings; j !== m; ++j) {
  32813. var bindingsForPath = bindings[j],
  32814. firstActive = bindingsForPath[lastCachedIndex],
  32815. binding = bindingsForPath[index];
  32816. bindingsForPath[index] = firstActive;
  32817. bindingsForPath[lastCachedIndex] = binding;
  32818. }
  32819. }
  32820. } // for arguments
  32821. this.nCachedObjects_ = nCachedObjects;
  32822. },
  32823. // remove & forget
  32824. uncache: function uncache() {
  32825. var objects = this._objects,
  32826. indicesByUUID = this._indicesByUUID,
  32827. bindings = this._bindings,
  32828. nBindings = bindings.length;
  32829. var nCachedObjects = this.nCachedObjects_,
  32830. nObjects = objects.length;
  32831. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32832. var object = arguments[i],
  32833. uuid = object.uuid,
  32834. index = indicesByUUID[uuid];
  32835. if (index !== undefined) {
  32836. delete indicesByUUID[uuid];
  32837. if (index < nCachedObjects) {
  32838. // object is cached, shrink the CACHED region
  32839. var firstActiveIndex = --nCachedObjects,
  32840. lastCachedObject = objects[firstActiveIndex],
  32841. lastIndex = --nObjects,
  32842. lastObject = objects[lastIndex]; // last cached object takes this object's place
  32843. indicesByUUID[lastCachedObject.uuid] = index;
  32844. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  32845. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  32846. objects[firstActiveIndex] = lastObject;
  32847. objects.pop(); // accounting is done, now do the same for all bindings
  32848. for (var j = 0, m = nBindings; j !== m; ++j) {
  32849. var bindingsForPath = bindings[j],
  32850. lastCached = bindingsForPath[firstActiveIndex],
  32851. last = bindingsForPath[lastIndex];
  32852. bindingsForPath[index] = lastCached;
  32853. bindingsForPath[firstActiveIndex] = last;
  32854. bindingsForPath.pop();
  32855. }
  32856. } else {
  32857. // object is active, just swap with the last and pop
  32858. var _lastIndex = --nObjects,
  32859. _lastObject = objects[_lastIndex];
  32860. if (_lastIndex > 0) {
  32861. indicesByUUID[_lastObject.uuid] = index;
  32862. }
  32863. objects[index] = _lastObject;
  32864. objects.pop(); // accounting is done, now do the same for all bindings
  32865. for (var _j2 = 0, _m2 = nBindings; _j2 !== _m2; ++_j2) {
  32866. var _bindingsForPath = bindings[_j2];
  32867. _bindingsForPath[index] = _bindingsForPath[_lastIndex];
  32868. _bindingsForPath.pop();
  32869. }
  32870. } // cached or active
  32871. } // if object is known
  32872. } // for arguments
  32873. this.nCachedObjects_ = nCachedObjects;
  32874. },
  32875. // Internal interface used by befriended PropertyBinding.Composite:
  32876. subscribe_: function subscribe_(path, parsedPath) {
  32877. // returns an array of bindings for the given path that is changed
  32878. // according to the contained objects in the group
  32879. var indicesByPath = this._bindingsIndicesByPath;
  32880. var index = indicesByPath[path];
  32881. var bindings = this._bindings;
  32882. if (index !== undefined) return bindings[index];
  32883. var paths = this._paths,
  32884. parsedPaths = this._parsedPaths,
  32885. objects = this._objects,
  32886. nObjects = objects.length,
  32887. nCachedObjects = this.nCachedObjects_,
  32888. bindingsForPath = new Array(nObjects);
  32889. index = bindings.length;
  32890. indicesByPath[path] = index;
  32891. paths.push(path);
  32892. parsedPaths.push(parsedPath);
  32893. bindings.push(bindingsForPath);
  32894. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  32895. var object = objects[i];
  32896. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  32897. }
  32898. return bindingsForPath;
  32899. },
  32900. unsubscribe_: function unsubscribe_(path) {
  32901. // tells the group to forget about a property path and no longer
  32902. // update the array previously obtained with 'subscribe_'
  32903. var indicesByPath = this._bindingsIndicesByPath,
  32904. index = indicesByPath[path];
  32905. if (index !== undefined) {
  32906. var paths = this._paths,
  32907. parsedPaths = this._parsedPaths,
  32908. bindings = this._bindings,
  32909. lastBindingsIndex = bindings.length - 1,
  32910. lastBindings = bindings[lastBindingsIndex],
  32911. lastBindingsPath = path[lastBindingsIndex];
  32912. indicesByPath[lastBindingsPath] = index;
  32913. bindings[index] = lastBindings;
  32914. bindings.pop();
  32915. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  32916. parsedPaths.pop();
  32917. paths[index] = paths[lastBindingsIndex];
  32918. paths.pop();
  32919. }
  32920. }
  32921. });
  32922. var AnimationAction = /*#__PURE__*/function () {
  32923. function AnimationAction(mixer, clip, localRoot, blendMode) {
  32924. if (localRoot === void 0) {
  32925. localRoot = null;
  32926. }
  32927. if (blendMode === void 0) {
  32928. blendMode = clip.blendMode;
  32929. }
  32930. this._mixer = mixer;
  32931. this._clip = clip;
  32932. this._localRoot = localRoot;
  32933. this.blendMode = blendMode;
  32934. var tracks = clip.tracks,
  32935. nTracks = tracks.length,
  32936. interpolants = new Array(nTracks);
  32937. var interpolantSettings = {
  32938. endingStart: ZeroCurvatureEnding,
  32939. endingEnd: ZeroCurvatureEnding
  32940. };
  32941. for (var i = 0; i !== nTracks; ++i) {
  32942. var interpolant = tracks[i].createInterpolant(null);
  32943. interpolants[i] = interpolant;
  32944. interpolant.settings = interpolantSettings;
  32945. }
  32946. this._interpolantSettings = interpolantSettings;
  32947. this._interpolants = interpolants; // bound by the mixer
  32948. // inside: PropertyMixer (managed by the mixer)
  32949. this._propertyBindings = new Array(nTracks);
  32950. this._cacheIndex = null; // for the memory manager
  32951. this._byClipCacheIndex = null; // for the memory manager
  32952. this._timeScaleInterpolant = null;
  32953. this._weightInterpolant = null;
  32954. this.loop = LoopRepeat;
  32955. this._loopCount = -1; // global mixer time when the action is to be started
  32956. // it's set back to 'null' upon start of the action
  32957. this._startTime = null; // scaled local time of the action
  32958. // gets clamped or wrapped to 0..clip.duration according to loop
  32959. this.time = 0;
  32960. this.timeScale = 1;
  32961. this._effectiveTimeScale = 1;
  32962. this.weight = 1;
  32963. this._effectiveWeight = 1;
  32964. this.repetitions = Infinity; // no. of repetitions when looping
  32965. this.paused = false; // true -> zero effective time scale
  32966. this.enabled = true; // false -> zero effective weight
  32967. this.clampWhenFinished = false; // keep feeding the last frame?
  32968. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  32969. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  32970. } // State & Scheduling
  32971. var _proto = AnimationAction.prototype;
  32972. _proto.play = function play() {
  32973. this._mixer._activateAction(this);
  32974. return this;
  32975. };
  32976. _proto.stop = function stop() {
  32977. this._mixer._deactivateAction(this);
  32978. return this.reset();
  32979. };
  32980. _proto.reset = function reset() {
  32981. this.paused = false;
  32982. this.enabled = true;
  32983. this.time = 0; // restart clip
  32984. this._loopCount = -1; // forget previous loops
  32985. this._startTime = null; // forget scheduling
  32986. return this.stopFading().stopWarping();
  32987. };
  32988. _proto.isRunning = function isRunning() {
  32989. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  32990. } // return true when play has been called
  32991. ;
  32992. _proto.isScheduled = function isScheduled() {
  32993. return this._mixer._isActiveAction(this);
  32994. };
  32995. _proto.startAt = function startAt(time) {
  32996. this._startTime = time;
  32997. return this;
  32998. };
  32999. _proto.setLoop = function setLoop(mode, repetitions) {
  33000. this.loop = mode;
  33001. this.repetitions = repetitions;
  33002. return this;
  33003. } // Weight
  33004. // set the weight stopping any scheduled fading
  33005. // although .enabled = false yields an effective weight of zero, this
  33006. // method does *not* change .enabled, because it would be confusing
  33007. ;
  33008. _proto.setEffectiveWeight = function setEffectiveWeight(weight) {
  33009. this.weight = weight; // note: same logic as when updated at runtime
  33010. this._effectiveWeight = this.enabled ? weight : 0;
  33011. return this.stopFading();
  33012. } // return the weight considering fading and .enabled
  33013. ;
  33014. _proto.getEffectiveWeight = function getEffectiveWeight() {
  33015. return this._effectiveWeight;
  33016. };
  33017. _proto.fadeIn = function fadeIn(duration) {
  33018. return this._scheduleFading(duration, 0, 1);
  33019. };
  33020. _proto.fadeOut = function fadeOut(duration) {
  33021. return this._scheduleFading(duration, 1, 0);
  33022. };
  33023. _proto.crossFadeFrom = function crossFadeFrom(fadeOutAction, duration, warp) {
  33024. fadeOutAction.fadeOut(duration);
  33025. this.fadeIn(duration);
  33026. if (warp) {
  33027. var fadeInDuration = this._clip.duration,
  33028. fadeOutDuration = fadeOutAction._clip.duration,
  33029. startEndRatio = fadeOutDuration / fadeInDuration,
  33030. endStartRatio = fadeInDuration / fadeOutDuration;
  33031. fadeOutAction.warp(1.0, startEndRatio, duration);
  33032. this.warp(endStartRatio, 1.0, duration);
  33033. }
  33034. return this;
  33035. };
  33036. _proto.crossFadeTo = function crossFadeTo(fadeInAction, duration, warp) {
  33037. return fadeInAction.crossFadeFrom(this, duration, warp);
  33038. };
  33039. _proto.stopFading = function stopFading() {
  33040. var weightInterpolant = this._weightInterpolant;
  33041. if (weightInterpolant !== null) {
  33042. this._weightInterpolant = null;
  33043. this._mixer._takeBackControlInterpolant(weightInterpolant);
  33044. }
  33045. return this;
  33046. } // Time Scale Control
  33047. // set the time scale stopping any scheduled warping
  33048. // although .paused = true yields an effective time scale of zero, this
  33049. // method does *not* change .paused, because it would be confusing
  33050. ;
  33051. _proto.setEffectiveTimeScale = function setEffectiveTimeScale(timeScale) {
  33052. this.timeScale = timeScale;
  33053. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  33054. return this.stopWarping();
  33055. } // return the time scale considering warping and .paused
  33056. ;
  33057. _proto.getEffectiveTimeScale = function getEffectiveTimeScale() {
  33058. return this._effectiveTimeScale;
  33059. };
  33060. _proto.setDuration = function setDuration(duration) {
  33061. this.timeScale = this._clip.duration / duration;
  33062. return this.stopWarping();
  33063. };
  33064. _proto.syncWith = function syncWith(action) {
  33065. this.time = action.time;
  33066. this.timeScale = action.timeScale;
  33067. return this.stopWarping();
  33068. };
  33069. _proto.halt = function halt(duration) {
  33070. return this.warp(this._effectiveTimeScale, 0, duration);
  33071. };
  33072. _proto.warp = function warp(startTimeScale, endTimeScale, duration) {
  33073. var mixer = this._mixer,
  33074. now = mixer.time,
  33075. timeScale = this.timeScale;
  33076. var interpolant = this._timeScaleInterpolant;
  33077. if (interpolant === null) {
  33078. interpolant = mixer._lendControlInterpolant();
  33079. this._timeScaleInterpolant = interpolant;
  33080. }
  33081. var times = interpolant.parameterPositions,
  33082. values = interpolant.sampleValues;
  33083. times[0] = now;
  33084. times[1] = now + duration;
  33085. values[0] = startTimeScale / timeScale;
  33086. values[1] = endTimeScale / timeScale;
  33087. return this;
  33088. };
  33089. _proto.stopWarping = function stopWarping() {
  33090. var timeScaleInterpolant = this._timeScaleInterpolant;
  33091. if (timeScaleInterpolant !== null) {
  33092. this._timeScaleInterpolant = null;
  33093. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  33094. }
  33095. return this;
  33096. } // Object Accessors
  33097. ;
  33098. _proto.getMixer = function getMixer() {
  33099. return this._mixer;
  33100. };
  33101. _proto.getClip = function getClip() {
  33102. return this._clip;
  33103. };
  33104. _proto.getRoot = function getRoot() {
  33105. return this._localRoot || this._mixer._root;
  33106. } // Interna
  33107. ;
  33108. _proto._update = function _update(time, deltaTime, timeDirection, accuIndex) {
  33109. // called by the mixer
  33110. if (!this.enabled) {
  33111. // call ._updateWeight() to update ._effectiveWeight
  33112. this._updateWeight(time);
  33113. return;
  33114. }
  33115. var startTime = this._startTime;
  33116. if (startTime !== null) {
  33117. // check for scheduled start of action
  33118. var timeRunning = (time - startTime) * timeDirection;
  33119. if (timeRunning < 0 || timeDirection === 0) {
  33120. return; // yet to come / don't decide when delta = 0
  33121. } // start
  33122. this._startTime = null; // unschedule
  33123. deltaTime = timeDirection * timeRunning;
  33124. } // apply time scale and advance time
  33125. deltaTime *= this._updateTimeScale(time);
  33126. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  33127. // an effective weight of 0
  33128. var weight = this._updateWeight(time);
  33129. if (weight > 0) {
  33130. var _interpolants = this._interpolants;
  33131. var propertyMixers = this._propertyBindings;
  33132. switch (this.blendMode) {
  33133. case AdditiveAnimationBlendMode:
  33134. for (var j = 0, m = _interpolants.length; j !== m; ++j) {
  33135. _interpolants[j].evaluate(clipTime);
  33136. propertyMixers[j].accumulateAdditive(weight);
  33137. }
  33138. break;
  33139. case NormalAnimationBlendMode:
  33140. default:
  33141. for (var _j = 0, _m = _interpolants.length; _j !== _m; ++_j) {
  33142. _interpolants[_j].evaluate(clipTime);
  33143. propertyMixers[_j].accumulate(accuIndex, weight);
  33144. }
  33145. }
  33146. }
  33147. };
  33148. _proto._updateWeight = function _updateWeight(time) {
  33149. var weight = 0;
  33150. if (this.enabled) {
  33151. weight = this.weight;
  33152. var interpolant = this._weightInterpolant;
  33153. if (interpolant !== null) {
  33154. var interpolantValue = interpolant.evaluate(time)[0];
  33155. weight *= interpolantValue;
  33156. if (time > interpolant.parameterPositions[1]) {
  33157. this.stopFading();
  33158. if (interpolantValue === 0) {
  33159. // faded out, disable
  33160. this.enabled = false;
  33161. }
  33162. }
  33163. }
  33164. }
  33165. this._effectiveWeight = weight;
  33166. return weight;
  33167. };
  33168. _proto._updateTimeScale = function _updateTimeScale(time) {
  33169. var timeScale = 0;
  33170. if (!this.paused) {
  33171. timeScale = this.timeScale;
  33172. var interpolant = this._timeScaleInterpolant;
  33173. if (interpolant !== null) {
  33174. var interpolantValue = interpolant.evaluate(time)[0];
  33175. timeScale *= interpolantValue;
  33176. if (time > interpolant.parameterPositions[1]) {
  33177. this.stopWarping();
  33178. if (timeScale === 0) {
  33179. // motion has halted, pause
  33180. this.paused = true;
  33181. } else {
  33182. // warp done - apply final time scale
  33183. this.timeScale = timeScale;
  33184. }
  33185. }
  33186. }
  33187. }
  33188. this._effectiveTimeScale = timeScale;
  33189. return timeScale;
  33190. };
  33191. _proto._updateTime = function _updateTime(deltaTime) {
  33192. var duration = this._clip.duration;
  33193. var loop = this.loop;
  33194. var time = this.time + deltaTime;
  33195. var loopCount = this._loopCount;
  33196. var pingPong = loop === LoopPingPong;
  33197. if (deltaTime === 0) {
  33198. if (loopCount === -1) return time;
  33199. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  33200. }
  33201. if (loop === LoopOnce) {
  33202. if (loopCount === -1) {
  33203. // just started
  33204. this._loopCount = 0;
  33205. this._setEndings(true, true, false);
  33206. }
  33207. handle_stop: {
  33208. if (time >= duration) {
  33209. time = duration;
  33210. } else if (time < 0) {
  33211. time = 0;
  33212. } else {
  33213. this.time = time;
  33214. break handle_stop;
  33215. }
  33216. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  33217. this.time = time;
  33218. this._mixer.dispatchEvent({
  33219. type: 'finished',
  33220. action: this,
  33221. direction: deltaTime < 0 ? -1 : 1
  33222. });
  33223. }
  33224. } else {
  33225. // repetitive Repeat or PingPong
  33226. if (loopCount === -1) {
  33227. // just started
  33228. if (deltaTime >= 0) {
  33229. loopCount = 0;
  33230. this._setEndings(true, this.repetitions === 0, pingPong);
  33231. } else {
  33232. // when looping in reverse direction, the initial
  33233. // transition through zero counts as a repetition,
  33234. // so leave loopCount at -1
  33235. this._setEndings(this.repetitions === 0, true, pingPong);
  33236. }
  33237. }
  33238. if (time >= duration || time < 0) {
  33239. // wrap around
  33240. var loopDelta = Math.floor(time / duration); // signed
  33241. time -= duration * loopDelta;
  33242. loopCount += Math.abs(loopDelta);
  33243. var pending = this.repetitions - loopCount;
  33244. if (pending <= 0) {
  33245. // have to stop (switch state, clamp time, fire event)
  33246. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  33247. time = deltaTime > 0 ? duration : 0;
  33248. this.time = time;
  33249. this._mixer.dispatchEvent({
  33250. type: 'finished',
  33251. action: this,
  33252. direction: deltaTime > 0 ? 1 : -1
  33253. });
  33254. } else {
  33255. // keep running
  33256. if (pending === 1) {
  33257. // entering the last round
  33258. var atStart = deltaTime < 0;
  33259. this._setEndings(atStart, !atStart, pingPong);
  33260. } else {
  33261. this._setEndings(false, false, pingPong);
  33262. }
  33263. this._loopCount = loopCount;
  33264. this.time = time;
  33265. this._mixer.dispatchEvent({
  33266. type: 'loop',
  33267. action: this,
  33268. loopDelta: loopDelta
  33269. });
  33270. }
  33271. } else {
  33272. this.time = time;
  33273. }
  33274. if (pingPong && (loopCount & 1) === 1) {
  33275. // invert time for the "pong round"
  33276. return duration - time;
  33277. }
  33278. }
  33279. return time;
  33280. };
  33281. _proto._setEndings = function _setEndings(atStart, atEnd, pingPong) {
  33282. var settings = this._interpolantSettings;
  33283. if (pingPong) {
  33284. settings.endingStart = ZeroSlopeEnding;
  33285. settings.endingEnd = ZeroSlopeEnding;
  33286. } else {
  33287. // assuming for LoopOnce atStart == atEnd == true
  33288. if (atStart) {
  33289. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  33290. } else {
  33291. settings.endingStart = WrapAroundEnding;
  33292. }
  33293. if (atEnd) {
  33294. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  33295. } else {
  33296. settings.endingEnd = WrapAroundEnding;
  33297. }
  33298. }
  33299. };
  33300. _proto._scheduleFading = function _scheduleFading(duration, weightNow, weightThen) {
  33301. var mixer = this._mixer,
  33302. now = mixer.time;
  33303. var interpolant = this._weightInterpolant;
  33304. if (interpolant === null) {
  33305. interpolant = mixer._lendControlInterpolant();
  33306. this._weightInterpolant = interpolant;
  33307. }
  33308. var times = interpolant.parameterPositions,
  33309. values = interpolant.sampleValues;
  33310. times[0] = now;
  33311. values[0] = weightNow;
  33312. times[1] = now + duration;
  33313. values[1] = weightThen;
  33314. return this;
  33315. };
  33316. return AnimationAction;
  33317. }();
  33318. function AnimationMixer(root) {
  33319. this._root = root;
  33320. this._initMemoryManager();
  33321. this._accuIndex = 0;
  33322. this.time = 0;
  33323. this.timeScale = 1.0;
  33324. }
  33325. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  33326. constructor: AnimationMixer,
  33327. _bindAction: function _bindAction(action, prototypeAction) {
  33328. var root = action._localRoot || this._root,
  33329. tracks = action._clip.tracks,
  33330. nTracks = tracks.length,
  33331. bindings = action._propertyBindings,
  33332. interpolants = action._interpolants,
  33333. rootUuid = root.uuid,
  33334. bindingsByRoot = this._bindingsByRootAndName;
  33335. var bindingsByName = bindingsByRoot[rootUuid];
  33336. if (bindingsByName === undefined) {
  33337. bindingsByName = {};
  33338. bindingsByRoot[rootUuid] = bindingsByName;
  33339. }
  33340. for (var i = 0; i !== nTracks; ++i) {
  33341. var track = tracks[i],
  33342. trackName = track.name;
  33343. var binding = bindingsByName[trackName];
  33344. if (binding !== undefined) {
  33345. bindings[i] = binding;
  33346. } else {
  33347. binding = bindings[i];
  33348. if (binding !== undefined) {
  33349. // existing binding, make sure the cache knows
  33350. if (binding._cacheIndex === null) {
  33351. ++binding.referenceCount;
  33352. this._addInactiveBinding(binding, rootUuid, trackName);
  33353. }
  33354. continue;
  33355. }
  33356. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  33357. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  33358. ++binding.referenceCount;
  33359. this._addInactiveBinding(binding, rootUuid, trackName);
  33360. bindings[i] = binding;
  33361. }
  33362. interpolants[i].resultBuffer = binding.buffer;
  33363. }
  33364. },
  33365. _activateAction: function _activateAction(action) {
  33366. if (!this._isActiveAction(action)) {
  33367. if (action._cacheIndex === null) {
  33368. // this action has been forgotten by the cache, but the user
  33369. // appears to be still using it -> rebind
  33370. var rootUuid = (action._localRoot || this._root).uuid,
  33371. clipUuid = action._clip.uuid,
  33372. actionsForClip = this._actionsByClip[clipUuid];
  33373. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  33374. this._addInactiveAction(action, clipUuid, rootUuid);
  33375. }
  33376. var bindings = action._propertyBindings; // increment reference counts / sort out state
  33377. for (var i = 0, n = bindings.length; i !== n; ++i) {
  33378. var binding = bindings[i];
  33379. if (binding.useCount++ === 0) {
  33380. this._lendBinding(binding);
  33381. binding.saveOriginalState();
  33382. }
  33383. }
  33384. this._lendAction(action);
  33385. }
  33386. },
  33387. _deactivateAction: function _deactivateAction(action) {
  33388. if (this._isActiveAction(action)) {
  33389. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  33390. for (var i = 0, n = bindings.length; i !== n; ++i) {
  33391. var binding = bindings[i];
  33392. if (--binding.useCount === 0) {
  33393. binding.restoreOriginalState();
  33394. this._takeBackBinding(binding);
  33395. }
  33396. }
  33397. this._takeBackAction(action);
  33398. }
  33399. },
  33400. // Memory manager
  33401. _initMemoryManager: function _initMemoryManager() {
  33402. this._actions = []; // 'nActiveActions' followed by inactive ones
  33403. this._nActiveActions = 0;
  33404. this._actionsByClip = {}; // inside:
  33405. // {
  33406. // knownActions: Array< AnimationAction > - used as prototypes
  33407. // actionByRoot: AnimationAction - lookup
  33408. // }
  33409. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  33410. this._nActiveBindings = 0;
  33411. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  33412. this._controlInterpolants = []; // same game as above
  33413. this._nActiveControlInterpolants = 0;
  33414. var scope = this;
  33415. this.stats = {
  33416. actions: {
  33417. get total() {
  33418. return scope._actions.length;
  33419. },
  33420. get inUse() {
  33421. return scope._nActiveActions;
  33422. }
  33423. },
  33424. bindings: {
  33425. get total() {
  33426. return scope._bindings.length;
  33427. },
  33428. get inUse() {
  33429. return scope._nActiveBindings;
  33430. }
  33431. },
  33432. controlInterpolants: {
  33433. get total() {
  33434. return scope._controlInterpolants.length;
  33435. },
  33436. get inUse() {
  33437. return scope._nActiveControlInterpolants;
  33438. }
  33439. }
  33440. };
  33441. },
  33442. // Memory management for AnimationAction objects
  33443. _isActiveAction: function _isActiveAction(action) {
  33444. var index = action._cacheIndex;
  33445. return index !== null && index < this._nActiveActions;
  33446. },
  33447. _addInactiveAction: function _addInactiveAction(action, clipUuid, rootUuid) {
  33448. var actions = this._actions,
  33449. actionsByClip = this._actionsByClip;
  33450. var actionsForClip = actionsByClip[clipUuid];
  33451. if (actionsForClip === undefined) {
  33452. actionsForClip = {
  33453. knownActions: [action],
  33454. actionByRoot: {}
  33455. };
  33456. action._byClipCacheIndex = 0;
  33457. actionsByClip[clipUuid] = actionsForClip;
  33458. } else {
  33459. var knownActions = actionsForClip.knownActions;
  33460. action._byClipCacheIndex = knownActions.length;
  33461. knownActions.push(action);
  33462. }
  33463. action._cacheIndex = actions.length;
  33464. actions.push(action);
  33465. actionsForClip.actionByRoot[rootUuid] = action;
  33466. },
  33467. _removeInactiveAction: function _removeInactiveAction(action) {
  33468. var actions = this._actions,
  33469. lastInactiveAction = actions[actions.length - 1],
  33470. cacheIndex = action._cacheIndex;
  33471. lastInactiveAction._cacheIndex = cacheIndex;
  33472. actions[cacheIndex] = lastInactiveAction;
  33473. actions.pop();
  33474. action._cacheIndex = null;
  33475. var clipUuid = action._clip.uuid,
  33476. actionsByClip = this._actionsByClip,
  33477. actionsForClip = actionsByClip[clipUuid],
  33478. knownActionsForClip = actionsForClip.knownActions,
  33479. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  33480. byClipCacheIndex = action._byClipCacheIndex;
  33481. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  33482. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  33483. knownActionsForClip.pop();
  33484. action._byClipCacheIndex = null;
  33485. var actionByRoot = actionsForClip.actionByRoot,
  33486. rootUuid = (action._localRoot || this._root).uuid;
  33487. delete actionByRoot[rootUuid];
  33488. if (knownActionsForClip.length === 0) {
  33489. delete actionsByClip[clipUuid];
  33490. }
  33491. this._removeInactiveBindingsForAction(action);
  33492. },
  33493. _removeInactiveBindingsForAction: function _removeInactiveBindingsForAction(action) {
  33494. var bindings = action._propertyBindings;
  33495. for (var i = 0, n = bindings.length; i !== n; ++i) {
  33496. var binding = bindings[i];
  33497. if (--binding.referenceCount === 0) {
  33498. this._removeInactiveBinding(binding);
  33499. }
  33500. }
  33501. },
  33502. _lendAction: function _lendAction(action) {
  33503. // [ active actions | inactive actions ]
  33504. // [ active actions >| inactive actions ]
  33505. // s a
  33506. // <-swap->
  33507. // a s
  33508. var actions = this._actions,
  33509. prevIndex = action._cacheIndex,
  33510. lastActiveIndex = this._nActiveActions++,
  33511. firstInactiveAction = actions[lastActiveIndex];
  33512. action._cacheIndex = lastActiveIndex;
  33513. actions[lastActiveIndex] = action;
  33514. firstInactiveAction._cacheIndex = prevIndex;
  33515. actions[prevIndex] = firstInactiveAction;
  33516. },
  33517. _takeBackAction: function _takeBackAction(action) {
  33518. // [ active actions | inactive actions ]
  33519. // [ active actions |< inactive actions ]
  33520. // a s
  33521. // <-swap->
  33522. // s a
  33523. var actions = this._actions,
  33524. prevIndex = action._cacheIndex,
  33525. firstInactiveIndex = --this._nActiveActions,
  33526. lastActiveAction = actions[firstInactiveIndex];
  33527. action._cacheIndex = firstInactiveIndex;
  33528. actions[firstInactiveIndex] = action;
  33529. lastActiveAction._cacheIndex = prevIndex;
  33530. actions[prevIndex] = lastActiveAction;
  33531. },
  33532. // Memory management for PropertyMixer objects
  33533. _addInactiveBinding: function _addInactiveBinding(binding, rootUuid, trackName) {
  33534. var bindingsByRoot = this._bindingsByRootAndName,
  33535. bindings = this._bindings;
  33536. var bindingByName = bindingsByRoot[rootUuid];
  33537. if (bindingByName === undefined) {
  33538. bindingByName = {};
  33539. bindingsByRoot[rootUuid] = bindingByName;
  33540. }
  33541. bindingByName[trackName] = binding;
  33542. binding._cacheIndex = bindings.length;
  33543. bindings.push(binding);
  33544. },
  33545. _removeInactiveBinding: function _removeInactiveBinding(binding) {
  33546. var bindings = this._bindings,
  33547. propBinding = binding.binding,
  33548. rootUuid = propBinding.rootNode.uuid,
  33549. trackName = propBinding.path,
  33550. bindingsByRoot = this._bindingsByRootAndName,
  33551. bindingByName = bindingsByRoot[rootUuid],
  33552. lastInactiveBinding = bindings[bindings.length - 1],
  33553. cacheIndex = binding._cacheIndex;
  33554. lastInactiveBinding._cacheIndex = cacheIndex;
  33555. bindings[cacheIndex] = lastInactiveBinding;
  33556. bindings.pop();
  33557. delete bindingByName[trackName];
  33558. if (Object.keys(bindingByName).length === 0) {
  33559. delete bindingsByRoot[rootUuid];
  33560. }
  33561. },
  33562. _lendBinding: function _lendBinding(binding) {
  33563. var bindings = this._bindings,
  33564. prevIndex = binding._cacheIndex,
  33565. lastActiveIndex = this._nActiveBindings++,
  33566. firstInactiveBinding = bindings[lastActiveIndex];
  33567. binding._cacheIndex = lastActiveIndex;
  33568. bindings[lastActiveIndex] = binding;
  33569. firstInactiveBinding._cacheIndex = prevIndex;
  33570. bindings[prevIndex] = firstInactiveBinding;
  33571. },
  33572. _takeBackBinding: function _takeBackBinding(binding) {
  33573. var bindings = this._bindings,
  33574. prevIndex = binding._cacheIndex,
  33575. firstInactiveIndex = --this._nActiveBindings,
  33576. lastActiveBinding = bindings[firstInactiveIndex];
  33577. binding._cacheIndex = firstInactiveIndex;
  33578. bindings[firstInactiveIndex] = binding;
  33579. lastActiveBinding._cacheIndex = prevIndex;
  33580. bindings[prevIndex] = lastActiveBinding;
  33581. },
  33582. // Memory management of Interpolants for weight and time scale
  33583. _lendControlInterpolant: function _lendControlInterpolant() {
  33584. var interpolants = this._controlInterpolants,
  33585. lastActiveIndex = this._nActiveControlInterpolants++;
  33586. var interpolant = interpolants[lastActiveIndex];
  33587. if (interpolant === undefined) {
  33588. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  33589. interpolant.__cacheIndex = lastActiveIndex;
  33590. interpolants[lastActiveIndex] = interpolant;
  33591. }
  33592. return interpolant;
  33593. },
  33594. _takeBackControlInterpolant: function _takeBackControlInterpolant(interpolant) {
  33595. var interpolants = this._controlInterpolants,
  33596. prevIndex = interpolant.__cacheIndex,
  33597. firstInactiveIndex = --this._nActiveControlInterpolants,
  33598. lastActiveInterpolant = interpolants[firstInactiveIndex];
  33599. interpolant.__cacheIndex = firstInactiveIndex;
  33600. interpolants[firstInactiveIndex] = interpolant;
  33601. lastActiveInterpolant.__cacheIndex = prevIndex;
  33602. interpolants[prevIndex] = lastActiveInterpolant;
  33603. },
  33604. _controlInterpolantsResultBuffer: new Float32Array(1),
  33605. // return an action for a clip optionally using a custom root target
  33606. // object (this method allocates a lot of dynamic memory in case a
  33607. // previously unknown clip/root combination is specified)
  33608. clipAction: function clipAction(clip, optionalRoot, blendMode) {
  33609. var root = optionalRoot || this._root,
  33610. rootUuid = root.uuid;
  33611. var clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  33612. var clipUuid = clipObject !== null ? clipObject.uuid : clip;
  33613. var actionsForClip = this._actionsByClip[clipUuid];
  33614. var prototypeAction = null;
  33615. if (blendMode === undefined) {
  33616. if (clipObject !== null) {
  33617. blendMode = clipObject.blendMode;
  33618. } else {
  33619. blendMode = NormalAnimationBlendMode;
  33620. }
  33621. }
  33622. if (actionsForClip !== undefined) {
  33623. var existingAction = actionsForClip.actionByRoot[rootUuid];
  33624. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  33625. return existingAction;
  33626. } // we know the clip, so we don't have to parse all
  33627. // the bindings again but can just copy
  33628. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  33629. if (clipObject === null) clipObject = prototypeAction._clip;
  33630. } // clip must be known when specified via string
  33631. if (clipObject === null) return null; // allocate all resources required to run it
  33632. var newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  33633. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  33634. this._addInactiveAction(newAction, clipUuid, rootUuid);
  33635. return newAction;
  33636. },
  33637. // get an existing action
  33638. existingAction: function existingAction(clip, optionalRoot) {
  33639. var root = optionalRoot || this._root,
  33640. rootUuid = root.uuid,
  33641. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  33642. clipUuid = clipObject ? clipObject.uuid : clip,
  33643. actionsForClip = this._actionsByClip[clipUuid];
  33644. if (actionsForClip !== undefined) {
  33645. return actionsForClip.actionByRoot[rootUuid] || null;
  33646. }
  33647. return null;
  33648. },
  33649. // deactivates all previously scheduled actions
  33650. stopAllAction: function stopAllAction() {
  33651. var actions = this._actions,
  33652. nActions = this._nActiveActions;
  33653. for (var i = nActions - 1; i >= 0; --i) {
  33654. actions[i].stop();
  33655. }
  33656. return this;
  33657. },
  33658. // advance the time and update apply the animation
  33659. update: function update(deltaTime) {
  33660. deltaTime *= this.timeScale;
  33661. var actions = this._actions,
  33662. nActions = this._nActiveActions,
  33663. time = this.time += deltaTime,
  33664. timeDirection = Math.sign(deltaTime),
  33665. accuIndex = this._accuIndex ^= 1; // run active actions
  33666. for (var i = 0; i !== nActions; ++i) {
  33667. var action = actions[i];
  33668. action._update(time, deltaTime, timeDirection, accuIndex);
  33669. } // update scene graph
  33670. var bindings = this._bindings,
  33671. nBindings = this._nActiveBindings;
  33672. for (var _i = 0; _i !== nBindings; ++_i) {
  33673. bindings[_i].apply(accuIndex);
  33674. }
  33675. return this;
  33676. },
  33677. // Allows you to seek to a specific time in an animation.
  33678. setTime: function setTime(timeInSeconds) {
  33679. this.time = 0; // Zero out time attribute for AnimationMixer object;
  33680. for (var i = 0; i < this._actions.length; i++) {
  33681. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  33682. }
  33683. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  33684. },
  33685. // return this mixer's root target object
  33686. getRoot: function getRoot() {
  33687. return this._root;
  33688. },
  33689. // free all resources specific to a particular clip
  33690. uncacheClip: function uncacheClip(clip) {
  33691. var actions = this._actions,
  33692. clipUuid = clip.uuid,
  33693. actionsByClip = this._actionsByClip,
  33694. actionsForClip = actionsByClip[clipUuid];
  33695. if (actionsForClip !== undefined) {
  33696. // note: just calling _removeInactiveAction would mess up the
  33697. // iteration state and also require updating the state we can
  33698. // just throw away
  33699. var actionsToRemove = actionsForClip.knownActions;
  33700. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  33701. var action = actionsToRemove[i];
  33702. this._deactivateAction(action);
  33703. var cacheIndex = action._cacheIndex,
  33704. lastInactiveAction = actions[actions.length - 1];
  33705. action._cacheIndex = null;
  33706. action._byClipCacheIndex = null;
  33707. lastInactiveAction._cacheIndex = cacheIndex;
  33708. actions[cacheIndex] = lastInactiveAction;
  33709. actions.pop();
  33710. this._removeInactiveBindingsForAction(action);
  33711. }
  33712. delete actionsByClip[clipUuid];
  33713. }
  33714. },
  33715. // free all resources specific to a particular root target object
  33716. uncacheRoot: function uncacheRoot(root) {
  33717. var rootUuid = root.uuid,
  33718. actionsByClip = this._actionsByClip;
  33719. for (var clipUuid in actionsByClip) {
  33720. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  33721. action = actionByRoot[rootUuid];
  33722. if (action !== undefined) {
  33723. this._deactivateAction(action);
  33724. this._removeInactiveAction(action);
  33725. }
  33726. }
  33727. var bindingsByRoot = this._bindingsByRootAndName,
  33728. bindingByName = bindingsByRoot[rootUuid];
  33729. if (bindingByName !== undefined) {
  33730. for (var trackName in bindingByName) {
  33731. var binding = bindingByName[trackName];
  33732. binding.restoreOriginalState();
  33733. this._removeInactiveBinding(binding);
  33734. }
  33735. }
  33736. },
  33737. // remove a targeted clip from the cache
  33738. uncacheAction: function uncacheAction(clip, optionalRoot) {
  33739. var action = this.existingAction(clip, optionalRoot);
  33740. if (action !== null) {
  33741. this._deactivateAction(action);
  33742. this._removeInactiveAction(action);
  33743. }
  33744. }
  33745. });
  33746. var Uniform = /*#__PURE__*/function () {
  33747. function Uniform(value) {
  33748. if (typeof value === 'string') {
  33749. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  33750. value = arguments[1];
  33751. }
  33752. this.value = value;
  33753. }
  33754. var _proto = Uniform.prototype;
  33755. _proto.clone = function clone() {
  33756. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  33757. };
  33758. return Uniform;
  33759. }();
  33760. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  33761. InterleavedBuffer.call(this, array, stride);
  33762. this.meshPerAttribute = meshPerAttribute || 1;
  33763. }
  33764. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  33765. constructor: InstancedInterleavedBuffer,
  33766. isInstancedInterleavedBuffer: true,
  33767. copy: function copy(source) {
  33768. InterleavedBuffer.prototype.copy.call(this, source);
  33769. this.meshPerAttribute = source.meshPerAttribute;
  33770. return this;
  33771. },
  33772. clone: function clone(data) {
  33773. var ib = InterleavedBuffer.prototype.clone.call(this, data);
  33774. ib.meshPerAttribute = this.meshPerAttribute;
  33775. return ib;
  33776. },
  33777. toJSON: function toJSON(data) {
  33778. var json = InterleavedBuffer.prototype.toJSON.call(this, data);
  33779. json.isInstancedInterleavedBuffer = true;
  33780. json.meshPerAttribute = this.meshPerAttribute;
  33781. return json;
  33782. }
  33783. });
  33784. function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
  33785. this.buffer = buffer;
  33786. this.type = type;
  33787. this.itemSize = itemSize;
  33788. this.elementSize = elementSize;
  33789. this.count = count;
  33790. this.version = 0;
  33791. }
  33792. Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
  33793. set: function set(value) {
  33794. if (value === true) this.version++;
  33795. }
  33796. });
  33797. Object.assign(GLBufferAttribute.prototype, {
  33798. isGLBufferAttribute: true,
  33799. setBuffer: function setBuffer(buffer) {
  33800. this.buffer = buffer;
  33801. return this;
  33802. },
  33803. setType: function setType(type, elementSize) {
  33804. this.type = type;
  33805. this.elementSize = elementSize;
  33806. return this;
  33807. },
  33808. setItemSize: function setItemSize(itemSize) {
  33809. this.itemSize = itemSize;
  33810. return this;
  33811. },
  33812. setCount: function setCount(count) {
  33813. this.count = count;
  33814. return this;
  33815. }
  33816. });
  33817. function Raycaster(origin, direction, near, far) {
  33818. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  33819. this.near = near || 0;
  33820. this.far = far || Infinity;
  33821. this.camera = null;
  33822. this.layers = new Layers();
  33823. this.params = {
  33824. Mesh: {},
  33825. Line: {
  33826. threshold: 1
  33827. },
  33828. LOD: {},
  33829. Points: {
  33830. threshold: 1
  33831. },
  33832. Sprite: {}
  33833. };
  33834. Object.defineProperties(this.params, {
  33835. PointCloud: {
  33836. get: function get() {
  33837. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  33838. return this.Points;
  33839. }
  33840. }
  33841. });
  33842. }
  33843. function ascSort(a, b) {
  33844. return a.distance - b.distance;
  33845. }
  33846. function _intersectObject(object, raycaster, intersects, recursive) {
  33847. if (object.layers.test(raycaster.layers)) {
  33848. object.raycast(raycaster, intersects);
  33849. }
  33850. if (recursive === true) {
  33851. var children = object.children;
  33852. for (var i = 0, l = children.length; i < l; i++) {
  33853. _intersectObject(children[i], raycaster, intersects, true);
  33854. }
  33855. }
  33856. }
  33857. Object.assign(Raycaster.prototype, {
  33858. set: function set(origin, direction) {
  33859. // direction is assumed to be normalized (for accurate distance calculations)
  33860. this.ray.set(origin, direction);
  33861. },
  33862. setFromCamera: function setFromCamera(coords, camera) {
  33863. if (camera && camera.isPerspectiveCamera) {
  33864. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  33865. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  33866. this.camera = camera;
  33867. } else if (camera && camera.isOrthographicCamera) {
  33868. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  33869. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  33870. this.camera = camera;
  33871. } else {
  33872. console.error('THREE.Raycaster: Unsupported camera type.');
  33873. }
  33874. },
  33875. intersectObject: function intersectObject(object, recursive, optionalTarget) {
  33876. var intersects = optionalTarget || [];
  33877. _intersectObject(object, this, intersects, recursive);
  33878. intersects.sort(ascSort);
  33879. return intersects;
  33880. },
  33881. intersectObjects: function intersectObjects(objects, recursive, optionalTarget) {
  33882. var intersects = optionalTarget || [];
  33883. if (Array.isArray(objects) === false) {
  33884. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  33885. return intersects;
  33886. }
  33887. for (var i = 0, l = objects.length; i < l; i++) {
  33888. _intersectObject(objects[i], this, intersects, recursive);
  33889. }
  33890. intersects.sort(ascSort);
  33891. return intersects;
  33892. }
  33893. });
  33894. /**
  33895. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  33896. *
  33897. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  33898. * The azimuthal angle (theta) is measured from the positive z-axis.
  33899. */
  33900. var Spherical = /*#__PURE__*/function () {
  33901. function Spherical(radius, phi, theta) {
  33902. if (radius === void 0) {
  33903. radius = 1;
  33904. }
  33905. if (phi === void 0) {
  33906. phi = 0;
  33907. }
  33908. if (theta === void 0) {
  33909. theta = 0;
  33910. }
  33911. this.radius = radius;
  33912. this.phi = phi; // polar angle
  33913. this.theta = theta; // azimuthal angle
  33914. return this;
  33915. }
  33916. var _proto = Spherical.prototype;
  33917. _proto.set = function set(radius, phi, theta) {
  33918. this.radius = radius;
  33919. this.phi = phi;
  33920. this.theta = theta;
  33921. return this;
  33922. };
  33923. _proto.clone = function clone() {
  33924. return new this.constructor().copy(this);
  33925. };
  33926. _proto.copy = function copy(other) {
  33927. this.radius = other.radius;
  33928. this.phi = other.phi;
  33929. this.theta = other.theta;
  33930. return this;
  33931. } // restrict phi to be betwee EPS and PI-EPS
  33932. ;
  33933. _proto.makeSafe = function makeSafe() {
  33934. var EPS = 0.000001;
  33935. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  33936. return this;
  33937. };
  33938. _proto.setFromVector3 = function setFromVector3(v) {
  33939. return this.setFromCartesianCoords(v.x, v.y, v.z);
  33940. };
  33941. _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
  33942. this.radius = Math.sqrt(x * x + y * y + z * z);
  33943. if (this.radius === 0) {
  33944. this.theta = 0;
  33945. this.phi = 0;
  33946. } else {
  33947. this.theta = Math.atan2(x, z);
  33948. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  33949. }
  33950. return this;
  33951. };
  33952. return Spherical;
  33953. }();
  33954. /**
  33955. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  33956. */
  33957. var Cylindrical = /*#__PURE__*/function () {
  33958. function Cylindrical(radius, theta, y) {
  33959. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  33960. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  33961. this.y = y !== undefined ? y : 0; // height above the x-z plane
  33962. return this;
  33963. }
  33964. var _proto = Cylindrical.prototype;
  33965. _proto.set = function set(radius, theta, y) {
  33966. this.radius = radius;
  33967. this.theta = theta;
  33968. this.y = y;
  33969. return this;
  33970. };
  33971. _proto.clone = function clone() {
  33972. return new this.constructor().copy(this);
  33973. };
  33974. _proto.copy = function copy(other) {
  33975. this.radius = other.radius;
  33976. this.theta = other.theta;
  33977. this.y = other.y;
  33978. return this;
  33979. };
  33980. _proto.setFromVector3 = function setFromVector3(v) {
  33981. return this.setFromCartesianCoords(v.x, v.y, v.z);
  33982. };
  33983. _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
  33984. this.radius = Math.sqrt(x * x + z * z);
  33985. this.theta = Math.atan2(x, z);
  33986. this.y = y;
  33987. return this;
  33988. };
  33989. return Cylindrical;
  33990. }();
  33991. var _vector$7 = /*@__PURE__*/new Vector2();
  33992. var Box2 = /*#__PURE__*/function () {
  33993. function Box2(min, max) {
  33994. Object.defineProperty(this, 'isBox2', {
  33995. value: true
  33996. });
  33997. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  33998. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  33999. }
  34000. var _proto = Box2.prototype;
  34001. _proto.set = function set(min, max) {
  34002. this.min.copy(min);
  34003. this.max.copy(max);
  34004. return this;
  34005. };
  34006. _proto.setFromPoints = function setFromPoints(points) {
  34007. this.makeEmpty();
  34008. for (var i = 0, il = points.length; i < il; i++) {
  34009. this.expandByPoint(points[i]);
  34010. }
  34011. return this;
  34012. };
  34013. _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
  34014. var halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  34015. this.min.copy(center).sub(halfSize);
  34016. this.max.copy(center).add(halfSize);
  34017. return this;
  34018. };
  34019. _proto.clone = function clone() {
  34020. return new this.constructor().copy(this);
  34021. };
  34022. _proto.copy = function copy(box) {
  34023. this.min.copy(box.min);
  34024. this.max.copy(box.max);
  34025. return this;
  34026. };
  34027. _proto.makeEmpty = function makeEmpty() {
  34028. this.min.x = this.min.y = +Infinity;
  34029. this.max.x = this.max.y = -Infinity;
  34030. return this;
  34031. };
  34032. _proto.isEmpty = function isEmpty() {
  34033. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  34034. return this.max.x < this.min.x || this.max.y < this.min.y;
  34035. };
  34036. _proto.getCenter = function getCenter(target) {
  34037. if (target === undefined) {
  34038. console.warn('THREE.Box2: .getCenter() target is now required');
  34039. target = new Vector2();
  34040. }
  34041. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  34042. };
  34043. _proto.getSize = function getSize(target) {
  34044. if (target === undefined) {
  34045. console.warn('THREE.Box2: .getSize() target is now required');
  34046. target = new Vector2();
  34047. }
  34048. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  34049. };
  34050. _proto.expandByPoint = function expandByPoint(point) {
  34051. this.min.min(point);
  34052. this.max.max(point);
  34053. return this;
  34054. };
  34055. _proto.expandByVector = function expandByVector(vector) {
  34056. this.min.sub(vector);
  34057. this.max.add(vector);
  34058. return this;
  34059. };
  34060. _proto.expandByScalar = function expandByScalar(scalar) {
  34061. this.min.addScalar(-scalar);
  34062. this.max.addScalar(scalar);
  34063. return this;
  34064. };
  34065. _proto.containsPoint = function containsPoint(point) {
  34066. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  34067. };
  34068. _proto.containsBox = function containsBox(box) {
  34069. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  34070. };
  34071. _proto.getParameter = function getParameter(point, target) {
  34072. // This can potentially have a divide by zero if the box
  34073. // has a size dimension of 0.
  34074. if (target === undefined) {
  34075. console.warn('THREE.Box2: .getParameter() target is now required');
  34076. target = new Vector2();
  34077. }
  34078. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  34079. };
  34080. _proto.intersectsBox = function intersectsBox(box) {
  34081. // using 4 splitting planes to rule out intersections
  34082. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  34083. };
  34084. _proto.clampPoint = function clampPoint(point, target) {
  34085. if (target === undefined) {
  34086. console.warn('THREE.Box2: .clampPoint() target is now required');
  34087. target = new Vector2();
  34088. }
  34089. return target.copy(point).clamp(this.min, this.max);
  34090. };
  34091. _proto.distanceToPoint = function distanceToPoint(point) {
  34092. var clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  34093. return clampedPoint.sub(point).length();
  34094. };
  34095. _proto.intersect = function intersect(box) {
  34096. this.min.max(box.min);
  34097. this.max.min(box.max);
  34098. return this;
  34099. };
  34100. _proto.union = function union(box) {
  34101. this.min.min(box.min);
  34102. this.max.max(box.max);
  34103. return this;
  34104. };
  34105. _proto.translate = function translate(offset) {
  34106. this.min.add(offset);
  34107. this.max.add(offset);
  34108. return this;
  34109. };
  34110. _proto.equals = function equals(box) {
  34111. return box.min.equals(this.min) && box.max.equals(this.max);
  34112. };
  34113. return Box2;
  34114. }();
  34115. var _startP = /*@__PURE__*/new Vector3();
  34116. var _startEnd = /*@__PURE__*/new Vector3();
  34117. var Line3 = /*#__PURE__*/function () {
  34118. function Line3(start, end) {
  34119. this.start = start !== undefined ? start : new Vector3();
  34120. this.end = end !== undefined ? end : new Vector3();
  34121. }
  34122. var _proto = Line3.prototype;
  34123. _proto.set = function set(start, end) {
  34124. this.start.copy(start);
  34125. this.end.copy(end);
  34126. return this;
  34127. };
  34128. _proto.clone = function clone() {
  34129. return new this.constructor().copy(this);
  34130. };
  34131. _proto.copy = function copy(line) {
  34132. this.start.copy(line.start);
  34133. this.end.copy(line.end);
  34134. return this;
  34135. };
  34136. _proto.getCenter = function getCenter(target) {
  34137. if (target === undefined) {
  34138. console.warn('THREE.Line3: .getCenter() target is now required');
  34139. target = new Vector3();
  34140. }
  34141. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  34142. };
  34143. _proto.delta = function delta(target) {
  34144. if (target === undefined) {
  34145. console.warn('THREE.Line3: .delta() target is now required');
  34146. target = new Vector3();
  34147. }
  34148. return target.subVectors(this.end, this.start);
  34149. };
  34150. _proto.distanceSq = function distanceSq() {
  34151. return this.start.distanceToSquared(this.end);
  34152. };
  34153. _proto.distance = function distance() {
  34154. return this.start.distanceTo(this.end);
  34155. };
  34156. _proto.at = function at(t, target) {
  34157. if (target === undefined) {
  34158. console.warn('THREE.Line3: .at() target is now required');
  34159. target = new Vector3();
  34160. }
  34161. return this.delta(target).multiplyScalar(t).add(this.start);
  34162. };
  34163. _proto.closestPointToPointParameter = function closestPointToPointParameter(point, clampToLine) {
  34164. _startP.subVectors(point, this.start);
  34165. _startEnd.subVectors(this.end, this.start);
  34166. var startEnd2 = _startEnd.dot(_startEnd);
  34167. var startEnd_startP = _startEnd.dot(_startP);
  34168. var t = startEnd_startP / startEnd2;
  34169. if (clampToLine) {
  34170. t = MathUtils.clamp(t, 0, 1);
  34171. }
  34172. return t;
  34173. };
  34174. _proto.closestPointToPoint = function closestPointToPoint(point, clampToLine, target) {
  34175. var t = this.closestPointToPointParameter(point, clampToLine);
  34176. if (target === undefined) {
  34177. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  34178. target = new Vector3();
  34179. }
  34180. return this.delta(target).multiplyScalar(t).add(this.start);
  34181. };
  34182. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  34183. this.start.applyMatrix4(matrix);
  34184. this.end.applyMatrix4(matrix);
  34185. return this;
  34186. };
  34187. _proto.equals = function equals(line) {
  34188. return line.start.equals(this.start) && line.end.equals(this.end);
  34189. };
  34190. return Line3;
  34191. }();
  34192. function ImmediateRenderObject(material) {
  34193. Object3D.call(this);
  34194. this.material = material;
  34195. this.render = function ()
  34196. /* renderCallback */
  34197. {};
  34198. this.hasPositions = false;
  34199. this.hasNormals = false;
  34200. this.hasColors = false;
  34201. this.hasUvs = false;
  34202. this.positionArray = null;
  34203. this.normalArray = null;
  34204. this.colorArray = null;
  34205. this.uvArray = null;
  34206. this.count = 0;
  34207. }
  34208. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  34209. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  34210. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  34211. var _vector$8 = /*@__PURE__*/new Vector3();
  34212. var SpotLightHelper = /*#__PURE__*/function (_Object3D) {
  34213. _inheritsLoose(SpotLightHelper, _Object3D);
  34214. function SpotLightHelper(light, color) {
  34215. var _this;
  34216. _this = _Object3D.call(this) || this;
  34217. _this.light = light;
  34218. _this.light.updateMatrixWorld();
  34219. _this.matrix = light.matrixWorld;
  34220. _this.matrixAutoUpdate = false;
  34221. _this.color = color;
  34222. var geometry = new BufferGeometry();
  34223. var positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  34224. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  34225. var p1 = i / l * Math.PI * 2;
  34226. var p2 = j / l * Math.PI * 2;
  34227. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  34228. }
  34229. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34230. var material = new LineBasicMaterial({
  34231. fog: false,
  34232. toneMapped: false
  34233. });
  34234. _this.cone = new LineSegments(geometry, material);
  34235. _this.add(_this.cone);
  34236. _this.update();
  34237. return _this;
  34238. }
  34239. var _proto = SpotLightHelper.prototype;
  34240. _proto.dispose = function dispose() {
  34241. this.cone.geometry.dispose();
  34242. this.cone.material.dispose();
  34243. };
  34244. _proto.update = function update() {
  34245. this.light.updateMatrixWorld();
  34246. var coneLength = this.light.distance ? this.light.distance : 1000;
  34247. var coneWidth = coneLength * Math.tan(this.light.angle);
  34248. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  34249. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  34250. this.cone.lookAt(_vector$8);
  34251. if (this.color !== undefined) {
  34252. this.cone.material.color.set(this.color);
  34253. } else {
  34254. this.cone.material.color.copy(this.light.color);
  34255. }
  34256. };
  34257. return SpotLightHelper;
  34258. }(Object3D);
  34259. var _vector$9 = /*@__PURE__*/new Vector3();
  34260. var _boneMatrix = /*@__PURE__*/new Matrix4();
  34261. var _matrixWorldInv = /*@__PURE__*/new Matrix4();
  34262. var SkeletonHelper = /*#__PURE__*/function (_LineSegments) {
  34263. _inheritsLoose(SkeletonHelper, _LineSegments);
  34264. function SkeletonHelper(object) {
  34265. var _this;
  34266. var bones = getBoneList(object);
  34267. var geometry = new BufferGeometry();
  34268. var vertices = [];
  34269. var colors = [];
  34270. var color1 = new Color(0, 0, 1);
  34271. var color2 = new Color(0, 1, 0);
  34272. for (var i = 0; i < bones.length; i++) {
  34273. var bone = bones[i];
  34274. if (bone.parent && bone.parent.isBone) {
  34275. vertices.push(0, 0, 0);
  34276. vertices.push(0, 0, 0);
  34277. colors.push(color1.r, color1.g, color1.b);
  34278. colors.push(color2.r, color2.g, color2.b);
  34279. }
  34280. }
  34281. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34282. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34283. var material = new LineBasicMaterial({
  34284. vertexColors: true,
  34285. depthTest: false,
  34286. depthWrite: false,
  34287. toneMapped: false,
  34288. transparent: true
  34289. });
  34290. _this = _LineSegments.call(this, geometry, material) || this;
  34291. _this.type = 'SkeletonHelper';
  34292. _this.isSkeletonHelper = true;
  34293. _this.root = object;
  34294. _this.bones = bones;
  34295. _this.matrix = object.matrixWorld;
  34296. _this.matrixAutoUpdate = false;
  34297. return _this;
  34298. }
  34299. var _proto = SkeletonHelper.prototype;
  34300. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34301. var bones = this.bones;
  34302. var geometry = this.geometry;
  34303. var position = geometry.getAttribute('position');
  34304. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  34305. for (var i = 0, j = 0; i < bones.length; i++) {
  34306. var bone = bones[i];
  34307. if (bone.parent && bone.parent.isBone) {
  34308. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  34309. _vector$9.setFromMatrixPosition(_boneMatrix);
  34310. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  34311. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  34312. _vector$9.setFromMatrixPosition(_boneMatrix);
  34313. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  34314. j += 2;
  34315. }
  34316. }
  34317. geometry.getAttribute('position').needsUpdate = true;
  34318. _LineSegments.prototype.updateMatrixWorld.call(this, force);
  34319. };
  34320. return SkeletonHelper;
  34321. }(LineSegments);
  34322. function getBoneList(object) {
  34323. var boneList = [];
  34324. if (object && object.isBone) {
  34325. boneList.push(object);
  34326. }
  34327. for (var i = 0; i < object.children.length; i++) {
  34328. boneList.push.apply(boneList, getBoneList(object.children[i]));
  34329. }
  34330. return boneList;
  34331. }
  34332. var PointLightHelper = /*#__PURE__*/function (_Mesh) {
  34333. _inheritsLoose(PointLightHelper, _Mesh);
  34334. function PointLightHelper(light, sphereSize, color) {
  34335. var _this;
  34336. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  34337. var material = new MeshBasicMaterial({
  34338. wireframe: true,
  34339. fog: false,
  34340. toneMapped: false
  34341. });
  34342. _this = _Mesh.call(this, geometry, material) || this;
  34343. _this.light = light;
  34344. _this.light.updateMatrixWorld();
  34345. _this.color = color;
  34346. _this.type = 'PointLightHelper';
  34347. _this.matrix = _this.light.matrixWorld;
  34348. _this.matrixAutoUpdate = false;
  34349. _this.update();
  34350. /*
  34351. // TODO: delete this comment?
  34352. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  34353. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  34354. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  34355. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  34356. const d = light.distance;
  34357. if ( d === 0.0 ) {
  34358. this.lightDistance.visible = false;
  34359. } else {
  34360. this.lightDistance.scale.set( d, d, d );
  34361. }
  34362. this.add( this.lightDistance );
  34363. */
  34364. return _this;
  34365. }
  34366. var _proto = PointLightHelper.prototype;
  34367. _proto.dispose = function dispose() {
  34368. this.geometry.dispose();
  34369. this.material.dispose();
  34370. };
  34371. _proto.update = function update() {
  34372. if (this.color !== undefined) {
  34373. this.material.color.set(this.color);
  34374. } else {
  34375. this.material.color.copy(this.light.color);
  34376. }
  34377. /*
  34378. const d = this.light.distance;
  34379. if ( d === 0.0 ) {
  34380. this.lightDistance.visible = false;
  34381. } else {
  34382. this.lightDistance.visible = true;
  34383. this.lightDistance.scale.set( d, d, d );
  34384. }
  34385. */
  34386. };
  34387. return PointLightHelper;
  34388. }(Mesh);
  34389. var _vector$a = /*@__PURE__*/new Vector3();
  34390. var _color1 = /*@__PURE__*/new Color();
  34391. var _color2 = /*@__PURE__*/new Color();
  34392. var HemisphereLightHelper = /*#__PURE__*/function (_Object3D) {
  34393. _inheritsLoose(HemisphereLightHelper, _Object3D);
  34394. function HemisphereLightHelper(light, size, color) {
  34395. var _this;
  34396. _this = _Object3D.call(this) || this;
  34397. _this.light = light;
  34398. _this.light.updateMatrixWorld();
  34399. _this.matrix = light.matrixWorld;
  34400. _this.matrixAutoUpdate = false;
  34401. _this.color = color;
  34402. var geometry = new OctahedronBufferGeometry(size);
  34403. geometry.rotateY(Math.PI * 0.5);
  34404. _this.material = new MeshBasicMaterial({
  34405. wireframe: true,
  34406. fog: false,
  34407. toneMapped: false
  34408. });
  34409. if (_this.color === undefined) _this.material.vertexColors = true;
  34410. var position = geometry.getAttribute('position');
  34411. var colors = new Float32Array(position.count * 3);
  34412. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  34413. _this.add(new Mesh(geometry, _this.material));
  34414. _this.update();
  34415. return _this;
  34416. }
  34417. var _proto = HemisphereLightHelper.prototype;
  34418. _proto.dispose = function dispose() {
  34419. this.children[0].geometry.dispose();
  34420. this.children[0].material.dispose();
  34421. };
  34422. _proto.update = function update() {
  34423. var mesh = this.children[0];
  34424. if (this.color !== undefined) {
  34425. this.material.color.set(this.color);
  34426. } else {
  34427. var colors = mesh.geometry.getAttribute('color');
  34428. _color1.copy(this.light.color);
  34429. _color2.copy(this.light.groundColor);
  34430. for (var i = 0, l = colors.count; i < l; i++) {
  34431. var color = i < l / 2 ? _color1 : _color2;
  34432. colors.setXYZ(i, color.r, color.g, color.b);
  34433. }
  34434. colors.needsUpdate = true;
  34435. }
  34436. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  34437. };
  34438. return HemisphereLightHelper;
  34439. }(Object3D);
  34440. var GridHelper = /*#__PURE__*/function (_LineSegments) {
  34441. _inheritsLoose(GridHelper, _LineSegments);
  34442. function GridHelper(size, divisions, color1, color2) {
  34443. var _this;
  34444. if (size === void 0) {
  34445. size = 10;
  34446. }
  34447. if (divisions === void 0) {
  34448. divisions = 10;
  34449. }
  34450. if (color1 === void 0) {
  34451. color1 = 0x444444;
  34452. }
  34453. if (color2 === void 0) {
  34454. color2 = 0x888888;
  34455. }
  34456. color1 = new Color(color1);
  34457. color2 = new Color(color2);
  34458. var center = divisions / 2;
  34459. var step = size / divisions;
  34460. var halfSize = size / 2;
  34461. var vertices = [],
  34462. colors = [];
  34463. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  34464. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  34465. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  34466. var color = i === center ? color1 : color2;
  34467. color.toArray(colors, j);
  34468. j += 3;
  34469. color.toArray(colors, j);
  34470. j += 3;
  34471. color.toArray(colors, j);
  34472. j += 3;
  34473. color.toArray(colors, j);
  34474. j += 3;
  34475. }
  34476. var geometry = new BufferGeometry();
  34477. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34478. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34479. var material = new LineBasicMaterial({
  34480. vertexColors: true,
  34481. toneMapped: false
  34482. });
  34483. _this = _LineSegments.call(this, geometry, material) || this;
  34484. _this.type = 'GridHelper';
  34485. return _this;
  34486. }
  34487. return GridHelper;
  34488. }(LineSegments);
  34489. var PolarGridHelper = /*#__PURE__*/function (_LineSegments) {
  34490. _inheritsLoose(PolarGridHelper, _LineSegments);
  34491. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  34492. var _this;
  34493. if (radius === void 0) {
  34494. radius = 10;
  34495. }
  34496. if (radials === void 0) {
  34497. radials = 16;
  34498. }
  34499. if (circles === void 0) {
  34500. circles = 8;
  34501. }
  34502. if (divisions === void 0) {
  34503. divisions = 64;
  34504. }
  34505. if (color1 === void 0) {
  34506. color1 = 0x444444;
  34507. }
  34508. if (color2 === void 0) {
  34509. color2 = 0x888888;
  34510. }
  34511. color1 = new Color(color1);
  34512. color2 = new Color(color2);
  34513. var vertices = [];
  34514. var colors = []; // create the radials
  34515. for (var i = 0; i <= radials; i++) {
  34516. var v = i / radials * (Math.PI * 2);
  34517. var x = Math.sin(v) * radius;
  34518. var z = Math.cos(v) * radius;
  34519. vertices.push(0, 0, 0);
  34520. vertices.push(x, 0, z);
  34521. var color = i & 1 ? color1 : color2;
  34522. colors.push(color.r, color.g, color.b);
  34523. colors.push(color.r, color.g, color.b);
  34524. } // create the circles
  34525. for (var _i = 0; _i <= circles; _i++) {
  34526. var _color = _i & 1 ? color1 : color2;
  34527. var r = radius - radius / circles * _i;
  34528. for (var j = 0; j < divisions; j++) {
  34529. // first vertex
  34530. var _v = j / divisions * (Math.PI * 2);
  34531. var _x = Math.sin(_v) * r;
  34532. var _z = Math.cos(_v) * r;
  34533. vertices.push(_x, 0, _z);
  34534. colors.push(_color.r, _color.g, _color.b); // second vertex
  34535. _v = (j + 1) / divisions * (Math.PI * 2);
  34536. _x = Math.sin(_v) * r;
  34537. _z = Math.cos(_v) * r;
  34538. vertices.push(_x, 0, _z);
  34539. colors.push(_color.r, _color.g, _color.b);
  34540. }
  34541. }
  34542. var geometry = new BufferGeometry();
  34543. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34544. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34545. var material = new LineBasicMaterial({
  34546. vertexColors: true,
  34547. toneMapped: false
  34548. });
  34549. _this = _LineSegments.call(this, geometry, material) || this;
  34550. _this.type = 'PolarGridHelper';
  34551. return _this;
  34552. }
  34553. return PolarGridHelper;
  34554. }(LineSegments);
  34555. var _v1$6 = /*@__PURE__*/new Vector3();
  34556. var _v2$3 = /*@__PURE__*/new Vector3();
  34557. var _v3$1 = /*@__PURE__*/new Vector3();
  34558. var DirectionalLightHelper = /*#__PURE__*/function (_Object3D) {
  34559. _inheritsLoose(DirectionalLightHelper, _Object3D);
  34560. function DirectionalLightHelper(light, size, color) {
  34561. var _this;
  34562. _this = _Object3D.call(this) || this;
  34563. _this.light = light;
  34564. _this.light.updateMatrixWorld();
  34565. _this.matrix = light.matrixWorld;
  34566. _this.matrixAutoUpdate = false;
  34567. _this.color = color;
  34568. if (size === undefined) size = 1;
  34569. var geometry = new BufferGeometry();
  34570. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  34571. var material = new LineBasicMaterial({
  34572. fog: false,
  34573. toneMapped: false
  34574. });
  34575. _this.lightPlane = new Line(geometry, material);
  34576. _this.add(_this.lightPlane);
  34577. geometry = new BufferGeometry();
  34578. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  34579. _this.targetLine = new Line(geometry, material);
  34580. _this.add(_this.targetLine);
  34581. _this.update();
  34582. return _this;
  34583. }
  34584. var _proto = DirectionalLightHelper.prototype;
  34585. _proto.dispose = function dispose() {
  34586. this.lightPlane.geometry.dispose();
  34587. this.lightPlane.material.dispose();
  34588. this.targetLine.geometry.dispose();
  34589. this.targetLine.material.dispose();
  34590. };
  34591. _proto.update = function update() {
  34592. _v1$6.setFromMatrixPosition(this.light.matrixWorld);
  34593. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  34594. _v3$1.subVectors(_v2$3, _v1$6);
  34595. this.lightPlane.lookAt(_v2$3);
  34596. if (this.color !== undefined) {
  34597. this.lightPlane.material.color.set(this.color);
  34598. this.targetLine.material.color.set(this.color);
  34599. } else {
  34600. this.lightPlane.material.color.copy(this.light.color);
  34601. this.targetLine.material.color.copy(this.light.color);
  34602. }
  34603. this.targetLine.lookAt(_v2$3);
  34604. this.targetLine.scale.z = _v3$1.length();
  34605. };
  34606. return DirectionalLightHelper;
  34607. }(Object3D);
  34608. var _vector$b = /*@__PURE__*/new Vector3();
  34609. var _camera = /*@__PURE__*/new Camera();
  34610. /**
  34611. * - shows frustum, line of sight and up of the camera
  34612. * - suitable for fast updates
  34613. * - based on frustum visualization in lightgl.js shadowmap example
  34614. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  34615. */
  34616. var CameraHelper = /*#__PURE__*/function (_LineSegments) {
  34617. _inheritsLoose(CameraHelper, _LineSegments);
  34618. function CameraHelper(camera) {
  34619. var _this;
  34620. var geometry = new BufferGeometry();
  34621. var material = new LineBasicMaterial({
  34622. color: 0xffffff,
  34623. vertexColors: true,
  34624. toneMapped: false
  34625. });
  34626. var vertices = [];
  34627. var colors = [];
  34628. var pointMap = {}; // colors
  34629. var colorFrustum = new Color(0xffaa00);
  34630. var colorCone = new Color(0xff0000);
  34631. var colorUp = new Color(0x00aaff);
  34632. var colorTarget = new Color(0xffffff);
  34633. var colorCross = new Color(0x333333); // near
  34634. addLine('n1', 'n2', colorFrustum);
  34635. addLine('n2', 'n4', colorFrustum);
  34636. addLine('n4', 'n3', colorFrustum);
  34637. addLine('n3', 'n1', colorFrustum); // far
  34638. addLine('f1', 'f2', colorFrustum);
  34639. addLine('f2', 'f4', colorFrustum);
  34640. addLine('f4', 'f3', colorFrustum);
  34641. addLine('f3', 'f1', colorFrustum); // sides
  34642. addLine('n1', 'f1', colorFrustum);
  34643. addLine('n2', 'f2', colorFrustum);
  34644. addLine('n3', 'f3', colorFrustum);
  34645. addLine('n4', 'f4', colorFrustum); // cone
  34646. addLine('p', 'n1', colorCone);
  34647. addLine('p', 'n2', colorCone);
  34648. addLine('p', 'n3', colorCone);
  34649. addLine('p', 'n4', colorCone); // up
  34650. addLine('u1', 'u2', colorUp);
  34651. addLine('u2', 'u3', colorUp);
  34652. addLine('u3', 'u1', colorUp); // target
  34653. addLine('c', 't', colorTarget);
  34654. addLine('p', 'c', colorCross); // cross
  34655. addLine('cn1', 'cn2', colorCross);
  34656. addLine('cn3', 'cn4', colorCross);
  34657. addLine('cf1', 'cf2', colorCross);
  34658. addLine('cf3', 'cf4', colorCross);
  34659. function addLine(a, b, color) {
  34660. addPoint(a, color);
  34661. addPoint(b, color);
  34662. }
  34663. function addPoint(id, color) {
  34664. vertices.push(0, 0, 0);
  34665. colors.push(color.r, color.g, color.b);
  34666. if (pointMap[id] === undefined) {
  34667. pointMap[id] = [];
  34668. }
  34669. pointMap[id].push(vertices.length / 3 - 1);
  34670. }
  34671. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34672. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34673. _this = _LineSegments.call(this, geometry, material) || this;
  34674. _this.type = 'CameraHelper';
  34675. _this.camera = camera;
  34676. if (_this.camera.updateProjectionMatrix) _this.camera.updateProjectionMatrix();
  34677. _this.matrix = camera.matrixWorld;
  34678. _this.matrixAutoUpdate = false;
  34679. _this.pointMap = pointMap;
  34680. _this.update();
  34681. return _this;
  34682. }
  34683. var _proto = CameraHelper.prototype;
  34684. _proto.update = function update() {
  34685. var geometry = this.geometry;
  34686. var pointMap = this.pointMap;
  34687. var w = 1,
  34688. h = 1; // we need just camera projection matrix inverse
  34689. // world matrix must be identity
  34690. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  34691. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  34692. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  34693. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  34694. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  34695. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  34696. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  34697. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  34698. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  34699. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  34700. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  34701. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  34702. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  34703. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  34704. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  34705. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  34706. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  34707. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  34708. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  34709. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  34710. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  34711. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  34712. geometry.getAttribute('position').needsUpdate = true;
  34713. };
  34714. return CameraHelper;
  34715. }(LineSegments);
  34716. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  34717. _vector$b.set(x, y, z).unproject(camera);
  34718. var points = pointMap[point];
  34719. if (points !== undefined) {
  34720. var position = geometry.getAttribute('position');
  34721. for (var i = 0, l = points.length; i < l; i++) {
  34722. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  34723. }
  34724. }
  34725. }
  34726. var _box$3 = /*@__PURE__*/new Box3();
  34727. var BoxHelper = /*#__PURE__*/function (_LineSegments) {
  34728. _inheritsLoose(BoxHelper, _LineSegments);
  34729. function BoxHelper(object, color) {
  34730. var _this;
  34731. if (color === void 0) {
  34732. color = 0xffff00;
  34733. }
  34734. var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  34735. var positions = new Float32Array(8 * 3);
  34736. var geometry = new BufferGeometry();
  34737. geometry.setIndex(new BufferAttribute(indices, 1));
  34738. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  34739. _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
  34740. color: color,
  34741. toneMapped: false
  34742. })) || this;
  34743. _this.object = object;
  34744. _this.type = 'BoxHelper';
  34745. _this.matrixAutoUpdate = false;
  34746. _this.update();
  34747. return _this;
  34748. }
  34749. var _proto = BoxHelper.prototype;
  34750. _proto.update = function update(object) {
  34751. if (object !== undefined) {
  34752. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  34753. }
  34754. if (this.object !== undefined) {
  34755. _box$3.setFromObject(this.object);
  34756. }
  34757. if (_box$3.isEmpty()) return;
  34758. var min = _box$3.min;
  34759. var max = _box$3.max;
  34760. /*
  34761. 5____4
  34762. 1/___0/|
  34763. | 6__|_7
  34764. 2/___3/
  34765. 0: max.x, max.y, max.z
  34766. 1: min.x, max.y, max.z
  34767. 2: min.x, min.y, max.z
  34768. 3: max.x, min.y, max.z
  34769. 4: max.x, max.y, min.z
  34770. 5: min.x, max.y, min.z
  34771. 6: min.x, min.y, min.z
  34772. 7: max.x, min.y, min.z
  34773. */
  34774. var position = this.geometry.attributes.position;
  34775. var array = position.array;
  34776. array[0] = max.x;
  34777. array[1] = max.y;
  34778. array[2] = max.z;
  34779. array[3] = min.x;
  34780. array[4] = max.y;
  34781. array[5] = max.z;
  34782. array[6] = min.x;
  34783. array[7] = min.y;
  34784. array[8] = max.z;
  34785. array[9] = max.x;
  34786. array[10] = min.y;
  34787. array[11] = max.z;
  34788. array[12] = max.x;
  34789. array[13] = max.y;
  34790. array[14] = min.z;
  34791. array[15] = min.x;
  34792. array[16] = max.y;
  34793. array[17] = min.z;
  34794. array[18] = min.x;
  34795. array[19] = min.y;
  34796. array[20] = min.z;
  34797. array[21] = max.x;
  34798. array[22] = min.y;
  34799. array[23] = min.z;
  34800. position.needsUpdate = true;
  34801. this.geometry.computeBoundingSphere();
  34802. };
  34803. _proto.setFromObject = function setFromObject(object) {
  34804. this.object = object;
  34805. this.update();
  34806. return this;
  34807. };
  34808. _proto.copy = function copy(source) {
  34809. LineSegments.prototype.copy.call(this, source);
  34810. this.object = source.object;
  34811. return this;
  34812. };
  34813. return BoxHelper;
  34814. }(LineSegments);
  34815. var Box3Helper = /*#__PURE__*/function (_LineSegments) {
  34816. _inheritsLoose(Box3Helper, _LineSegments);
  34817. function Box3Helper(box, color) {
  34818. var _this;
  34819. if (color === void 0) {
  34820. color = 0xffff00;
  34821. }
  34822. var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  34823. var positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
  34824. var geometry = new BufferGeometry();
  34825. geometry.setIndex(new BufferAttribute(indices, 1));
  34826. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34827. _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
  34828. color: color,
  34829. toneMapped: false
  34830. })) || this;
  34831. _this.box = box;
  34832. _this.type = 'Box3Helper';
  34833. _this.geometry.computeBoundingSphere();
  34834. return _this;
  34835. }
  34836. var _proto = Box3Helper.prototype;
  34837. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34838. var box = this.box;
  34839. if (box.isEmpty()) return;
  34840. box.getCenter(this.position);
  34841. box.getSize(this.scale);
  34842. this.scale.multiplyScalar(0.5);
  34843. _LineSegments.prototype.updateMatrixWorld.call(this, force);
  34844. };
  34845. return Box3Helper;
  34846. }(LineSegments);
  34847. var PlaneHelper = /*#__PURE__*/function (_Line) {
  34848. _inheritsLoose(PlaneHelper, _Line);
  34849. function PlaneHelper(plane, size, hex) {
  34850. var _this;
  34851. if (size === void 0) {
  34852. size = 1;
  34853. }
  34854. if (hex === void 0) {
  34855. hex = 0xffff00;
  34856. }
  34857. var color = hex;
  34858. var positions = [1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0];
  34859. var geometry = new BufferGeometry();
  34860. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34861. geometry.computeBoundingSphere();
  34862. _this = _Line.call(this, geometry, new LineBasicMaterial({
  34863. color: color,
  34864. toneMapped: false
  34865. })) || this;
  34866. _this.type = 'PlaneHelper';
  34867. _this.plane = plane;
  34868. _this.size = size;
  34869. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  34870. var geometry2 = new BufferGeometry();
  34871. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  34872. geometry2.computeBoundingSphere();
  34873. _this.add(new Mesh(geometry2, new MeshBasicMaterial({
  34874. color: color,
  34875. opacity: 0.2,
  34876. transparent: true,
  34877. depthWrite: false,
  34878. toneMapped: false
  34879. })));
  34880. return _this;
  34881. }
  34882. var _proto = PlaneHelper.prototype;
  34883. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34884. var scale = -this.plane.constant;
  34885. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  34886. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  34887. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  34888. this.lookAt(this.plane.normal);
  34889. _Line.prototype.updateMatrixWorld.call(this, force);
  34890. };
  34891. return PlaneHelper;
  34892. }(Line);
  34893. var _axis = /*@__PURE__*/new Vector3();
  34894. var _lineGeometry, _coneGeometry;
  34895. var ArrowHelper = /*#__PURE__*/function (_Object3D) {
  34896. _inheritsLoose(ArrowHelper, _Object3D);
  34897. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  34898. var _this;
  34899. _this = _Object3D.call(this) || this; // dir is assumed to be normalized
  34900. _this.type = 'ArrowHelper';
  34901. if (dir === undefined) dir = new Vector3(0, 0, 1);
  34902. if (origin === undefined) origin = new Vector3(0, 0, 0);
  34903. if (length === undefined) length = 1;
  34904. if (color === undefined) color = 0xffff00;
  34905. if (headLength === undefined) headLength = 0.2 * length;
  34906. if (headWidth === undefined) headWidth = 0.2 * headLength;
  34907. if (_lineGeometry === undefined) {
  34908. _lineGeometry = new BufferGeometry();
  34909. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  34910. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  34911. _coneGeometry.translate(0, -0.5, 0);
  34912. }
  34913. _this.position.copy(origin);
  34914. _this.line = new Line(_lineGeometry, new LineBasicMaterial({
  34915. color: color,
  34916. toneMapped: false
  34917. }));
  34918. _this.line.matrixAutoUpdate = false;
  34919. _this.add(_this.line);
  34920. _this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  34921. color: color,
  34922. toneMapped: false
  34923. }));
  34924. _this.cone.matrixAutoUpdate = false;
  34925. _this.add(_this.cone);
  34926. _this.setDirection(dir);
  34927. _this.setLength(length, headLength, headWidth);
  34928. return _this;
  34929. }
  34930. var _proto = ArrowHelper.prototype;
  34931. _proto.setDirection = function setDirection(dir) {
  34932. // dir is assumed to be normalized
  34933. if (dir.y > 0.99999) {
  34934. this.quaternion.set(0, 0, 0, 1);
  34935. } else if (dir.y < -0.99999) {
  34936. this.quaternion.set(1, 0, 0, 0);
  34937. } else {
  34938. _axis.set(dir.z, 0, -dir.x).normalize();
  34939. var radians = Math.acos(dir.y);
  34940. this.quaternion.setFromAxisAngle(_axis, radians);
  34941. }
  34942. };
  34943. _proto.setLength = function setLength(length, headLength, headWidth) {
  34944. if (headLength === undefined) headLength = 0.2 * length;
  34945. if (headWidth === undefined) headWidth = 0.2 * headLength;
  34946. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  34947. this.line.updateMatrix();
  34948. this.cone.scale.set(headWidth, headLength, headWidth);
  34949. this.cone.position.y = length;
  34950. this.cone.updateMatrix();
  34951. };
  34952. _proto.setColor = function setColor(color) {
  34953. this.line.material.color.set(color);
  34954. this.cone.material.color.set(color);
  34955. };
  34956. _proto.copy = function copy(source) {
  34957. _Object3D.prototype.copy.call(this, source, false);
  34958. this.line.copy(source.line);
  34959. this.cone.copy(source.cone);
  34960. return this;
  34961. };
  34962. return ArrowHelper;
  34963. }(Object3D);
  34964. var AxesHelper = /*#__PURE__*/function (_LineSegments) {
  34965. _inheritsLoose(AxesHelper, _LineSegments);
  34966. function AxesHelper(size) {
  34967. var _this;
  34968. if (size === void 0) {
  34969. size = 1;
  34970. }
  34971. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  34972. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  34973. var geometry = new BufferGeometry();
  34974. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34975. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34976. var material = new LineBasicMaterial({
  34977. vertexColors: true,
  34978. toneMapped: false
  34979. });
  34980. _this = _LineSegments.call(this, geometry, material) || this;
  34981. _this.type = 'AxesHelper';
  34982. return _this;
  34983. }
  34984. return AxesHelper;
  34985. }(LineSegments);
  34986. var _floatView = new Float32Array(1);
  34987. var _int32View = new Int32Array(_floatView.buffer);
  34988. var DataUtils = {
  34989. // Converts float32 to float16 (stored as uint16 value).
  34990. toHalfFloat: function toHalfFloat(val) {
  34991. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  34992. /* This method is faster than the OpenEXR implementation (very often
  34993. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  34994. * by James Tursa?s half-precision code. */
  34995. _floatView[0] = val;
  34996. var x = _int32View[0];
  34997. var bits = x >> 16 & 0x8000;
  34998. /* Get the sign */
  34999. var m = x >> 12 & 0x07ff;
  35000. /* Keep one extra bit for rounding */
  35001. var e = x >> 23 & 0xff;
  35002. /* Using int is faster here */
  35003. /* If zero, or denormal, or exponent underflows too much for a denormal
  35004. * half, return signed zero. */
  35005. if (e < 103) return bits;
  35006. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  35007. if (e > 142) {
  35008. bits |= 0x7c00;
  35009. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  35010. * not Inf, so make sure we set one mantissa bit too. */
  35011. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  35012. return bits;
  35013. }
  35014. /* If exponent underflows but not too much, return a denormal */
  35015. if (e < 113) {
  35016. m |= 0x0800;
  35017. /* Extra rounding may overflow and set mantissa to 0 and exponent
  35018. * to 1, which is OK. */
  35019. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  35020. return bits;
  35021. }
  35022. bits |= e - 112 << 10 | m >> 1;
  35023. /* Extra rounding. An overflow will set mantissa to 0 and increment
  35024. * the exponent, which is OK. */
  35025. bits += m & 1;
  35026. return bits;
  35027. }
  35028. };
  35029. var _ENCODINGS;
  35030. var LOD_MIN = 4;
  35031. var LOD_MAX = 8;
  35032. var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  35033. // chosen to approximate a Trowbridge-Reitz distribution function times the
  35034. // geometric shadowing function. These sigma values squared must match the
  35035. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  35036. var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  35037. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  35038. // samples and exit early, but not recompile the shader.
  35039. var MAX_SAMPLES = 20;
  35040. var ENCODINGS = (_ENCODINGS = {}, _ENCODINGS[LinearEncoding] = 0, _ENCODINGS[sRGBEncoding] = 1, _ENCODINGS[RGBEEncoding] = 2, _ENCODINGS[RGBM7Encoding] = 3, _ENCODINGS[RGBM16Encoding] = 4, _ENCODINGS[RGBDEncoding] = 5, _ENCODINGS[GammaEncoding] = 6, _ENCODINGS);
  35041. var _flatCamera = /*@__PURE__*/new OrthographicCamera();
  35042. var _createPlanes2 = /*@__PURE__*/_createPlanes(),
  35043. _lodPlanes = _createPlanes2._lodPlanes,
  35044. _sizeLods = _createPlanes2._sizeLods,
  35045. _sigmas = _createPlanes2._sigmas;
  35046. var _oldTarget = null; // Golden Ratio
  35047. var PHI = (1 + Math.sqrt(5)) / 2;
  35048. var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  35049. // same axis), used as axis directions evenly spread on a sphere.
  35050. var _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  35051. /**
  35052. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  35053. * (PMREM) from a cubeMap environment texture. This allows different levels of
  35054. * blur to be quickly accessed based on material roughness. It is packed into a
  35055. * special CubeUV format that allows us to perform custom interpolation so that
  35056. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  35057. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  35058. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  35059. * higher roughness levels. In this way we maintain resolution to smoothly
  35060. * interpolate diffuse lighting while limiting sampling computation.
  35061. */
  35062. var PMREMGenerator = /*#__PURE__*/function () {
  35063. function PMREMGenerator(renderer) {
  35064. this._renderer = renderer;
  35065. this._pingPongRenderTarget = null;
  35066. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  35067. this._equirectShader = null;
  35068. this._cubemapShader = null;
  35069. this._compileMaterial(this._blurMaterial);
  35070. }
  35071. /**
  35072. * Generates a PMREM from a supplied Scene, which can be faster than using an
  35073. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  35074. * in radians to be applied to the scene before PMREM generation. Optional near
  35075. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  35076. * is placed at the origin).
  35077. */
  35078. var _proto = PMREMGenerator.prototype;
  35079. _proto.fromScene = function fromScene(scene, sigma, near, far) {
  35080. if (sigma === void 0) {
  35081. sigma = 0;
  35082. }
  35083. if (near === void 0) {
  35084. near = 0.1;
  35085. }
  35086. if (far === void 0) {
  35087. far = 100;
  35088. }
  35089. _oldTarget = this._renderer.getRenderTarget();
  35090. var cubeUVRenderTarget = this._allocateTargets();
  35091. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  35092. if (sigma > 0) {
  35093. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  35094. }
  35095. this._applyPMREM(cubeUVRenderTarget);
  35096. this._cleanup(cubeUVRenderTarget);
  35097. return cubeUVRenderTarget;
  35098. }
  35099. /**
  35100. * Generates a PMREM from an equirectangular texture, which can be either LDR
  35101. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  35102. * as this matches best with the 256 x 256 cubemap output.
  35103. */
  35104. ;
  35105. _proto.fromEquirectangular = function fromEquirectangular(equirectangular) {
  35106. return this._fromTexture(equirectangular);
  35107. }
  35108. /**
  35109. * Generates a PMREM from an cubemap texture, which can be either LDR
  35110. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  35111. * as this matches best with the 256 x 256 cubemap output.
  35112. */
  35113. ;
  35114. _proto.fromCubemap = function fromCubemap(cubemap) {
  35115. return this._fromTexture(cubemap);
  35116. }
  35117. /**
  35118. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  35119. * your texture's network fetch for increased concurrency.
  35120. */
  35121. ;
  35122. _proto.compileCubemapShader = function compileCubemapShader() {
  35123. if (this._cubemapShader === null) {
  35124. this._cubemapShader = _getCubemapShader();
  35125. this._compileMaterial(this._cubemapShader);
  35126. }
  35127. }
  35128. /**
  35129. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  35130. * your texture's network fetch for increased concurrency.
  35131. */
  35132. ;
  35133. _proto.compileEquirectangularShader = function compileEquirectangularShader() {
  35134. if (this._equirectShader === null) {
  35135. this._equirectShader = _getEquirectShader();
  35136. this._compileMaterial(this._equirectShader);
  35137. }
  35138. }
  35139. /**
  35140. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  35141. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  35142. * one of them will cause any others to also become unusable.
  35143. */
  35144. ;
  35145. _proto.dispose = function dispose() {
  35146. this._blurMaterial.dispose();
  35147. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  35148. if (this._equirectShader !== null) this._equirectShader.dispose();
  35149. for (var i = 0; i < _lodPlanes.length; i++) {
  35150. _lodPlanes[i].dispose();
  35151. }
  35152. } // private interface
  35153. ;
  35154. _proto._cleanup = function _cleanup(outputTarget) {
  35155. this._pingPongRenderTarget.dispose();
  35156. this._renderer.setRenderTarget(_oldTarget);
  35157. outputTarget.scissorTest = false;
  35158. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  35159. };
  35160. _proto._fromTexture = function _fromTexture(texture) {
  35161. _oldTarget = this._renderer.getRenderTarget();
  35162. var cubeUVRenderTarget = this._allocateTargets(texture);
  35163. this._textureToCubeUV(texture, cubeUVRenderTarget);
  35164. this._applyPMREM(cubeUVRenderTarget);
  35165. this._cleanup(cubeUVRenderTarget);
  35166. return cubeUVRenderTarget;
  35167. };
  35168. _proto._allocateTargets = function _allocateTargets(texture) {
  35169. // warning: null texture is valid
  35170. var params = {
  35171. magFilter: NearestFilter,
  35172. minFilter: NearestFilter,
  35173. generateMipmaps: false,
  35174. type: UnsignedByteType,
  35175. format: RGBEFormat,
  35176. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  35177. depthBuffer: false
  35178. };
  35179. var cubeUVRenderTarget = _createRenderTarget(params);
  35180. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  35181. this._pingPongRenderTarget = _createRenderTarget(params);
  35182. return cubeUVRenderTarget;
  35183. };
  35184. _proto._compileMaterial = function _compileMaterial(material) {
  35185. var tmpMesh = new Mesh(_lodPlanes[0], material);
  35186. this._renderer.compile(tmpMesh, _flatCamera);
  35187. };
  35188. _proto._sceneToCubeUV = function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  35189. var fov = 90;
  35190. var aspect = 1;
  35191. var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  35192. var upSign = [1, -1, 1, 1, 1, 1];
  35193. var forwardSign = [1, 1, 1, -1, -1, -1];
  35194. var renderer = this._renderer;
  35195. var outputEncoding = renderer.outputEncoding;
  35196. var toneMapping = renderer.toneMapping;
  35197. var clearColor = renderer.getClearColor();
  35198. var clearAlpha = renderer.getClearAlpha();
  35199. renderer.toneMapping = NoToneMapping;
  35200. renderer.outputEncoding = LinearEncoding;
  35201. var background = scene.background;
  35202. if (background && background.isColor) {
  35203. background.convertSRGBToLinear(); // Convert linear to RGBE
  35204. var maxComponent = Math.max(background.r, background.g, background.b);
  35205. var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  35206. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  35207. var alpha = (fExp + 128.0) / 255.0;
  35208. renderer.setClearColor(background, alpha);
  35209. scene.background = null;
  35210. }
  35211. for (var i = 0; i < 6; i++) {
  35212. var col = i % 3;
  35213. if (col == 0) {
  35214. cubeCamera.up.set(0, upSign[i], 0);
  35215. cubeCamera.lookAt(forwardSign[i], 0, 0);
  35216. } else if (col == 1) {
  35217. cubeCamera.up.set(0, 0, upSign[i]);
  35218. cubeCamera.lookAt(0, forwardSign[i], 0);
  35219. } else {
  35220. cubeCamera.up.set(0, upSign[i], 0);
  35221. cubeCamera.lookAt(0, 0, forwardSign[i]);
  35222. }
  35223. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  35224. renderer.setRenderTarget(cubeUVRenderTarget);
  35225. renderer.render(scene, cubeCamera);
  35226. }
  35227. renderer.toneMapping = toneMapping;
  35228. renderer.outputEncoding = outputEncoding;
  35229. renderer.setClearColor(clearColor, clearAlpha);
  35230. };
  35231. _proto._textureToCubeUV = function _textureToCubeUV(texture, cubeUVRenderTarget) {
  35232. var renderer = this._renderer;
  35233. if (texture.isCubeTexture) {
  35234. if (this._cubemapShader == null) {
  35235. this._cubemapShader = _getCubemapShader();
  35236. }
  35237. } else {
  35238. if (this._equirectShader == null) {
  35239. this._equirectShader = _getEquirectShader();
  35240. }
  35241. }
  35242. var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  35243. var mesh = new Mesh(_lodPlanes[0], material);
  35244. var uniforms = material.uniforms;
  35245. uniforms['envMap'].value = texture;
  35246. if (!texture.isCubeTexture) {
  35247. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  35248. }
  35249. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  35250. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  35251. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  35252. renderer.setRenderTarget(cubeUVRenderTarget);
  35253. renderer.render(mesh, _flatCamera);
  35254. };
  35255. _proto._applyPMREM = function _applyPMREM(cubeUVRenderTarget) {
  35256. var renderer = this._renderer;
  35257. var autoClear = renderer.autoClear;
  35258. renderer.autoClear = false;
  35259. for (var i = 1; i < TOTAL_LODS; i++) {
  35260. var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  35261. var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  35262. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  35263. }
  35264. renderer.autoClear = autoClear;
  35265. }
  35266. /**
  35267. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  35268. * vertically and horizontally, but this breaks down on a cube. Here we apply
  35269. * the blur latitudinally (around the poles), and then longitudinally (towards
  35270. * the poles) to approximate the orthogonally-separable blur. It is least
  35271. * accurate at the poles, but still does a decent job.
  35272. */
  35273. ;
  35274. _proto._blur = function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  35275. var pingPongRenderTarget = this._pingPongRenderTarget;
  35276. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  35277. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  35278. };
  35279. _proto._halfBlur = function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  35280. var renderer = this._renderer;
  35281. var blurMaterial = this._blurMaterial;
  35282. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  35283. console.error('blur direction must be either latitudinal or longitudinal!');
  35284. } // Number of standard deviations at which to cut off the discrete approximation.
  35285. var STANDARD_DEVIATIONS = 3;
  35286. var blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  35287. var blurUniforms = blurMaterial.uniforms;
  35288. var pixels = _sizeLods[lodIn] - 1;
  35289. var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  35290. var sigmaPixels = sigmaRadians / radiansPerPixel;
  35291. var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  35292. if (samples > MAX_SAMPLES) {
  35293. console.warn("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES);
  35294. }
  35295. var weights = [];
  35296. var sum = 0;
  35297. for (var i = 0; i < MAX_SAMPLES; ++i) {
  35298. var _x = i / sigmaPixels;
  35299. var weight = Math.exp(-_x * _x / 2);
  35300. weights.push(weight);
  35301. if (i == 0) {
  35302. sum += weight;
  35303. } else if (i < samples) {
  35304. sum += 2 * weight;
  35305. }
  35306. }
  35307. for (var _i = 0; _i < weights.length; _i++) {
  35308. weights[_i] = weights[_i] / sum;
  35309. }
  35310. blurUniforms['envMap'].value = targetIn.texture;
  35311. blurUniforms['samples'].value = samples;
  35312. blurUniforms['weights'].value = weights;
  35313. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  35314. if (poleAxis) {
  35315. blurUniforms['poleAxis'].value = poleAxis;
  35316. }
  35317. blurUniforms['dTheta'].value = radiansPerPixel;
  35318. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  35319. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  35320. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  35321. var outputSize = _sizeLods[lodOut];
  35322. var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  35323. var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  35324. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  35325. renderer.setRenderTarget(targetOut);
  35326. renderer.render(blurMesh, _flatCamera);
  35327. };
  35328. return PMREMGenerator;
  35329. }();
  35330. function _isLDR(texture) {
  35331. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  35332. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  35333. }
  35334. function _createPlanes() {
  35335. var _lodPlanes = [];
  35336. var _sizeLods = [];
  35337. var _sigmas = [];
  35338. var lod = LOD_MAX;
  35339. for (var i = 0; i < TOTAL_LODS; i++) {
  35340. var sizeLod = Math.pow(2, lod);
  35341. _sizeLods.push(sizeLod);
  35342. var sigma = 1.0 / sizeLod;
  35343. if (i > LOD_MAX - LOD_MIN) {
  35344. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  35345. } else if (i == 0) {
  35346. sigma = 0;
  35347. }
  35348. _sigmas.push(sigma);
  35349. var texelSize = 1.0 / (sizeLod - 1);
  35350. var min = -texelSize / 2;
  35351. var max = 1 + texelSize / 2;
  35352. var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  35353. var cubeFaces = 6;
  35354. var vertices = 6;
  35355. var positionSize = 3;
  35356. var uvSize = 2;
  35357. var faceIndexSize = 1;
  35358. var position = new Float32Array(positionSize * vertices * cubeFaces);
  35359. var uv = new Float32Array(uvSize * vertices * cubeFaces);
  35360. var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  35361. for (var face = 0; face < cubeFaces; face++) {
  35362. var x = face % 3 * 2 / 3 - 1;
  35363. var y = face > 2 ? 0 : -1;
  35364. var coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  35365. position.set(coordinates, positionSize * vertices * face);
  35366. uv.set(uv1, uvSize * vertices * face);
  35367. var fill = [face, face, face, face, face, face];
  35368. faceIndex.set(fill, faceIndexSize * vertices * face);
  35369. }
  35370. var planes = new BufferGeometry();
  35371. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  35372. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  35373. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  35374. _lodPlanes.push(planes);
  35375. if (lod > LOD_MIN) {
  35376. lod--;
  35377. }
  35378. }
  35379. return {
  35380. _lodPlanes: _lodPlanes,
  35381. _sizeLods: _sizeLods,
  35382. _sigmas: _sigmas
  35383. };
  35384. }
  35385. function _createRenderTarget(params) {
  35386. var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  35387. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  35388. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  35389. cubeUVRenderTarget.scissorTest = true;
  35390. return cubeUVRenderTarget;
  35391. }
  35392. function _setViewport(target, x, y, width, height) {
  35393. target.viewport.set(x, y, width, height);
  35394. target.scissor.set(x, y, width, height);
  35395. }
  35396. function _getBlurShader(maxSamples) {
  35397. var weights = new Float32Array(maxSamples);
  35398. var poleAxis = new Vector3(0, 1, 0);
  35399. var shaderMaterial = new RawShaderMaterial({
  35400. name: 'SphericalGaussianBlur',
  35401. defines: {
  35402. 'n': maxSamples
  35403. },
  35404. uniforms: {
  35405. 'envMap': {
  35406. value: null
  35407. },
  35408. 'samples': {
  35409. value: 1
  35410. },
  35411. 'weights': {
  35412. value: weights
  35413. },
  35414. 'latitudinal': {
  35415. value: false
  35416. },
  35417. 'dTheta': {
  35418. value: 0
  35419. },
  35420. 'mipInt': {
  35421. value: 0
  35422. },
  35423. 'poleAxis': {
  35424. value: poleAxis
  35425. },
  35426. 'inputEncoding': {
  35427. value: ENCODINGS[LinearEncoding]
  35428. },
  35429. 'outputEncoding': {
  35430. value: ENCODINGS[LinearEncoding]
  35431. }
  35432. },
  35433. vertexShader: _getCommonVertexShader(),
  35434. fragmentShader:
  35435. /* glsl */
  35436. "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
  35437. blending: NoBlending,
  35438. depthTest: false,
  35439. depthWrite: false
  35440. });
  35441. return shaderMaterial;
  35442. }
  35443. function _getEquirectShader() {
  35444. var texelSize = new Vector2(1, 1);
  35445. var shaderMaterial = new RawShaderMaterial({
  35446. name: 'EquirectangularToCubeUV',
  35447. uniforms: {
  35448. 'envMap': {
  35449. value: null
  35450. },
  35451. 'texelSize': {
  35452. value: texelSize
  35453. },
  35454. 'inputEncoding': {
  35455. value: ENCODINGS[LinearEncoding]
  35456. },
  35457. 'outputEncoding': {
  35458. value: ENCODINGS[LinearEncoding]
  35459. }
  35460. },
  35461. vertexShader: _getCommonVertexShader(),
  35462. fragmentShader:
  35463. /* glsl */
  35464. "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
  35465. blending: NoBlending,
  35466. depthTest: false,
  35467. depthWrite: false
  35468. });
  35469. return shaderMaterial;
  35470. }
  35471. function _getCubemapShader() {
  35472. var shaderMaterial = new RawShaderMaterial({
  35473. name: 'CubemapToCubeUV',
  35474. uniforms: {
  35475. 'envMap': {
  35476. value: null
  35477. },
  35478. 'inputEncoding': {
  35479. value: ENCODINGS[LinearEncoding]
  35480. },
  35481. 'outputEncoding': {
  35482. value: ENCODINGS[LinearEncoding]
  35483. }
  35484. },
  35485. vertexShader: _getCommonVertexShader(),
  35486. fragmentShader:
  35487. /* glsl */
  35488. "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
  35489. blending: NoBlending,
  35490. depthTest: false,
  35491. depthWrite: false
  35492. });
  35493. return shaderMaterial;
  35494. }
  35495. function _getCommonVertexShader() {
  35496. return (
  35497. /* glsl */
  35498. "\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"
  35499. );
  35500. }
  35501. function _getEncodings() {
  35502. return (
  35503. /* glsl */
  35504. "\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include <encodings_pars_fragment>\n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t"
  35505. );
  35506. }
  35507. function Face4(a, b, c, d, normal, color, materialIndex) {
  35508. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  35509. return new Face3(a, b, c, normal, color, materialIndex);
  35510. }
  35511. var LineStrip = 0;
  35512. var LinePieces = 1;
  35513. var NoColors = 0;
  35514. var FaceColors = 1;
  35515. var VertexColors = 2;
  35516. function MeshFaceMaterial(materials) {
  35517. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  35518. return materials;
  35519. }
  35520. function MultiMaterial(materials) {
  35521. if (materials === void 0) {
  35522. materials = [];
  35523. }
  35524. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  35525. materials.isMultiMaterial = true;
  35526. materials.materials = materials;
  35527. materials.clone = function () {
  35528. return materials.slice();
  35529. };
  35530. return materials;
  35531. }
  35532. function PointCloud(geometry, material) {
  35533. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  35534. return new Points(geometry, material);
  35535. }
  35536. function Particle(material) {
  35537. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  35538. return new Sprite(material);
  35539. }
  35540. function ParticleSystem(geometry, material) {
  35541. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  35542. return new Points(geometry, material);
  35543. }
  35544. function PointCloudMaterial(parameters) {
  35545. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  35546. return new PointsMaterial(parameters);
  35547. }
  35548. function ParticleBasicMaterial(parameters) {
  35549. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  35550. return new PointsMaterial(parameters);
  35551. }
  35552. function ParticleSystemMaterial(parameters) {
  35553. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  35554. return new PointsMaterial(parameters);
  35555. }
  35556. function Vertex(x, y, z) {
  35557. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  35558. return new Vector3(x, y, z);
  35559. } //
  35560. function DynamicBufferAttribute(array, itemSize) {
  35561. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  35562. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  35563. }
  35564. function Int8Attribute(array, itemSize) {
  35565. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  35566. return new Int8BufferAttribute(array, itemSize);
  35567. }
  35568. function Uint8Attribute(array, itemSize) {
  35569. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  35570. return new Uint8BufferAttribute(array, itemSize);
  35571. }
  35572. function Uint8ClampedAttribute(array, itemSize) {
  35573. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  35574. return new Uint8ClampedBufferAttribute(array, itemSize);
  35575. }
  35576. function Int16Attribute(array, itemSize) {
  35577. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  35578. return new Int16BufferAttribute(array, itemSize);
  35579. }
  35580. function Uint16Attribute(array, itemSize) {
  35581. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  35582. return new Uint16BufferAttribute(array, itemSize);
  35583. }
  35584. function Int32Attribute(array, itemSize) {
  35585. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  35586. return new Int32BufferAttribute(array, itemSize);
  35587. }
  35588. function Uint32Attribute(array, itemSize) {
  35589. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  35590. return new Uint32BufferAttribute(array, itemSize);
  35591. }
  35592. function Float32Attribute(array, itemSize) {
  35593. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  35594. return new Float32BufferAttribute(array, itemSize);
  35595. }
  35596. function Float64Attribute(array, itemSize) {
  35597. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  35598. return new Float64BufferAttribute(array, itemSize);
  35599. } //
  35600. Curve.create = function (construct, getPoint) {
  35601. console.log('THREE.Curve.create() has been deprecated');
  35602. construct.prototype = Object.create(Curve.prototype);
  35603. construct.prototype.constructor = construct;
  35604. construct.prototype.getPoint = getPoint;
  35605. return construct;
  35606. }; //
  35607. Object.assign(CurvePath.prototype, {
  35608. createPointsGeometry: function createPointsGeometry(divisions) {
  35609. console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)
  35610. var pts = this.getPoints(divisions);
  35611. return this.createGeometry(pts);
  35612. },
  35613. createSpacedPointsGeometry: function createSpacedPointsGeometry(divisions) {
  35614. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  35615. var pts = this.getSpacedPoints(divisions);
  35616. return this.createGeometry(pts);
  35617. },
  35618. createGeometry: function createGeometry(points) {
  35619. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  35620. var geometry = new Geometry();
  35621. for (var i = 0, l = points.length; i < l; i++) {
  35622. var point = points[i];
  35623. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  35624. }
  35625. return geometry;
  35626. }
  35627. }); //
  35628. Object.assign(Path.prototype, {
  35629. fromPoints: function fromPoints(points) {
  35630. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  35631. return this.setFromPoints(points);
  35632. }
  35633. }); //
  35634. function ClosedSplineCurve3(points) {
  35635. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  35636. CatmullRomCurve3.call(this, points);
  35637. this.type = 'catmullrom';
  35638. this.closed = true;
  35639. }
  35640. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  35641. function SplineCurve3(points) {
  35642. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  35643. CatmullRomCurve3.call(this, points);
  35644. this.type = 'catmullrom';
  35645. }
  35646. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  35647. function Spline(points) {
  35648. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  35649. CatmullRomCurve3.call(this, points);
  35650. this.type = 'catmullrom';
  35651. }
  35652. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  35653. Object.assign(Spline.prototype, {
  35654. initFromArray: function initFromArray()
  35655. /* a */
  35656. {
  35657. console.error('THREE.Spline: .initFromArray() has been removed.');
  35658. },
  35659. getControlPointsArray: function getControlPointsArray()
  35660. /* optionalTarget */
  35661. {
  35662. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  35663. },
  35664. reparametrizeByArcLength: function reparametrizeByArcLength()
  35665. /* samplingCoef */
  35666. {
  35667. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  35668. }
  35669. }); //
  35670. function AxisHelper(size) {
  35671. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  35672. return new AxesHelper(size);
  35673. }
  35674. function BoundingBoxHelper(object, color) {
  35675. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  35676. return new BoxHelper(object, color);
  35677. }
  35678. function EdgesHelper(object, hex) {
  35679. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  35680. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  35681. color: hex !== undefined ? hex : 0xffffff
  35682. }));
  35683. }
  35684. GridHelper.prototype.setColors = function () {
  35685. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  35686. };
  35687. SkeletonHelper.prototype.update = function () {
  35688. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  35689. };
  35690. function WireframeHelper(object, hex) {
  35691. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  35692. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  35693. color: hex !== undefined ? hex : 0xffffff
  35694. }));
  35695. } //
  35696. Object.assign(Loader.prototype, {
  35697. extractUrlBase: function extractUrlBase(url) {
  35698. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  35699. return LoaderUtils.extractUrlBase(url);
  35700. }
  35701. });
  35702. Loader.Handlers = {
  35703. add: function add()
  35704. /* regex, loader */
  35705. {
  35706. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  35707. },
  35708. get: function get()
  35709. /* file */
  35710. {
  35711. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  35712. }
  35713. };
  35714. function XHRLoader(manager) {
  35715. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  35716. return new FileLoader(manager);
  35717. }
  35718. function BinaryTextureLoader(manager) {
  35719. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  35720. return new DataTextureLoader(manager);
  35721. } //
  35722. Object.assign(Box2.prototype, {
  35723. center: function center(optionalTarget) {
  35724. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  35725. return this.getCenter(optionalTarget);
  35726. },
  35727. empty: function empty() {
  35728. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  35729. return this.isEmpty();
  35730. },
  35731. isIntersectionBox: function isIntersectionBox(box) {
  35732. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  35733. return this.intersectsBox(box);
  35734. },
  35735. size: function size(optionalTarget) {
  35736. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  35737. return this.getSize(optionalTarget);
  35738. }
  35739. });
  35740. Object.assign(Box3.prototype, {
  35741. center: function center(optionalTarget) {
  35742. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  35743. return this.getCenter(optionalTarget);
  35744. },
  35745. empty: function empty() {
  35746. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  35747. return this.isEmpty();
  35748. },
  35749. isIntersectionBox: function isIntersectionBox(box) {
  35750. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  35751. return this.intersectsBox(box);
  35752. },
  35753. isIntersectionSphere: function isIntersectionSphere(sphere) {
  35754. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  35755. return this.intersectsSphere(sphere);
  35756. },
  35757. size: function size(optionalTarget) {
  35758. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  35759. return this.getSize(optionalTarget);
  35760. }
  35761. });
  35762. Object.assign(Sphere.prototype, {
  35763. empty: function empty() {
  35764. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  35765. return this.isEmpty();
  35766. }
  35767. });
  35768. Frustum.prototype.setFromMatrix = function (m) {
  35769. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  35770. return this.setFromProjectionMatrix(m);
  35771. };
  35772. Line3.prototype.center = function (optionalTarget) {
  35773. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  35774. return this.getCenter(optionalTarget);
  35775. };
  35776. Object.assign(MathUtils, {
  35777. random16: function random16() {
  35778. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  35779. return Math.random();
  35780. },
  35781. nearestPowerOfTwo: function nearestPowerOfTwo(value) {
  35782. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  35783. return MathUtils.floorPowerOfTwo(value);
  35784. },
  35785. nextPowerOfTwo: function nextPowerOfTwo(value) {
  35786. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  35787. return MathUtils.ceilPowerOfTwo(value);
  35788. }
  35789. });
  35790. Object.assign(Matrix3.prototype, {
  35791. flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
  35792. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  35793. return this.toArray(array, offset);
  35794. },
  35795. multiplyVector3: function multiplyVector3(vector) {
  35796. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  35797. return vector.applyMatrix3(this);
  35798. },
  35799. multiplyVector3Array: function multiplyVector3Array()
  35800. /* a */
  35801. {
  35802. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  35803. },
  35804. applyToBufferAttribute: function applyToBufferAttribute(attribute) {
  35805. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  35806. return attribute.applyMatrix3(this);
  35807. },
  35808. applyToVector3Array: function applyToVector3Array()
  35809. /* array, offset, length */
  35810. {
  35811. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  35812. },
  35813. getInverse: function getInverse(matrix) {
  35814. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  35815. return this.copy(matrix).invert();
  35816. }
  35817. });
  35818. Object.assign(Matrix4.prototype, {
  35819. extractPosition: function extractPosition(m) {
  35820. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  35821. return this.copyPosition(m);
  35822. },
  35823. flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
  35824. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  35825. return this.toArray(array, offset);
  35826. },
  35827. getPosition: function getPosition() {
  35828. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  35829. return new Vector3().setFromMatrixColumn(this, 3);
  35830. },
  35831. setRotationFromQuaternion: function setRotationFromQuaternion(q) {
  35832. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  35833. return this.makeRotationFromQuaternion(q);
  35834. },
  35835. multiplyToArray: function multiplyToArray() {
  35836. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  35837. },
  35838. multiplyVector3: function multiplyVector3(vector) {
  35839. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35840. return vector.applyMatrix4(this);
  35841. },
  35842. multiplyVector4: function multiplyVector4(vector) {
  35843. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35844. return vector.applyMatrix4(this);
  35845. },
  35846. multiplyVector3Array: function multiplyVector3Array()
  35847. /* a */
  35848. {
  35849. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  35850. },
  35851. rotateAxis: function rotateAxis(v) {
  35852. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  35853. v.transformDirection(this);
  35854. },
  35855. crossVector: function crossVector(vector) {
  35856. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35857. return vector.applyMatrix4(this);
  35858. },
  35859. translate: function translate() {
  35860. console.error('THREE.Matrix4: .translate() has been removed.');
  35861. },
  35862. rotateX: function rotateX() {
  35863. console.error('THREE.Matrix4: .rotateX() has been removed.');
  35864. },
  35865. rotateY: function rotateY() {
  35866. console.error('THREE.Matrix4: .rotateY() has been removed.');
  35867. },
  35868. rotateZ: function rotateZ() {
  35869. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  35870. },
  35871. rotateByAxis: function rotateByAxis() {
  35872. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  35873. },
  35874. applyToBufferAttribute: function applyToBufferAttribute(attribute) {
  35875. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  35876. return attribute.applyMatrix4(this);
  35877. },
  35878. applyToVector3Array: function applyToVector3Array()
  35879. /* array, offset, length */
  35880. {
  35881. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  35882. },
  35883. makeFrustum: function makeFrustum(left, right, bottom, top, near, far) {
  35884. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  35885. return this.makePerspective(left, right, top, bottom, near, far);
  35886. },
  35887. getInverse: function getInverse(matrix) {
  35888. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  35889. return this.copy(matrix).invert();
  35890. }
  35891. });
  35892. Plane.prototype.isIntersectionLine = function (line) {
  35893. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  35894. return this.intersectsLine(line);
  35895. };
  35896. Object.assign(Quaternion.prototype, {
  35897. multiplyVector3: function multiplyVector3(vector) {
  35898. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  35899. return vector.applyQuaternion(this);
  35900. },
  35901. inverse: function inverse() {
  35902. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  35903. return this.invert();
  35904. }
  35905. });
  35906. Object.assign(Ray.prototype, {
  35907. isIntersectionBox: function isIntersectionBox(box) {
  35908. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  35909. return this.intersectsBox(box);
  35910. },
  35911. isIntersectionPlane: function isIntersectionPlane(plane) {
  35912. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  35913. return this.intersectsPlane(plane);
  35914. },
  35915. isIntersectionSphere: function isIntersectionSphere(sphere) {
  35916. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  35917. return this.intersectsSphere(sphere);
  35918. }
  35919. });
  35920. Object.assign(Triangle.prototype, {
  35921. area: function area() {
  35922. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  35923. return this.getArea();
  35924. },
  35925. barycoordFromPoint: function barycoordFromPoint(point, target) {
  35926. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  35927. return this.getBarycoord(point, target);
  35928. },
  35929. midpoint: function midpoint(target) {
  35930. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  35931. return this.getMidpoint(target);
  35932. },
  35933. normal: function normal(target) {
  35934. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  35935. return this.getNormal(target);
  35936. },
  35937. plane: function plane(target) {
  35938. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  35939. return this.getPlane(target);
  35940. }
  35941. });
  35942. Object.assign(Triangle, {
  35943. barycoordFromPoint: function barycoordFromPoint(point, a, b, c, target) {
  35944. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  35945. return Triangle.getBarycoord(point, a, b, c, target);
  35946. },
  35947. normal: function normal(a, b, c, target) {
  35948. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  35949. return Triangle.getNormal(a, b, c, target);
  35950. }
  35951. });
  35952. Object.assign(Shape.prototype, {
  35953. extractAllPoints: function extractAllPoints(divisions) {
  35954. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  35955. return this.extractPoints(divisions);
  35956. },
  35957. extrude: function extrude(options) {
  35958. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  35959. return new ExtrudeGeometry(this, options);
  35960. },
  35961. makeGeometry: function makeGeometry(options) {
  35962. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  35963. return new ShapeGeometry(this, options);
  35964. }
  35965. });
  35966. Object.assign(Vector2.prototype, {
  35967. fromAttribute: function fromAttribute(attribute, index, offset) {
  35968. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35969. return this.fromBufferAttribute(attribute, index, offset);
  35970. },
  35971. distanceToManhattan: function distanceToManhattan(v) {
  35972. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  35973. return this.manhattanDistanceTo(v);
  35974. },
  35975. lengthManhattan: function lengthManhattan() {
  35976. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  35977. return this.manhattanLength();
  35978. }
  35979. });
  35980. Object.assign(Vector3.prototype, {
  35981. setEulerFromRotationMatrix: function setEulerFromRotationMatrix() {
  35982. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  35983. },
  35984. setEulerFromQuaternion: function setEulerFromQuaternion() {
  35985. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  35986. },
  35987. getPositionFromMatrix: function getPositionFromMatrix(m) {
  35988. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  35989. return this.setFromMatrixPosition(m);
  35990. },
  35991. getScaleFromMatrix: function getScaleFromMatrix(m) {
  35992. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  35993. return this.setFromMatrixScale(m);
  35994. },
  35995. getColumnFromMatrix: function getColumnFromMatrix(index, matrix) {
  35996. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  35997. return this.setFromMatrixColumn(matrix, index);
  35998. },
  35999. applyProjection: function applyProjection(m) {
  36000. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  36001. return this.applyMatrix4(m);
  36002. },
  36003. fromAttribute: function fromAttribute(attribute, index, offset) {
  36004. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  36005. return this.fromBufferAttribute(attribute, index, offset);
  36006. },
  36007. distanceToManhattan: function distanceToManhattan(v) {
  36008. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  36009. return this.manhattanDistanceTo(v);
  36010. },
  36011. lengthManhattan: function lengthManhattan() {
  36012. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  36013. return this.manhattanLength();
  36014. }
  36015. });
  36016. Object.assign(Vector4.prototype, {
  36017. fromAttribute: function fromAttribute(attribute, index, offset) {
  36018. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  36019. return this.fromBufferAttribute(attribute, index, offset);
  36020. },
  36021. lengthManhattan: function lengthManhattan() {
  36022. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  36023. return this.manhattanLength();
  36024. }
  36025. }); //
  36026. Object.assign(Geometry.prototype, {
  36027. computeTangents: function computeTangents() {
  36028. console.error('THREE.Geometry: .computeTangents() has been removed.');
  36029. },
  36030. computeLineDistances: function computeLineDistances() {
  36031. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  36032. },
  36033. applyMatrix: function applyMatrix(matrix) {
  36034. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  36035. return this.applyMatrix4(matrix);
  36036. }
  36037. });
  36038. Object.assign(Object3D.prototype, {
  36039. getChildByName: function getChildByName(name) {
  36040. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  36041. return this.getObjectByName(name);
  36042. },
  36043. renderDepth: function renderDepth() {
  36044. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  36045. },
  36046. translate: function translate(distance, axis) {
  36047. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  36048. return this.translateOnAxis(axis, distance);
  36049. },
  36050. getWorldRotation: function getWorldRotation() {
  36051. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  36052. },
  36053. applyMatrix: function applyMatrix(matrix) {
  36054. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  36055. return this.applyMatrix4(matrix);
  36056. }
  36057. });
  36058. Object.defineProperties(Object3D.prototype, {
  36059. eulerOrder: {
  36060. get: function get() {
  36061. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  36062. return this.rotation.order;
  36063. },
  36064. set: function set(value) {
  36065. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  36066. this.rotation.order = value;
  36067. }
  36068. },
  36069. useQuaternion: {
  36070. get: function get() {
  36071. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  36072. },
  36073. set: function set() {
  36074. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  36075. }
  36076. }
  36077. });
  36078. Object.assign(Mesh.prototype, {
  36079. setDrawMode: function setDrawMode() {
  36080. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  36081. }
  36082. });
  36083. Object.defineProperties(Mesh.prototype, {
  36084. drawMode: {
  36085. get: function get() {
  36086. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  36087. return TrianglesDrawMode;
  36088. },
  36089. set: function set() {
  36090. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  36091. }
  36092. }
  36093. });
  36094. Object.defineProperties(LOD.prototype, {
  36095. objects: {
  36096. get: function get() {
  36097. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  36098. return this.levels;
  36099. }
  36100. }
  36101. });
  36102. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  36103. get: function get() {
  36104. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  36105. },
  36106. set: function set() {
  36107. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  36108. }
  36109. });
  36110. SkinnedMesh.prototype.initBones = function () {
  36111. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  36112. };
  36113. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  36114. get: function get() {
  36115. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  36116. return this.arcLengthDivisions;
  36117. },
  36118. set: function set(value) {
  36119. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  36120. this.arcLengthDivisions = value;
  36121. }
  36122. }); //
  36123. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  36124. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  36125. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  36126. this.setFocalLength(focalLength);
  36127. }; //
  36128. Object.defineProperties(Light.prototype, {
  36129. onlyShadow: {
  36130. set: function set() {
  36131. console.warn('THREE.Light: .onlyShadow has been removed.');
  36132. }
  36133. },
  36134. shadowCameraFov: {
  36135. set: function set(value) {
  36136. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  36137. this.shadow.camera.fov = value;
  36138. }
  36139. },
  36140. shadowCameraLeft: {
  36141. set: function set(value) {
  36142. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  36143. this.shadow.camera.left = value;
  36144. }
  36145. },
  36146. shadowCameraRight: {
  36147. set: function set(value) {
  36148. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  36149. this.shadow.camera.right = value;
  36150. }
  36151. },
  36152. shadowCameraTop: {
  36153. set: function set(value) {
  36154. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  36155. this.shadow.camera.top = value;
  36156. }
  36157. },
  36158. shadowCameraBottom: {
  36159. set: function set(value) {
  36160. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  36161. this.shadow.camera.bottom = value;
  36162. }
  36163. },
  36164. shadowCameraNear: {
  36165. set: function set(value) {
  36166. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  36167. this.shadow.camera.near = value;
  36168. }
  36169. },
  36170. shadowCameraFar: {
  36171. set: function set(value) {
  36172. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  36173. this.shadow.camera.far = value;
  36174. }
  36175. },
  36176. shadowCameraVisible: {
  36177. set: function set() {
  36178. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  36179. }
  36180. },
  36181. shadowBias: {
  36182. set: function set(value) {
  36183. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  36184. this.shadow.bias = value;
  36185. }
  36186. },
  36187. shadowDarkness: {
  36188. set: function set() {
  36189. console.warn('THREE.Light: .shadowDarkness has been removed.');
  36190. }
  36191. },
  36192. shadowMapWidth: {
  36193. set: function set(value) {
  36194. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  36195. this.shadow.mapSize.width = value;
  36196. }
  36197. },
  36198. shadowMapHeight: {
  36199. set: function set(value) {
  36200. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  36201. this.shadow.mapSize.height = value;
  36202. }
  36203. }
  36204. }); //
  36205. Object.defineProperties(BufferAttribute.prototype, {
  36206. length: {
  36207. get: function get() {
  36208. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  36209. return this.array.length;
  36210. }
  36211. },
  36212. dynamic: {
  36213. get: function get() {
  36214. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  36215. return this.usage === DynamicDrawUsage;
  36216. },
  36217. set: function set()
  36218. /* value */
  36219. {
  36220. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  36221. this.setUsage(DynamicDrawUsage);
  36222. }
  36223. }
  36224. });
  36225. Object.assign(BufferAttribute.prototype, {
  36226. setDynamic: function setDynamic(value) {
  36227. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  36228. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  36229. return this;
  36230. },
  36231. copyIndicesArray: function copyIndicesArray()
  36232. /* indices */
  36233. {
  36234. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  36235. },
  36236. setArray: function setArray()
  36237. /* array */
  36238. {
  36239. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  36240. }
  36241. });
  36242. Object.assign(BufferGeometry.prototype, {
  36243. addIndex: function addIndex(index) {
  36244. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  36245. this.setIndex(index);
  36246. },
  36247. addAttribute: function addAttribute(name, attribute) {
  36248. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  36249. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  36250. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  36251. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  36252. }
  36253. if (name === 'index') {
  36254. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  36255. this.setIndex(attribute);
  36256. return this;
  36257. }
  36258. return this.setAttribute(name, attribute);
  36259. },
  36260. addDrawCall: function addDrawCall(start, count, indexOffset) {
  36261. if (indexOffset !== undefined) {
  36262. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  36263. }
  36264. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  36265. this.addGroup(start, count);
  36266. },
  36267. clearDrawCalls: function clearDrawCalls() {
  36268. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  36269. this.clearGroups();
  36270. },
  36271. computeTangents: function computeTangents() {
  36272. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  36273. },
  36274. computeOffsets: function computeOffsets() {
  36275. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  36276. },
  36277. removeAttribute: function removeAttribute(name) {
  36278. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  36279. return this.deleteAttribute(name);
  36280. },
  36281. applyMatrix: function applyMatrix(matrix) {
  36282. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  36283. return this.applyMatrix4(matrix);
  36284. }
  36285. });
  36286. Object.defineProperties(BufferGeometry.prototype, {
  36287. drawcalls: {
  36288. get: function get() {
  36289. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  36290. return this.groups;
  36291. }
  36292. },
  36293. offsets: {
  36294. get: function get() {
  36295. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  36296. return this.groups;
  36297. }
  36298. }
  36299. });
  36300. Object.defineProperties(InstancedBufferGeometry.prototype, {
  36301. maxInstancedCount: {
  36302. get: function get() {
  36303. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  36304. return this.instanceCount;
  36305. },
  36306. set: function set(value) {
  36307. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  36308. this.instanceCount = value;
  36309. }
  36310. }
  36311. });
  36312. Object.defineProperties(Raycaster.prototype, {
  36313. linePrecision: {
  36314. get: function get() {
  36315. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  36316. return this.params.Line.threshold;
  36317. },
  36318. set: function set(value) {
  36319. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  36320. this.params.Line.threshold = value;
  36321. }
  36322. }
  36323. });
  36324. Object.defineProperties(InterleavedBuffer.prototype, {
  36325. dynamic: {
  36326. get: function get() {
  36327. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  36328. return this.usage === DynamicDrawUsage;
  36329. },
  36330. set: function set(value) {
  36331. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  36332. this.setUsage(value);
  36333. }
  36334. }
  36335. });
  36336. Object.assign(InterleavedBuffer.prototype, {
  36337. setDynamic: function setDynamic(value) {
  36338. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  36339. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  36340. return this;
  36341. },
  36342. setArray: function setArray()
  36343. /* array */
  36344. {
  36345. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  36346. }
  36347. }); //
  36348. Object.assign(ExtrudeBufferGeometry.prototype, {
  36349. getArrays: function getArrays() {
  36350. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  36351. },
  36352. addShapeList: function addShapeList() {
  36353. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  36354. },
  36355. addShape: function addShape() {
  36356. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  36357. }
  36358. }); //
  36359. Object.assign(Scene.prototype, {
  36360. dispose: function dispose() {
  36361. console.error('THREE.Scene: .dispose() has been removed.');
  36362. }
  36363. }); //
  36364. Object.defineProperties(Uniform.prototype, {
  36365. dynamic: {
  36366. set: function set() {
  36367. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  36368. }
  36369. },
  36370. onUpdate: {
  36371. value: function value() {
  36372. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  36373. return this;
  36374. }
  36375. }
  36376. }); //
  36377. Object.defineProperties(Material.prototype, {
  36378. wrapAround: {
  36379. get: function get() {
  36380. console.warn('THREE.Material: .wrapAround has been removed.');
  36381. },
  36382. set: function set() {
  36383. console.warn('THREE.Material: .wrapAround has been removed.');
  36384. }
  36385. },
  36386. overdraw: {
  36387. get: function get() {
  36388. console.warn('THREE.Material: .overdraw has been removed.');
  36389. },
  36390. set: function set() {
  36391. console.warn('THREE.Material: .overdraw has been removed.');
  36392. }
  36393. },
  36394. wrapRGB: {
  36395. get: function get() {
  36396. console.warn('THREE.Material: .wrapRGB has been removed.');
  36397. return new Color();
  36398. }
  36399. },
  36400. shading: {
  36401. get: function get() {
  36402. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  36403. },
  36404. set: function set(value) {
  36405. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  36406. this.flatShading = value === FlatShading;
  36407. }
  36408. },
  36409. stencilMask: {
  36410. get: function get() {
  36411. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  36412. return this.stencilFuncMask;
  36413. },
  36414. set: function set(value) {
  36415. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  36416. this.stencilFuncMask = value;
  36417. }
  36418. }
  36419. });
  36420. Object.defineProperties(MeshPhongMaterial.prototype, {
  36421. metal: {
  36422. get: function get() {
  36423. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  36424. return false;
  36425. },
  36426. set: function set() {
  36427. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  36428. }
  36429. }
  36430. });
  36431. Object.defineProperties(MeshPhysicalMaterial.prototype, {
  36432. transparency: {
  36433. get: function get() {
  36434. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  36435. return this.transmission;
  36436. },
  36437. set: function set(value) {
  36438. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  36439. this.transmission = value;
  36440. }
  36441. }
  36442. });
  36443. Object.defineProperties(ShaderMaterial.prototype, {
  36444. derivatives: {
  36445. get: function get() {
  36446. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  36447. return this.extensions.derivatives;
  36448. },
  36449. set: function set(value) {
  36450. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  36451. this.extensions.derivatives = value;
  36452. }
  36453. }
  36454. }); //
  36455. Object.assign(WebGLRenderer.prototype, {
  36456. clearTarget: function clearTarget(renderTarget, color, depth, stencil) {
  36457. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  36458. this.setRenderTarget(renderTarget);
  36459. this.clear(color, depth, stencil);
  36460. },
  36461. animate: function animate(callback) {
  36462. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  36463. this.setAnimationLoop(callback);
  36464. },
  36465. getCurrentRenderTarget: function getCurrentRenderTarget() {
  36466. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  36467. return this.getRenderTarget();
  36468. },
  36469. getMaxAnisotropy: function getMaxAnisotropy() {
  36470. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  36471. return this.capabilities.getMaxAnisotropy();
  36472. },
  36473. getPrecision: function getPrecision() {
  36474. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  36475. return this.capabilities.precision;
  36476. },
  36477. resetGLState: function resetGLState() {
  36478. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  36479. return this.state.reset();
  36480. },
  36481. supportsFloatTextures: function supportsFloatTextures() {
  36482. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  36483. return this.extensions.get('OES_texture_float');
  36484. },
  36485. supportsHalfFloatTextures: function supportsHalfFloatTextures() {
  36486. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  36487. return this.extensions.get('OES_texture_half_float');
  36488. },
  36489. supportsStandardDerivatives: function supportsStandardDerivatives() {
  36490. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  36491. return this.extensions.get('OES_standard_derivatives');
  36492. },
  36493. supportsCompressedTextureS3TC: function supportsCompressedTextureS3TC() {
  36494. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  36495. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  36496. },
  36497. supportsCompressedTexturePVRTC: function supportsCompressedTexturePVRTC() {
  36498. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  36499. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  36500. },
  36501. supportsBlendMinMax: function supportsBlendMinMax() {
  36502. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  36503. return this.extensions.get('EXT_blend_minmax');
  36504. },
  36505. supportsVertexTextures: function supportsVertexTextures() {
  36506. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  36507. return this.capabilities.vertexTextures;
  36508. },
  36509. supportsInstancedArrays: function supportsInstancedArrays() {
  36510. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  36511. return this.extensions.get('ANGLE_instanced_arrays');
  36512. },
  36513. enableScissorTest: function enableScissorTest(boolean) {
  36514. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  36515. this.setScissorTest(boolean);
  36516. },
  36517. initMaterial: function initMaterial() {
  36518. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  36519. },
  36520. addPrePlugin: function addPrePlugin() {
  36521. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  36522. },
  36523. addPostPlugin: function addPostPlugin() {
  36524. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  36525. },
  36526. updateShadowMap: function updateShadowMap() {
  36527. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  36528. },
  36529. setFaceCulling: function setFaceCulling() {
  36530. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  36531. },
  36532. allocTextureUnit: function allocTextureUnit() {
  36533. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  36534. },
  36535. setTexture: function setTexture() {
  36536. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  36537. },
  36538. setTextureCube: function setTextureCube() {
  36539. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  36540. },
  36541. getActiveMipMapLevel: function getActiveMipMapLevel() {
  36542. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  36543. return this.getActiveMipmapLevel();
  36544. }
  36545. });
  36546. Object.defineProperties(WebGLRenderer.prototype, {
  36547. shadowMapEnabled: {
  36548. get: function get() {
  36549. return this.shadowMap.enabled;
  36550. },
  36551. set: function set(value) {
  36552. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  36553. this.shadowMap.enabled = value;
  36554. }
  36555. },
  36556. shadowMapType: {
  36557. get: function get() {
  36558. return this.shadowMap.type;
  36559. },
  36560. set: function set(value) {
  36561. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  36562. this.shadowMap.type = value;
  36563. }
  36564. },
  36565. shadowMapCullFace: {
  36566. get: function get() {
  36567. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  36568. return undefined;
  36569. },
  36570. set: function set()
  36571. /* value */
  36572. {
  36573. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  36574. }
  36575. },
  36576. context: {
  36577. get: function get() {
  36578. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  36579. return this.getContext();
  36580. }
  36581. },
  36582. vr: {
  36583. get: function get() {
  36584. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  36585. return this.xr;
  36586. }
  36587. },
  36588. gammaInput: {
  36589. get: function get() {
  36590. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  36591. return false;
  36592. },
  36593. set: function set() {
  36594. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  36595. }
  36596. },
  36597. gammaOutput: {
  36598. get: function get() {
  36599. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  36600. return false;
  36601. },
  36602. set: function set(value) {
  36603. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  36604. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  36605. }
  36606. },
  36607. toneMappingWhitePoint: {
  36608. get: function get() {
  36609. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  36610. return 1.0;
  36611. },
  36612. set: function set() {
  36613. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  36614. }
  36615. }
  36616. });
  36617. Object.defineProperties(WebGLShadowMap.prototype, {
  36618. cullFace: {
  36619. get: function get() {
  36620. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  36621. return undefined;
  36622. },
  36623. set: function set()
  36624. /* cullFace */
  36625. {
  36626. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  36627. }
  36628. },
  36629. renderReverseSided: {
  36630. get: function get() {
  36631. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  36632. return undefined;
  36633. },
  36634. set: function set() {
  36635. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  36636. }
  36637. },
  36638. renderSingleSided: {
  36639. get: function get() {
  36640. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  36641. return undefined;
  36642. },
  36643. set: function set() {
  36644. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  36645. }
  36646. }
  36647. });
  36648. function WebGLRenderTargetCube(width, height, options) {
  36649. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  36650. return new WebGLCubeRenderTarget(width, options);
  36651. } //
  36652. Object.defineProperties(WebGLRenderTarget.prototype, {
  36653. wrapS: {
  36654. get: function get() {
  36655. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  36656. return this.texture.wrapS;
  36657. },
  36658. set: function set(value) {
  36659. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  36660. this.texture.wrapS = value;
  36661. }
  36662. },
  36663. wrapT: {
  36664. get: function get() {
  36665. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  36666. return this.texture.wrapT;
  36667. },
  36668. set: function set(value) {
  36669. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  36670. this.texture.wrapT = value;
  36671. }
  36672. },
  36673. magFilter: {
  36674. get: function get() {
  36675. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  36676. return this.texture.magFilter;
  36677. },
  36678. set: function set(value) {
  36679. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  36680. this.texture.magFilter = value;
  36681. }
  36682. },
  36683. minFilter: {
  36684. get: function get() {
  36685. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  36686. return this.texture.minFilter;
  36687. },
  36688. set: function set(value) {
  36689. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  36690. this.texture.minFilter = value;
  36691. }
  36692. },
  36693. anisotropy: {
  36694. get: function get() {
  36695. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  36696. return this.texture.anisotropy;
  36697. },
  36698. set: function set(value) {
  36699. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  36700. this.texture.anisotropy = value;
  36701. }
  36702. },
  36703. offset: {
  36704. get: function get() {
  36705. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  36706. return this.texture.offset;
  36707. },
  36708. set: function set(value) {
  36709. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  36710. this.texture.offset = value;
  36711. }
  36712. },
  36713. repeat: {
  36714. get: function get() {
  36715. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  36716. return this.texture.repeat;
  36717. },
  36718. set: function set(value) {
  36719. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  36720. this.texture.repeat = value;
  36721. }
  36722. },
  36723. format: {
  36724. get: function get() {
  36725. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  36726. return this.texture.format;
  36727. },
  36728. set: function set(value) {
  36729. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  36730. this.texture.format = value;
  36731. }
  36732. },
  36733. type: {
  36734. get: function get() {
  36735. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  36736. return this.texture.type;
  36737. },
  36738. set: function set(value) {
  36739. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  36740. this.texture.type = value;
  36741. }
  36742. },
  36743. generateMipmaps: {
  36744. get: function get() {
  36745. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  36746. return this.texture.generateMipmaps;
  36747. },
  36748. set: function set(value) {
  36749. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  36750. this.texture.generateMipmaps = value;
  36751. }
  36752. }
  36753. }); //
  36754. Object.defineProperties(Audio.prototype, {
  36755. load: {
  36756. value: function value(file) {
  36757. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  36758. var scope = this;
  36759. var audioLoader = new AudioLoader();
  36760. audioLoader.load(file, function (buffer) {
  36761. scope.setBuffer(buffer);
  36762. });
  36763. return this;
  36764. }
  36765. },
  36766. startTime: {
  36767. set: function set() {
  36768. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  36769. }
  36770. }
  36771. });
  36772. AudioAnalyser.prototype.getData = function () {
  36773. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  36774. return this.getFrequencyData();
  36775. }; //
  36776. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  36777. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  36778. return this.update(renderer, scene);
  36779. };
  36780. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  36781. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  36782. return this.renderTarget.clear(renderer, color, depth, stencil);
  36783. }; //
  36784. var GeometryUtils = {
  36785. merge: function merge(geometry1, geometry2, materialIndexOffset) {
  36786. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  36787. var matrix;
  36788. if (geometry2.isMesh) {
  36789. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  36790. matrix = geometry2.matrix;
  36791. geometry2 = geometry2.geometry;
  36792. }
  36793. geometry1.merge(geometry2, matrix, materialIndexOffset);
  36794. },
  36795. center: function center(geometry) {
  36796. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  36797. return geometry.center();
  36798. }
  36799. };
  36800. ImageUtils.crossOrigin = undefined;
  36801. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  36802. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  36803. var loader = new TextureLoader();
  36804. loader.setCrossOrigin(this.crossOrigin);
  36805. var texture = loader.load(url, onLoad, undefined, onError);
  36806. if (mapping) texture.mapping = mapping;
  36807. return texture;
  36808. };
  36809. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  36810. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  36811. var loader = new CubeTextureLoader();
  36812. loader.setCrossOrigin(this.crossOrigin);
  36813. var texture = loader.load(urls, onLoad, undefined, onError);
  36814. if (mapping) texture.mapping = mapping;
  36815. return texture;
  36816. };
  36817. ImageUtils.loadCompressedTexture = function () {
  36818. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  36819. };
  36820. ImageUtils.loadCompressedTextureCube = function () {
  36821. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  36822. }; //
  36823. function CanvasRenderer() {
  36824. console.error('THREE.CanvasRenderer has been removed');
  36825. } //
  36826. function JSONLoader() {
  36827. console.error('THREE.JSONLoader has been removed.');
  36828. } //
  36829. var SceneUtils = {
  36830. createMultiMaterialObject: function createMultiMaterialObject()
  36831. /* geometry, materials */
  36832. {
  36833. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36834. },
  36835. detach: function detach()
  36836. /* child, parent, scene */
  36837. {
  36838. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36839. },
  36840. attach: function attach()
  36841. /* child, scene, parent */
  36842. {
  36843. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36844. }
  36845. }; //
  36846. function LensFlare() {
  36847. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  36848. }
  36849. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  36850. /* eslint-disable no-undef */
  36851. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  36852. detail: {
  36853. revision: REVISION
  36854. }
  36855. }));
  36856. /* eslint-enable no-undef */
  36857. }
  36858. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  36859. exports.AddEquation = AddEquation;
  36860. exports.AddOperation = AddOperation;
  36861. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  36862. exports.AdditiveBlending = AdditiveBlending;
  36863. exports.AlphaFormat = AlphaFormat;
  36864. exports.AlwaysDepth = AlwaysDepth;
  36865. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  36866. exports.AmbientLight = AmbientLight;
  36867. exports.AmbientLightProbe = AmbientLightProbe;
  36868. exports.AnimationClip = AnimationClip;
  36869. exports.AnimationLoader = AnimationLoader;
  36870. exports.AnimationMixer = AnimationMixer;
  36871. exports.AnimationObjectGroup = AnimationObjectGroup;
  36872. exports.AnimationUtils = AnimationUtils;
  36873. exports.ArcCurve = ArcCurve;
  36874. exports.ArrayCamera = ArrayCamera;
  36875. exports.ArrowHelper = ArrowHelper;
  36876. exports.Audio = Audio;
  36877. exports.AudioAnalyser = AudioAnalyser;
  36878. exports.AudioContext = AudioContext;
  36879. exports.AudioListener = AudioListener;
  36880. exports.AudioLoader = AudioLoader;
  36881. exports.AxesHelper = AxesHelper;
  36882. exports.AxisHelper = AxisHelper;
  36883. exports.BackSide = BackSide;
  36884. exports.BasicDepthPacking = BasicDepthPacking;
  36885. exports.BasicShadowMap = BasicShadowMap;
  36886. exports.BinaryTextureLoader = BinaryTextureLoader;
  36887. exports.Bone = Bone;
  36888. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  36889. exports.BoundingBoxHelper = BoundingBoxHelper;
  36890. exports.Box2 = Box2;
  36891. exports.Box3 = Box3;
  36892. exports.Box3Helper = Box3Helper;
  36893. exports.BoxBufferGeometry = BoxBufferGeometry;
  36894. exports.BoxGeometry = BoxGeometry;
  36895. exports.BoxHelper = BoxHelper;
  36896. exports.BufferAttribute = BufferAttribute;
  36897. exports.BufferGeometry = BufferGeometry;
  36898. exports.BufferGeometryLoader = BufferGeometryLoader;
  36899. exports.ByteType = ByteType;
  36900. exports.Cache = Cache;
  36901. exports.Camera = Camera;
  36902. exports.CameraHelper = CameraHelper;
  36903. exports.CanvasRenderer = CanvasRenderer;
  36904. exports.CanvasTexture = CanvasTexture;
  36905. exports.CatmullRomCurve3 = CatmullRomCurve3;
  36906. exports.CineonToneMapping = CineonToneMapping;
  36907. exports.CircleBufferGeometry = CircleBufferGeometry;
  36908. exports.CircleGeometry = CircleGeometry;
  36909. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  36910. exports.Clock = Clock;
  36911. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  36912. exports.Color = Color;
  36913. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  36914. exports.CompressedTexture = CompressedTexture;
  36915. exports.CompressedTextureLoader = CompressedTextureLoader;
  36916. exports.ConeBufferGeometry = ConeBufferGeometry;
  36917. exports.ConeGeometry = ConeGeometry;
  36918. exports.CubeCamera = CubeCamera;
  36919. exports.CubeGeometry = BoxGeometry;
  36920. exports.CubeReflectionMapping = CubeReflectionMapping;
  36921. exports.CubeRefractionMapping = CubeRefractionMapping;
  36922. exports.CubeTexture = CubeTexture;
  36923. exports.CubeTextureLoader = CubeTextureLoader;
  36924. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  36925. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  36926. exports.CubicBezierCurve = CubicBezierCurve;
  36927. exports.CubicBezierCurve3 = CubicBezierCurve3;
  36928. exports.CubicInterpolant = CubicInterpolant;
  36929. exports.CullFaceBack = CullFaceBack;
  36930. exports.CullFaceFront = CullFaceFront;
  36931. exports.CullFaceFrontBack = CullFaceFrontBack;
  36932. exports.CullFaceNone = CullFaceNone;
  36933. exports.Curve = Curve;
  36934. exports.CurvePath = CurvePath;
  36935. exports.CustomBlending = CustomBlending;
  36936. exports.CustomToneMapping = CustomToneMapping;
  36937. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  36938. exports.CylinderGeometry = CylinderGeometry;
  36939. exports.Cylindrical = Cylindrical;
  36940. exports.DataTexture = DataTexture;
  36941. exports.DataTexture2DArray = DataTexture2DArray;
  36942. exports.DataTexture3D = DataTexture3D;
  36943. exports.DataTextureLoader = DataTextureLoader;
  36944. exports.DataUtils = DataUtils;
  36945. exports.DecrementStencilOp = DecrementStencilOp;
  36946. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  36947. exports.DefaultLoadingManager = DefaultLoadingManager;
  36948. exports.DepthFormat = DepthFormat;
  36949. exports.DepthStencilFormat = DepthStencilFormat;
  36950. exports.DepthTexture = DepthTexture;
  36951. exports.DirectionalLight = DirectionalLight;
  36952. exports.DirectionalLightHelper = DirectionalLightHelper;
  36953. exports.DiscreteInterpolant = DiscreteInterpolant;
  36954. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  36955. exports.DodecahedronGeometry = DodecahedronGeometry;
  36956. exports.DoubleSide = DoubleSide;
  36957. exports.DstAlphaFactor = DstAlphaFactor;
  36958. exports.DstColorFactor = DstColorFactor;
  36959. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  36960. exports.DynamicCopyUsage = DynamicCopyUsage;
  36961. exports.DynamicDrawUsage = DynamicDrawUsage;
  36962. exports.DynamicReadUsage = DynamicReadUsage;
  36963. exports.EdgesGeometry = EdgesGeometry;
  36964. exports.EdgesHelper = EdgesHelper;
  36965. exports.EllipseCurve = EllipseCurve;
  36966. exports.EqualDepth = EqualDepth;
  36967. exports.EqualStencilFunc = EqualStencilFunc;
  36968. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  36969. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  36970. exports.Euler = Euler;
  36971. exports.EventDispatcher = EventDispatcher;
  36972. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  36973. exports.ExtrudeGeometry = ExtrudeGeometry;
  36974. exports.Face3 = Face3;
  36975. exports.Face4 = Face4;
  36976. exports.FaceColors = FaceColors;
  36977. exports.FileLoader = FileLoader;
  36978. exports.FlatShading = FlatShading;
  36979. exports.Float16BufferAttribute = Float16BufferAttribute;
  36980. exports.Float32Attribute = Float32Attribute;
  36981. exports.Float32BufferAttribute = Float32BufferAttribute;
  36982. exports.Float64Attribute = Float64Attribute;
  36983. exports.Float64BufferAttribute = Float64BufferAttribute;
  36984. exports.FloatType = FloatType;
  36985. exports.Fog = Fog;
  36986. exports.FogExp2 = FogExp2;
  36987. exports.Font = Font;
  36988. exports.FontLoader = FontLoader;
  36989. exports.FrontSide = FrontSide;
  36990. exports.Frustum = Frustum;
  36991. exports.GLBufferAttribute = GLBufferAttribute;
  36992. exports.GLSL1 = GLSL1;
  36993. exports.GLSL3 = GLSL3;
  36994. exports.GammaEncoding = GammaEncoding;
  36995. exports.Geometry = Geometry;
  36996. exports.GeometryUtils = GeometryUtils;
  36997. exports.GreaterDepth = GreaterDepth;
  36998. exports.GreaterEqualDepth = GreaterEqualDepth;
  36999. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  37000. exports.GreaterStencilFunc = GreaterStencilFunc;
  37001. exports.GridHelper = GridHelper;
  37002. exports.Group = Group;
  37003. exports.HalfFloatType = HalfFloatType;
  37004. exports.HemisphereLight = HemisphereLight;
  37005. exports.HemisphereLightHelper = HemisphereLightHelper;
  37006. exports.HemisphereLightProbe = HemisphereLightProbe;
  37007. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  37008. exports.IcosahedronGeometry = IcosahedronGeometry;
  37009. exports.ImageBitmapLoader = ImageBitmapLoader;
  37010. exports.ImageLoader = ImageLoader;
  37011. exports.ImageUtils = ImageUtils;
  37012. exports.ImmediateRenderObject = ImmediateRenderObject;
  37013. exports.IncrementStencilOp = IncrementStencilOp;
  37014. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  37015. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  37016. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  37017. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  37018. exports.InstancedMesh = InstancedMesh;
  37019. exports.Int16Attribute = Int16Attribute;
  37020. exports.Int16BufferAttribute = Int16BufferAttribute;
  37021. exports.Int32Attribute = Int32Attribute;
  37022. exports.Int32BufferAttribute = Int32BufferAttribute;
  37023. exports.Int8Attribute = Int8Attribute;
  37024. exports.Int8BufferAttribute = Int8BufferAttribute;
  37025. exports.IntType = IntType;
  37026. exports.InterleavedBuffer = InterleavedBuffer;
  37027. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  37028. exports.Interpolant = Interpolant;
  37029. exports.InterpolateDiscrete = InterpolateDiscrete;
  37030. exports.InterpolateLinear = InterpolateLinear;
  37031. exports.InterpolateSmooth = InterpolateSmooth;
  37032. exports.InvertStencilOp = InvertStencilOp;
  37033. exports.JSONLoader = JSONLoader;
  37034. exports.KeepStencilOp = KeepStencilOp;
  37035. exports.KeyframeTrack = KeyframeTrack;
  37036. exports.LOD = LOD;
  37037. exports.LatheBufferGeometry = LatheBufferGeometry;
  37038. exports.LatheGeometry = LatheGeometry;
  37039. exports.Layers = Layers;
  37040. exports.LensFlare = LensFlare;
  37041. exports.LessDepth = LessDepth;
  37042. exports.LessEqualDepth = LessEqualDepth;
  37043. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  37044. exports.LessStencilFunc = LessStencilFunc;
  37045. exports.Light = Light;
  37046. exports.LightProbe = LightProbe;
  37047. exports.Line = Line;
  37048. exports.Line3 = Line3;
  37049. exports.LineBasicMaterial = LineBasicMaterial;
  37050. exports.LineCurve = LineCurve;
  37051. exports.LineCurve3 = LineCurve3;
  37052. exports.LineDashedMaterial = LineDashedMaterial;
  37053. exports.LineLoop = LineLoop;
  37054. exports.LinePieces = LinePieces;
  37055. exports.LineSegments = LineSegments;
  37056. exports.LineStrip = LineStrip;
  37057. exports.LinearEncoding = LinearEncoding;
  37058. exports.LinearFilter = LinearFilter;
  37059. exports.LinearInterpolant = LinearInterpolant;
  37060. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  37061. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  37062. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  37063. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  37064. exports.LinearToneMapping = LinearToneMapping;
  37065. exports.Loader = Loader;
  37066. exports.LoaderUtils = LoaderUtils;
  37067. exports.LoadingManager = LoadingManager;
  37068. exports.LogLuvEncoding = LogLuvEncoding;
  37069. exports.LoopOnce = LoopOnce;
  37070. exports.LoopPingPong = LoopPingPong;
  37071. exports.LoopRepeat = LoopRepeat;
  37072. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  37073. exports.LuminanceFormat = LuminanceFormat;
  37074. exports.MOUSE = MOUSE;
  37075. exports.Material = Material;
  37076. exports.MaterialLoader = MaterialLoader;
  37077. exports.Math = MathUtils;
  37078. exports.MathUtils = MathUtils;
  37079. exports.Matrix3 = Matrix3;
  37080. exports.Matrix4 = Matrix4;
  37081. exports.MaxEquation = MaxEquation;
  37082. exports.Mesh = Mesh;
  37083. exports.MeshBasicMaterial = MeshBasicMaterial;
  37084. exports.MeshDepthMaterial = MeshDepthMaterial;
  37085. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  37086. exports.MeshFaceMaterial = MeshFaceMaterial;
  37087. exports.MeshLambertMaterial = MeshLambertMaterial;
  37088. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  37089. exports.MeshNormalMaterial = MeshNormalMaterial;
  37090. exports.MeshPhongMaterial = MeshPhongMaterial;
  37091. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  37092. exports.MeshStandardMaterial = MeshStandardMaterial;
  37093. exports.MeshToonMaterial = MeshToonMaterial;
  37094. exports.MinEquation = MinEquation;
  37095. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  37096. exports.MixOperation = MixOperation;
  37097. exports.MultiMaterial = MultiMaterial;
  37098. exports.MultiplyBlending = MultiplyBlending;
  37099. exports.MultiplyOperation = MultiplyOperation;
  37100. exports.NearestFilter = NearestFilter;
  37101. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  37102. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  37103. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  37104. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  37105. exports.NeverDepth = NeverDepth;
  37106. exports.NeverStencilFunc = NeverStencilFunc;
  37107. exports.NoBlending = NoBlending;
  37108. exports.NoColors = NoColors;
  37109. exports.NoToneMapping = NoToneMapping;
  37110. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  37111. exports.NormalBlending = NormalBlending;
  37112. exports.NotEqualDepth = NotEqualDepth;
  37113. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  37114. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  37115. exports.Object3D = Object3D;
  37116. exports.ObjectLoader = ObjectLoader;
  37117. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  37118. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  37119. exports.OctahedronGeometry = OctahedronGeometry;
  37120. exports.OneFactor = OneFactor;
  37121. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  37122. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  37123. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  37124. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  37125. exports.OrthographicCamera = OrthographicCamera;
  37126. exports.PCFShadowMap = PCFShadowMap;
  37127. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  37128. exports.PMREMGenerator = PMREMGenerator;
  37129. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  37130. exports.ParametricGeometry = ParametricGeometry;
  37131. exports.Particle = Particle;
  37132. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  37133. exports.ParticleSystem = ParticleSystem;
  37134. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  37135. exports.Path = Path;
  37136. exports.PerspectiveCamera = PerspectiveCamera;
  37137. exports.Plane = Plane;
  37138. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  37139. exports.PlaneGeometry = PlaneGeometry;
  37140. exports.PlaneHelper = PlaneHelper;
  37141. exports.PointCloud = PointCloud;
  37142. exports.PointCloudMaterial = PointCloudMaterial;
  37143. exports.PointLight = PointLight;
  37144. exports.PointLightHelper = PointLightHelper;
  37145. exports.Points = Points;
  37146. exports.PointsMaterial = PointsMaterial;
  37147. exports.PolarGridHelper = PolarGridHelper;
  37148. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  37149. exports.PolyhedronGeometry = PolyhedronGeometry;
  37150. exports.PositionalAudio = PositionalAudio;
  37151. exports.PropertyBinding = PropertyBinding;
  37152. exports.PropertyMixer = PropertyMixer;
  37153. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  37154. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  37155. exports.Quaternion = Quaternion;
  37156. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  37157. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  37158. exports.REVISION = REVISION;
  37159. exports.RGBADepthPacking = RGBADepthPacking;
  37160. exports.RGBAFormat = RGBAFormat;
  37161. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  37162. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  37163. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  37164. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  37165. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  37166. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  37167. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  37168. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  37169. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  37170. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  37171. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  37172. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  37173. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  37174. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  37175. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  37176. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  37177. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  37178. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  37179. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  37180. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  37181. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  37182. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  37183. exports.RGBDEncoding = RGBDEncoding;
  37184. exports.RGBEEncoding = RGBEEncoding;
  37185. exports.RGBEFormat = RGBEFormat;
  37186. exports.RGBFormat = RGBFormat;
  37187. exports.RGBIntegerFormat = RGBIntegerFormat;
  37188. exports.RGBM16Encoding = RGBM16Encoding;
  37189. exports.RGBM7Encoding = RGBM7Encoding;
  37190. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  37191. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  37192. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  37193. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  37194. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  37195. exports.RGFormat = RGFormat;
  37196. exports.RGIntegerFormat = RGIntegerFormat;
  37197. exports.RawShaderMaterial = RawShaderMaterial;
  37198. exports.Ray = Ray;
  37199. exports.Raycaster = Raycaster;
  37200. exports.RectAreaLight = RectAreaLight;
  37201. exports.RedFormat = RedFormat;
  37202. exports.RedIntegerFormat = RedIntegerFormat;
  37203. exports.ReinhardToneMapping = ReinhardToneMapping;
  37204. exports.RepeatWrapping = RepeatWrapping;
  37205. exports.ReplaceStencilOp = ReplaceStencilOp;
  37206. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  37207. exports.RingBufferGeometry = RingBufferGeometry;
  37208. exports.RingGeometry = RingGeometry;
  37209. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  37210. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  37211. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  37212. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  37213. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  37214. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  37215. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  37216. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  37217. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  37218. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  37219. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  37220. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  37221. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  37222. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  37223. exports.Scene = Scene;
  37224. exports.SceneUtils = SceneUtils;
  37225. exports.ShaderChunk = ShaderChunk;
  37226. exports.ShaderLib = ShaderLib;
  37227. exports.ShaderMaterial = ShaderMaterial;
  37228. exports.ShadowMaterial = ShadowMaterial;
  37229. exports.Shape = Shape;
  37230. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  37231. exports.ShapeGeometry = ShapeGeometry;
  37232. exports.ShapePath = ShapePath;
  37233. exports.ShapeUtils = ShapeUtils;
  37234. exports.ShortType = ShortType;
  37235. exports.Skeleton = Skeleton;
  37236. exports.SkeletonHelper = SkeletonHelper;
  37237. exports.SkinnedMesh = SkinnedMesh;
  37238. exports.SmoothShading = SmoothShading;
  37239. exports.Sphere = Sphere;
  37240. exports.SphereBufferGeometry = SphereBufferGeometry;
  37241. exports.SphereGeometry = SphereGeometry;
  37242. exports.Spherical = Spherical;
  37243. exports.SphericalHarmonics3 = SphericalHarmonics3;
  37244. exports.Spline = Spline;
  37245. exports.SplineCurve = SplineCurve;
  37246. exports.SplineCurve3 = SplineCurve3;
  37247. exports.SpotLight = SpotLight;
  37248. exports.SpotLightHelper = SpotLightHelper;
  37249. exports.Sprite = Sprite;
  37250. exports.SpriteMaterial = SpriteMaterial;
  37251. exports.SrcAlphaFactor = SrcAlphaFactor;
  37252. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  37253. exports.SrcColorFactor = SrcColorFactor;
  37254. exports.StaticCopyUsage = StaticCopyUsage;
  37255. exports.StaticDrawUsage = StaticDrawUsage;
  37256. exports.StaticReadUsage = StaticReadUsage;
  37257. exports.StereoCamera = StereoCamera;
  37258. exports.StreamCopyUsage = StreamCopyUsage;
  37259. exports.StreamDrawUsage = StreamDrawUsage;
  37260. exports.StreamReadUsage = StreamReadUsage;
  37261. exports.StringKeyframeTrack = StringKeyframeTrack;
  37262. exports.SubtractEquation = SubtractEquation;
  37263. exports.SubtractiveBlending = SubtractiveBlending;
  37264. exports.TOUCH = TOUCH;
  37265. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  37266. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  37267. exports.TetrahedronGeometry = TetrahedronGeometry;
  37268. exports.TextBufferGeometry = TextBufferGeometry;
  37269. exports.TextGeometry = TextGeometry;
  37270. exports.Texture = Texture;
  37271. exports.TextureLoader = TextureLoader;
  37272. exports.TorusBufferGeometry = TorusBufferGeometry;
  37273. exports.TorusGeometry = TorusGeometry;
  37274. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  37275. exports.TorusKnotGeometry = TorusKnotGeometry;
  37276. exports.Triangle = Triangle;
  37277. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  37278. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  37279. exports.TrianglesDrawMode = TrianglesDrawMode;
  37280. exports.TubeBufferGeometry = TubeBufferGeometry;
  37281. exports.TubeGeometry = TubeGeometry;
  37282. exports.UVMapping = UVMapping;
  37283. exports.Uint16Attribute = Uint16Attribute;
  37284. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  37285. exports.Uint32Attribute = Uint32Attribute;
  37286. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  37287. exports.Uint8Attribute = Uint8Attribute;
  37288. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  37289. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  37290. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  37291. exports.Uniform = Uniform;
  37292. exports.UniformsLib = UniformsLib;
  37293. exports.UniformsUtils = UniformsUtils;
  37294. exports.UnsignedByteType = UnsignedByteType;
  37295. exports.UnsignedInt248Type = UnsignedInt248Type;
  37296. exports.UnsignedIntType = UnsignedIntType;
  37297. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  37298. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  37299. exports.UnsignedShort565Type = UnsignedShort565Type;
  37300. exports.UnsignedShortType = UnsignedShortType;
  37301. exports.VSMShadowMap = VSMShadowMap;
  37302. exports.Vector2 = Vector2;
  37303. exports.Vector3 = Vector3;
  37304. exports.Vector4 = Vector4;
  37305. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  37306. exports.Vertex = Vertex;
  37307. exports.VertexColors = VertexColors;
  37308. exports.VideoTexture = VideoTexture;
  37309. exports.WebGL1Renderer = WebGL1Renderer;
  37310. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  37311. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  37312. exports.WebGLRenderTarget = WebGLRenderTarget;
  37313. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  37314. exports.WebGLRenderer = WebGLRenderer;
  37315. exports.WebGLUtils = WebGLUtils;
  37316. exports.WireframeGeometry = WireframeGeometry;
  37317. exports.WireframeHelper = WireframeHelper;
  37318. exports.WrapAroundEnding = WrapAroundEnding;
  37319. exports.XHRLoader = XHRLoader;
  37320. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  37321. exports.ZeroFactor = ZeroFactor;
  37322. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  37323. exports.ZeroStencilOp = ZeroStencilOp;
  37324. exports.sRGBEncoding = sRGBEncoding;
  37325. Object.defineProperty(exports, '__esModule', { value: true });
  37326. })));
  37327. },{}],58:[function(_dereq_,module,exports){
  37328. THREE.DRACOLoader = function ( manager ) {
  37329. THREE.Loader.call( this, manager );
  37330. this.decoderPath = '';
  37331. this.decoderConfig = {};
  37332. this.decoderBinary = null;
  37333. this.decoderPending = null;
  37334. this.workerLimit = 4;
  37335. this.workerPool = [];
  37336. this.workerNextTaskID = 1;
  37337. this.workerSourceURL = '';
  37338. this.defaultAttributeIDs = {
  37339. position: 'POSITION',
  37340. normal: 'NORMAL',
  37341. color: 'COLOR',
  37342. uv: 'TEX_COORD'
  37343. };
  37344. this.defaultAttributeTypes = {
  37345. position: 'Float32Array',
  37346. normal: 'Float32Array',
  37347. color: 'Float32Array',
  37348. uv: 'Float32Array'
  37349. };
  37350. };
  37351. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  37352. constructor: THREE.DRACOLoader,
  37353. setDecoderPath: function ( path ) {
  37354. this.decoderPath = path;
  37355. return this;
  37356. },
  37357. setDecoderConfig: function ( config ) {
  37358. this.decoderConfig = config;
  37359. return this;
  37360. },
  37361. setWorkerLimit: function ( workerLimit ) {
  37362. this.workerLimit = workerLimit;
  37363. return this;
  37364. },
  37365. /** @deprecated */
  37366. setVerbosity: function () {
  37367. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  37368. },
  37369. /** @deprecated */
  37370. setDrawMode: function () {
  37371. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  37372. },
  37373. /** @deprecated */
  37374. setSkipDequantization: function () {
  37375. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  37376. },
  37377. load: function ( url, onLoad, onProgress, onError ) {
  37378. var loader = new THREE.FileLoader( this.manager );
  37379. loader.setPath( this.path );
  37380. loader.setResponseType( 'arraybuffer' );
  37381. loader.setRequestHeader( this.requestHeader );
  37382. loader.setWithCredentials( this.withCredentials );
  37383. loader.load( url, ( buffer ) => {
  37384. var taskConfig = {
  37385. attributeIDs: this.defaultAttributeIDs,
  37386. attributeTypes: this.defaultAttributeTypes,
  37387. useUniqueIDs: false
  37388. };
  37389. this.decodeGeometry( buffer, taskConfig )
  37390. .then( onLoad )
  37391. .catch( onError );
  37392. }, onProgress, onError );
  37393. },
  37394. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  37395. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  37396. var taskConfig = {
  37397. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  37398. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  37399. useUniqueIDs: !! attributeIDs
  37400. };
  37401. this.decodeGeometry( buffer, taskConfig ).then( callback );
  37402. },
  37403. decodeGeometry: function ( buffer, taskConfig ) {
  37404. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  37405. // references (rather than names) to typed array constructors. These must be
  37406. // serialized before sending them to the worker.
  37407. for ( var attribute in taskConfig.attributeTypes ) {
  37408. var type = taskConfig.attributeTypes[ attribute ];
  37409. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  37410. taskConfig.attributeTypes[ attribute ] = type.name;
  37411. }
  37412. }
  37413. //
  37414. var taskKey = JSON.stringify( taskConfig );
  37415. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  37416. // again from this thread.
  37417. if ( THREE.DRACOLoader.taskCache.has( buffer ) ) {
  37418. var cachedTask = THREE.DRACOLoader.taskCache.get( buffer );
  37419. if ( cachedTask.key === taskKey ) {
  37420. return cachedTask.promise;
  37421. } else if ( buffer.byteLength === 0 ) {
  37422. // Technically, it would be possible to wait for the previous task to complete,
  37423. // transfer the buffer back, and decode again with the second configuration. That
  37424. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  37425. // different ways, so this is left unimplemented.
  37426. throw new Error(
  37427. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  37428. 'settings. Buffer has already been transferred.'
  37429. );
  37430. }
  37431. }
  37432. //
  37433. var worker;
  37434. var taskID = this.workerNextTaskID ++;
  37435. var taskCost = buffer.byteLength;
  37436. // Obtain a worker and assign a task, and construct a geometry instance
  37437. // when the task completes.
  37438. var geometryPending = this._getWorker( taskID, taskCost )
  37439. .then( ( _worker ) => {
  37440. worker = _worker;
  37441. return new Promise( ( resolve, reject ) => {
  37442. worker._callbacks[ taskID ] = { resolve, reject };
  37443. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  37444. // this.debug();
  37445. } );
  37446. } )
  37447. .then( ( message ) => this._createGeometry( message.geometry ) );
  37448. // Remove task from the task list.
  37449. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  37450. geometryPending
  37451. .catch( () => true )
  37452. .then( () => {
  37453. if ( worker && taskID ) {
  37454. this._releaseTask( worker, taskID );
  37455. // this.debug();
  37456. }
  37457. } );
  37458. // Cache the task result.
  37459. THREE.DRACOLoader.taskCache.set( buffer, {
  37460. key: taskKey,
  37461. promise: geometryPending
  37462. } );
  37463. return geometryPending;
  37464. },
  37465. _createGeometry: function ( geometryData ) {
  37466. var geometry = new THREE.BufferGeometry();
  37467. if ( geometryData.index ) {
  37468. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  37469. }
  37470. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  37471. var attribute = geometryData.attributes[ i ];
  37472. var name = attribute.name;
  37473. var array = attribute.array;
  37474. var itemSize = attribute.itemSize;
  37475. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  37476. }
  37477. return geometry;
  37478. },
  37479. _loadLibrary: function ( url, responseType ) {
  37480. var loader = new THREE.FileLoader( this.manager );
  37481. loader.setPath( this.decoderPath );
  37482. loader.setResponseType( responseType );
  37483. loader.setWithCredentials( this.withCredentials );
  37484. return new Promise( ( resolve, reject ) => {
  37485. loader.load( url, resolve, undefined, reject );
  37486. } );
  37487. },
  37488. preload: function () {
  37489. this._initDecoder();
  37490. return this;
  37491. },
  37492. _initDecoder: function () {
  37493. if ( this.decoderPending ) return this.decoderPending;
  37494. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  37495. var librariesPending = [];
  37496. if ( useJS ) {
  37497. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  37498. } else {
  37499. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  37500. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  37501. }
  37502. this.decoderPending = Promise.all( librariesPending )
  37503. .then( ( libraries ) => {
  37504. var jsContent = libraries[ 0 ];
  37505. if ( ! useJS ) {
  37506. this.decoderConfig.wasmBinary = libraries[ 1 ];
  37507. }
  37508. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  37509. var body = [
  37510. '/* draco decoder */',
  37511. jsContent,
  37512. '',
  37513. '/* worker */',
  37514. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  37515. ].join( '\n' );
  37516. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  37517. } );
  37518. return this.decoderPending;
  37519. },
  37520. _getWorker: function ( taskID, taskCost ) {
  37521. return this._initDecoder().then( () => {
  37522. if ( this.workerPool.length < this.workerLimit ) {
  37523. var worker = new Worker( this.workerSourceURL );
  37524. worker._callbacks = {};
  37525. worker._taskCosts = {};
  37526. worker._taskLoad = 0;
  37527. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  37528. worker.onmessage = function ( e ) {
  37529. var message = e.data;
  37530. switch ( message.type ) {
  37531. case 'decode':
  37532. worker._callbacks[ message.id ].resolve( message );
  37533. break;
  37534. case 'error':
  37535. worker._callbacks[ message.id ].reject( message );
  37536. break;
  37537. default:
  37538. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  37539. }
  37540. };
  37541. this.workerPool.push( worker );
  37542. } else {
  37543. this.workerPool.sort( function ( a, b ) {
  37544. return a._taskLoad > b._taskLoad ? - 1 : 1;
  37545. } );
  37546. }
  37547. var worker = this.workerPool[ this.workerPool.length - 1 ];
  37548. worker._taskCosts[ taskID ] = taskCost;
  37549. worker._taskLoad += taskCost;
  37550. return worker;
  37551. } );
  37552. },
  37553. _releaseTask: function ( worker, taskID ) {
  37554. worker._taskLoad -= worker._taskCosts[ taskID ];
  37555. delete worker._callbacks[ taskID ];
  37556. delete worker._taskCosts[ taskID ];
  37557. },
  37558. debug: function () {
  37559. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  37560. },
  37561. dispose: function () {
  37562. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  37563. this.workerPool[ i ].terminate();
  37564. }
  37565. this.workerPool.length = 0;
  37566. return this;
  37567. }
  37568. } );
  37569. /* WEB WORKER */
  37570. THREE.DRACOLoader.DRACOWorker = function () {
  37571. var decoderConfig;
  37572. var decoderPending;
  37573. onmessage = function ( e ) {
  37574. var message = e.data;
  37575. switch ( message.type ) {
  37576. case 'init':
  37577. decoderConfig = message.decoderConfig;
  37578. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  37579. decoderConfig.onModuleLoaded = function ( draco ) {
  37580. // Module is Promise-like. Wrap before resolving to avoid loop.
  37581. resolve( { draco: draco } );
  37582. };
  37583. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  37584. } );
  37585. break;
  37586. case 'decode':
  37587. var buffer = message.buffer;
  37588. var taskConfig = message.taskConfig;
  37589. decoderPending.then( ( module ) => {
  37590. var draco = module.draco;
  37591. var decoder = new draco.Decoder();
  37592. var decoderBuffer = new draco.DecoderBuffer();
  37593. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  37594. try {
  37595. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  37596. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  37597. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  37598. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  37599. } catch ( error ) {
  37600. console.error( error );
  37601. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  37602. } finally {
  37603. draco.destroy( decoderBuffer );
  37604. draco.destroy( decoder );
  37605. }
  37606. } );
  37607. break;
  37608. }
  37609. };
  37610. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  37611. var attributeIDs = taskConfig.attributeIDs;
  37612. var attributeTypes = taskConfig.attributeTypes;
  37613. var dracoGeometry;
  37614. var decodingStatus;
  37615. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  37616. if ( geometryType === draco.TRIANGULAR_MESH ) {
  37617. dracoGeometry = new draco.Mesh();
  37618. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  37619. } else if ( geometryType === draco.POINT_CLOUD ) {
  37620. dracoGeometry = new draco.PointCloud();
  37621. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  37622. } else {
  37623. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  37624. }
  37625. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  37626. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  37627. }
  37628. var geometry = { index: null, attributes: [] };
  37629. // Gather all vertex attributes.
  37630. for ( var attributeName in attributeIDs ) {
  37631. var attributeType = self[ attributeTypes[ attributeName ] ];
  37632. var attribute;
  37633. var attributeID;
  37634. // A Draco file may be created with default vertex attributes, whose attribute IDs
  37635. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  37636. // a Draco file may contain a custom set of attributes, identified by known unique
  37637. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  37638. if ( taskConfig.useUniqueIDs ) {
  37639. attributeID = attributeIDs[ attributeName ];
  37640. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  37641. } else {
  37642. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  37643. if ( attributeID === - 1 ) continue;
  37644. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  37645. }
  37646. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  37647. }
  37648. // Add index.
  37649. if ( geometryType === draco.TRIANGULAR_MESH ) {
  37650. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  37651. }
  37652. draco.destroy( dracoGeometry );
  37653. return geometry;
  37654. }
  37655. function decodeIndex( draco, decoder, dracoGeometry ) {
  37656. var numFaces = dracoGeometry.num_faces();
  37657. var numIndices = numFaces * 3;
  37658. var byteLength = numIndices * 4;
  37659. var ptr = draco._malloc( byteLength );
  37660. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  37661. var index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  37662. draco._free( ptr );
  37663. return { array: index, itemSize: 1 };
  37664. }
  37665. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  37666. var numComponents = attribute.num_components();
  37667. var numPoints = dracoGeometry.num_points();
  37668. var numValues = numPoints * numComponents;
  37669. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  37670. var dataType = getDracoDataType( draco, attributeType );
  37671. var ptr = draco._malloc( byteLength );
  37672. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  37673. var array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  37674. draco._free( ptr );
  37675. return {
  37676. name: attributeName,
  37677. array: array,
  37678. itemSize: numComponents
  37679. };
  37680. }
  37681. function getDracoDataType( draco, attributeType ) {
  37682. switch ( attributeType ) {
  37683. case Float32Array: return draco.DT_FLOAT32;
  37684. case Int8Array: return draco.DT_INT8;
  37685. case Int16Array: return draco.DT_INT16;
  37686. case Int32Array: return draco.DT_INT32;
  37687. case Uint8Array: return draco.DT_UINT8;
  37688. case Uint16Array: return draco.DT_UINT16;
  37689. case Uint32Array: return draco.DT_UINT32;
  37690. }
  37691. }
  37692. };
  37693. THREE.DRACOLoader.taskCache = new WeakMap();
  37694. /** Deprecated static methods */
  37695. /** @deprecated */
  37696. THREE.DRACOLoader.setDecoderPath = function () {
  37697. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  37698. };
  37699. /** @deprecated */
  37700. THREE.DRACOLoader.setDecoderConfig = function () {
  37701. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  37702. };
  37703. /** @deprecated */
  37704. THREE.DRACOLoader.releaseDecoderModule = function () {
  37705. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  37706. };
  37707. /** @deprecated */
  37708. THREE.DRACOLoader.getDecoderModule = function () {
  37709. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  37710. };
  37711. },{}],59:[function(_dereq_,module,exports){
  37712. THREE.GLTFLoader = ( function () {
  37713. function GLTFLoader( manager ) {
  37714. THREE.Loader.call( this, manager );
  37715. this.dracoLoader = null;
  37716. this.ddsLoader = null;
  37717. this.ktx2Loader = null;
  37718. this.meshoptDecoder = null;
  37719. this.pluginCallbacks = [];
  37720. this.register( function ( parser ) {
  37721. return new GLTFMaterialsClearcoatExtension( parser );
  37722. } );
  37723. this.register( function ( parser ) {
  37724. return new GLTFTextureBasisUExtension( parser );
  37725. } );
  37726. this.register( function ( parser ) {
  37727. return new GLTFTextureWebPExtension( parser );
  37728. } );
  37729. this.register( function ( parser ) {
  37730. return new GLTFMaterialsTransmissionExtension( parser );
  37731. } );
  37732. this.register( function ( parser ) {
  37733. return new GLTFLightsExtension( parser );
  37734. } );
  37735. this.register( function ( parser ) {
  37736. return new GLTFMeshoptCompression( parser );
  37737. } );
  37738. }
  37739. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  37740. constructor: GLTFLoader,
  37741. load: function ( url, onLoad, onProgress, onError ) {
  37742. var scope = this;
  37743. var resourcePath;
  37744. if ( this.resourcePath !== '' ) {
  37745. resourcePath = this.resourcePath;
  37746. } else if ( this.path !== '' ) {
  37747. resourcePath = this.path;
  37748. } else {
  37749. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  37750. }
  37751. // Tells the LoadingManager to track an extra item, which resolves after
  37752. // the model is fully loaded. This means the count of items loaded will
  37753. // be incorrect, but ensures manager.onLoad() does not fire early.
  37754. this.manager.itemStart( url );
  37755. var _onError = function ( e ) {
  37756. if ( onError ) {
  37757. onError( e );
  37758. } else {
  37759. console.error( e );
  37760. }
  37761. scope.manager.itemError( url );
  37762. scope.manager.itemEnd( url );
  37763. };
  37764. var loader = new THREE.FileLoader( this.manager );
  37765. loader.setPath( this.path );
  37766. loader.setResponseType( 'arraybuffer' );
  37767. loader.setRequestHeader( this.requestHeader );
  37768. loader.setWithCredentials( this.withCredentials );
  37769. loader.load( url, function ( data ) {
  37770. try {
  37771. scope.parse( data, resourcePath, function ( gltf ) {
  37772. onLoad( gltf );
  37773. scope.manager.itemEnd( url );
  37774. }, _onError );
  37775. } catch ( e ) {
  37776. _onError( e );
  37777. }
  37778. }, onProgress, _onError );
  37779. },
  37780. setDRACOLoader: function ( dracoLoader ) {
  37781. this.dracoLoader = dracoLoader;
  37782. return this;
  37783. },
  37784. setDDSLoader: function ( ddsLoader ) {
  37785. this.ddsLoader = ddsLoader;
  37786. return this;
  37787. },
  37788. setKTX2Loader: function ( ktx2Loader ) {
  37789. this.ktx2Loader = ktx2Loader;
  37790. return this;
  37791. },
  37792. setMeshoptDecoder: function ( meshoptDecoder ) {
  37793. this.meshoptDecoder = meshoptDecoder;
  37794. return this;
  37795. },
  37796. register: function ( callback ) {
  37797. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  37798. this.pluginCallbacks.push( callback );
  37799. }
  37800. return this;
  37801. },
  37802. unregister: function ( callback ) {
  37803. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  37804. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  37805. }
  37806. return this;
  37807. },
  37808. parse: function ( data, path, onLoad, onError ) {
  37809. var content;
  37810. var extensions = {};
  37811. var plugins = {};
  37812. if ( typeof data === 'string' ) {
  37813. content = data;
  37814. } else {
  37815. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  37816. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  37817. try {
  37818. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  37819. } catch ( error ) {
  37820. if ( onError ) onError( error );
  37821. return;
  37822. }
  37823. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  37824. } else {
  37825. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  37826. }
  37827. }
  37828. var json = JSON.parse( content );
  37829. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  37830. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  37831. return;
  37832. }
  37833. var parser = new GLTFParser( json, {
  37834. path: path || this.resourcePath || '',
  37835. crossOrigin: this.crossOrigin,
  37836. manager: this.manager,
  37837. ktx2Loader: this.ktx2Loader,
  37838. meshoptDecoder: this.meshoptDecoder
  37839. } );
  37840. parser.fileLoader.setRequestHeader( this.requestHeader );
  37841. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  37842. var plugin = this.pluginCallbacks[ i ]( parser );
  37843. plugins[ plugin.name ] = plugin;
  37844. // Workaround to avoid determining as unknown extension
  37845. // in addUnknownExtensionsToUserData().
  37846. // Remove this workaround if we move all the existing
  37847. // extension handlers to plugin system
  37848. extensions[ plugin.name ] = true;
  37849. }
  37850. if ( json.extensionsUsed ) {
  37851. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  37852. var extensionName = json.extensionsUsed[ i ];
  37853. var extensionsRequired = json.extensionsRequired || [];
  37854. switch ( extensionName ) {
  37855. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  37856. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  37857. break;
  37858. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  37859. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  37860. break;
  37861. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  37862. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  37863. break;
  37864. case EXTENSIONS.MSFT_TEXTURE_DDS:
  37865. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  37866. break;
  37867. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  37868. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  37869. break;
  37870. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  37871. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  37872. break;
  37873. default:
  37874. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  37875. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  37876. }
  37877. }
  37878. }
  37879. }
  37880. parser.setExtensions( extensions );
  37881. parser.setPlugins( plugins );
  37882. parser.parse( onLoad, onError );
  37883. }
  37884. } );
  37885. /* GLTFREGISTRY */
  37886. function GLTFRegistry() {
  37887. var objects = {};
  37888. return {
  37889. get: function ( key ) {
  37890. return objects[ key ];
  37891. },
  37892. add: function ( key, object ) {
  37893. objects[ key ] = object;
  37894. },
  37895. remove: function ( key ) {
  37896. delete objects[ key ];
  37897. },
  37898. removeAll: function () {
  37899. objects = {};
  37900. }
  37901. };
  37902. }
  37903. /*********************************/
  37904. /********** EXTENSIONS ***********/
  37905. /*********************************/
  37906. var EXTENSIONS = {
  37907. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  37908. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  37909. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  37910. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  37911. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  37912. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  37913. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  37914. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  37915. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  37916. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  37917. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  37918. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  37919. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  37920. };
  37921. /**
  37922. * DDS Texture Extension
  37923. *
  37924. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  37925. *
  37926. */
  37927. function GLTFTextureDDSExtension( ddsLoader ) {
  37928. if ( ! ddsLoader ) {
  37929. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  37930. }
  37931. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  37932. this.ddsLoader = ddsLoader;
  37933. }
  37934. /**
  37935. * Punctual Lights Extension
  37936. *
  37937. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  37938. */
  37939. function GLTFLightsExtension( parser ) {
  37940. this.parser = parser;
  37941. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  37942. // Object3D instance caches
  37943. this.cache = { refs: {}, uses: {} };
  37944. }
  37945. GLTFLightsExtension.prototype._markDefs = function () {
  37946. var parser = this.parser;
  37947. var nodeDefs = this.parser.json.nodes || [];
  37948. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  37949. var nodeDef = nodeDefs[ nodeIndex ];
  37950. if ( nodeDef.extensions
  37951. && nodeDef.extensions[ this.name ]
  37952. && nodeDef.extensions[ this.name ].light !== undefined ) {
  37953. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  37954. }
  37955. }
  37956. };
  37957. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  37958. var parser = this.parser;
  37959. var cacheKey = 'light:' + lightIndex;
  37960. var dependency = parser.cache.get( cacheKey );
  37961. if ( dependency ) return dependency;
  37962. var json = parser.json;
  37963. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  37964. var lightDefs = extensions.lights || [];
  37965. var lightDef = lightDefs[ lightIndex ];
  37966. var lightNode;
  37967. var color = new THREE.Color( 0xffffff );
  37968. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  37969. var range = lightDef.range !== undefined ? lightDef.range : 0;
  37970. switch ( lightDef.type ) {
  37971. case 'directional':
  37972. lightNode = new THREE.DirectionalLight( color );
  37973. lightNode.target.position.set( 0, 0, - 1 );
  37974. lightNode.add( lightNode.target );
  37975. break;
  37976. case 'point':
  37977. lightNode = new THREE.PointLight( color );
  37978. lightNode.distance = range;
  37979. break;
  37980. case 'spot':
  37981. lightNode = new THREE.SpotLight( color );
  37982. lightNode.distance = range;
  37983. // Handle spotlight properties.
  37984. lightDef.spot = lightDef.spot || {};
  37985. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  37986. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  37987. lightNode.angle = lightDef.spot.outerConeAngle;
  37988. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  37989. lightNode.target.position.set( 0, 0, - 1 );
  37990. lightNode.add( lightNode.target );
  37991. break;
  37992. default:
  37993. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  37994. }
  37995. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  37996. // here, because node-level parsing will only override position if explicitly specified.
  37997. lightNode.position.set( 0, 0, 0 );
  37998. lightNode.decay = 2;
  37999. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  38000. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  38001. dependency = Promise.resolve( lightNode );
  38002. parser.cache.add( cacheKey, dependency );
  38003. return dependency;
  38004. };
  38005. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  38006. var self = this;
  38007. var parser = this.parser;
  38008. var json = parser.json;
  38009. var nodeDef = json.nodes[ nodeIndex ];
  38010. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  38011. var lightIndex = lightDef.light;
  38012. if ( lightIndex === undefined ) return null;
  38013. return this._loadLight( lightIndex ).then( function ( light ) {
  38014. return parser._getNodeRef( self.cache, lightIndex, light );
  38015. } );
  38016. };
  38017. /**
  38018. * Unlit Materials Extension
  38019. *
  38020. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  38021. */
  38022. function GLTFMaterialsUnlitExtension() {
  38023. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  38024. }
  38025. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  38026. return THREE.MeshBasicMaterial;
  38027. };
  38028. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  38029. var pending = [];
  38030. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  38031. materialParams.opacity = 1.0;
  38032. var metallicRoughness = materialDef.pbrMetallicRoughness;
  38033. if ( metallicRoughness ) {
  38034. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  38035. var array = metallicRoughness.baseColorFactor;
  38036. materialParams.color.fromArray( array );
  38037. materialParams.opacity = array[ 3 ];
  38038. }
  38039. if ( metallicRoughness.baseColorTexture !== undefined ) {
  38040. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  38041. }
  38042. }
  38043. return Promise.all( pending );
  38044. };
  38045. /**
  38046. * Clearcoat Materials Extension
  38047. *
  38048. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  38049. */
  38050. function GLTFMaterialsClearcoatExtension( parser ) {
  38051. this.parser = parser;
  38052. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  38053. }
  38054. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  38055. var parser = this.parser;
  38056. var materialDef = parser.json.materials[ materialIndex ];
  38057. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  38058. return THREE.MeshPhysicalMaterial;
  38059. };
  38060. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  38061. var parser = this.parser;
  38062. var materialDef = parser.json.materials[ materialIndex ];
  38063. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  38064. return Promise.resolve();
  38065. }
  38066. var pending = [];
  38067. var extension = materialDef.extensions[ this.name ];
  38068. if ( extension.clearcoatFactor !== undefined ) {
  38069. materialParams.clearcoat = extension.clearcoatFactor;
  38070. }
  38071. if ( extension.clearcoatTexture !== undefined ) {
  38072. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  38073. }
  38074. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  38075. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  38076. }
  38077. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  38078. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  38079. }
  38080. if ( extension.clearcoatNormalTexture !== undefined ) {
  38081. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  38082. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  38083. var scale = extension.clearcoatNormalTexture.scale;
  38084. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  38085. }
  38086. }
  38087. return Promise.all( pending );
  38088. };
  38089. /**
  38090. * Transmission Materials Extension
  38091. *
  38092. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  38093. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  38094. */
  38095. function GLTFMaterialsTransmissionExtension( parser ) {
  38096. this.parser = parser;
  38097. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  38098. }
  38099. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  38100. var parser = this.parser;
  38101. var materialDef = parser.json.materials[ materialIndex ];
  38102. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  38103. return THREE.MeshPhysicalMaterial;
  38104. };
  38105. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  38106. var parser = this.parser;
  38107. var materialDef = parser.json.materials[ materialIndex ];
  38108. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  38109. return Promise.resolve();
  38110. }
  38111. var pending = [];
  38112. var extension = materialDef.extensions[ this.name ];
  38113. if ( extension.transmissionFactor !== undefined ) {
  38114. materialParams.transmission = extension.transmissionFactor;
  38115. }
  38116. if ( extension.transmissionTexture !== undefined ) {
  38117. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  38118. }
  38119. return Promise.all( pending );
  38120. };
  38121. /**
  38122. * BasisU Texture Extension
  38123. *
  38124. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  38125. */
  38126. function GLTFTextureBasisUExtension( parser ) {
  38127. this.parser = parser;
  38128. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  38129. }
  38130. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  38131. var parser = this.parser;
  38132. var json = parser.json;
  38133. var textureDef = json.textures[ textureIndex ];
  38134. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  38135. return null;
  38136. }
  38137. var extension = textureDef.extensions[ this.name ];
  38138. var source = json.images[ extension.source ];
  38139. var loader = parser.options.ktx2Loader;
  38140. if ( ! loader ) {
  38141. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  38142. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  38143. } else {
  38144. // Assumes that the extension is optional and that a fallback texture is present
  38145. return null;
  38146. }
  38147. }
  38148. return parser.loadTextureImage( textureIndex, source, loader );
  38149. };
  38150. /**
  38151. * WebP Texture Extension
  38152. *
  38153. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  38154. */
  38155. function GLTFTextureWebPExtension( parser ) {
  38156. this.parser = parser;
  38157. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  38158. this.isSupported = null;
  38159. }
  38160. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  38161. var name = this.name;
  38162. var parser = this.parser;
  38163. var json = parser.json;
  38164. var textureDef = json.textures[ textureIndex ];
  38165. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  38166. return null;
  38167. }
  38168. var extension = textureDef.extensions[ name ];
  38169. var source = json.images[ extension.source ];
  38170. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  38171. return this.detectSupport().then( function ( isSupported ) {
  38172. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  38173. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  38174. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  38175. }
  38176. // Fall back to PNG or JPEG.
  38177. return parser.loadTexture( textureIndex );
  38178. } );
  38179. };
  38180. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  38181. if ( ! this.isSupported ) {
  38182. this.isSupported = new Promise( function ( resolve ) {
  38183. var image = new Image();
  38184. // Lossy test image. Support for lossy images doesn't guarantee support for all
  38185. // WebP images, unfortunately.
  38186. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  38187. image.onload = image.onerror = function () {
  38188. resolve( image.height === 1 );
  38189. };
  38190. } );
  38191. }
  38192. return this.isSupported;
  38193. };
  38194. /**
  38195. * meshopt BufferView Compression Extension
  38196. *
  38197. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  38198. */
  38199. function GLTFMeshoptCompression( parser ) {
  38200. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  38201. this.parser = parser;
  38202. }
  38203. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  38204. var json = this.parser.json;
  38205. var bufferView = json.bufferViews[ index ];
  38206. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  38207. var extensionDef = bufferView.extensions[ this.name ];
  38208. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  38209. var decoder = this.parser.options.meshoptDecoder;
  38210. if ( ! decoder || ! decoder.supported ) {
  38211. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  38212. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  38213. } else {
  38214. // Assumes that the extension is optional and that fallback buffer data is present
  38215. return null;
  38216. }
  38217. }
  38218. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  38219. var byteOffset = extensionDef.byteOffset || 0;
  38220. var byteLength = extensionDef.byteLength || 0;
  38221. var count = extensionDef.count;
  38222. var stride = extensionDef.byteStride;
  38223. var result = new ArrayBuffer( count * stride );
  38224. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  38225. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  38226. return result;
  38227. } );
  38228. } else {
  38229. return null;
  38230. }
  38231. };
  38232. /* BINARY EXTENSION */
  38233. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  38234. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  38235. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  38236. function GLTFBinaryExtension( data ) {
  38237. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  38238. this.content = null;
  38239. this.body = null;
  38240. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  38241. this.header = {
  38242. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  38243. version: headerView.getUint32( 4, true ),
  38244. length: headerView.getUint32( 8, true )
  38245. };
  38246. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  38247. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  38248. } else if ( this.header.version < 2.0 ) {
  38249. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  38250. }
  38251. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  38252. var chunkIndex = 0;
  38253. while ( chunkIndex < chunkView.byteLength ) {
  38254. var chunkLength = chunkView.getUint32( chunkIndex, true );
  38255. chunkIndex += 4;
  38256. var chunkType = chunkView.getUint32( chunkIndex, true );
  38257. chunkIndex += 4;
  38258. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  38259. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  38260. this.content = THREE.LoaderUtils.decodeText( contentArray );
  38261. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  38262. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  38263. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  38264. }
  38265. // Clients must ignore chunks with unknown types.
  38266. chunkIndex += chunkLength;
  38267. }
  38268. if ( this.content === null ) {
  38269. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  38270. }
  38271. }
  38272. /**
  38273. * DRACO Mesh Compression Extension
  38274. *
  38275. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  38276. */
  38277. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  38278. if ( ! dracoLoader ) {
  38279. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  38280. }
  38281. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  38282. this.json = json;
  38283. this.dracoLoader = dracoLoader;
  38284. this.dracoLoader.preload();
  38285. }
  38286. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  38287. var json = this.json;
  38288. var dracoLoader = this.dracoLoader;
  38289. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  38290. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  38291. var threeAttributeMap = {};
  38292. var attributeNormalizedMap = {};
  38293. var attributeTypeMap = {};
  38294. for ( var attributeName in gltfAttributeMap ) {
  38295. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  38296. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  38297. }
  38298. for ( attributeName in primitive.attributes ) {
  38299. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  38300. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  38301. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  38302. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  38303. attributeTypeMap[ threeAttributeName ] = componentType;
  38304. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  38305. }
  38306. }
  38307. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  38308. return new Promise( function ( resolve ) {
  38309. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  38310. for ( var attributeName in geometry.attributes ) {
  38311. var attribute = geometry.attributes[ attributeName ];
  38312. var normalized = attributeNormalizedMap[ attributeName ];
  38313. if ( normalized !== undefined ) attribute.normalized = normalized;
  38314. }
  38315. resolve( geometry );
  38316. }, threeAttributeMap, attributeTypeMap );
  38317. } );
  38318. } );
  38319. };
  38320. /**
  38321. * Texture Transform Extension
  38322. *
  38323. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  38324. */
  38325. function GLTFTextureTransformExtension() {
  38326. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  38327. }
  38328. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  38329. texture = texture.clone();
  38330. if ( transform.offset !== undefined ) {
  38331. texture.offset.fromArray( transform.offset );
  38332. }
  38333. if ( transform.rotation !== undefined ) {
  38334. texture.rotation = transform.rotation;
  38335. }
  38336. if ( transform.scale !== undefined ) {
  38337. texture.repeat.fromArray( transform.scale );
  38338. }
  38339. if ( transform.texCoord !== undefined ) {
  38340. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  38341. }
  38342. texture.needsUpdate = true;
  38343. return texture;
  38344. };
  38345. /**
  38346. * Specular-Glossiness Extension
  38347. *
  38348. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  38349. */
  38350. /**
  38351. * A sub class of THREE.StandardMaterial with some of the functionality
  38352. * changed via the `onBeforeCompile` callback
  38353. * @pailhead
  38354. */
  38355. function GLTFMeshStandardSGMaterial( params ) {
  38356. THREE.MeshStandardMaterial.call( this );
  38357. this.isGLTFSpecularGlossinessMaterial = true;
  38358. //various chunks that need replacing
  38359. var specularMapParsFragmentChunk = [
  38360. '#ifdef USE_SPECULARMAP',
  38361. ' uniform sampler2D specularMap;',
  38362. '#endif'
  38363. ].join( '\n' );
  38364. var glossinessMapParsFragmentChunk = [
  38365. '#ifdef USE_GLOSSINESSMAP',
  38366. ' uniform sampler2D glossinessMap;',
  38367. '#endif'
  38368. ].join( '\n' );
  38369. var specularMapFragmentChunk = [
  38370. 'vec3 specularFactor = specular;',
  38371. '#ifdef USE_SPECULARMAP',
  38372. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  38373. ' texelSpecular = sRGBToLinear( texelSpecular );',
  38374. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  38375. ' specularFactor *= texelSpecular.rgb;',
  38376. '#endif'
  38377. ].join( '\n' );
  38378. var glossinessMapFragmentChunk = [
  38379. 'float glossinessFactor = glossiness;',
  38380. '#ifdef USE_GLOSSINESSMAP',
  38381. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  38382. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  38383. ' glossinessFactor *= texelGlossiness.a;',
  38384. '#endif'
  38385. ].join( '\n' );
  38386. var lightPhysicalFragmentChunk = [
  38387. 'PhysicalMaterial material;',
  38388. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  38389. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  38390. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  38391. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  38392. 'material.specularRoughness += geometryRoughness;',
  38393. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  38394. 'material.specularColor = specularFactor;',
  38395. ].join( '\n' );
  38396. var uniforms = {
  38397. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  38398. glossiness: { value: 1 },
  38399. specularMap: { value: null },
  38400. glossinessMap: { value: null }
  38401. };
  38402. this._extraUniforms = uniforms;
  38403. this.onBeforeCompile = function ( shader ) {
  38404. for ( var uniformName in uniforms ) {
  38405. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  38406. }
  38407. shader.fragmentShader = shader.fragmentShader
  38408. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  38409. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  38410. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  38411. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  38412. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  38413. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  38414. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  38415. };
  38416. Object.defineProperties( this, {
  38417. specular: {
  38418. get: function () {
  38419. return uniforms.specular.value;
  38420. },
  38421. set: function ( v ) {
  38422. uniforms.specular.value = v;
  38423. }
  38424. },
  38425. specularMap: {
  38426. get: function () {
  38427. return uniforms.specularMap.value;
  38428. },
  38429. set: function ( v ) {
  38430. uniforms.specularMap.value = v;
  38431. if ( v ) {
  38432. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  38433. } else {
  38434. delete this.defines.USE_SPECULARMAP;
  38435. }
  38436. }
  38437. },
  38438. glossiness: {
  38439. get: function () {
  38440. return uniforms.glossiness.value;
  38441. },
  38442. set: function ( v ) {
  38443. uniforms.glossiness.value = v;
  38444. }
  38445. },
  38446. glossinessMap: {
  38447. get: function () {
  38448. return uniforms.glossinessMap.value;
  38449. },
  38450. set: function ( v ) {
  38451. uniforms.glossinessMap.value = v;
  38452. if ( v ) {
  38453. this.defines.USE_GLOSSINESSMAP = '';
  38454. this.defines.USE_UV = '';
  38455. } else {
  38456. delete this.defines.USE_GLOSSINESSMAP;
  38457. delete this.defines.USE_UV;
  38458. }
  38459. }
  38460. }
  38461. } );
  38462. delete this.metalness;
  38463. delete this.roughness;
  38464. delete this.metalnessMap;
  38465. delete this.roughnessMap;
  38466. this.setValues( params );
  38467. }
  38468. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  38469. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  38470. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  38471. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  38472. this.specularMap = source.specularMap;
  38473. this.specular.copy( source.specular );
  38474. this.glossinessMap = source.glossinessMap;
  38475. this.glossiness = source.glossiness;
  38476. delete this.metalness;
  38477. delete this.roughness;
  38478. delete this.metalnessMap;
  38479. delete this.roughnessMap;
  38480. return this;
  38481. };
  38482. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  38483. return {
  38484. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  38485. specularGlossinessParams: [
  38486. 'color',
  38487. 'map',
  38488. 'lightMap',
  38489. 'lightMapIntensity',
  38490. 'aoMap',
  38491. 'aoMapIntensity',
  38492. 'emissive',
  38493. 'emissiveIntensity',
  38494. 'emissiveMap',
  38495. 'bumpMap',
  38496. 'bumpScale',
  38497. 'normalMap',
  38498. 'normalMapType',
  38499. 'displacementMap',
  38500. 'displacementScale',
  38501. 'displacementBias',
  38502. 'specularMap',
  38503. 'specular',
  38504. 'glossinessMap',
  38505. 'glossiness',
  38506. 'alphaMap',
  38507. 'envMap',
  38508. 'envMapIntensity',
  38509. 'refractionRatio',
  38510. ],
  38511. getMaterialType: function () {
  38512. return GLTFMeshStandardSGMaterial;
  38513. },
  38514. extendParams: function ( materialParams, materialDef, parser ) {
  38515. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  38516. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  38517. materialParams.opacity = 1.0;
  38518. var pending = [];
  38519. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  38520. var array = pbrSpecularGlossiness.diffuseFactor;
  38521. materialParams.color.fromArray( array );
  38522. materialParams.opacity = array[ 3 ];
  38523. }
  38524. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  38525. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  38526. }
  38527. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  38528. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  38529. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  38530. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  38531. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  38532. }
  38533. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  38534. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  38535. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  38536. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  38537. }
  38538. return Promise.all( pending );
  38539. },
  38540. createMaterial: function ( materialParams ) {
  38541. var material = new GLTFMeshStandardSGMaterial( materialParams );
  38542. material.fog = true;
  38543. material.color = materialParams.color;
  38544. material.map = materialParams.map === undefined ? null : materialParams.map;
  38545. material.lightMap = null;
  38546. material.lightMapIntensity = 1.0;
  38547. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  38548. material.aoMapIntensity = 1.0;
  38549. material.emissive = materialParams.emissive;
  38550. material.emissiveIntensity = 1.0;
  38551. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  38552. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  38553. material.bumpScale = 1;
  38554. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  38555. material.normalMapType = THREE.TangentSpaceNormalMap;
  38556. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  38557. material.displacementMap = null;
  38558. material.displacementScale = 1;
  38559. material.displacementBias = 0;
  38560. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  38561. material.specular = materialParams.specular;
  38562. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  38563. material.glossiness = materialParams.glossiness;
  38564. material.alphaMap = null;
  38565. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  38566. material.envMapIntensity = 1.0;
  38567. material.refractionRatio = 0.98;
  38568. return material;
  38569. },
  38570. };
  38571. }
  38572. /**
  38573. * Mesh Quantization Extension
  38574. *
  38575. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  38576. */
  38577. function GLTFMeshQuantizationExtension() {
  38578. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  38579. }
  38580. /*********************************/
  38581. /********** INTERPOLATION ********/
  38582. /*********************************/
  38583. // Spline Interpolation
  38584. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  38585. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  38586. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  38587. }
  38588. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  38589. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  38590. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  38591. // Copies a sample value to the result buffer. See description of glTF
  38592. // CUBICSPLINE values layout in interpolate_() function below.
  38593. var result = this.resultBuffer,
  38594. values = this.sampleValues,
  38595. valueSize = this.valueSize,
  38596. offset = index * valueSize * 3 + valueSize;
  38597. for ( var i = 0; i !== valueSize; i ++ ) {
  38598. result[ i ] = values[ offset + i ];
  38599. }
  38600. return result;
  38601. };
  38602. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  38603. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  38604. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  38605. var result = this.resultBuffer;
  38606. var values = this.sampleValues;
  38607. var stride = this.valueSize;
  38608. var stride2 = stride * 2;
  38609. var stride3 = stride * 3;
  38610. var td = t1 - t0;
  38611. var p = ( t - t0 ) / td;
  38612. var pp = p * p;
  38613. var ppp = pp * p;
  38614. var offset1 = i1 * stride3;
  38615. var offset0 = offset1 - stride3;
  38616. var s2 = - 2 * ppp + 3 * pp;
  38617. var s3 = ppp - pp;
  38618. var s0 = 1 - s2;
  38619. var s1 = s3 - pp + p;
  38620. // Layout of keyframe output values for CUBICSPLINE animations:
  38621. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  38622. for ( var i = 0; i !== stride; i ++ ) {
  38623. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  38624. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  38625. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  38626. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  38627. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  38628. }
  38629. return result;
  38630. };
  38631. /*********************************/
  38632. /********** INTERNALS ************/
  38633. /*********************************/
  38634. /* CONSTANTS */
  38635. var WEBGL_CONSTANTS = {
  38636. FLOAT: 5126,
  38637. //FLOAT_MAT2: 35674,
  38638. FLOAT_MAT3: 35675,
  38639. FLOAT_MAT4: 35676,
  38640. FLOAT_VEC2: 35664,
  38641. FLOAT_VEC3: 35665,
  38642. FLOAT_VEC4: 35666,
  38643. LINEAR: 9729,
  38644. REPEAT: 10497,
  38645. SAMPLER_2D: 35678,
  38646. POINTS: 0,
  38647. LINES: 1,
  38648. LINE_LOOP: 2,
  38649. LINE_STRIP: 3,
  38650. TRIANGLES: 4,
  38651. TRIANGLE_STRIP: 5,
  38652. TRIANGLE_FAN: 6,
  38653. UNSIGNED_BYTE: 5121,
  38654. UNSIGNED_SHORT: 5123
  38655. };
  38656. var WEBGL_COMPONENT_TYPES = {
  38657. 5120: Int8Array,
  38658. 5121: Uint8Array,
  38659. 5122: Int16Array,
  38660. 5123: Uint16Array,
  38661. 5125: Uint32Array,
  38662. 5126: Float32Array
  38663. };
  38664. var WEBGL_FILTERS = {
  38665. 9728: THREE.NearestFilter,
  38666. 9729: THREE.LinearFilter,
  38667. 9984: THREE.NearestMipmapNearestFilter,
  38668. 9985: THREE.LinearMipmapNearestFilter,
  38669. 9986: THREE.NearestMipmapLinearFilter,
  38670. 9987: THREE.LinearMipmapLinearFilter
  38671. };
  38672. var WEBGL_WRAPPINGS = {
  38673. 33071: THREE.ClampToEdgeWrapping,
  38674. 33648: THREE.MirroredRepeatWrapping,
  38675. 10497: THREE.RepeatWrapping
  38676. };
  38677. var WEBGL_TYPE_SIZES = {
  38678. 'SCALAR': 1,
  38679. 'VEC2': 2,
  38680. 'VEC3': 3,
  38681. 'VEC4': 4,
  38682. 'MAT2': 4,
  38683. 'MAT3': 9,
  38684. 'MAT4': 16
  38685. };
  38686. var ATTRIBUTES = {
  38687. POSITION: 'position',
  38688. NORMAL: 'normal',
  38689. TANGENT: 'tangent',
  38690. TEXCOORD_0: 'uv',
  38691. TEXCOORD_1: 'uv2',
  38692. COLOR_0: 'color',
  38693. WEIGHTS_0: 'skinWeight',
  38694. JOINTS_0: 'skinIndex',
  38695. };
  38696. var PATH_PROPERTIES = {
  38697. scale: 'scale',
  38698. translation: 'position',
  38699. rotation: 'quaternion',
  38700. weights: 'morphTargetInfluences'
  38701. };
  38702. var INTERPOLATION = {
  38703. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  38704. // keyframe track will be initialized with a default interpolation type, then modified.
  38705. LINEAR: THREE.InterpolateLinear,
  38706. STEP: THREE.InterpolateDiscrete
  38707. };
  38708. var ALPHA_MODES = {
  38709. OPAQUE: 'OPAQUE',
  38710. MASK: 'MASK',
  38711. BLEND: 'BLEND'
  38712. };
  38713. /* UTILITY FUNCTIONS */
  38714. function resolveURL( url, path ) {
  38715. // Invalid URL
  38716. if ( typeof url !== 'string' || url === '' ) return '';
  38717. // Host Relative URL
  38718. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  38719. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  38720. }
  38721. // Absolute URL http://,https://,//
  38722. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  38723. // Data URI
  38724. if ( /^data:.*,.*$/i.test( url ) ) return url;
  38725. // Blob URL
  38726. if ( /^blob:.*$/i.test( url ) ) return url;
  38727. // Relative URL
  38728. return path + url;
  38729. }
  38730. /**
  38731. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  38732. */
  38733. function createDefaultMaterial( cache ) {
  38734. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  38735. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  38736. color: 0xFFFFFF,
  38737. emissive: 0x000000,
  38738. metalness: 1,
  38739. roughness: 1,
  38740. transparent: false,
  38741. depthTest: true,
  38742. side: THREE.FrontSide
  38743. } );
  38744. }
  38745. return cache[ 'DefaultMaterial' ];
  38746. }
  38747. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  38748. // Add unknown glTF extensions to an object's userData.
  38749. for ( var name in objectDef.extensions ) {
  38750. if ( knownExtensions[ name ] === undefined ) {
  38751. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  38752. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  38753. }
  38754. }
  38755. }
  38756. /**
  38757. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  38758. * @param {GLTF.definition} gltfDef
  38759. */
  38760. function assignExtrasToUserData( object, gltfDef ) {
  38761. if ( gltfDef.extras !== undefined ) {
  38762. if ( typeof gltfDef.extras === 'object' ) {
  38763. Object.assign( object.userData, gltfDef.extras );
  38764. } else {
  38765. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  38766. }
  38767. }
  38768. }
  38769. /**
  38770. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  38771. *
  38772. * @param {THREE.BufferGeometry} geometry
  38773. * @param {Array<GLTF.Target>} targets
  38774. * @param {GLTFParser} parser
  38775. * @return {Promise<THREE.BufferGeometry>}
  38776. */
  38777. function addMorphTargets( geometry, targets, parser ) {
  38778. var hasMorphPosition = false;
  38779. var hasMorphNormal = false;
  38780. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38781. var target = targets[ i ];
  38782. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  38783. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  38784. if ( hasMorphPosition && hasMorphNormal ) break;
  38785. }
  38786. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  38787. var pendingPositionAccessors = [];
  38788. var pendingNormalAccessors = [];
  38789. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38790. var target = targets[ i ];
  38791. if ( hasMorphPosition ) {
  38792. var pendingAccessor = target.POSITION !== undefined
  38793. ? parser.getDependency( 'accessor', target.POSITION )
  38794. : geometry.attributes.position;
  38795. pendingPositionAccessors.push( pendingAccessor );
  38796. }
  38797. if ( hasMorphNormal ) {
  38798. var pendingAccessor = target.NORMAL !== undefined
  38799. ? parser.getDependency( 'accessor', target.NORMAL )
  38800. : geometry.attributes.normal;
  38801. pendingNormalAccessors.push( pendingAccessor );
  38802. }
  38803. }
  38804. return Promise.all( [
  38805. Promise.all( pendingPositionAccessors ),
  38806. Promise.all( pendingNormalAccessors )
  38807. ] ).then( function ( accessors ) {
  38808. var morphPositions = accessors[ 0 ];
  38809. var morphNormals = accessors[ 1 ];
  38810. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  38811. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  38812. geometry.morphTargetsRelative = true;
  38813. return geometry;
  38814. } );
  38815. }
  38816. /**
  38817. * @param {THREE.Mesh} mesh
  38818. * @param {GLTF.Mesh} meshDef
  38819. */
  38820. function updateMorphTargets( mesh, meshDef ) {
  38821. mesh.updateMorphTargets();
  38822. if ( meshDef.weights !== undefined ) {
  38823. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  38824. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  38825. }
  38826. }
  38827. // .extras has user-defined data, so check that .extras.targetNames is an array.
  38828. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  38829. var targetNames = meshDef.extras.targetNames;
  38830. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  38831. mesh.morphTargetDictionary = {};
  38832. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  38833. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  38834. }
  38835. } else {
  38836. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  38837. }
  38838. }
  38839. }
  38840. function createPrimitiveKey( primitiveDef ) {
  38841. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  38842. var geometryKey;
  38843. if ( dracoExtension ) {
  38844. geometryKey = 'draco:' + dracoExtension.bufferView
  38845. + ':' + dracoExtension.indices
  38846. + ':' + createAttributesKey( dracoExtension.attributes );
  38847. } else {
  38848. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  38849. }
  38850. return geometryKey;
  38851. }
  38852. function createAttributesKey( attributes ) {
  38853. var attributesKey = '';
  38854. var keys = Object.keys( attributes ).sort();
  38855. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  38856. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  38857. }
  38858. return attributesKey;
  38859. }
  38860. /* GLTF PARSER */
  38861. function GLTFParser( json, options ) {
  38862. this.json = json || {};
  38863. this.extensions = {};
  38864. this.plugins = {};
  38865. this.options = options || {};
  38866. // loader object cache
  38867. this.cache = new GLTFRegistry();
  38868. // associations between Three.js objects and glTF elements
  38869. this.associations = new Map();
  38870. // BufferGeometry caching
  38871. this.primitiveCache = {};
  38872. // Object3D instance caches
  38873. this.meshCache = { refs: {}, uses: {} };
  38874. this.cameraCache = { refs: {}, uses: {} };
  38875. this.lightCache = { refs: {}, uses: {} };
  38876. // Track node names, to ensure no duplicates
  38877. this.nodeNamesUsed = {};
  38878. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  38879. // expensive work of uploading a texture to the GPU off the main thread.
  38880. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  38881. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  38882. } else {
  38883. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  38884. }
  38885. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  38886. this.fileLoader = new THREE.FileLoader( this.options.manager );
  38887. this.fileLoader.setResponseType( 'arraybuffer' );
  38888. if ( this.options.crossOrigin === 'use-credentials' ) {
  38889. this.fileLoader.setWithCredentials( true );
  38890. }
  38891. }
  38892. GLTFParser.prototype.setExtensions = function ( extensions ) {
  38893. this.extensions = extensions;
  38894. };
  38895. GLTFParser.prototype.setPlugins = function ( plugins ) {
  38896. this.plugins = plugins;
  38897. };
  38898. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  38899. var parser = this;
  38900. var json = this.json;
  38901. var extensions = this.extensions;
  38902. // Clear the loader cache
  38903. this.cache.removeAll();
  38904. // Mark the special nodes/meshes in json for efficient parse
  38905. this._invokeAll( function ( ext ) {
  38906. return ext._markDefs && ext._markDefs();
  38907. } );
  38908. Promise.all( [
  38909. this.getDependencies( 'scene' ),
  38910. this.getDependencies( 'animation' ),
  38911. this.getDependencies( 'camera' ),
  38912. ] ).then( function ( dependencies ) {
  38913. var result = {
  38914. scene: dependencies[ 0 ][ json.scene || 0 ],
  38915. scenes: dependencies[ 0 ],
  38916. animations: dependencies[ 1 ],
  38917. cameras: dependencies[ 2 ],
  38918. asset: json.asset,
  38919. parser: parser,
  38920. userData: {}
  38921. };
  38922. addUnknownExtensionsToUserData( extensions, result, json );
  38923. assignExtrasToUserData( result, json );
  38924. onLoad( result );
  38925. } ).catch( onError );
  38926. };
  38927. /**
  38928. * Marks the special nodes/meshes in json for efficient parse.
  38929. */
  38930. GLTFParser.prototype._markDefs = function () {
  38931. var nodeDefs = this.json.nodes || [];
  38932. var skinDefs = this.json.skins || [];
  38933. var meshDefs = this.json.meshes || [];
  38934. // Nothing in the node definition indicates whether it is a Bone or an
  38935. // Object3D. Use the skins' joint references to mark bones.
  38936. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  38937. var joints = skinDefs[ skinIndex ].joints;
  38938. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  38939. nodeDefs[ joints[ i ] ].isBone = true;
  38940. }
  38941. }
  38942. // Iterate over all nodes, marking references to shared resources,
  38943. // as well as skeleton joints.
  38944. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  38945. var nodeDef = nodeDefs[ nodeIndex ];
  38946. if ( nodeDef.mesh !== undefined ) {
  38947. this._addNodeRef( this.meshCache, nodeDef.mesh );
  38948. // Nothing in the mesh definition indicates whether it is
  38949. // a SkinnedMesh or Mesh. Use the node's mesh reference
  38950. // to mark SkinnedMesh if node has skin.
  38951. if ( nodeDef.skin !== undefined ) {
  38952. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  38953. }
  38954. }
  38955. if ( nodeDef.camera !== undefined ) {
  38956. this._addNodeRef( this.cameraCache, nodeDef.camera );
  38957. }
  38958. }
  38959. };
  38960. /**
  38961. * Counts references to shared node / Object3D resources. These resources
  38962. * can be reused, or "instantiated", at multiple nodes in the scene
  38963. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  38964. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  38965. * Textures) can be reused directly and are not marked here.
  38966. *
  38967. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  38968. */
  38969. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  38970. if ( index === undefined ) return;
  38971. if ( cache.refs[ index ] === undefined ) {
  38972. cache.refs[ index ] = cache.uses[ index ] = 0;
  38973. }
  38974. cache.refs[ index ] ++;
  38975. };
  38976. /** Returns a reference to a shared resource, cloning it if necessary. */
  38977. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  38978. if ( cache.refs[ index ] <= 1 ) return object;
  38979. var ref = object.clone();
  38980. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  38981. return ref;
  38982. };
  38983. GLTFParser.prototype._invokeOne = function ( func ) {
  38984. var extensions = Object.values( this.plugins );
  38985. extensions.push( this );
  38986. for ( var i = 0; i < extensions.length; i ++ ) {
  38987. var result = func( extensions[ i ] );
  38988. if ( result ) return result;
  38989. }
  38990. };
  38991. GLTFParser.prototype._invokeAll = function ( func ) {
  38992. var extensions = Object.values( this.plugins );
  38993. extensions.unshift( this );
  38994. var pending = [];
  38995. for ( var i = 0; i < extensions.length; i ++ ) {
  38996. var result = func( extensions[ i ] );
  38997. if ( result ) pending.push( result );
  38998. }
  38999. return pending;
  39000. };
  39001. /**
  39002. * Requests the specified dependency asynchronously, with caching.
  39003. * @param {string} type
  39004. * @param {number} index
  39005. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  39006. */
  39007. GLTFParser.prototype.getDependency = function ( type, index ) {
  39008. var cacheKey = type + ':' + index;
  39009. var dependency = this.cache.get( cacheKey );
  39010. if ( ! dependency ) {
  39011. switch ( type ) {
  39012. case 'scene':
  39013. dependency = this.loadScene( index );
  39014. break;
  39015. case 'node':
  39016. dependency = this.loadNode( index );
  39017. break;
  39018. case 'mesh':
  39019. dependency = this._invokeOne( function ( ext ) {
  39020. return ext.loadMesh && ext.loadMesh( index );
  39021. } );
  39022. break;
  39023. case 'accessor':
  39024. dependency = this.loadAccessor( index );
  39025. break;
  39026. case 'bufferView':
  39027. dependency = this._invokeOne( function ( ext ) {
  39028. return ext.loadBufferView && ext.loadBufferView( index );
  39029. } );
  39030. break;
  39031. case 'buffer':
  39032. dependency = this.loadBuffer( index );
  39033. break;
  39034. case 'material':
  39035. dependency = this._invokeOne( function ( ext ) {
  39036. return ext.loadMaterial && ext.loadMaterial( index );
  39037. } );
  39038. break;
  39039. case 'texture':
  39040. dependency = this._invokeOne( function ( ext ) {
  39041. return ext.loadTexture && ext.loadTexture( index );
  39042. } );
  39043. break;
  39044. case 'skin':
  39045. dependency = this.loadSkin( index );
  39046. break;
  39047. case 'animation':
  39048. dependency = this.loadAnimation( index );
  39049. break;
  39050. case 'camera':
  39051. dependency = this.loadCamera( index );
  39052. break;
  39053. default:
  39054. throw new Error( 'Unknown type: ' + type );
  39055. }
  39056. this.cache.add( cacheKey, dependency );
  39057. }
  39058. return dependency;
  39059. };
  39060. /**
  39061. * Requests all dependencies of the specified type asynchronously, with caching.
  39062. * @param {string} type
  39063. * @return {Promise<Array<Object>>}
  39064. */
  39065. GLTFParser.prototype.getDependencies = function ( type ) {
  39066. var dependencies = this.cache.get( type );
  39067. if ( ! dependencies ) {
  39068. var parser = this;
  39069. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  39070. dependencies = Promise.all( defs.map( function ( def, index ) {
  39071. return parser.getDependency( type, index );
  39072. } ) );
  39073. this.cache.add( type, dependencies );
  39074. }
  39075. return dependencies;
  39076. };
  39077. /**
  39078. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  39079. * @param {number} bufferIndex
  39080. * @return {Promise<ArrayBuffer>}
  39081. */
  39082. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  39083. var bufferDef = this.json.buffers[ bufferIndex ];
  39084. var loader = this.fileLoader;
  39085. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  39086. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  39087. }
  39088. // If present, GLB container is required to be the first buffer.
  39089. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  39090. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  39091. }
  39092. var options = this.options;
  39093. return new Promise( function ( resolve, reject ) {
  39094. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  39095. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  39096. } );
  39097. } );
  39098. };
  39099. /**
  39100. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  39101. * @param {number} bufferViewIndex
  39102. * @return {Promise<ArrayBuffer>}
  39103. */
  39104. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  39105. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  39106. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  39107. var byteLength = bufferViewDef.byteLength || 0;
  39108. var byteOffset = bufferViewDef.byteOffset || 0;
  39109. return buffer.slice( byteOffset, byteOffset + byteLength );
  39110. } );
  39111. };
  39112. /**
  39113. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  39114. * @param {number} accessorIndex
  39115. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  39116. */
  39117. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  39118. var parser = this;
  39119. var json = this.json;
  39120. var accessorDef = this.json.accessors[ accessorIndex ];
  39121. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  39122. // Ignore empty accessors, which may be used to declare runtime
  39123. // information about attributes coming from another source (e.g. Draco
  39124. // compression extension).
  39125. return Promise.resolve( null );
  39126. }
  39127. var pendingBufferViews = [];
  39128. if ( accessorDef.bufferView !== undefined ) {
  39129. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  39130. } else {
  39131. pendingBufferViews.push( null );
  39132. }
  39133. if ( accessorDef.sparse !== undefined ) {
  39134. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  39135. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  39136. }
  39137. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  39138. var bufferView = bufferViews[ 0 ];
  39139. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  39140. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  39141. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  39142. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  39143. var itemBytes = elementBytes * itemSize;
  39144. var byteOffset = accessorDef.byteOffset || 0;
  39145. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  39146. var normalized = accessorDef.normalized === true;
  39147. var array, bufferAttribute;
  39148. // The buffer is not interleaved if the stride is the item size in bytes.
  39149. if ( byteStride && byteStride !== itemBytes ) {
  39150. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  39151. // This makes sure that IBA.count reflects accessor.count properly
  39152. var ibSlice = Math.floor( byteOffset / byteStride );
  39153. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  39154. var ib = parser.cache.get( ibCacheKey );
  39155. if ( ! ib ) {
  39156. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  39157. // Integer parameters to IB/IBA are in array elements, not bytes.
  39158. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  39159. parser.cache.add( ibCacheKey, ib );
  39160. }
  39161. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  39162. } else {
  39163. if ( bufferView === null ) {
  39164. array = new TypedArray( accessorDef.count * itemSize );
  39165. } else {
  39166. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  39167. }
  39168. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  39169. }
  39170. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  39171. if ( accessorDef.sparse !== undefined ) {
  39172. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  39173. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  39174. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  39175. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  39176. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  39177. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  39178. if ( bufferView !== null ) {
  39179. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  39180. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  39181. }
  39182. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  39183. var index = sparseIndices[ i ];
  39184. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  39185. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  39186. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  39187. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  39188. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  39189. }
  39190. }
  39191. return bufferAttribute;
  39192. } );
  39193. };
  39194. /**
  39195. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  39196. * @param {number} textureIndex
  39197. * @return {Promise<THREE.Texture>}
  39198. */
  39199. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  39200. var parser = this;
  39201. var json = this.json;
  39202. var options = this.options;
  39203. var textureDef = json.textures[ textureIndex ];
  39204. var textureExtensions = textureDef.extensions || {};
  39205. var source;
  39206. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  39207. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  39208. } else {
  39209. source = json.images[ textureDef.source ];
  39210. }
  39211. var loader;
  39212. if ( source.uri ) {
  39213. loader = options.manager.getHandler( source.uri );
  39214. }
  39215. if ( ! loader ) {
  39216. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  39217. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  39218. : this.textureLoader;
  39219. }
  39220. return this.loadTextureImage( textureIndex, source, loader );
  39221. };
  39222. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  39223. var parser = this;
  39224. var json = this.json;
  39225. var options = this.options;
  39226. var textureDef = json.textures[ textureIndex ];
  39227. var URL = self.URL || self.webkitURL;
  39228. var sourceURI = source.uri;
  39229. var isObjectURL = false;
  39230. var hasAlpha = true;
  39231. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  39232. if ( source.bufferView !== undefined ) {
  39233. // Load binary image data from bufferView, if provided.
  39234. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  39235. if ( source.mimeType === 'image/png' ) {
  39236. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  39237. // alpha channel. This check is conservative — the image could have an alpha
  39238. // channel with all values == 1, and the indexed type (colorType == 3) only
  39239. // sometimes contains alpha.
  39240. //
  39241. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  39242. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  39243. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  39244. }
  39245. isObjectURL = true;
  39246. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  39247. sourceURI = URL.createObjectURL( blob );
  39248. return sourceURI;
  39249. } );
  39250. }
  39251. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  39252. return new Promise( function ( resolve, reject ) {
  39253. var onLoad = resolve;
  39254. if ( loader.isImageBitmapLoader === true ) {
  39255. onLoad = function ( imageBitmap ) {
  39256. resolve( new THREE.CanvasTexture( imageBitmap ) );
  39257. };
  39258. }
  39259. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  39260. } );
  39261. } ).then( function ( texture ) {
  39262. // Clean up resources and configure Texture.
  39263. if ( isObjectURL === true ) {
  39264. URL.revokeObjectURL( sourceURI );
  39265. }
  39266. texture.flipY = false;
  39267. if ( textureDef.name ) texture.name = textureDef.name;
  39268. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  39269. if ( ! hasAlpha ) texture.format = THREE.RGBFormat;
  39270. var samplers = json.samplers || {};
  39271. var sampler = samplers[ textureDef.sampler ] || {};
  39272. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  39273. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  39274. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  39275. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  39276. parser.associations.set( texture, {
  39277. type: 'textures',
  39278. index: textureIndex
  39279. } );
  39280. return texture;
  39281. } );
  39282. };
  39283. /**
  39284. * Asynchronously assigns a texture to the given material parameters.
  39285. * @param {Object} materialParams
  39286. * @param {string} mapName
  39287. * @param {Object} mapDef
  39288. * @return {Promise}
  39289. */
  39290. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  39291. var parser = this;
  39292. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  39293. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  39294. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  39295. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  39296. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  39297. }
  39298. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  39299. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  39300. if ( transform ) {
  39301. var gltfReference = parser.associations.get( texture );
  39302. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  39303. parser.associations.set( texture, gltfReference );
  39304. }
  39305. }
  39306. materialParams[ mapName ] = texture;
  39307. } );
  39308. };
  39309. /**
  39310. * Assigns final material to a Mesh, Line, or Points instance. The instance
  39311. * already has a material (generated from the glTF material options alone)
  39312. * but reuse of the same glTF material may require multiple threejs materials
  39313. * to accomodate different primitive types, defines, etc. New materials will
  39314. * be created if necessary, and reused from a cache.
  39315. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  39316. */
  39317. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  39318. var geometry = mesh.geometry;
  39319. var material = mesh.material;
  39320. var useVertexTangents = geometry.attributes.tangent !== undefined;
  39321. var useVertexColors = geometry.attributes.color !== undefined;
  39322. var useFlatShading = geometry.attributes.normal === undefined;
  39323. var useSkinning = mesh.isSkinnedMesh === true;
  39324. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  39325. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  39326. if ( mesh.isPoints ) {
  39327. var cacheKey = 'PointsMaterial:' + material.uuid;
  39328. var pointsMaterial = this.cache.get( cacheKey );
  39329. if ( ! pointsMaterial ) {
  39330. pointsMaterial = new THREE.PointsMaterial();
  39331. THREE.Material.prototype.copy.call( pointsMaterial, material );
  39332. pointsMaterial.color.copy( material.color );
  39333. pointsMaterial.map = material.map;
  39334. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  39335. this.cache.add( cacheKey, pointsMaterial );
  39336. }
  39337. material = pointsMaterial;
  39338. } else if ( mesh.isLine ) {
  39339. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  39340. var lineMaterial = this.cache.get( cacheKey );
  39341. if ( ! lineMaterial ) {
  39342. lineMaterial = new THREE.LineBasicMaterial();
  39343. THREE.Material.prototype.copy.call( lineMaterial, material );
  39344. lineMaterial.color.copy( material.color );
  39345. this.cache.add( cacheKey, lineMaterial );
  39346. }
  39347. material = lineMaterial;
  39348. }
  39349. // Clone the material if it will be modified
  39350. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  39351. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  39352. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  39353. if ( useSkinning ) cacheKey += 'skinning:';
  39354. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  39355. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  39356. if ( useFlatShading ) cacheKey += 'flat-shading:';
  39357. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  39358. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  39359. var cachedMaterial = this.cache.get( cacheKey );
  39360. if ( ! cachedMaterial ) {
  39361. cachedMaterial = material.clone();
  39362. if ( useSkinning ) cachedMaterial.skinning = true;
  39363. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  39364. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  39365. if ( useFlatShading ) cachedMaterial.flatShading = true;
  39366. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  39367. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  39368. this.cache.add( cacheKey, cachedMaterial );
  39369. this.associations.set( cachedMaterial, this.associations.get( material ) );
  39370. }
  39371. material = cachedMaterial;
  39372. }
  39373. // workarounds for mesh and geometry
  39374. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  39375. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  39376. }
  39377. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  39378. if ( material.normalScale && ! useVertexTangents ) {
  39379. material.normalScale.y = - material.normalScale.y;
  39380. }
  39381. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  39382. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  39383. }
  39384. mesh.material = material;
  39385. };
  39386. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  39387. return THREE.MeshStandardMaterial;
  39388. };
  39389. /**
  39390. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  39391. * @param {number} materialIndex
  39392. * @return {Promise<THREE.Material>}
  39393. */
  39394. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  39395. var parser = this;
  39396. var json = this.json;
  39397. var extensions = this.extensions;
  39398. var materialDef = json.materials[ materialIndex ];
  39399. var materialType;
  39400. var materialParams = {};
  39401. var materialExtensions = materialDef.extensions || {};
  39402. var pending = [];
  39403. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  39404. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  39405. materialType = sgExtension.getMaterialType();
  39406. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  39407. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  39408. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  39409. materialType = kmuExtension.getMaterialType();
  39410. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  39411. } else {
  39412. // Specification:
  39413. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  39414. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  39415. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  39416. materialParams.opacity = 1.0;
  39417. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  39418. var array = metallicRoughness.baseColorFactor;
  39419. materialParams.color.fromArray( array );
  39420. materialParams.opacity = array[ 3 ];
  39421. }
  39422. if ( metallicRoughness.baseColorTexture !== undefined ) {
  39423. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  39424. }
  39425. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  39426. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  39427. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  39428. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  39429. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  39430. }
  39431. materialType = this._invokeOne( function ( ext ) {
  39432. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  39433. } );
  39434. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  39435. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  39436. } ) ) );
  39437. }
  39438. if ( materialDef.doubleSided === true ) {
  39439. materialParams.side = THREE.DoubleSide;
  39440. }
  39441. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  39442. if ( alphaMode === ALPHA_MODES.BLEND ) {
  39443. materialParams.transparent = true;
  39444. // See: https://github.com/mrdoob/three.js/issues/17706
  39445. materialParams.depthWrite = false;
  39446. } else {
  39447. materialParams.transparent = false;
  39448. if ( alphaMode === ALPHA_MODES.MASK ) {
  39449. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  39450. }
  39451. }
  39452. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  39453. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  39454. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  39455. if ( materialDef.normalTexture.scale !== undefined ) {
  39456. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  39457. }
  39458. }
  39459. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  39460. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  39461. if ( materialDef.occlusionTexture.strength !== undefined ) {
  39462. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  39463. }
  39464. }
  39465. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  39466. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  39467. }
  39468. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  39469. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  39470. }
  39471. return Promise.all( pending ).then( function () {
  39472. var material;
  39473. if ( materialType === GLTFMeshStandardSGMaterial ) {
  39474. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  39475. } else {
  39476. material = new materialType( materialParams );
  39477. }
  39478. if ( materialDef.name ) material.name = materialDef.name;
  39479. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  39480. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  39481. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  39482. assignExtrasToUserData( material, materialDef );
  39483. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  39484. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  39485. return material;
  39486. } );
  39487. };
  39488. /** When Object3D instances are targeted by animation, they need unique names. */
  39489. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  39490. var name = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
  39491. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  39492. name = originalName + '_' + i;
  39493. }
  39494. this.nodeNamesUsed[ name ] = true;
  39495. return name;
  39496. };
  39497. /**
  39498. * @param {THREE.BufferGeometry} geometry
  39499. * @param {GLTF.Primitive} primitiveDef
  39500. * @param {GLTFParser} parser
  39501. */
  39502. function computeBounds( geometry, primitiveDef, parser ) {
  39503. var attributes = primitiveDef.attributes;
  39504. var box = new THREE.Box3();
  39505. if ( attributes.POSITION !== undefined ) {
  39506. var accessor = parser.json.accessors[ attributes.POSITION ];
  39507. var min = accessor.min;
  39508. var max = accessor.max;
  39509. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  39510. if ( min !== undefined && max !== undefined ) {
  39511. box.set(
  39512. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  39513. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  39514. } else {
  39515. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  39516. return;
  39517. }
  39518. } else {
  39519. return;
  39520. }
  39521. var targets = primitiveDef.targets;
  39522. if ( targets !== undefined ) {
  39523. var maxDisplacement = new THREE.Vector3();
  39524. var vector = new THREE.Vector3();
  39525. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  39526. var target = targets[ i ];
  39527. if ( target.POSITION !== undefined ) {
  39528. var accessor = parser.json.accessors[ target.POSITION ];
  39529. var min = accessor.min;
  39530. var max = accessor.max;
  39531. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  39532. if ( min !== undefined && max !== undefined ) {
  39533. // we need to get max of absolute components because target weight is [-1,1]
  39534. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  39535. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  39536. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  39537. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  39538. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  39539. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  39540. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  39541. maxDisplacement.max( vector );
  39542. } else {
  39543. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  39544. }
  39545. }
  39546. }
  39547. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  39548. box.expandByVector( maxDisplacement );
  39549. }
  39550. geometry.boundingBox = box;
  39551. var sphere = new THREE.Sphere();
  39552. box.getCenter( sphere.center );
  39553. sphere.radius = box.min.distanceTo( box.max ) / 2;
  39554. geometry.boundingSphere = sphere;
  39555. }
  39556. /**
  39557. * @param {THREE.BufferGeometry} geometry
  39558. * @param {GLTF.Primitive} primitiveDef
  39559. * @param {GLTFParser} parser
  39560. * @return {Promise<THREE.BufferGeometry>}
  39561. */
  39562. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  39563. var attributes = primitiveDef.attributes;
  39564. var pending = [];
  39565. function assignAttributeAccessor( accessorIndex, attributeName ) {
  39566. return parser.getDependency( 'accessor', accessorIndex )
  39567. .then( function ( accessor ) {
  39568. geometry.setAttribute( attributeName, accessor );
  39569. } );
  39570. }
  39571. for ( var gltfAttributeName in attributes ) {
  39572. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  39573. // Skip attributes already provided by e.g. Draco extension.
  39574. if ( threeAttributeName in geometry.attributes ) continue;
  39575. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  39576. }
  39577. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  39578. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  39579. geometry.setIndex( accessor );
  39580. } );
  39581. pending.push( accessor );
  39582. }
  39583. assignExtrasToUserData( geometry, primitiveDef );
  39584. computeBounds( geometry, primitiveDef, parser );
  39585. return Promise.all( pending ).then( function () {
  39586. return primitiveDef.targets !== undefined
  39587. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  39588. : geometry;
  39589. } );
  39590. }
  39591. /**
  39592. * @param {THREE.BufferGeometry} geometry
  39593. * @param {Number} drawMode
  39594. * @return {THREE.BufferGeometry}
  39595. */
  39596. function toTrianglesDrawMode( geometry, drawMode ) {
  39597. var index = geometry.getIndex();
  39598. // generate index if not present
  39599. if ( index === null ) {
  39600. var indices = [];
  39601. var position = geometry.getAttribute( 'position' );
  39602. if ( position !== undefined ) {
  39603. for ( var i = 0; i < position.count; i ++ ) {
  39604. indices.push( i );
  39605. }
  39606. geometry.setIndex( indices );
  39607. index = geometry.getIndex();
  39608. } else {
  39609. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  39610. return geometry;
  39611. }
  39612. }
  39613. //
  39614. var numberOfTriangles = index.count - 2;
  39615. var newIndices = [];
  39616. if ( drawMode === THREE.TriangleFanDrawMode ) {
  39617. // gl.TRIANGLE_FAN
  39618. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  39619. newIndices.push( index.getX( 0 ) );
  39620. newIndices.push( index.getX( i ) );
  39621. newIndices.push( index.getX( i + 1 ) );
  39622. }
  39623. } else {
  39624. // gl.TRIANGLE_STRIP
  39625. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  39626. if ( i % 2 === 0 ) {
  39627. newIndices.push( index.getX( i ) );
  39628. newIndices.push( index.getX( i + 1 ) );
  39629. newIndices.push( index.getX( i + 2 ) );
  39630. } else {
  39631. newIndices.push( index.getX( i + 2 ) );
  39632. newIndices.push( index.getX( i + 1 ) );
  39633. newIndices.push( index.getX( i ) );
  39634. }
  39635. }
  39636. }
  39637. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  39638. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  39639. }
  39640. // build final geometry
  39641. var newGeometry = geometry.clone();
  39642. newGeometry.setIndex( newIndices );
  39643. return newGeometry;
  39644. }
  39645. /**
  39646. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  39647. *
  39648. * Creates BufferGeometries from primitives.
  39649. *
  39650. * @param {Array<GLTF.Primitive>} primitives
  39651. * @return {Promise<Array<THREE.BufferGeometry>>}
  39652. */
  39653. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  39654. var parser = this;
  39655. var extensions = this.extensions;
  39656. var cache = this.primitiveCache;
  39657. function createDracoPrimitive( primitive ) {
  39658. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  39659. .decodePrimitive( primitive, parser )
  39660. .then( function ( geometry ) {
  39661. return addPrimitiveAttributes( geometry, primitive, parser );
  39662. } );
  39663. }
  39664. var pending = [];
  39665. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  39666. var primitive = primitives[ i ];
  39667. var cacheKey = createPrimitiveKey( primitive );
  39668. // See if we've already created this geometry
  39669. var cached = cache[ cacheKey ];
  39670. if ( cached ) {
  39671. // Use the cached geometry if it exists
  39672. pending.push( cached.promise );
  39673. } else {
  39674. var geometryPromise;
  39675. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  39676. // Use DRACO geometry if available
  39677. geometryPromise = createDracoPrimitive( primitive );
  39678. } else {
  39679. // Otherwise create a new geometry
  39680. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  39681. }
  39682. // Cache this geometry
  39683. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  39684. pending.push( geometryPromise );
  39685. }
  39686. }
  39687. return Promise.all( pending );
  39688. };
  39689. /**
  39690. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  39691. * @param {number} meshIndex
  39692. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  39693. */
  39694. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  39695. var parser = this;
  39696. var json = this.json;
  39697. var extensions = this.extensions;
  39698. var meshDef = json.meshes[ meshIndex ];
  39699. var primitives = meshDef.primitives;
  39700. var pending = [];
  39701. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  39702. var material = primitives[ i ].material === undefined
  39703. ? createDefaultMaterial( this.cache )
  39704. : this.getDependency( 'material', primitives[ i ].material );
  39705. pending.push( material );
  39706. }
  39707. pending.push( parser.loadGeometries( primitives ) );
  39708. return Promise.all( pending ).then( function ( results ) {
  39709. var materials = results.slice( 0, results.length - 1 );
  39710. var geometries = results[ results.length - 1 ];
  39711. var meshes = [];
  39712. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  39713. var geometry = geometries[ i ];
  39714. var primitive = primitives[ i ];
  39715. // 1. create Mesh
  39716. var mesh;
  39717. var material = materials[ i ];
  39718. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  39719. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  39720. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  39721. primitive.mode === undefined ) {
  39722. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  39723. mesh = meshDef.isSkinnedMesh === true
  39724. ? new THREE.SkinnedMesh( geometry, material )
  39725. : new THREE.Mesh( geometry, material );
  39726. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  39727. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  39728. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  39729. mesh.normalizeSkinWeights();
  39730. }
  39731. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  39732. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  39733. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  39734. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  39735. }
  39736. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  39737. mesh = new THREE.LineSegments( geometry, material );
  39738. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  39739. mesh = new THREE.Line( geometry, material );
  39740. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  39741. mesh = new THREE.LineLoop( geometry, material );
  39742. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  39743. mesh = new THREE.Points( geometry, material );
  39744. } else {
  39745. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  39746. }
  39747. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  39748. updateMorphTargets( mesh, meshDef );
  39749. }
  39750. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  39751. assignExtrasToUserData( mesh, meshDef );
  39752. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  39753. parser.assignFinalMaterial( mesh );
  39754. meshes.push( mesh );
  39755. }
  39756. if ( meshes.length === 1 ) {
  39757. return meshes[ 0 ];
  39758. }
  39759. var group = new THREE.Group();
  39760. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  39761. group.add( meshes[ i ] );
  39762. }
  39763. return group;
  39764. } );
  39765. };
  39766. /**
  39767. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  39768. * @param {number} cameraIndex
  39769. * @return {Promise<THREE.Camera>}
  39770. */
  39771. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  39772. var camera;
  39773. var cameraDef = this.json.cameras[ cameraIndex ];
  39774. var params = cameraDef[ cameraDef.type ];
  39775. if ( ! params ) {
  39776. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  39777. return;
  39778. }
  39779. if ( cameraDef.type === 'perspective' ) {
  39780. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  39781. } else if ( cameraDef.type === 'orthographic' ) {
  39782. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  39783. }
  39784. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  39785. assignExtrasToUserData( camera, cameraDef );
  39786. return Promise.resolve( camera );
  39787. };
  39788. /**
  39789. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  39790. * @param {number} skinIndex
  39791. * @return {Promise<Object>}
  39792. */
  39793. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  39794. var skinDef = this.json.skins[ skinIndex ];
  39795. var skinEntry = { joints: skinDef.joints };
  39796. if ( skinDef.inverseBindMatrices === undefined ) {
  39797. return Promise.resolve( skinEntry );
  39798. }
  39799. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  39800. skinEntry.inverseBindMatrices = accessor;
  39801. return skinEntry;
  39802. } );
  39803. };
  39804. /**
  39805. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  39806. * @param {number} animationIndex
  39807. * @return {Promise<THREE.AnimationClip>}
  39808. */
  39809. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  39810. var json = this.json;
  39811. var animationDef = json.animations[ animationIndex ];
  39812. var pendingNodes = [];
  39813. var pendingInputAccessors = [];
  39814. var pendingOutputAccessors = [];
  39815. var pendingSamplers = [];
  39816. var pendingTargets = [];
  39817. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  39818. var channel = animationDef.channels[ i ];
  39819. var sampler = animationDef.samplers[ channel.sampler ];
  39820. var target = channel.target;
  39821. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  39822. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  39823. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  39824. pendingNodes.push( this.getDependency( 'node', name ) );
  39825. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  39826. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  39827. pendingSamplers.push( sampler );
  39828. pendingTargets.push( target );
  39829. }
  39830. return Promise.all( [
  39831. Promise.all( pendingNodes ),
  39832. Promise.all( pendingInputAccessors ),
  39833. Promise.all( pendingOutputAccessors ),
  39834. Promise.all( pendingSamplers ),
  39835. Promise.all( pendingTargets )
  39836. ] ).then( function ( dependencies ) {
  39837. var nodes = dependencies[ 0 ];
  39838. var inputAccessors = dependencies[ 1 ];
  39839. var outputAccessors = dependencies[ 2 ];
  39840. var samplers = dependencies[ 3 ];
  39841. var targets = dependencies[ 4 ];
  39842. var tracks = [];
  39843. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  39844. var node = nodes[ i ];
  39845. var inputAccessor = inputAccessors[ i ];
  39846. var outputAccessor = outputAccessors[ i ];
  39847. var sampler = samplers[ i ];
  39848. var target = targets[ i ];
  39849. if ( node === undefined ) continue;
  39850. node.updateMatrix();
  39851. node.matrixAutoUpdate = true;
  39852. var TypedKeyframeTrack;
  39853. switch ( PATH_PROPERTIES[ target.path ] ) {
  39854. case PATH_PROPERTIES.weights:
  39855. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  39856. break;
  39857. case PATH_PROPERTIES.rotation:
  39858. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  39859. break;
  39860. case PATH_PROPERTIES.position:
  39861. case PATH_PROPERTIES.scale:
  39862. default:
  39863. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  39864. break;
  39865. }
  39866. var targetName = node.name ? node.name : node.uuid;
  39867. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  39868. var targetNames = [];
  39869. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  39870. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  39871. node.traverse( function ( object ) {
  39872. if ( object.isMesh === true && object.morphTargetInfluences ) {
  39873. targetNames.push( object.name ? object.name : object.uuid );
  39874. }
  39875. } );
  39876. } else {
  39877. targetNames.push( targetName );
  39878. }
  39879. var outputArray = outputAccessor.array;
  39880. if ( outputAccessor.normalized ) {
  39881. var scale;
  39882. if ( outputArray.constructor === Int8Array ) {
  39883. scale = 1 / 127;
  39884. } else if ( outputArray.constructor === Uint8Array ) {
  39885. scale = 1 / 255;
  39886. } else if ( outputArray.constructor == Int16Array ) {
  39887. scale = 1 / 32767;
  39888. } else if ( outputArray.constructor === Uint16Array ) {
  39889. scale = 1 / 65535;
  39890. } else {
  39891. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  39892. }
  39893. var scaled = new Float32Array( outputArray.length );
  39894. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  39895. scaled[ j ] = outputArray[ j ] * scale;
  39896. }
  39897. outputArray = scaled;
  39898. }
  39899. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  39900. var track = new TypedKeyframeTrack(
  39901. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  39902. inputAccessor.array,
  39903. outputArray,
  39904. interpolation
  39905. );
  39906. // Override interpolation with custom factory method.
  39907. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  39908. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  39909. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  39910. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  39911. // must be divided by three to get the interpolant's sampleSize argument.
  39912. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  39913. };
  39914. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  39915. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  39916. }
  39917. tracks.push( track );
  39918. }
  39919. }
  39920. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  39921. return new THREE.AnimationClip( name, undefined, tracks );
  39922. } );
  39923. };
  39924. /**
  39925. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  39926. * @param {number} nodeIndex
  39927. * @return {Promise<THREE.Object3D>}
  39928. */
  39929. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  39930. var json = this.json;
  39931. var extensions = this.extensions;
  39932. var parser = this;
  39933. var nodeDef = json.nodes[ nodeIndex ];
  39934. // reserve node's name before its dependencies, so the root has the intended name.
  39935. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  39936. return ( function () {
  39937. var pending = [];
  39938. if ( nodeDef.mesh !== undefined ) {
  39939. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  39940. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  39941. // if weights are provided on the node, override weights on the mesh.
  39942. if ( nodeDef.weights !== undefined ) {
  39943. node.traverse( function ( o ) {
  39944. if ( ! o.isMesh ) return;
  39945. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  39946. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  39947. }
  39948. } );
  39949. }
  39950. return node;
  39951. } ) );
  39952. }
  39953. if ( nodeDef.camera !== undefined ) {
  39954. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  39955. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  39956. } ) );
  39957. }
  39958. parser._invokeAll( function ( ext ) {
  39959. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  39960. } ).forEach( function ( promise ) {
  39961. pending.push( promise );
  39962. } );
  39963. return Promise.all( pending );
  39964. }() ).then( function ( objects ) {
  39965. var node;
  39966. // .isBone isn't in glTF spec. See ._markDefs
  39967. if ( nodeDef.isBone === true ) {
  39968. node = new THREE.Bone();
  39969. } else if ( objects.length > 1 ) {
  39970. node = new THREE.Group();
  39971. } else if ( objects.length === 1 ) {
  39972. node = objects[ 0 ];
  39973. } else {
  39974. node = new THREE.Object3D();
  39975. }
  39976. if ( node !== objects[ 0 ] ) {
  39977. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  39978. node.add( objects[ i ] );
  39979. }
  39980. }
  39981. if ( nodeDef.name ) {
  39982. node.userData.name = nodeDef.name;
  39983. node.name = nodeName;
  39984. }
  39985. assignExtrasToUserData( node, nodeDef );
  39986. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  39987. if ( nodeDef.matrix !== undefined ) {
  39988. var matrix = new THREE.Matrix4();
  39989. matrix.fromArray( nodeDef.matrix );
  39990. node.applyMatrix4( matrix );
  39991. } else {
  39992. if ( nodeDef.translation !== undefined ) {
  39993. node.position.fromArray( nodeDef.translation );
  39994. }
  39995. if ( nodeDef.rotation !== undefined ) {
  39996. node.quaternion.fromArray( nodeDef.rotation );
  39997. }
  39998. if ( nodeDef.scale !== undefined ) {
  39999. node.scale.fromArray( nodeDef.scale );
  40000. }
  40001. }
  40002. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  40003. return node;
  40004. } );
  40005. };
  40006. /**
  40007. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  40008. * @param {number} sceneIndex
  40009. * @return {Promise<THREE.Group>}
  40010. */
  40011. GLTFParser.prototype.loadScene = function () {
  40012. // scene node hierachy builder
  40013. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  40014. var nodeDef = json.nodes[ nodeId ];
  40015. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  40016. if ( nodeDef.skin === undefined ) return node;
  40017. // build skeleton here as well
  40018. var skinEntry;
  40019. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  40020. skinEntry = skin;
  40021. var pendingJoints = [];
  40022. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  40023. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  40024. }
  40025. return Promise.all( pendingJoints );
  40026. } ).then( function ( jointNodes ) {
  40027. node.traverse( function ( mesh ) {
  40028. if ( ! mesh.isMesh ) return;
  40029. var bones = [];
  40030. var boneInverses = [];
  40031. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  40032. var jointNode = jointNodes[ j ];
  40033. if ( jointNode ) {
  40034. bones.push( jointNode );
  40035. var mat = new THREE.Matrix4();
  40036. if ( skinEntry.inverseBindMatrices !== undefined ) {
  40037. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  40038. }
  40039. boneInverses.push( mat );
  40040. } else {
  40041. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  40042. }
  40043. }
  40044. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  40045. } );
  40046. return node;
  40047. } );
  40048. } ).then( function ( node ) {
  40049. // build node hierachy
  40050. parentObject.add( node );
  40051. var pending = [];
  40052. if ( nodeDef.children ) {
  40053. var children = nodeDef.children;
  40054. for ( var i = 0, il = children.length; i < il; i ++ ) {
  40055. var child = children[ i ];
  40056. pending.push( buildNodeHierachy( child, node, json, parser ) );
  40057. }
  40058. }
  40059. return Promise.all( pending );
  40060. } );
  40061. }
  40062. return function loadScene( sceneIndex ) {
  40063. var json = this.json;
  40064. var extensions = this.extensions;
  40065. var sceneDef = this.json.scenes[ sceneIndex ];
  40066. var parser = this;
  40067. // Loader returns Group, not Scene.
  40068. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  40069. var scene = new THREE.Group();
  40070. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  40071. assignExtrasToUserData( scene, sceneDef );
  40072. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  40073. var nodeIds = sceneDef.nodes || [];
  40074. var pending = [];
  40075. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  40076. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  40077. }
  40078. return Promise.all( pending ).then( function () {
  40079. return scene;
  40080. } );
  40081. };
  40082. }();
  40083. return GLTFLoader;
  40084. } )();
  40085. },{}],60:[function(_dereq_,module,exports){
  40086. /**
  40087. * Loads a Wavefront .mtl file specifying materials
  40088. */
  40089. THREE.MTLLoader = function ( manager ) {
  40090. THREE.Loader.call( this, manager );
  40091. };
  40092. THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  40093. constructor: THREE.MTLLoader,
  40094. /**
  40095. * Loads and parses a MTL asset from a URL.
  40096. *
  40097. * @param {String} url - URL to the MTL file.
  40098. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  40099. * @param {Function} [onProgress] - Callback for download progress.
  40100. * @param {Function} [onError] - Callback for download errors.
  40101. *
  40102. * @see setPath setResourcePath
  40103. *
  40104. * @note In order for relative texture references to resolve correctly
  40105. * you must call setResourcePath() explicitly prior to load.
  40106. */
  40107. load: function ( url, onLoad, onProgress, onError ) {
  40108. var scope = this;
  40109. var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  40110. var loader = new THREE.FileLoader( this.manager );
  40111. loader.setPath( this.path );
  40112. loader.setRequestHeader( this.requestHeader );
  40113. loader.setWithCredentials( this.withCredentials );
  40114. loader.load( url, function ( text ) {
  40115. try {
  40116. onLoad( scope.parse( text, path ) );
  40117. } catch ( e ) {
  40118. if ( onError ) {
  40119. onError( e );
  40120. } else {
  40121. console.error( e );
  40122. }
  40123. scope.manager.itemError( url );
  40124. }
  40125. }, onProgress, onError );
  40126. },
  40127. setMaterialOptions: function ( value ) {
  40128. this.materialOptions = value;
  40129. return this;
  40130. },
  40131. /**
  40132. * Parses a MTL file.
  40133. *
  40134. * @param {String} text - Content of MTL file
  40135. * @return {THREE.MTLLoader.MaterialCreator}
  40136. *
  40137. * @see setPath setResourcePath
  40138. *
  40139. * @note In order for relative texture references to resolve correctly
  40140. * you must call setResourcePath() explicitly prior to parse.
  40141. */
  40142. parse: function ( text, path ) {
  40143. var lines = text.split( '\n' );
  40144. var info = {};
  40145. var delimiter_pattern = /\s+/;
  40146. var materialsInfo = {};
  40147. for ( var i = 0; i < lines.length; i ++ ) {
  40148. var line = lines[ i ];
  40149. line = line.trim();
  40150. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  40151. // Blank line or comment ignore
  40152. continue;
  40153. }
  40154. var pos = line.indexOf( ' ' );
  40155. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  40156. key = key.toLowerCase();
  40157. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  40158. value = value.trim();
  40159. if ( key === 'newmtl' ) {
  40160. // New material
  40161. info = { name: value };
  40162. materialsInfo[ value ] = info;
  40163. } else {
  40164. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  40165. var ss = value.split( delimiter_pattern, 3 );
  40166. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  40167. } else {
  40168. info[ key ] = value;
  40169. }
  40170. }
  40171. }
  40172. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  40173. materialCreator.setCrossOrigin( this.crossOrigin );
  40174. materialCreator.setManager( this.manager );
  40175. materialCreator.setMaterials( materialsInfo );
  40176. return materialCreator;
  40177. }
  40178. } );
  40179. /**
  40180. * Create a new THREE.MTLLoader.MaterialCreator
  40181. * @param baseUrl - Url relative to which textures are loaded
  40182. * @param options - Set of options on how to construct the materials
  40183. * side: Which side to apply the material
  40184. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  40185. * wrap: What type of wrapping to apply for textures
  40186. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  40187. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  40188. * Default: false, assumed to be already normalized
  40189. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  40190. * Default: false
  40191. * @constructor
  40192. */
  40193. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  40194. this.baseUrl = baseUrl || '';
  40195. this.options = options;
  40196. this.materialsInfo = {};
  40197. this.materials = {};
  40198. this.materialsArray = [];
  40199. this.nameLookup = {};
  40200. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  40201. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  40202. };
  40203. THREE.MTLLoader.MaterialCreator.prototype = {
  40204. constructor: THREE.MTLLoader.MaterialCreator,
  40205. crossOrigin: 'anonymous',
  40206. setCrossOrigin: function ( value ) {
  40207. this.crossOrigin = value;
  40208. return this;
  40209. },
  40210. setManager: function ( value ) {
  40211. this.manager = value;
  40212. },
  40213. setMaterials: function ( materialsInfo ) {
  40214. this.materialsInfo = this.convert( materialsInfo );
  40215. this.materials = {};
  40216. this.materialsArray = [];
  40217. this.nameLookup = {};
  40218. },
  40219. convert: function ( materialsInfo ) {
  40220. if ( ! this.options ) return materialsInfo;
  40221. var converted = {};
  40222. for ( var mn in materialsInfo ) {
  40223. // Convert materials info into normalized form based on options
  40224. var mat = materialsInfo[ mn ];
  40225. var covmat = {};
  40226. converted[ mn ] = covmat;
  40227. for ( var prop in mat ) {
  40228. var save = true;
  40229. var value = mat[ prop ];
  40230. var lprop = prop.toLowerCase();
  40231. switch ( lprop ) {
  40232. case 'kd':
  40233. case 'ka':
  40234. case 'ks':
  40235. // Diffuse color (color under white light) using RGB values
  40236. if ( this.options && this.options.normalizeRGB ) {
  40237. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  40238. }
  40239. if ( this.options && this.options.ignoreZeroRGBs ) {
  40240. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  40241. // ignore
  40242. save = false;
  40243. }
  40244. }
  40245. break;
  40246. default:
  40247. break;
  40248. }
  40249. if ( save ) {
  40250. covmat[ lprop ] = value;
  40251. }
  40252. }
  40253. }
  40254. return converted;
  40255. },
  40256. preload: function () {
  40257. for ( var mn in this.materialsInfo ) {
  40258. this.create( mn );
  40259. }
  40260. },
  40261. getIndex: function ( materialName ) {
  40262. return this.nameLookup[ materialName ];
  40263. },
  40264. getAsArray: function () {
  40265. var index = 0;
  40266. for ( var mn in this.materialsInfo ) {
  40267. this.materialsArray[ index ] = this.create( mn );
  40268. this.nameLookup[ mn ] = index;
  40269. index ++;
  40270. }
  40271. return this.materialsArray;
  40272. },
  40273. create: function ( materialName ) {
  40274. if ( this.materials[ materialName ] === undefined ) {
  40275. this.createMaterial_( materialName );
  40276. }
  40277. return this.materials[ materialName ];
  40278. },
  40279. createMaterial_: function ( materialName ) {
  40280. // Create material
  40281. var scope = this;
  40282. var mat = this.materialsInfo[ materialName ];
  40283. var params = {
  40284. name: materialName,
  40285. side: this.side
  40286. };
  40287. function resolveURL( baseUrl, url ) {
  40288. if ( typeof url !== 'string' || url === '' )
  40289. return '';
  40290. // Absolute URL
  40291. if ( /^https?:\/\//i.test( url ) ) return url;
  40292. return baseUrl + url;
  40293. }
  40294. function setMapForType( mapType, value ) {
  40295. if ( params[ mapType ] ) return; // Keep the first encountered texture
  40296. var texParams = scope.getTextureParams( value, params );
  40297. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  40298. map.repeat.copy( texParams.scale );
  40299. map.offset.copy( texParams.offset );
  40300. map.wrapS = scope.wrap;
  40301. map.wrapT = scope.wrap;
  40302. params[ mapType ] = map;
  40303. }
  40304. for ( var prop in mat ) {
  40305. var value = mat[ prop ];
  40306. var n;
  40307. if ( value === '' ) continue;
  40308. switch ( prop.toLowerCase() ) {
  40309. // Ns is material specular exponent
  40310. case 'kd':
  40311. // Diffuse color (color under white light) using RGB values
  40312. params.color = new THREE.Color().fromArray( value );
  40313. break;
  40314. case 'ks':
  40315. // Specular color (color when light is reflected from shiny surface) using RGB values
  40316. params.specular = new THREE.Color().fromArray( value );
  40317. break;
  40318. case 'ke':
  40319. // Emissive using RGB values
  40320. params.emissive = new THREE.Color().fromArray( value );
  40321. break;
  40322. case 'map_kd':
  40323. // Diffuse texture map
  40324. setMapForType( "map", value );
  40325. break;
  40326. case 'map_ks':
  40327. // Specular map
  40328. setMapForType( "specularMap", value );
  40329. break;
  40330. case 'map_ke':
  40331. // Emissive map
  40332. setMapForType( "emissiveMap", value );
  40333. break;
  40334. case 'norm':
  40335. setMapForType( "normalMap", value );
  40336. break;
  40337. case 'map_bump':
  40338. case 'bump':
  40339. // Bump texture map
  40340. setMapForType( "bumpMap", value );
  40341. break;
  40342. case 'map_d':
  40343. // Alpha map
  40344. setMapForType( "alphaMap", value );
  40345. params.transparent = true;
  40346. break;
  40347. case 'ns':
  40348. // The specular exponent (defines the focus of the specular highlight)
  40349. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  40350. params.shininess = parseFloat( value );
  40351. break;
  40352. case 'd':
  40353. n = parseFloat( value );
  40354. if ( n < 1 ) {
  40355. params.opacity = n;
  40356. params.transparent = true;
  40357. }
  40358. break;
  40359. case 'tr':
  40360. n = parseFloat( value );
  40361. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  40362. if ( n > 0 ) {
  40363. params.opacity = 1 - n;
  40364. params.transparent = true;
  40365. }
  40366. break;
  40367. default:
  40368. break;
  40369. }
  40370. }
  40371. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  40372. return this.materials[ materialName ];
  40373. },
  40374. getTextureParams: function ( value, matParams ) {
  40375. var texParams = {
  40376. scale: new THREE.Vector2( 1, 1 ),
  40377. offset: new THREE.Vector2( 0, 0 )
  40378. };
  40379. var items = value.split( /\s+/ );
  40380. var pos;
  40381. pos = items.indexOf( '-bm' );
  40382. if ( pos >= 0 ) {
  40383. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  40384. items.splice( pos, 2 );
  40385. }
  40386. pos = items.indexOf( '-s' );
  40387. if ( pos >= 0 ) {
  40388. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  40389. items.splice( pos, 4 ); // we expect 3 parameters here!
  40390. }
  40391. pos = items.indexOf( '-o' );
  40392. if ( pos >= 0 ) {
  40393. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  40394. items.splice( pos, 4 ); // we expect 3 parameters here!
  40395. }
  40396. texParams.url = items.join( ' ' ).trim();
  40397. return texParams;
  40398. },
  40399. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  40400. var texture;
  40401. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  40402. var loader = manager.getHandler( url );
  40403. if ( loader === null ) {
  40404. loader = new THREE.TextureLoader( manager );
  40405. }
  40406. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  40407. texture = loader.load( url, onLoad, onProgress, onError );
  40408. if ( mapping !== undefined ) texture.mapping = mapping;
  40409. return texture;
  40410. }
  40411. };
  40412. },{}],61:[function(_dereq_,module,exports){
  40413. THREE.OBJLoader = ( function () {
  40414. // o object_name | g group_name
  40415. var object_pattern = /^[og]\s*(.+)?/;
  40416. // mtllib file_reference
  40417. var material_library_pattern = /^mtllib /;
  40418. // usemtl material_name
  40419. var material_use_pattern = /^usemtl /;
  40420. // usemap map_name
  40421. var map_use_pattern = /^usemap /;
  40422. var vA = new THREE.Vector3();
  40423. var vB = new THREE.Vector3();
  40424. var vC = new THREE.Vector3();
  40425. var ab = new THREE.Vector3();
  40426. var cb = new THREE.Vector3();
  40427. function ParserState() {
  40428. var state = {
  40429. objects: [],
  40430. object: {},
  40431. vertices: [],
  40432. normals: [],
  40433. colors: [],
  40434. uvs: [],
  40435. materials: {},
  40436. materialLibraries: [],
  40437. startObject: function ( name, fromDeclaration ) {
  40438. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  40439. // file. We need to use it for the first parsed g/o to keep things in sync.
  40440. if ( this.object && this.object.fromDeclaration === false ) {
  40441. this.object.name = name;
  40442. this.object.fromDeclaration = ( fromDeclaration !== false );
  40443. return;
  40444. }
  40445. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  40446. if ( this.object && typeof this.object._finalize === 'function' ) {
  40447. this.object._finalize( true );
  40448. }
  40449. this.object = {
  40450. name: name || '',
  40451. fromDeclaration: ( fromDeclaration !== false ),
  40452. geometry: {
  40453. vertices: [],
  40454. normals: [],
  40455. colors: [],
  40456. uvs: [],
  40457. hasUVIndices: false
  40458. },
  40459. materials: [],
  40460. smooth: true,
  40461. startMaterial: function ( name, libraries ) {
  40462. var previous = this._finalize( false );
  40463. // New usemtl declaration overwrites an inherited material, except if faces were declared
  40464. // after the material, then it must be preserved for proper MultiMaterial continuation.
  40465. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  40466. this.materials.splice( previous.index, 1 );
  40467. }
  40468. var material = {
  40469. index: this.materials.length,
  40470. name: name || '',
  40471. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  40472. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  40473. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  40474. groupEnd: - 1,
  40475. groupCount: - 1,
  40476. inherited: false,
  40477. clone: function ( index ) {
  40478. var cloned = {
  40479. index: ( typeof index === 'number' ? index : this.index ),
  40480. name: this.name,
  40481. mtllib: this.mtllib,
  40482. smooth: this.smooth,
  40483. groupStart: 0,
  40484. groupEnd: - 1,
  40485. groupCount: - 1,
  40486. inherited: false
  40487. };
  40488. cloned.clone = this.clone.bind( cloned );
  40489. return cloned;
  40490. }
  40491. };
  40492. this.materials.push( material );
  40493. return material;
  40494. },
  40495. currentMaterial: function () {
  40496. if ( this.materials.length > 0 ) {
  40497. return this.materials[ this.materials.length - 1 ];
  40498. }
  40499. return undefined;
  40500. },
  40501. _finalize: function ( end ) {
  40502. var lastMultiMaterial = this.currentMaterial();
  40503. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  40504. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  40505. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  40506. lastMultiMaterial.inherited = false;
  40507. }
  40508. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  40509. if ( end && this.materials.length > 1 ) {
  40510. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  40511. if ( this.materials[ mi ].groupCount <= 0 ) {
  40512. this.materials.splice( mi, 1 );
  40513. }
  40514. }
  40515. }
  40516. // Guarantee at least one empty material, this makes the creation later more straight forward.
  40517. if ( end && this.materials.length === 0 ) {
  40518. this.materials.push( {
  40519. name: '',
  40520. smooth: this.smooth
  40521. } );
  40522. }
  40523. return lastMultiMaterial;
  40524. }
  40525. };
  40526. // Inherit previous objects material.
  40527. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  40528. // If a usemtl declaration is encountered while this new object is being parsed, it will
  40529. // overwrite the inherited material. Exception being that there was already face declarations
  40530. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  40531. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  40532. var declared = previousMaterial.clone( 0 );
  40533. declared.inherited = true;
  40534. this.object.materials.push( declared );
  40535. }
  40536. this.objects.push( this.object );
  40537. },
  40538. finalize: function () {
  40539. if ( this.object && typeof this.object._finalize === 'function' ) {
  40540. this.object._finalize( true );
  40541. }
  40542. },
  40543. parseVertexIndex: function ( value, len ) {
  40544. var index = parseInt( value, 10 );
  40545. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  40546. },
  40547. parseNormalIndex: function ( value, len ) {
  40548. var index = parseInt( value, 10 );
  40549. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  40550. },
  40551. parseUVIndex: function ( value, len ) {
  40552. var index = parseInt( value, 10 );
  40553. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  40554. },
  40555. addVertex: function ( a, b, c ) {
  40556. var src = this.vertices;
  40557. var dst = this.object.geometry.vertices;
  40558. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  40559. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  40560. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  40561. },
  40562. addVertexPoint: function ( a ) {
  40563. var src = this.vertices;
  40564. var dst = this.object.geometry.vertices;
  40565. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  40566. },
  40567. addVertexLine: function ( a ) {
  40568. var src = this.vertices;
  40569. var dst = this.object.geometry.vertices;
  40570. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  40571. },
  40572. addNormal: function ( a, b, c ) {
  40573. var src = this.normals;
  40574. var dst = this.object.geometry.normals;
  40575. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  40576. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  40577. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  40578. },
  40579. addFaceNormal: function ( a, b, c ) {
  40580. var src = this.vertices;
  40581. var dst = this.object.geometry.normals;
  40582. vA.fromArray( src, a );
  40583. vB.fromArray( src, b );
  40584. vC.fromArray( src, c );
  40585. cb.subVectors( vC, vB );
  40586. ab.subVectors( vA, vB );
  40587. cb.cross( ab );
  40588. cb.normalize();
  40589. dst.push( cb.x, cb.y, cb.z );
  40590. dst.push( cb.x, cb.y, cb.z );
  40591. dst.push( cb.x, cb.y, cb.z );
  40592. },
  40593. addColor: function ( a, b, c ) {
  40594. var src = this.colors;
  40595. var dst = this.object.geometry.colors;
  40596. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  40597. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  40598. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  40599. },
  40600. addUV: function ( a, b, c ) {
  40601. var src = this.uvs;
  40602. var dst = this.object.geometry.uvs;
  40603. dst.push( src[ a + 0 ], src[ a + 1 ] );
  40604. dst.push( src[ b + 0 ], src[ b + 1 ] );
  40605. dst.push( src[ c + 0 ], src[ c + 1 ] );
  40606. },
  40607. addDefaultUV: function () {
  40608. var dst = this.object.geometry.uvs;
  40609. dst.push( 0, 0 );
  40610. dst.push( 0, 0 );
  40611. dst.push( 0, 0 );
  40612. },
  40613. addUVLine: function ( a ) {
  40614. var src = this.uvs;
  40615. var dst = this.object.geometry.uvs;
  40616. dst.push( src[ a + 0 ], src[ a + 1 ] );
  40617. },
  40618. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  40619. var vLen = this.vertices.length;
  40620. var ia = this.parseVertexIndex( a, vLen );
  40621. var ib = this.parseVertexIndex( b, vLen );
  40622. var ic = this.parseVertexIndex( c, vLen );
  40623. this.addVertex( ia, ib, ic );
  40624. this.addColor( ia, ib, ic );
  40625. // normals
  40626. if ( na !== undefined && na !== '' ) {
  40627. var nLen = this.normals.length;
  40628. ia = this.parseNormalIndex( na, nLen );
  40629. ib = this.parseNormalIndex( nb, nLen );
  40630. ic = this.parseNormalIndex( nc, nLen );
  40631. this.addNormal( ia, ib, ic );
  40632. } else {
  40633. this.addFaceNormal( ia, ib, ic );
  40634. }
  40635. // uvs
  40636. if ( ua !== undefined && ua !== '' ) {
  40637. var uvLen = this.uvs.length;
  40638. ia = this.parseUVIndex( ua, uvLen );
  40639. ib = this.parseUVIndex( ub, uvLen );
  40640. ic = this.parseUVIndex( uc, uvLen );
  40641. this.addUV( ia, ib, ic );
  40642. this.object.geometry.hasUVIndices = true;
  40643. } else {
  40644. // add placeholder values (for inconsistent face definitions)
  40645. this.addDefaultUV();
  40646. }
  40647. },
  40648. addPointGeometry: function ( vertices ) {
  40649. this.object.geometry.type = 'Points';
  40650. var vLen = this.vertices.length;
  40651. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  40652. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  40653. this.addVertexPoint( index );
  40654. this.addColor( index );
  40655. }
  40656. },
  40657. addLineGeometry: function ( vertices, uvs ) {
  40658. this.object.geometry.type = 'Line';
  40659. var vLen = this.vertices.length;
  40660. var uvLen = this.uvs.length;
  40661. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  40662. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  40663. }
  40664. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  40665. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  40666. }
  40667. }
  40668. };
  40669. state.startObject( '', false );
  40670. return state;
  40671. }
  40672. //
  40673. function OBJLoader( manager ) {
  40674. THREE.Loader.call( this, manager );
  40675. this.materials = null;
  40676. }
  40677. OBJLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  40678. constructor: OBJLoader,
  40679. load: function ( url, onLoad, onProgress, onError ) {
  40680. var scope = this;
  40681. var loader = new THREE.FileLoader( this.manager );
  40682. loader.setPath( this.path );
  40683. loader.setRequestHeader( this.requestHeader );
  40684. loader.setWithCredentials( this.withCredentials );
  40685. loader.load( url, function ( text ) {
  40686. try {
  40687. onLoad( scope.parse( text ) );
  40688. } catch ( e ) {
  40689. if ( onError ) {
  40690. onError( e );
  40691. } else {
  40692. console.error( e );
  40693. }
  40694. scope.manager.itemError( url );
  40695. }
  40696. }, onProgress, onError );
  40697. },
  40698. setMaterials: function ( materials ) {
  40699. this.materials = materials;
  40700. return this;
  40701. },
  40702. parse: function ( text ) {
  40703. var state = new ParserState();
  40704. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  40705. // This is faster than String.split with regex that splits on both
  40706. text = text.replace( /\r\n/g, '\n' );
  40707. }
  40708. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  40709. // join lines separated by a line continuation character (\)
  40710. text = text.replace( /\\\n/g, '' );
  40711. }
  40712. var lines = text.split( '\n' );
  40713. var line = '', lineFirstChar = '';
  40714. var lineLength = 0;
  40715. var result = [];
  40716. // Faster to just trim left side of the line. Use if available.
  40717. var trimLeft = ( typeof ''.trimLeft === 'function' );
  40718. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  40719. line = lines[ i ];
  40720. line = trimLeft ? line.trimLeft() : line.trim();
  40721. lineLength = line.length;
  40722. if ( lineLength === 0 ) continue;
  40723. lineFirstChar = line.charAt( 0 );
  40724. // @todo invoke passed in handler if any
  40725. if ( lineFirstChar === '#' ) continue;
  40726. if ( lineFirstChar === 'v' ) {
  40727. var data = line.split( /\s+/ );
  40728. switch ( data[ 0 ] ) {
  40729. case 'v':
  40730. state.vertices.push(
  40731. parseFloat( data[ 1 ] ),
  40732. parseFloat( data[ 2 ] ),
  40733. parseFloat( data[ 3 ] )
  40734. );
  40735. if ( data.length >= 7 ) {
  40736. state.colors.push(
  40737. parseFloat( data[ 4 ] ),
  40738. parseFloat( data[ 5 ] ),
  40739. parseFloat( data[ 6 ] )
  40740. );
  40741. } else {
  40742. // if no colors are defined, add placeholders so color and vertex indices match
  40743. state.colors.push( undefined, undefined, undefined );
  40744. }
  40745. break;
  40746. case 'vn':
  40747. state.normals.push(
  40748. parseFloat( data[ 1 ] ),
  40749. parseFloat( data[ 2 ] ),
  40750. parseFloat( data[ 3 ] )
  40751. );
  40752. break;
  40753. case 'vt':
  40754. state.uvs.push(
  40755. parseFloat( data[ 1 ] ),
  40756. parseFloat( data[ 2 ] )
  40757. );
  40758. break;
  40759. }
  40760. } else if ( lineFirstChar === 'f' ) {
  40761. var lineData = line.substr( 1 ).trim();
  40762. var vertexData = lineData.split( /\s+/ );
  40763. var faceVertices = [];
  40764. // Parse the face vertex data into an easy to work with format
  40765. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  40766. var vertex = vertexData[ j ];
  40767. if ( vertex.length > 0 ) {
  40768. var vertexParts = vertex.split( '/' );
  40769. faceVertices.push( vertexParts );
  40770. }
  40771. }
  40772. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  40773. var v1 = faceVertices[ 0 ];
  40774. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  40775. var v2 = faceVertices[ j ];
  40776. var v3 = faceVertices[ j + 1 ];
  40777. state.addFace(
  40778. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  40779. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  40780. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  40781. );
  40782. }
  40783. } else if ( lineFirstChar === 'l' ) {
  40784. var lineParts = line.substring( 1 ).trim().split( " " );
  40785. var lineVertices = [], lineUVs = [];
  40786. if ( line.indexOf( "/" ) === - 1 ) {
  40787. lineVertices = lineParts;
  40788. } else {
  40789. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  40790. var parts = lineParts[ li ].split( "/" );
  40791. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  40792. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  40793. }
  40794. }
  40795. state.addLineGeometry( lineVertices, lineUVs );
  40796. } else if ( lineFirstChar === 'p' ) {
  40797. var lineData = line.substr( 1 ).trim();
  40798. var pointData = lineData.split( " " );
  40799. state.addPointGeometry( pointData );
  40800. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  40801. // o object_name
  40802. // or
  40803. // g group_name
  40804. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  40805. // var name = result[ 0 ].substr( 1 ).trim();
  40806. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  40807. state.startObject( name );
  40808. } else if ( material_use_pattern.test( line ) ) {
  40809. // material
  40810. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  40811. } else if ( material_library_pattern.test( line ) ) {
  40812. // mtl file
  40813. state.materialLibraries.push( line.substring( 7 ).trim() );
  40814. } else if ( map_use_pattern.test( line ) ) {
  40815. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  40816. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  40817. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  40818. } else if ( lineFirstChar === 's' ) {
  40819. result = line.split( ' ' );
  40820. // smooth shading
  40821. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  40822. // but does not define a usemtl for each face set.
  40823. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  40824. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  40825. // where explicit usemtl defines geometry groups.
  40826. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  40827. /*
  40828. * http://paulbourke.net/dataformats/obj/
  40829. * or
  40830. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  40831. *
  40832. * From chapter "Grouping" Syntax explanation "s group_number":
  40833. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  40834. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  40835. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  40836. * than 0."
  40837. */
  40838. if ( result.length > 1 ) {
  40839. var value = result[ 1 ].trim().toLowerCase();
  40840. state.object.smooth = ( value !== '0' && value !== 'off' );
  40841. } else {
  40842. // ZBrush can produce "s" lines #11707
  40843. state.object.smooth = true;
  40844. }
  40845. var material = state.object.currentMaterial();
  40846. if ( material ) material.smooth = state.object.smooth;
  40847. } else {
  40848. // Handle null terminated files without exception
  40849. if ( line === '\0' ) continue;
  40850. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  40851. }
  40852. }
  40853. state.finalize();
  40854. var container = new THREE.Group();
  40855. container.materialLibraries = [].concat( state.materialLibraries );
  40856. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  40857. if ( hasPrimitives === true ) {
  40858. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  40859. var object = state.objects[ i ];
  40860. var geometry = object.geometry;
  40861. var materials = object.materials;
  40862. var isLine = ( geometry.type === 'Line' );
  40863. var isPoints = ( geometry.type === 'Points' );
  40864. var hasVertexColors = false;
  40865. // Skip o/g line declarations that did not follow with any faces
  40866. if ( geometry.vertices.length === 0 ) continue;
  40867. var buffergeometry = new THREE.BufferGeometry();
  40868. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  40869. if ( geometry.normals.length > 0 ) {
  40870. buffergeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  40871. }
  40872. if ( geometry.colors.length > 0 ) {
  40873. hasVertexColors = true;
  40874. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  40875. }
  40876. if ( geometry.hasUVIndices === true ) {
  40877. buffergeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  40878. }
  40879. // Create materials
  40880. var createdMaterials = [];
  40881. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  40882. var sourceMaterial = materials[ mi ];
  40883. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  40884. var material = state.materials[ materialHash ];
  40885. if ( this.materials !== null ) {
  40886. material = this.materials.create( sourceMaterial.name );
  40887. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  40888. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  40889. var materialLine = new THREE.LineBasicMaterial();
  40890. THREE.Material.prototype.copy.call( materialLine, material );
  40891. materialLine.color.copy( material.color );
  40892. material = materialLine;
  40893. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  40894. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  40895. THREE.Material.prototype.copy.call( materialPoints, material );
  40896. materialPoints.color.copy( material.color );
  40897. materialPoints.map = material.map;
  40898. material = materialPoints;
  40899. }
  40900. }
  40901. if ( material === undefined ) {
  40902. if ( isLine ) {
  40903. material = new THREE.LineBasicMaterial();
  40904. } else if ( isPoints ) {
  40905. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  40906. } else {
  40907. material = new THREE.MeshPhongMaterial();
  40908. }
  40909. material.name = sourceMaterial.name;
  40910. material.flatShading = sourceMaterial.smooth ? false : true;
  40911. material.vertexColors = hasVertexColors;
  40912. state.materials[ materialHash ] = material;
  40913. }
  40914. createdMaterials.push( material );
  40915. }
  40916. // Create mesh
  40917. var mesh;
  40918. if ( createdMaterials.length > 1 ) {
  40919. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  40920. var sourceMaterial = materials[ mi ];
  40921. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  40922. }
  40923. if ( isLine ) {
  40924. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  40925. } else if ( isPoints ) {
  40926. mesh = new THREE.Points( buffergeometry, createdMaterials );
  40927. } else {
  40928. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  40929. }
  40930. } else {
  40931. if ( isLine ) {
  40932. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  40933. } else if ( isPoints ) {
  40934. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  40935. } else {
  40936. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  40937. }
  40938. }
  40939. mesh.name = object.name;
  40940. container.add( mesh );
  40941. }
  40942. } else {
  40943. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  40944. if ( state.vertices.length > 0 ) {
  40945. var material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  40946. var buffergeometry = new THREE.BufferGeometry();
  40947. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( state.vertices, 3 ) );
  40948. if ( state.colors.length > 0 ) {
  40949. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( state.colors, 3 ) );
  40950. material.vertexColors = true;
  40951. }
  40952. var points = new THREE.Points( buffergeometry, material );
  40953. container.add( points );
  40954. }
  40955. }
  40956. return container;
  40957. }
  40958. } );
  40959. return OBJLoader;
  40960. } )();
  40961. },{}],62:[function(_dereq_,module,exports){
  40962. var createLayout = _dereq_('layout-bmfont-text')
  40963. var inherits = _dereq_('inherits')
  40964. var createIndices = _dereq_('quad-indices')
  40965. var buffer = _dereq_('three-buffer-vertex-data')
  40966. var assign = _dereq_('object-assign')
  40967. var vertices = _dereq_('./lib/vertices')
  40968. var utils = _dereq_('./lib/utils')
  40969. var Base = THREE.BufferGeometry
  40970. module.exports = function createTextGeometry (opt) {
  40971. return new TextGeometry(opt)
  40972. }
  40973. function TextGeometry (opt) {
  40974. Base.call(this)
  40975. if (typeof opt === 'string') {
  40976. opt = { text: opt }
  40977. }
  40978. // use these as default values for any subsequent
  40979. // calls to update()
  40980. this._opt = assign({}, opt)
  40981. // also do an initial setup...
  40982. if (opt) this.update(opt)
  40983. }
  40984. inherits(TextGeometry, Base)
  40985. TextGeometry.prototype.update = function (opt) {
  40986. if (typeof opt === 'string') {
  40987. opt = { text: opt }
  40988. }
  40989. // use constructor defaults
  40990. opt = assign({}, this._opt, opt)
  40991. if (!opt.font) {
  40992. throw new TypeError('must specify a { font } in options')
  40993. }
  40994. this.layout = createLayout(opt)
  40995. // get vec2 texcoords
  40996. var flipY = opt.flipY !== false
  40997. // the desired BMFont data
  40998. var font = opt.font
  40999. // determine texture size from font file
  41000. var texWidth = font.common.scaleW
  41001. var texHeight = font.common.scaleH
  41002. // get visible glyphs
  41003. var glyphs = this.layout.glyphs.filter(function (glyph) {
  41004. var bitmap = glyph.data
  41005. return bitmap.width * bitmap.height > 0
  41006. })
  41007. // provide visible glyphs for convenience
  41008. this.visibleGlyphs = glyphs
  41009. // get common vertex data
  41010. var positions = vertices.positions(glyphs)
  41011. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  41012. var indices = createIndices({
  41013. clockwise: true,
  41014. type: 'uint16',
  41015. count: glyphs.length
  41016. })
  41017. // update vertex data
  41018. buffer.index(this, indices, 1, 'uint16')
  41019. buffer.attr(this, 'position', positions, 2)
  41020. buffer.attr(this, 'uv', uvs, 2)
  41021. // update multipage data
  41022. if (!opt.multipage && 'page' in this.attributes) {
  41023. // disable multipage rendering
  41024. this.removeAttribute('page')
  41025. } else if (opt.multipage) {
  41026. var pages = vertices.pages(glyphs)
  41027. // enable multipage rendering
  41028. buffer.attr(this, 'page', pages, 1)
  41029. }
  41030. }
  41031. TextGeometry.prototype.computeBoundingSphere = function () {
  41032. if (this.boundingSphere === null) {
  41033. this.boundingSphere = new THREE.Sphere()
  41034. }
  41035. var positions = this.attributes.position.array
  41036. var itemSize = this.attributes.position.itemSize
  41037. if (!positions || !itemSize || positions.length < 2) {
  41038. this.boundingSphere.radius = 0
  41039. this.boundingSphere.center.set(0, 0, 0)
  41040. return
  41041. }
  41042. utils.computeSphere(positions, this.boundingSphere)
  41043. if (isNaN(this.boundingSphere.radius)) {
  41044. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  41045. 'Computed radius is NaN. The ' +
  41046. '"position" attribute is likely to have NaN values.')
  41047. }
  41048. }
  41049. TextGeometry.prototype.computeBoundingBox = function () {
  41050. if (this.boundingBox === null) {
  41051. this.boundingBox = new THREE.Box3()
  41052. }
  41053. var bbox = this.boundingBox
  41054. var positions = this.attributes.position.array
  41055. var itemSize = this.attributes.position.itemSize
  41056. if (!positions || !itemSize || positions.length < 2) {
  41057. bbox.makeEmpty()
  41058. return
  41059. }
  41060. utils.computeBox(positions, bbox)
  41061. }
  41062. },{"./lib/utils":63,"./lib/vertices":64,"inherits":30,"layout-bmfont-text":36,"object-assign":39,"quad-indices":51,"three-buffer-vertex-data":65}],63:[function(_dereq_,module,exports){
  41063. var itemSize = 2
  41064. var box = { min: [0, 0], max: [0, 0] }
  41065. function bounds (positions) {
  41066. var count = positions.length / itemSize
  41067. box.min[0] = positions[0]
  41068. box.min[1] = positions[1]
  41069. box.max[0] = positions[0]
  41070. box.max[1] = positions[1]
  41071. for (var i = 0; i < count; i++) {
  41072. var x = positions[i * itemSize + 0]
  41073. var y = positions[i * itemSize + 1]
  41074. box.min[0] = Math.min(x, box.min[0])
  41075. box.min[1] = Math.min(y, box.min[1])
  41076. box.max[0] = Math.max(x, box.max[0])
  41077. box.max[1] = Math.max(y, box.max[1])
  41078. }
  41079. }
  41080. module.exports.computeBox = function (positions, output) {
  41081. bounds(positions)
  41082. output.min.set(box.min[0], box.min[1], 0)
  41083. output.max.set(box.max[0], box.max[1], 0)
  41084. }
  41085. module.exports.computeSphere = function (positions, output) {
  41086. bounds(positions)
  41087. var minX = box.min[0]
  41088. var minY = box.min[1]
  41089. var maxX = box.max[0]
  41090. var maxY = box.max[1]
  41091. var width = maxX - minX
  41092. var height = maxY - minY
  41093. var length = Math.sqrt(width * width + height * height)
  41094. output.center.set(minX + width / 2, minY + height / 2, 0)
  41095. output.radius = length / 2
  41096. }
  41097. },{}],64:[function(_dereq_,module,exports){
  41098. module.exports.pages = function pages (glyphs) {
  41099. var pages = new Float32Array(glyphs.length * 4 * 1)
  41100. var i = 0
  41101. glyphs.forEach(function (glyph) {
  41102. var id = glyph.data.page || 0
  41103. pages[i++] = id
  41104. pages[i++] = id
  41105. pages[i++] = id
  41106. pages[i++] = id
  41107. })
  41108. return pages
  41109. }
  41110. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  41111. var uvs = new Float32Array(glyphs.length * 4 * 2)
  41112. var i = 0
  41113. glyphs.forEach(function (glyph) {
  41114. var bitmap = glyph.data
  41115. var bw = (bitmap.x + bitmap.width)
  41116. var bh = (bitmap.y + bitmap.height)
  41117. // top left position
  41118. var u0 = bitmap.x / texWidth
  41119. var v1 = bitmap.y / texHeight
  41120. var u1 = bw / texWidth
  41121. var v0 = bh / texHeight
  41122. if (flipY) {
  41123. v1 = (texHeight - bitmap.y) / texHeight
  41124. v0 = (texHeight - bh) / texHeight
  41125. }
  41126. // BL
  41127. uvs[i++] = u0
  41128. uvs[i++] = v1
  41129. // TL
  41130. uvs[i++] = u0
  41131. uvs[i++] = v0
  41132. // TR
  41133. uvs[i++] = u1
  41134. uvs[i++] = v0
  41135. // BR
  41136. uvs[i++] = u1
  41137. uvs[i++] = v1
  41138. })
  41139. return uvs
  41140. }
  41141. module.exports.positions = function positions (glyphs) {
  41142. var positions = new Float32Array(glyphs.length * 4 * 2)
  41143. var i = 0
  41144. glyphs.forEach(function (glyph) {
  41145. var bitmap = glyph.data
  41146. // bottom left position
  41147. var x = glyph.position[0] + bitmap.xoffset
  41148. var y = glyph.position[1] + bitmap.yoffset
  41149. // quad size
  41150. var w = bitmap.width
  41151. var h = bitmap.height
  41152. // BL
  41153. positions[i++] = x
  41154. positions[i++] = y
  41155. // TL
  41156. positions[i++] = x
  41157. positions[i++] = y + h
  41158. // TR
  41159. positions[i++] = x + w
  41160. positions[i++] = y + h
  41161. // BR
  41162. positions[i++] = x + w
  41163. positions[i++] = y
  41164. })
  41165. return positions
  41166. }
  41167. },{}],65:[function(_dereq_,module,exports){
  41168. var flatten = _dereq_('flatten-vertex-data')
  41169. var warned = false;
  41170. module.exports.attr = setAttribute
  41171. module.exports.index = setIndex
  41172. function setIndex (geometry, data, itemSize, dtype) {
  41173. if (typeof itemSize !== 'number') itemSize = 1
  41174. if (typeof dtype !== 'string') dtype = 'uint16'
  41175. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  41176. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  41177. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  41178. if (newAttrib) {
  41179. if (isR69) geometry.addAttribute('index', newAttrib)
  41180. else geometry.index = newAttrib
  41181. }
  41182. }
  41183. function setAttribute (geometry, key, data, itemSize, dtype) {
  41184. if (typeof itemSize !== 'number') itemSize = 3
  41185. if (typeof dtype !== 'string') dtype = 'float32'
  41186. if (Array.isArray(data) &&
  41187. Array.isArray(data[0]) &&
  41188. data[0].length !== itemSize) {
  41189. throw new Error('Nested vertex array has unexpected size; expected ' +
  41190. itemSize + ' but found ' + data[0].length)
  41191. }
  41192. var attrib = geometry.getAttribute(key)
  41193. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  41194. geometry.setAttribute(key, newAttrib)
  41195. }
  41196. function updateAttribute (attrib, data, itemSize, dtype) {
  41197. data = data || []
  41198. // create a new array with desired type
  41199. data = flatten(data, dtype)
  41200. attrib = new THREE.BufferAttribute(data, itemSize);
  41201. attrib.itemSize = itemSize;
  41202. attrib.needsUpdate = true;
  41203. return attrib
  41204. }
  41205. // Test whether the attribute needs to be re-created,
  41206. // returns false if we can re-use it as-is.
  41207. function rebuildAttribute (attrib, data, itemSize) {
  41208. if (attrib.itemSize !== itemSize) return true
  41209. if (!attrib.array) return true
  41210. var attribLength = attrib.array.length
  41211. if (Array.isArray(data) && Array.isArray(data[0])) {
  41212. // [ [ x, y, z ] ]
  41213. return attribLength !== data.length * itemSize
  41214. } else {
  41215. // [ x, y, z ]
  41216. return attribLength !== data.length
  41217. }
  41218. return false
  41219. }
  41220. },{"flatten-vertex-data":23}],66:[function(_dereq_,module,exports){
  41221. (function (setImmediate,clearImmediate){
  41222. var nextTick = _dereq_('process/browser.js').nextTick;
  41223. var apply = Function.prototype.apply;
  41224. var slice = Array.prototype.slice;
  41225. var immediateIds = {};
  41226. var nextImmediateId = 0;
  41227. // DOM APIs, for completeness
  41228. exports.setTimeout = function() {
  41229. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  41230. };
  41231. exports.setInterval = function() {
  41232. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  41233. };
  41234. exports.clearTimeout =
  41235. exports.clearInterval = function(timeout) { timeout.close(); };
  41236. function Timeout(id, clearFn) {
  41237. this._id = id;
  41238. this._clearFn = clearFn;
  41239. }
  41240. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  41241. Timeout.prototype.close = function() {
  41242. this._clearFn.call(window, this._id);
  41243. };
  41244. // Does not start the time, just sets up the members needed.
  41245. exports.enroll = function(item, msecs) {
  41246. clearTimeout(item._idleTimeoutId);
  41247. item._idleTimeout = msecs;
  41248. };
  41249. exports.unenroll = function(item) {
  41250. clearTimeout(item._idleTimeoutId);
  41251. item._idleTimeout = -1;
  41252. };
  41253. exports._unrefActive = exports.active = function(item) {
  41254. clearTimeout(item._idleTimeoutId);
  41255. var msecs = item._idleTimeout;
  41256. if (msecs >= 0) {
  41257. item._idleTimeoutId = setTimeout(function onTimeout() {
  41258. if (item._onTimeout)
  41259. item._onTimeout();
  41260. }, msecs);
  41261. }
  41262. };
  41263. // That's not how node.js implements it but the exposed api is the same.
  41264. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  41265. var id = nextImmediateId++;
  41266. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  41267. immediateIds[id] = true;
  41268. nextTick(function onNextTick() {
  41269. if (immediateIds[id]) {
  41270. // fn.call() is faster so we optimize for the common use-case
  41271. // @see http://jsperf.com/call-apply-segu
  41272. if (args) {
  41273. fn.apply(null, args);
  41274. } else {
  41275. fn.call(null);
  41276. }
  41277. // Prevent ids from leaking
  41278. exports.clearImmediate(id);
  41279. }
  41280. });
  41281. return id;
  41282. };
  41283. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  41284. delete immediateIds[id];
  41285. };
  41286. }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  41287. },{"process/browser.js":49,"timers":66}],67:[function(_dereq_,module,exports){
  41288. (function (global){
  41289. /**
  41290. * @license
  41291. * webvr-polyfill
  41292. * Copyright (c) 2015-2017 Google
  41293. * Licensed under the Apache License, Version 2.0 (the "License");
  41294. * you may not use this file except in compliance with the License.
  41295. * You may obtain a copy of the License at
  41296. *
  41297. * http://www.apache.org/licenses/LICENSE-2.0
  41298. *
  41299. * Unless required by applicable law or agreed to in writing, software
  41300. * distributed under the License is distributed on an "AS IS" BASIS,
  41301. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41302. * See the License for the specific language governing permissions and
  41303. * limitations under the License.
  41304. */
  41305. /**
  41306. * @license
  41307. * cardboard-vr-display
  41308. * Copyright (c) 2015-2017 Google
  41309. * Licensed under the Apache License, Version 2.0 (the "License");
  41310. * you may not use this file except in compliance with the License.
  41311. * You may obtain a copy of the License at
  41312. *
  41313. * http://www.apache.org/licenses/LICENSE-2.0
  41314. *
  41315. * Unless required by applicable law or agreed to in writing, software
  41316. * distributed under the License is distributed on an "AS IS" BASIS,
  41317. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41318. * See the License for the specific language governing permissions and
  41319. * limitations under the License.
  41320. */
  41321. /**
  41322. * @license
  41323. * webvr-polyfill-dpdb
  41324. * Copyright (c) 2017 Google
  41325. * Licensed under the Apache License, Version 2.0 (the "License");
  41326. * you may not use this file except in compliance with the License.
  41327. * You may obtain a copy of the License at
  41328. *
  41329. * http://www.apache.org/licenses/LICENSE-2.0
  41330. *
  41331. * Unless required by applicable law or agreed to in writing, software
  41332. * distributed under the License is distributed on an "AS IS" BASIS,
  41333. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41334. * See the License for the specific language governing permissions and
  41335. * limitations under the License.
  41336. */
  41337. /**
  41338. * @license
  41339. * wglu-preserve-state
  41340. * Copyright (c) 2016, Brandon Jones.
  41341. *
  41342. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41343. * of this software and associated documentation files (the "Software"), to deal
  41344. * in the Software without restriction, including without limitation the rights
  41345. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41346. * copies of the Software, and to permit persons to whom the Software is
  41347. * furnished to do so, subject to the following conditions:
  41348. *
  41349. * The above copyright notice and this permission notice shall be included in
  41350. * all copies or substantial portions of the Software.
  41351. *
  41352. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41353. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41354. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41355. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41356. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41357. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41358. * THE SOFTWARE.
  41359. */
  41360. /**
  41361. * @license
  41362. * nosleep.js
  41363. * Copyright (c) 2017, Rich Tibbett
  41364. *
  41365. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41366. * of this software and associated documentation files (the "Software"), to deal
  41367. * in the Software without restriction, including without limitation the rights
  41368. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41369. * copies of the Software, and to permit persons to whom the Software is
  41370. * furnished to do so, subject to the following conditions:
  41371. *
  41372. * The above copyright notice and this permission notice shall be included in
  41373. * all copies or substantial portions of the Software.
  41374. *
  41375. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41376. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41377. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41378. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41379. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41380. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41381. * THE SOFTWARE.
  41382. */
  41383. (function (global, factory) {
  41384. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  41385. typeof define === 'function' && define.amd ? define(factory) :
  41386. (global.WebVRPolyfill = factory());
  41387. }(this, (function () { 'use strict';
  41388. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  41389. function unwrapExports (x) {
  41390. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  41391. }
  41392. function createCommonjsModule(fn, module) {
  41393. return module = { exports: {} }, fn(module, module.exports), module.exports;
  41394. }
  41395. var isMobile = function isMobile() {
  41396. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  41397. );
  41398. };
  41399. var copyArray = function copyArray(source, dest) {
  41400. for (var i = 0, n = source.length; i < n; i++) {
  41401. dest[i] = source[i];
  41402. }
  41403. };
  41404. var extend = function extend(dest, src) {
  41405. for (var key in src) {
  41406. if (src.hasOwnProperty(key)) {
  41407. dest[key] = src[key];
  41408. }
  41409. }
  41410. return dest;
  41411. };
  41412. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  41413. /**
  41414. * @license
  41415. * cardboard-vr-display
  41416. * Copyright (c) 2015-2017 Google
  41417. * Licensed under the Apache License, Version 2.0 (the "License");
  41418. * you may not use this file except in compliance with the License.
  41419. * You may obtain a copy of the License at
  41420. *
  41421. * http://www.apache.org/licenses/LICENSE-2.0
  41422. *
  41423. * Unless required by applicable law or agreed to in writing, software
  41424. * distributed under the License is distributed on an "AS IS" BASIS,
  41425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41426. * See the License for the specific language governing permissions and
  41427. * limitations under the License.
  41428. */
  41429. /**
  41430. * @license
  41431. * gl-preserve-state
  41432. * Copyright (c) 2016, Brandon Jones.
  41433. *
  41434. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41435. * of this software and associated documentation files (the "Software"), to deal
  41436. * in the Software without restriction, including without limitation the rights
  41437. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41438. * copies of the Software, and to permit persons to whom the Software is
  41439. * furnished to do so, subject to the following conditions:
  41440. *
  41441. * The above copyright notice and this permission notice shall be included in
  41442. * all copies or substantial portions of the Software.
  41443. *
  41444. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41445. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41446. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41447. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41448. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41449. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41450. * THE SOFTWARE.
  41451. */
  41452. /**
  41453. * @license
  41454. * webvr-polyfill-dpdb
  41455. * Copyright (c) 2015-2017 Google
  41456. * Licensed under the Apache License, Version 2.0 (the "License");
  41457. * you may not use this file except in compliance with the License.
  41458. * You may obtain a copy of the License at
  41459. *
  41460. * http://www.apache.org/licenses/LICENSE-2.0
  41461. *
  41462. * Unless required by applicable law or agreed to in writing, software
  41463. * distributed under the License is distributed on an "AS IS" BASIS,
  41464. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41465. * See the License for the specific language governing permissions and
  41466. * limitations under the License.
  41467. */
  41468. /**
  41469. * @license
  41470. * nosleep.js
  41471. * Copyright (c) 2017, Rich Tibbett
  41472. *
  41473. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41474. * of this software and associated documentation files (the "Software"), to deal
  41475. * in the Software without restriction, including without limitation the rights
  41476. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41477. * copies of the Software, and to permit persons to whom the Software is
  41478. * furnished to do so, subject to the following conditions:
  41479. *
  41480. * The above copyright notice and this permission notice shall be included in
  41481. * all copies or substantial portions of the Software.
  41482. *
  41483. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41484. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41485. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41486. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41487. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41488. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41489. * THE SOFTWARE.
  41490. */
  41491. (function (global, factory) {
  41492. module.exports = factory();
  41493. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  41494. if (!(instance instanceof Constructor)) {
  41495. throw new TypeError("Cannot call a class as a function");
  41496. }
  41497. };
  41498. var createClass = function () {
  41499. function defineProperties(target, props) {
  41500. for (var i = 0; i < props.length; i++) {
  41501. var descriptor = props[i];
  41502. descriptor.enumerable = descriptor.enumerable || false;
  41503. descriptor.configurable = true;
  41504. if ("value" in descriptor) descriptor.writable = true;
  41505. Object.defineProperty(target, descriptor.key, descriptor);
  41506. }
  41507. }
  41508. return function (Constructor, protoProps, staticProps) {
  41509. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  41510. if (staticProps) defineProperties(Constructor, staticProps);
  41511. return Constructor;
  41512. };
  41513. }();
  41514. var slicedToArray = function () {
  41515. function sliceIterator(arr, i) {
  41516. var _arr = [];
  41517. var _n = true;
  41518. var _d = false;
  41519. var _e = undefined;
  41520. try {
  41521. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  41522. _arr.push(_s.value);
  41523. if (i && _arr.length === i) break;
  41524. }
  41525. } catch (err) {
  41526. _d = true;
  41527. _e = err;
  41528. } finally {
  41529. try {
  41530. if (!_n && _i["return"]) _i["return"]();
  41531. } finally {
  41532. if (_d) throw _e;
  41533. }
  41534. }
  41535. return _arr;
  41536. }
  41537. return function (arr, i) {
  41538. if (Array.isArray(arr)) {
  41539. return arr;
  41540. } else if (Symbol.iterator in Object(arr)) {
  41541. return sliceIterator(arr, i);
  41542. } else {
  41543. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  41544. }
  41545. };
  41546. }();
  41547. var MIN_TIMESTEP = 0.001;
  41548. var MAX_TIMESTEP = 1;
  41549. var dataUri = function dataUri(mimeType, svg) {
  41550. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  41551. };
  41552. var lerp = function lerp(a, b, t) {
  41553. return a + (b - a) * t;
  41554. };
  41555. var isIOS = function () {
  41556. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  41557. return function () {
  41558. return isIOS;
  41559. };
  41560. }();
  41561. var isWebViewAndroid = function () {
  41562. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  41563. return function () {
  41564. return isWebViewAndroid;
  41565. };
  41566. }();
  41567. var isSafari = function () {
  41568. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  41569. return function () {
  41570. return isSafari;
  41571. };
  41572. }();
  41573. var isFirefoxAndroid = function () {
  41574. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  41575. return function () {
  41576. return isFirefoxAndroid;
  41577. };
  41578. }();
  41579. var getChromeVersion = function () {
  41580. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  41581. var value = match ? parseInt(match[1], 10) : null;
  41582. return function () {
  41583. return value;
  41584. };
  41585. }();
  41586. var isSafariWithoutDeviceMotion = function () {
  41587. var value = false;
  41588. value = isIOS() && isSafari() && navigator.userAgent.indexOf('13_4') !== -1;
  41589. return function () {
  41590. return value;
  41591. };
  41592. }();
  41593. var isChromeWithoutDeviceMotion = function () {
  41594. var value = false;
  41595. if (getChromeVersion() === 65) {
  41596. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  41597. if (match) {
  41598. var _match$1$split = match[1].split('.'),
  41599. _match$1$split2 = slicedToArray(_match$1$split, 4),
  41600. major = _match$1$split2[0],
  41601. minor = _match$1$split2[1],
  41602. branch = _match$1$split2[2],
  41603. build = _match$1$split2[3];
  41604. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  41605. }
  41606. }
  41607. return function () {
  41608. return value;
  41609. };
  41610. }();
  41611. var isR7 = function () {
  41612. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  41613. return function () {
  41614. return isR7;
  41615. };
  41616. }();
  41617. var isLandscapeMode = function isLandscapeMode() {
  41618. var rtn = window.orientation == 90 || window.orientation == -90;
  41619. return isR7() ? !rtn : rtn;
  41620. };
  41621. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  41622. if (isNaN(timestampDeltaS)) {
  41623. return false;
  41624. }
  41625. if (timestampDeltaS <= MIN_TIMESTEP) {
  41626. return false;
  41627. }
  41628. if (timestampDeltaS > MAX_TIMESTEP) {
  41629. return false;
  41630. }
  41631. return true;
  41632. };
  41633. var getScreenWidth = function getScreenWidth() {
  41634. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  41635. };
  41636. var getScreenHeight = function getScreenHeight() {
  41637. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  41638. };
  41639. var requestFullscreen = function requestFullscreen(element) {
  41640. if (isWebViewAndroid()) {
  41641. return false;
  41642. }
  41643. if (element.requestFullscreen) {
  41644. element.requestFullscreen();
  41645. } else if (element.webkitRequestFullscreen) {
  41646. element.webkitRequestFullscreen();
  41647. } else if (element.mozRequestFullScreen) {
  41648. element.mozRequestFullScreen();
  41649. } else if (element.msRequestFullscreen) {
  41650. element.msRequestFullscreen();
  41651. } else {
  41652. return false;
  41653. }
  41654. return true;
  41655. };
  41656. var exitFullscreen = function exitFullscreen() {
  41657. if (document.exitFullscreen) {
  41658. document.exitFullscreen();
  41659. } else if (document.webkitExitFullscreen) {
  41660. document.webkitExitFullscreen();
  41661. } else if (document.mozCancelFullScreen) {
  41662. document.mozCancelFullScreen();
  41663. } else if (document.msExitFullscreen) {
  41664. document.msExitFullscreen();
  41665. } else {
  41666. return false;
  41667. }
  41668. return true;
  41669. };
  41670. var getFullscreenElement = function getFullscreenElement() {
  41671. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  41672. };
  41673. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  41674. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  41675. gl.shaderSource(vertexShader, vertexSource);
  41676. gl.compileShader(vertexShader);
  41677. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  41678. gl.shaderSource(fragmentShader, fragmentSource);
  41679. gl.compileShader(fragmentShader);
  41680. var program = gl.createProgram();
  41681. gl.attachShader(program, vertexShader);
  41682. gl.attachShader(program, fragmentShader);
  41683. for (var attribName in attribLocationMap) {
  41684. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  41685. }gl.linkProgram(program);
  41686. gl.deleteShader(vertexShader);
  41687. gl.deleteShader(fragmentShader);
  41688. return program;
  41689. };
  41690. var getProgramUniforms = function getProgramUniforms(gl, program) {
  41691. var uniforms = {};
  41692. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  41693. var uniformName = '';
  41694. for (var i = 0; i < uniformCount; i++) {
  41695. var uniformInfo = gl.getActiveUniform(program, i);
  41696. uniformName = uniformInfo.name.replace('[0]', '');
  41697. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  41698. }
  41699. return uniforms;
  41700. };
  41701. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  41702. var lr = 1 / (left - right),
  41703. bt = 1 / (bottom - top),
  41704. nf = 1 / (near - far);
  41705. out[0] = -2 * lr;
  41706. out[1] = 0;
  41707. out[2] = 0;
  41708. out[3] = 0;
  41709. out[4] = 0;
  41710. out[5] = -2 * bt;
  41711. out[6] = 0;
  41712. out[7] = 0;
  41713. out[8] = 0;
  41714. out[9] = 0;
  41715. out[10] = 2 * nf;
  41716. out[11] = 0;
  41717. out[12] = (left + right) * lr;
  41718. out[13] = (top + bottom) * bt;
  41719. out[14] = (far + near) * nf;
  41720. out[15] = 1;
  41721. return out;
  41722. };
  41723. var isMobile = function isMobile() {
  41724. var check = false;
  41725. (function (a) {
  41726. if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true;
  41727. })(navigator.userAgent || navigator.vendor || window.opera);
  41728. return check;
  41729. };
  41730. var extend = function extend(dest, src) {
  41731. for (var key in src) {
  41732. if (src.hasOwnProperty(key)) {
  41733. dest[key] = src[key];
  41734. }
  41735. }
  41736. return dest;
  41737. };
  41738. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  41739. if (isIOS()) {
  41740. var width = canvas.style.width;
  41741. var height = canvas.style.height;
  41742. canvas.style.width = parseInt(width) + 1 + 'px';
  41743. canvas.style.height = parseInt(height) + 'px';
  41744. setTimeout(function () {
  41745. canvas.style.width = width;
  41746. canvas.style.height = height;
  41747. }, 100);
  41748. }
  41749. window.canvas = canvas;
  41750. };
  41751. var frameDataFromPose = function () {
  41752. var piOver180 = Math.PI / 180.0;
  41753. var rad45 = Math.PI * 0.25;
  41754. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  41755. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  41756. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  41757. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  41758. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  41759. xScale = 2.0 / (leftTan + rightTan),
  41760. yScale = 2.0 / (upTan + downTan);
  41761. out[0] = xScale;
  41762. out[1] = 0.0;
  41763. out[2] = 0.0;
  41764. out[3] = 0.0;
  41765. out[4] = 0.0;
  41766. out[5] = yScale;
  41767. out[6] = 0.0;
  41768. out[7] = 0.0;
  41769. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  41770. out[9] = (upTan - downTan) * yScale * 0.5;
  41771. out[10] = far / (near - far);
  41772. out[11] = -1.0;
  41773. out[12] = 0.0;
  41774. out[13] = 0.0;
  41775. out[14] = far * near / (near - far);
  41776. out[15] = 0.0;
  41777. return out;
  41778. }
  41779. function mat4_fromRotationTranslation(out, q, v) {
  41780. var x = q[0],
  41781. y = q[1],
  41782. z = q[2],
  41783. w = q[3],
  41784. x2 = x + x,
  41785. y2 = y + y,
  41786. z2 = z + z,
  41787. xx = x * x2,
  41788. xy = x * y2,
  41789. xz = x * z2,
  41790. yy = y * y2,
  41791. yz = y * z2,
  41792. zz = z * z2,
  41793. wx = w * x2,
  41794. wy = w * y2,
  41795. wz = w * z2;
  41796. out[0] = 1 - (yy + zz);
  41797. out[1] = xy + wz;
  41798. out[2] = xz - wy;
  41799. out[3] = 0;
  41800. out[4] = xy - wz;
  41801. out[5] = 1 - (xx + zz);
  41802. out[6] = yz + wx;
  41803. out[7] = 0;
  41804. out[8] = xz + wy;
  41805. out[9] = yz - wx;
  41806. out[10] = 1 - (xx + yy);
  41807. out[11] = 0;
  41808. out[12] = v[0];
  41809. out[13] = v[1];
  41810. out[14] = v[2];
  41811. out[15] = 1;
  41812. return out;
  41813. }
  41814. function mat4_translate(out, a, v) {
  41815. var x = v[0],
  41816. y = v[1],
  41817. z = v[2],
  41818. a00,
  41819. a01,
  41820. a02,
  41821. a03,
  41822. a10,
  41823. a11,
  41824. a12,
  41825. a13,
  41826. a20,
  41827. a21,
  41828. a22,
  41829. a23;
  41830. if (a === out) {
  41831. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  41832. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  41833. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  41834. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  41835. } else {
  41836. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  41837. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  41838. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  41839. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  41840. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  41841. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  41842. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  41843. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  41844. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  41845. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  41846. }
  41847. return out;
  41848. }
  41849. function mat4_invert(out, a) {
  41850. var a00 = a[0],
  41851. a01 = a[1],
  41852. a02 = a[2],
  41853. a03 = a[3],
  41854. a10 = a[4],
  41855. a11 = a[5],
  41856. a12 = a[6],
  41857. a13 = a[7],
  41858. a20 = a[8],
  41859. a21 = a[9],
  41860. a22 = a[10],
  41861. a23 = a[11],
  41862. a30 = a[12],
  41863. a31 = a[13],
  41864. a32 = a[14],
  41865. a33 = a[15],
  41866. b00 = a00 * a11 - a01 * a10,
  41867. b01 = a00 * a12 - a02 * a10,
  41868. b02 = a00 * a13 - a03 * a10,
  41869. b03 = a01 * a12 - a02 * a11,
  41870. b04 = a01 * a13 - a03 * a11,
  41871. b05 = a02 * a13 - a03 * a12,
  41872. b06 = a20 * a31 - a21 * a30,
  41873. b07 = a20 * a32 - a22 * a30,
  41874. b08 = a20 * a33 - a23 * a30,
  41875. b09 = a21 * a32 - a22 * a31,
  41876. b10 = a21 * a33 - a23 * a31,
  41877. b11 = a22 * a33 - a23 * a32,
  41878. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  41879. if (!det) {
  41880. return null;
  41881. }
  41882. det = 1.0 / det;
  41883. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  41884. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  41885. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  41886. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  41887. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  41888. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  41889. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  41890. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  41891. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  41892. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  41893. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  41894. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  41895. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  41896. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  41897. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  41898. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  41899. return out;
  41900. }
  41901. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  41902. var defaultPosition = new Float32Array([0, 0, 0]);
  41903. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  41904. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  41905. var orientation = pose.orientation || defaultOrientation;
  41906. var position = pose.position || defaultPosition;
  41907. mat4_fromRotationTranslation(view, orientation, position);
  41908. if (offset) mat4_translate(view, view, offset);
  41909. mat4_invert(view, view);
  41910. }
  41911. return function (frameData, pose, vrDisplay) {
  41912. if (!frameData || !pose) return false;
  41913. frameData.pose = pose;
  41914. frameData.timestamp = pose.timestamp;
  41915. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  41916. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  41917. return true;
  41918. };
  41919. }();
  41920. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  41921. var isFramed = window.self !== window.top;
  41922. var refOrigin = getOriginFromUrl(document.referrer);
  41923. var thisOrigin = getOriginFromUrl(window.location.href);
  41924. return isFramed && refOrigin !== thisOrigin;
  41925. };
  41926. var getOriginFromUrl = function getOriginFromUrl(url) {
  41927. var domainIdx;
  41928. var protoSepIdx = url.indexOf("://");
  41929. if (protoSepIdx !== -1) {
  41930. domainIdx = protoSepIdx + 3;
  41931. } else {
  41932. domainIdx = 0;
  41933. }
  41934. var domainEndIdx = url.indexOf('/', domainIdx);
  41935. if (domainEndIdx === -1) {
  41936. domainEndIdx = url.length;
  41937. }
  41938. return url.substring(0, domainEndIdx);
  41939. };
  41940. var getQuaternionAngle = function getQuaternionAngle(quat) {
  41941. if (quat.w > 1) {
  41942. console.warn('getQuaternionAngle: w > 1');
  41943. return 0;
  41944. }
  41945. var angle = 2 * Math.acos(quat.w);
  41946. return angle;
  41947. };
  41948. var warnOnce = function () {
  41949. var observedWarnings = {};
  41950. return function (key, message) {
  41951. if (observedWarnings[key] === undefined) {
  41952. console.warn('webvr-polyfill: ' + message);
  41953. observedWarnings[key] = true;
  41954. }
  41955. };
  41956. }();
  41957. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  41958. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  41959. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  41960. };
  41961. function WGLUPreserveGLState(gl, bindings, callback) {
  41962. if (!bindings) {
  41963. callback(gl);
  41964. return;
  41965. }
  41966. var boundValues = [];
  41967. var activeTexture = null;
  41968. for (var i = 0; i < bindings.length; ++i) {
  41969. var binding = bindings[i];
  41970. switch (binding) {
  41971. case gl.TEXTURE_BINDING_2D:
  41972. case gl.TEXTURE_BINDING_CUBE_MAP:
  41973. var textureUnit = bindings[++i];
  41974. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  41975. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  41976. boundValues.push(null, null);
  41977. break;
  41978. }
  41979. if (!activeTexture) {
  41980. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  41981. }
  41982. gl.activeTexture(textureUnit);
  41983. boundValues.push(gl.getParameter(binding), null);
  41984. break;
  41985. case gl.ACTIVE_TEXTURE:
  41986. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  41987. boundValues.push(null);
  41988. break;
  41989. default:
  41990. boundValues.push(gl.getParameter(binding));
  41991. break;
  41992. }
  41993. }
  41994. callback(gl);
  41995. for (var i = 0; i < bindings.length; ++i) {
  41996. var binding = bindings[i];
  41997. var boundValue = boundValues[i];
  41998. switch (binding) {
  41999. case gl.ACTIVE_TEXTURE:
  42000. break;
  42001. case gl.ARRAY_BUFFER_BINDING:
  42002. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  42003. break;
  42004. case gl.COLOR_CLEAR_VALUE:
  42005. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  42006. break;
  42007. case gl.COLOR_WRITEMASK:
  42008. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  42009. break;
  42010. case gl.CURRENT_PROGRAM:
  42011. gl.useProgram(boundValue);
  42012. break;
  42013. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  42014. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  42015. break;
  42016. case gl.FRAMEBUFFER_BINDING:
  42017. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  42018. break;
  42019. case gl.RENDERBUFFER_BINDING:
  42020. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  42021. break;
  42022. case gl.TEXTURE_BINDING_2D:
  42023. var textureUnit = bindings[++i];
  42024. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  42025. break;
  42026. gl.activeTexture(textureUnit);
  42027. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  42028. break;
  42029. case gl.TEXTURE_BINDING_CUBE_MAP:
  42030. var textureUnit = bindings[++i];
  42031. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  42032. break;
  42033. gl.activeTexture(textureUnit);
  42034. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  42035. break;
  42036. case gl.VIEWPORT:
  42037. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  42038. break;
  42039. case gl.BLEND:
  42040. case gl.CULL_FACE:
  42041. case gl.DEPTH_TEST:
  42042. case gl.SCISSOR_TEST:
  42043. case gl.STENCIL_TEST:
  42044. if (boundValue) {
  42045. gl.enable(binding);
  42046. } else {
  42047. gl.disable(binding);
  42048. }
  42049. break;
  42050. default:
  42051. console.log("No GL restore behavior for 0x" + binding.toString(16));
  42052. break;
  42053. }
  42054. if (activeTexture) {
  42055. gl.activeTexture(activeTexture);
  42056. }
  42057. }
  42058. }
  42059. var glPreserveState = WGLUPreserveGLState;
  42060. var distortionVS = ['attribute vec2 position;', 'attribute vec3 texCoord;', 'varying vec2 vTexCoord;', 'uniform vec4 viewportOffsetScale[2];', 'void main() {', ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];', ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;', ' gl_Position = vec4( position, 1.0, 1.0 );', '}'].join('\n');
  42061. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  42062. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  42063. this.gl = gl;
  42064. this.cardboardUI = cardboardUI;
  42065. this.bufferScale = bufferScale;
  42066. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  42067. this.ctxAttribs = gl.getContextAttributes();
  42068. this.instanceExt = gl.getExtension('ANGLE_instanced_arrays');
  42069. this.meshWidth = 20;
  42070. this.meshHeight = 20;
  42071. this.bufferWidth = gl.drawingBufferWidth;
  42072. this.bufferHeight = gl.drawingBufferHeight;
  42073. this.realBindFramebuffer = gl.bindFramebuffer;
  42074. this.realEnable = gl.enable;
  42075. this.realDisable = gl.disable;
  42076. this.realColorMask = gl.colorMask;
  42077. this.realClearColor = gl.clearColor;
  42078. this.realViewport = gl.viewport;
  42079. if (!isIOS()) {
  42080. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  42081. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  42082. }
  42083. this.isPatched = false;
  42084. this.lastBoundFramebuffer = null;
  42085. this.cullFace = false;
  42086. this.depthTest = false;
  42087. this.blend = false;
  42088. this.scissorTest = false;
  42089. this.stencilTest = false;
  42090. this.viewport = [0, 0, 0, 0];
  42091. this.colorMask = [true, true, true, true];
  42092. this.clearColor = [0, 0, 0, 0];
  42093. this.attribs = {
  42094. position: 0,
  42095. texCoord: 1
  42096. };
  42097. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  42098. this.uniforms = getProgramUniforms(gl, this.program);
  42099. this.viewportOffsetScale = new Float32Array(8);
  42100. this.setTextureBounds();
  42101. this.vertexBuffer = gl.createBuffer();
  42102. this.indexBuffer = gl.createBuffer();
  42103. this.indexCount = 0;
  42104. this.renderTarget = gl.createTexture();
  42105. this.framebuffer = gl.createFramebuffer();
  42106. this.depthStencilBuffer = null;
  42107. this.depthBuffer = null;
  42108. this.stencilBuffer = null;
  42109. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  42110. this.depthStencilBuffer = gl.createRenderbuffer();
  42111. } else if (this.ctxAttribs.depth) {
  42112. this.depthBuffer = gl.createRenderbuffer();
  42113. } else if (this.ctxAttribs.stencil) {
  42114. this.stencilBuffer = gl.createRenderbuffer();
  42115. }
  42116. this.patch();
  42117. this.onResize();
  42118. }
  42119. CardboardDistorter.prototype.destroy = function () {
  42120. var gl = this.gl;
  42121. this.unpatch();
  42122. gl.deleteProgram(this.program);
  42123. gl.deleteBuffer(this.vertexBuffer);
  42124. gl.deleteBuffer(this.indexBuffer);
  42125. gl.deleteTexture(this.renderTarget);
  42126. gl.deleteFramebuffer(this.framebuffer);
  42127. if (this.depthStencilBuffer) {
  42128. gl.deleteRenderbuffer(this.depthStencilBuffer);
  42129. }
  42130. if (this.depthBuffer) {
  42131. gl.deleteRenderbuffer(this.depthBuffer);
  42132. }
  42133. if (this.stencilBuffer) {
  42134. gl.deleteRenderbuffer(this.stencilBuffer);
  42135. }
  42136. if (this.cardboardUI) {
  42137. this.cardboardUI.destroy();
  42138. }
  42139. };
  42140. CardboardDistorter.prototype.onResize = function () {
  42141. var gl = this.gl;
  42142. var self = this;
  42143. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  42144. glPreserveState(gl, glState, function (gl) {
  42145. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  42146. if (self.scissorTest) {
  42147. self.realDisable.call(gl, gl.SCISSOR_TEST);
  42148. }
  42149. self.realColorMask.call(gl, true, true, true, true);
  42150. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42151. self.realClearColor.call(gl, 0, 0, 0, 1);
  42152. gl.clear(gl.COLOR_BUFFER_BIT);
  42153. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  42154. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  42155. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, self.bufferWidth, self.bufferHeight, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  42156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  42157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  42158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  42159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  42160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  42161. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  42162. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  42163. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  42164. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  42165. } else if (self.ctxAttribs.depth) {
  42166. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  42167. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  42168. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  42169. } else if (self.ctxAttribs.stencil) {
  42170. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  42171. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  42172. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  42173. }
  42174. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  42175. console.error('Framebuffer incomplete!');
  42176. }
  42177. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  42178. if (self.scissorTest) {
  42179. self.realEnable.call(gl, gl.SCISSOR_TEST);
  42180. }
  42181. self.realColorMask.apply(gl, self.colorMask);
  42182. self.realViewport.apply(gl, self.viewport);
  42183. self.realClearColor.apply(gl, self.clearColor);
  42184. });
  42185. if (this.cardboardUI) {
  42186. this.cardboardUI.onResize();
  42187. }
  42188. };
  42189. CardboardDistorter.prototype.patch = function () {
  42190. if (this.isPatched) {
  42191. return;
  42192. }
  42193. var self = this;
  42194. var canvas = this.gl.canvas;
  42195. var gl = this.gl;
  42196. if (!isIOS()) {
  42197. canvas.width = getScreenWidth() * this.bufferScale;
  42198. canvas.height = getScreenHeight() * this.bufferScale;
  42199. Object.defineProperty(canvas, 'width', {
  42200. configurable: true,
  42201. enumerable: true,
  42202. get: function get() {
  42203. return self.bufferWidth;
  42204. },
  42205. set: function set(value) {
  42206. self.bufferWidth = value;
  42207. self.realCanvasWidth.set.call(canvas, value);
  42208. self.onResize();
  42209. }
  42210. });
  42211. Object.defineProperty(canvas, 'height', {
  42212. configurable: true,
  42213. enumerable: true,
  42214. get: function get() {
  42215. return self.bufferHeight;
  42216. },
  42217. set: function set(value) {
  42218. self.bufferHeight = value;
  42219. self.realCanvasHeight.set.call(canvas, value);
  42220. self.onResize();
  42221. }
  42222. });
  42223. }
  42224. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  42225. if (this.lastBoundFramebuffer == null) {
  42226. this.lastBoundFramebuffer = this.framebuffer;
  42227. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  42228. }
  42229. this.gl.bindFramebuffer = function (target, framebuffer) {
  42230. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  42231. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  42232. };
  42233. this.cullFace = gl.getParameter(gl.CULL_FACE);
  42234. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  42235. this.blend = gl.getParameter(gl.BLEND);
  42236. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  42237. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  42238. gl.enable = function (pname) {
  42239. switch (pname) {
  42240. case gl.CULL_FACE:
  42241. self.cullFace = true;break;
  42242. case gl.DEPTH_TEST:
  42243. self.depthTest = true;break;
  42244. case gl.BLEND:
  42245. self.blend = true;break;
  42246. case gl.SCISSOR_TEST:
  42247. self.scissorTest = true;break;
  42248. case gl.STENCIL_TEST:
  42249. self.stencilTest = true;break;
  42250. }
  42251. self.realEnable.call(gl, pname);
  42252. };
  42253. gl.disable = function (pname) {
  42254. switch (pname) {
  42255. case gl.CULL_FACE:
  42256. self.cullFace = false;break;
  42257. case gl.DEPTH_TEST:
  42258. self.depthTest = false;break;
  42259. case gl.BLEND:
  42260. self.blend = false;break;
  42261. case gl.SCISSOR_TEST:
  42262. self.scissorTest = false;break;
  42263. case gl.STENCIL_TEST:
  42264. self.stencilTest = false;break;
  42265. }
  42266. self.realDisable.call(gl, pname);
  42267. };
  42268. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  42269. gl.colorMask = function (r, g, b, a) {
  42270. self.colorMask[0] = r;
  42271. self.colorMask[1] = g;
  42272. self.colorMask[2] = b;
  42273. self.colorMask[3] = a;
  42274. self.realColorMask.call(gl, r, g, b, a);
  42275. };
  42276. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  42277. gl.clearColor = function (r, g, b, a) {
  42278. self.clearColor[0] = r;
  42279. self.clearColor[1] = g;
  42280. self.clearColor[2] = b;
  42281. self.clearColor[3] = a;
  42282. self.realClearColor.call(gl, r, g, b, a);
  42283. };
  42284. this.viewport = gl.getParameter(gl.VIEWPORT);
  42285. gl.viewport = function (x, y, w, h) {
  42286. self.viewport[0] = x;
  42287. self.viewport[1] = y;
  42288. self.viewport[2] = w;
  42289. self.viewport[3] = h;
  42290. self.realViewport.call(gl, x, y, w, h);
  42291. };
  42292. this.isPatched = true;
  42293. safariCssSizeWorkaround(canvas);
  42294. };
  42295. CardboardDistorter.prototype.unpatch = function () {
  42296. if (!this.isPatched) {
  42297. return;
  42298. }
  42299. var gl = this.gl;
  42300. var canvas = this.gl.canvas;
  42301. if (!isIOS()) {
  42302. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  42303. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  42304. }
  42305. canvas.width = this.bufferWidth;
  42306. canvas.height = this.bufferHeight;
  42307. gl.bindFramebuffer = this.realBindFramebuffer;
  42308. gl.enable = this.realEnable;
  42309. gl.disable = this.realDisable;
  42310. gl.colorMask = this.realColorMask;
  42311. gl.clearColor = this.realClearColor;
  42312. gl.viewport = this.realViewport;
  42313. if (this.lastBoundFramebuffer == this.framebuffer) {
  42314. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  42315. }
  42316. this.isPatched = false;
  42317. setTimeout(function () {
  42318. safariCssSizeWorkaround(canvas);
  42319. }, 1);
  42320. };
  42321. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  42322. if (!leftBounds) {
  42323. leftBounds = [0, 0, 0.5, 1];
  42324. }
  42325. if (!rightBounds) {
  42326. rightBounds = [0.5, 0, 0.5, 1];
  42327. }
  42328. this.viewportOffsetScale[0] = leftBounds[0];
  42329. this.viewportOffsetScale[1] = leftBounds[1];
  42330. this.viewportOffsetScale[2] = leftBounds[2];
  42331. this.viewportOffsetScale[3] = leftBounds[3];
  42332. this.viewportOffsetScale[4] = rightBounds[0];
  42333. this.viewportOffsetScale[5] = rightBounds[1];
  42334. this.viewportOffsetScale[6] = rightBounds[2];
  42335. this.viewportOffsetScale[7] = rightBounds[3];
  42336. };
  42337. CardboardDistorter.prototype.submitFrame = function () {
  42338. var gl = this.gl;
  42339. var self = this;
  42340. var glState = [];
  42341. if (!this.dirtySubmitFrameBindings) {
  42342. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  42343. }
  42344. glPreserveState(gl, glState, function (gl) {
  42345. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  42346. var positionDivisor = 0;
  42347. var texCoordDivisor = 0;
  42348. if (self.instanceExt) {
  42349. positionDivisor = gl.getVertexAttrib(self.attribs.position, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  42350. texCoordDivisor = gl.getVertexAttrib(self.attribs.texCoord, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  42351. }
  42352. if (self.cullFace) {
  42353. self.realDisable.call(gl, gl.CULL_FACE);
  42354. }
  42355. if (self.depthTest) {
  42356. self.realDisable.call(gl, gl.DEPTH_TEST);
  42357. }
  42358. if (self.blend) {
  42359. self.realDisable.call(gl, gl.BLEND);
  42360. }
  42361. if (self.scissorTest) {
  42362. self.realDisable.call(gl, gl.SCISSOR_TEST);
  42363. }
  42364. if (self.stencilTest) {
  42365. self.realDisable.call(gl, gl.STENCIL_TEST);
  42366. }
  42367. self.realColorMask.call(gl, true, true, true, true);
  42368. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42369. if (self.ctxAttribs.alpha || isIOS()) {
  42370. self.realClearColor.call(gl, 0, 0, 0, 1);
  42371. gl.clear(gl.COLOR_BUFFER_BIT);
  42372. }
  42373. gl.useProgram(self.program);
  42374. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  42375. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42376. gl.enableVertexAttribArray(self.attribs.position);
  42377. gl.enableVertexAttribArray(self.attribs.texCoord);
  42378. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  42379. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  42380. if (self.instanceExt) {
  42381. if (positionDivisor != 0) {
  42382. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, 0);
  42383. }
  42384. if (texCoordDivisor != 0) {
  42385. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, 0);
  42386. }
  42387. }
  42388. gl.activeTexture(gl.TEXTURE0);
  42389. gl.uniform1i(self.uniforms.diffuse, 0);
  42390. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  42391. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  42392. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  42393. if (self.cardboardUI) {
  42394. self.cardboardUI.renderNoState();
  42395. }
  42396. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  42397. if (!self.ctxAttribs.preserveDrawingBuffer) {
  42398. self.realClearColor.call(gl, 0, 0, 0, 0);
  42399. gl.clear(gl.COLOR_BUFFER_BIT);
  42400. }
  42401. if (!self.dirtySubmitFrameBindings) {
  42402. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  42403. }
  42404. if (self.cullFace) {
  42405. self.realEnable.call(gl, gl.CULL_FACE);
  42406. }
  42407. if (self.depthTest) {
  42408. self.realEnable.call(gl, gl.DEPTH_TEST);
  42409. }
  42410. if (self.blend) {
  42411. self.realEnable.call(gl, gl.BLEND);
  42412. }
  42413. if (self.scissorTest) {
  42414. self.realEnable.call(gl, gl.SCISSOR_TEST);
  42415. }
  42416. if (self.stencilTest) {
  42417. self.realEnable.call(gl, gl.STENCIL_TEST);
  42418. }
  42419. self.realColorMask.apply(gl, self.colorMask);
  42420. self.realViewport.apply(gl, self.viewport);
  42421. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  42422. self.realClearColor.apply(gl, self.clearColor);
  42423. }
  42424. if (self.instanceExt) {
  42425. if (positionDivisor != 0) {
  42426. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, positionDivisor);
  42427. }
  42428. if (texCoordDivisor != 0) {
  42429. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, texCoordDivisor);
  42430. }
  42431. }
  42432. });
  42433. if (isIOS()) {
  42434. var canvas = gl.canvas;
  42435. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  42436. self.bufferWidth = canvas.width;
  42437. self.bufferHeight = canvas.height;
  42438. self.onResize();
  42439. }
  42440. }
  42441. };
  42442. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  42443. var gl = this.gl;
  42444. var self = this;
  42445. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  42446. glPreserveState(gl, glState, function (gl) {
  42447. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  42448. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42449. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  42450. if (!self.indexCount) {
  42451. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  42452. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  42453. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  42454. self.indexCount = indices.length;
  42455. }
  42456. });
  42457. };
  42458. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  42459. var vertices = new Float32Array(2 * width * height * 5);
  42460. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  42461. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  42462. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  42463. var vidx = 0;
  42464. for (var e = 0; e < 2; e++) {
  42465. for (var j = 0; j < height; j++) {
  42466. for (var i = 0; i < width; i++, vidx++) {
  42467. var u = i / (width - 1);
  42468. var v = j / (height - 1);
  42469. var s = u;
  42470. var t = v;
  42471. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  42472. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  42473. var d = Math.sqrt(x * x + y * y);
  42474. var r = deviceInfo.distortion.distortInverse(d);
  42475. var p = x * r / d;
  42476. var q = y * r / d;
  42477. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  42478. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  42479. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  42480. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  42481. vertices[vidx * 5 + 0] = u;
  42482. vertices[vidx * 5 + 1] = v;
  42483. vertices[vidx * 5 + 2] = s;
  42484. vertices[vidx * 5 + 3] = t;
  42485. vertices[vidx * 5 + 4] = e;
  42486. }
  42487. }
  42488. var w = lensFrustum[2] - lensFrustum[0];
  42489. lensFrustum[0] = -(w + lensFrustum[0]);
  42490. lensFrustum[2] = w - lensFrustum[2];
  42491. w = noLensFrustum[2] - noLensFrustum[0];
  42492. noLensFrustum[0] = -(w + noLensFrustum[0]);
  42493. noLensFrustum[2] = w - noLensFrustum[2];
  42494. viewport.x = 1 - (viewport.x + viewport.width);
  42495. }
  42496. return vertices;
  42497. };
  42498. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  42499. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  42500. var halfwidth = width / 2;
  42501. var halfheight = height / 2;
  42502. var vidx = 0;
  42503. var iidx = 0;
  42504. for (var e = 0; e < 2; e++) {
  42505. for (var j = 0; j < height; j++) {
  42506. for (var i = 0; i < width; i++, vidx++) {
  42507. if (i == 0 || j == 0) continue;
  42508. if (i <= halfwidth == j <= halfheight) {
  42509. indices[iidx++] = vidx;
  42510. indices[iidx++] = vidx - width - 1;
  42511. indices[iidx++] = vidx - width;
  42512. indices[iidx++] = vidx - width - 1;
  42513. indices[iidx++] = vidx;
  42514. indices[iidx++] = vidx - 1;
  42515. } else {
  42516. indices[iidx++] = vidx - 1;
  42517. indices[iidx++] = vidx - width;
  42518. indices[iidx++] = vidx;
  42519. indices[iidx++] = vidx - width;
  42520. indices[iidx++] = vidx - 1;
  42521. indices[iidx++] = vidx - width - 1;
  42522. }
  42523. }
  42524. }
  42525. }
  42526. return indices;
  42527. };
  42528. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  42529. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  42530. if (descriptor.get === undefined || descriptor.set === undefined) {
  42531. descriptor.configurable = true;
  42532. descriptor.enumerable = true;
  42533. descriptor.get = function () {
  42534. return this.getAttribute(attrName);
  42535. };
  42536. descriptor.set = function (val) {
  42537. this.setAttribute(attrName, val);
  42538. };
  42539. }
  42540. return descriptor;
  42541. };
  42542. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  42543. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  42544. var DEG2RAD = Math.PI / 180.0;
  42545. var kAnglePerGearSection = 60;
  42546. var kOuterRimEndAngle = 12;
  42547. var kInnerRimBeginAngle = 20;
  42548. var kOuterRadius = 1;
  42549. var kMiddleRadius = 0.75;
  42550. var kInnerRadius = 0.3125;
  42551. var kCenterLineThicknessDp = 4;
  42552. var kButtonWidthDp = 28;
  42553. var kTouchSlopFactor = 1.5;
  42554. function CardboardUI(gl) {
  42555. this.gl = gl;
  42556. this.attribs = {
  42557. position: 0
  42558. };
  42559. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  42560. this.uniforms = getProgramUniforms(gl, this.program);
  42561. this.vertexBuffer = gl.createBuffer();
  42562. this.gearOffset = 0;
  42563. this.gearVertexCount = 0;
  42564. this.arrowOffset = 0;
  42565. this.arrowVertexCount = 0;
  42566. this.projMat = new Float32Array(16);
  42567. this.listener = null;
  42568. this.onResize();
  42569. }
  42570. CardboardUI.prototype.destroy = function () {
  42571. var gl = this.gl;
  42572. if (this.listener) {
  42573. gl.canvas.removeEventListener('click', this.listener, false);
  42574. }
  42575. gl.deleteProgram(this.program);
  42576. gl.deleteBuffer(this.vertexBuffer);
  42577. };
  42578. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  42579. var canvas = this.gl.canvas;
  42580. this.listener = function (event) {
  42581. var midline = canvas.clientWidth / 2;
  42582. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  42583. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  42584. optionsCallback(event);
  42585. }
  42586. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  42587. backCallback(event);
  42588. }
  42589. };
  42590. canvas.addEventListener('click', this.listener, false);
  42591. };
  42592. CardboardUI.prototype.onResize = function () {
  42593. var gl = this.gl;
  42594. var self = this;
  42595. var glState = [gl.ARRAY_BUFFER_BINDING];
  42596. glPreserveState(gl, glState, function (gl) {
  42597. var vertices = [];
  42598. var midline = gl.drawingBufferWidth / 2;
  42599. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  42600. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  42601. var dps = scalingRatio * window.devicePixelRatio;
  42602. var lineWidth = kCenterLineThicknessDp * dps / 2;
  42603. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  42604. var buttonScale = kButtonWidthDp * dps / 2;
  42605. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  42606. vertices.push(midline - lineWidth, buttonSize);
  42607. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  42608. vertices.push(midline + lineWidth, buttonSize);
  42609. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  42610. self.gearOffset = vertices.length / 2;
  42611. function addGearSegment(theta, r) {
  42612. var angle = (90 - theta) * DEG2RAD;
  42613. var x = Math.cos(angle);
  42614. var y = Math.sin(angle);
  42615. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  42616. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  42617. }
  42618. for (var i = 0; i <= 6; i++) {
  42619. var segmentTheta = i * kAnglePerGearSection;
  42620. addGearSegment(segmentTheta, kOuterRadius);
  42621. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  42622. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  42623. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  42624. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  42625. }
  42626. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  42627. self.arrowOffset = vertices.length / 2;
  42628. function addArrowVertex(x, y) {
  42629. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  42630. }
  42631. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  42632. addArrowVertex(0, buttonScale);
  42633. addArrowVertex(buttonScale, 0);
  42634. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  42635. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  42636. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  42637. addArrowVertex(0, buttonScale);
  42638. addArrowVertex(buttonScale, buttonScale * 2);
  42639. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  42640. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  42641. addArrowVertex(0, buttonScale);
  42642. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  42643. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  42644. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  42645. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  42646. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  42647. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42648. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  42649. });
  42650. };
  42651. CardboardUI.prototype.render = function () {
  42652. var gl = this.gl;
  42653. var self = this;
  42654. var glState = [gl.CULL_FACE, gl.DEPTH_TEST, gl.BLEND, gl.SCISSOR_TEST, gl.STENCIL_TEST, gl.COLOR_WRITEMASK, gl.VIEWPORT, gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING];
  42655. glPreserveState(gl, glState, function (gl) {
  42656. gl.disable(gl.CULL_FACE);
  42657. gl.disable(gl.DEPTH_TEST);
  42658. gl.disable(gl.BLEND);
  42659. gl.disable(gl.SCISSOR_TEST);
  42660. gl.disable(gl.STENCIL_TEST);
  42661. gl.colorMask(true, true, true, true);
  42662. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42663. self.renderNoState();
  42664. });
  42665. };
  42666. CardboardUI.prototype.renderNoState = function () {
  42667. var gl = this.gl;
  42668. gl.useProgram(this.program);
  42669. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  42670. gl.enableVertexAttribArray(this.attribs.position);
  42671. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  42672. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  42673. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  42674. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  42675. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  42676. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  42677. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  42678. };
  42679. function Distortion(coefficients) {
  42680. this.coefficients = coefficients;
  42681. }
  42682. Distortion.prototype.distortInverse = function (radius) {
  42683. var r0 = 0;
  42684. var r1 = 1;
  42685. var dr0 = radius - this.distort(r0);
  42686. while (Math.abs(r1 - r0) > 0.0001 ) {
  42687. var dr1 = radius - this.distort(r1);
  42688. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  42689. r0 = r1;
  42690. r1 = r2;
  42691. dr0 = dr1;
  42692. }
  42693. return r1;
  42694. };
  42695. Distortion.prototype.distort = function (radius) {
  42696. var r2 = radius * radius;
  42697. var ret = 0;
  42698. for (var i = 0; i < this.coefficients.length; i++) {
  42699. ret = r2 * (ret + this.coefficients[i]);
  42700. }
  42701. return (ret + 1) * radius;
  42702. };
  42703. var degToRad = Math.PI / 180;
  42704. var radToDeg = 180 / Math.PI;
  42705. var Vector3 = function Vector3(x, y, z) {
  42706. this.x = x || 0;
  42707. this.y = y || 0;
  42708. this.z = z || 0;
  42709. };
  42710. Vector3.prototype = {
  42711. constructor: Vector3,
  42712. set: function set(x, y, z) {
  42713. this.x = x;
  42714. this.y = y;
  42715. this.z = z;
  42716. return this;
  42717. },
  42718. copy: function copy(v) {
  42719. this.x = v.x;
  42720. this.y = v.y;
  42721. this.z = v.z;
  42722. return this;
  42723. },
  42724. length: function length() {
  42725. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  42726. },
  42727. normalize: function normalize() {
  42728. var scalar = this.length();
  42729. if (scalar !== 0) {
  42730. var invScalar = 1 / scalar;
  42731. this.multiplyScalar(invScalar);
  42732. } else {
  42733. this.x = 0;
  42734. this.y = 0;
  42735. this.z = 0;
  42736. }
  42737. return this;
  42738. },
  42739. multiplyScalar: function multiplyScalar(scalar) {
  42740. this.x *= scalar;
  42741. this.y *= scalar;
  42742. this.z *= scalar;
  42743. },
  42744. applyQuaternion: function applyQuaternion(q) {
  42745. var x = this.x;
  42746. var y = this.y;
  42747. var z = this.z;
  42748. var qx = q.x;
  42749. var qy = q.y;
  42750. var qz = q.z;
  42751. var qw = q.w;
  42752. var ix = qw * x + qy * z - qz * y;
  42753. var iy = qw * y + qz * x - qx * z;
  42754. var iz = qw * z + qx * y - qy * x;
  42755. var iw = -qx * x - qy * y - qz * z;
  42756. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  42757. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  42758. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  42759. return this;
  42760. },
  42761. dot: function dot(v) {
  42762. return this.x * v.x + this.y * v.y + this.z * v.z;
  42763. },
  42764. crossVectors: function crossVectors(a, b) {
  42765. var ax = a.x,
  42766. ay = a.y,
  42767. az = a.z;
  42768. var bx = b.x,
  42769. by = b.y,
  42770. bz = b.z;
  42771. this.x = ay * bz - az * by;
  42772. this.y = az * bx - ax * bz;
  42773. this.z = ax * by - ay * bx;
  42774. return this;
  42775. }
  42776. };
  42777. var Quaternion = function Quaternion(x, y, z, w) {
  42778. this.x = x || 0;
  42779. this.y = y || 0;
  42780. this.z = z || 0;
  42781. this.w = w !== undefined ? w : 1;
  42782. };
  42783. Quaternion.prototype = {
  42784. constructor: Quaternion,
  42785. set: function set(x, y, z, w) {
  42786. this.x = x;
  42787. this.y = y;
  42788. this.z = z;
  42789. this.w = w;
  42790. return this;
  42791. },
  42792. copy: function copy(quaternion) {
  42793. this.x = quaternion.x;
  42794. this.y = quaternion.y;
  42795. this.z = quaternion.z;
  42796. this.w = quaternion.w;
  42797. return this;
  42798. },
  42799. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  42800. var c1 = Math.cos(x / 2);
  42801. var c2 = Math.cos(y / 2);
  42802. var c3 = Math.cos(z / 2);
  42803. var s1 = Math.sin(x / 2);
  42804. var s2 = Math.sin(y / 2);
  42805. var s3 = Math.sin(z / 2);
  42806. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  42807. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  42808. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  42809. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  42810. return this;
  42811. },
  42812. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  42813. var c1 = Math.cos(x / 2);
  42814. var c2 = Math.cos(y / 2);
  42815. var c3 = Math.cos(z / 2);
  42816. var s1 = Math.sin(x / 2);
  42817. var s2 = Math.sin(y / 2);
  42818. var s3 = Math.sin(z / 2);
  42819. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  42820. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  42821. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  42822. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  42823. return this;
  42824. },
  42825. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  42826. var halfAngle = angle / 2,
  42827. s = Math.sin(halfAngle);
  42828. this.x = axis.x * s;
  42829. this.y = axis.y * s;
  42830. this.z = axis.z * s;
  42831. this.w = Math.cos(halfAngle);
  42832. return this;
  42833. },
  42834. multiply: function multiply(q) {
  42835. return this.multiplyQuaternions(this, q);
  42836. },
  42837. multiplyQuaternions: function multiplyQuaternions(a, b) {
  42838. var qax = a.x,
  42839. qay = a.y,
  42840. qaz = a.z,
  42841. qaw = a.w;
  42842. var qbx = b.x,
  42843. qby = b.y,
  42844. qbz = b.z,
  42845. qbw = b.w;
  42846. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  42847. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  42848. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  42849. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  42850. return this;
  42851. },
  42852. inverse: function inverse() {
  42853. this.x *= -1;
  42854. this.y *= -1;
  42855. this.z *= -1;
  42856. this.normalize();
  42857. return this;
  42858. },
  42859. normalize: function normalize() {
  42860. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  42861. if (l === 0) {
  42862. this.x = 0;
  42863. this.y = 0;
  42864. this.z = 0;
  42865. this.w = 1;
  42866. } else {
  42867. l = 1 / l;
  42868. this.x = this.x * l;
  42869. this.y = this.y * l;
  42870. this.z = this.z * l;
  42871. this.w = this.w * l;
  42872. }
  42873. return this;
  42874. },
  42875. slerp: function slerp(qb, t) {
  42876. if (t === 0) return this;
  42877. if (t === 1) return this.copy(qb);
  42878. var x = this.x,
  42879. y = this.y,
  42880. z = this.z,
  42881. w = this.w;
  42882. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  42883. if (cosHalfTheta < 0) {
  42884. this.w = -qb.w;
  42885. this.x = -qb.x;
  42886. this.y = -qb.y;
  42887. this.z = -qb.z;
  42888. cosHalfTheta = -cosHalfTheta;
  42889. } else {
  42890. this.copy(qb);
  42891. }
  42892. if (cosHalfTheta >= 1.0) {
  42893. this.w = w;
  42894. this.x = x;
  42895. this.y = y;
  42896. this.z = z;
  42897. return this;
  42898. }
  42899. var halfTheta = Math.acos(cosHalfTheta);
  42900. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  42901. if (Math.abs(sinHalfTheta) < 0.001) {
  42902. this.w = 0.5 * (w + this.w);
  42903. this.x = 0.5 * (x + this.x);
  42904. this.y = 0.5 * (y + this.y);
  42905. this.z = 0.5 * (z + this.z);
  42906. return this;
  42907. }
  42908. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  42909. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  42910. this.w = w * ratioA + this.w * ratioB;
  42911. this.x = x * ratioA + this.x * ratioB;
  42912. this.y = y * ratioA + this.y * ratioB;
  42913. this.z = z * ratioA + this.z * ratioB;
  42914. return this;
  42915. },
  42916. setFromUnitVectors: function () {
  42917. var v1, r;
  42918. var EPS = 0.000001;
  42919. return function (vFrom, vTo) {
  42920. if (v1 === undefined) v1 = new Vector3();
  42921. r = vFrom.dot(vTo) + 1;
  42922. if (r < EPS) {
  42923. r = 0;
  42924. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  42925. v1.set(-vFrom.y, vFrom.x, 0);
  42926. } else {
  42927. v1.set(0, -vFrom.z, vFrom.y);
  42928. }
  42929. } else {
  42930. v1.crossVectors(vFrom, vTo);
  42931. }
  42932. this.x = v1.x;
  42933. this.y = v1.y;
  42934. this.z = v1.z;
  42935. this.w = r;
  42936. this.normalize();
  42937. return this;
  42938. };
  42939. }()
  42940. };
  42941. function Device(params) {
  42942. this.width = params.width || getScreenWidth();
  42943. this.height = params.height || getScreenHeight();
  42944. this.widthMeters = params.widthMeters;
  42945. this.heightMeters = params.heightMeters;
  42946. this.bevelMeters = params.bevelMeters;
  42947. }
  42948. var DEFAULT_ANDROID = new Device({
  42949. widthMeters: 0.110,
  42950. heightMeters: 0.062,
  42951. bevelMeters: 0.004
  42952. });
  42953. var DEFAULT_IOS = new Device({
  42954. widthMeters: 0.1038,
  42955. heightMeters: 0.0584,
  42956. bevelMeters: 0.004
  42957. });
  42958. var Viewers = {
  42959. CardboardV1: new CardboardViewer({
  42960. id: 'CardboardV1',
  42961. label: 'Cardboard I/O 2014',
  42962. fov: 40,
  42963. interLensDistance: 0.060,
  42964. baselineLensDistance: 0.035,
  42965. screenLensDistance: 0.042,
  42966. distortionCoefficients: [0.441, 0.156],
  42967. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139, -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841, 0.0651772, -0.01488963, 0.001559834]
  42968. }),
  42969. CardboardV2: new CardboardViewer({
  42970. id: 'CardboardV2',
  42971. label: 'Cardboard I/O 2015',
  42972. fov: 60,
  42973. interLensDistance: 0.064,
  42974. baselineLensDistance: 0.035,
  42975. screenLensDistance: 0.039,
  42976. distortionCoefficients: [0.34, 0.55],
  42977. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051, 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956, -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  42978. })
  42979. };
  42980. function DeviceInfo(deviceParams, additionalViewers) {
  42981. this.viewer = Viewers.CardboardV2;
  42982. this.updateDeviceParams(deviceParams);
  42983. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  42984. for (var i = 0; i < additionalViewers.length; i++) {
  42985. var viewer = additionalViewers[i];
  42986. Viewers[viewer.id] = new CardboardViewer(viewer);
  42987. }
  42988. }
  42989. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  42990. this.device = this.determineDevice_(deviceParams) || this.device;
  42991. };
  42992. DeviceInfo.prototype.getDevice = function () {
  42993. return this.device;
  42994. };
  42995. DeviceInfo.prototype.setViewer = function (viewer) {
  42996. this.viewer = viewer;
  42997. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  42998. };
  42999. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  43000. if (!deviceParams) {
  43001. if (isIOS()) {
  43002. console.warn('Using fallback iOS device measurements.');
  43003. return DEFAULT_IOS;
  43004. } else {
  43005. console.warn('Using fallback Android device measurements.');
  43006. return DEFAULT_ANDROID;
  43007. }
  43008. }
  43009. var METERS_PER_INCH = 0.0254;
  43010. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  43011. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  43012. var width = getScreenWidth();
  43013. var height = getScreenHeight();
  43014. return new Device({
  43015. widthMeters: metersPerPixelX * width,
  43016. heightMeters: metersPerPixelY * height,
  43017. bevelMeters: deviceParams.bevelMm * 0.001
  43018. });
  43019. };
  43020. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  43021. var viewer = this.viewer;
  43022. var device = this.device;
  43023. var distortion = this.distortion;
  43024. var eyeToScreenDistance = viewer.screenLensDistance;
  43025. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  43026. var innerDist = viewer.interLensDistance / 2;
  43027. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  43028. var topDist = device.heightMeters - bottomDist;
  43029. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  43030. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  43031. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  43032. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  43033. return {
  43034. leftDegrees: Math.min(outerAngle, viewer.fov),
  43035. rightDegrees: Math.min(innerAngle, viewer.fov),
  43036. downDegrees: Math.min(bottomAngle, viewer.fov),
  43037. upDegrees: Math.min(topAngle, viewer.fov)
  43038. };
  43039. };
  43040. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  43041. var viewer = this.viewer;
  43042. var device = this.device;
  43043. var distortion = this.distortion;
  43044. var fovLeft = Math.tan(-degToRad * viewer.fov);
  43045. var fovTop = Math.tan(degToRad * viewer.fov);
  43046. var fovRight = Math.tan(degToRad * viewer.fov);
  43047. var fovBottom = Math.tan(-degToRad * viewer.fov);
  43048. var halfWidth = device.widthMeters / 4;
  43049. var halfHeight = device.heightMeters / 2;
  43050. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  43051. var centerX = viewer.interLensDistance / 2 - halfWidth;
  43052. var centerY = -verticalLensOffset;
  43053. var centerZ = viewer.screenLensDistance;
  43054. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  43055. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  43056. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  43057. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  43058. var result = new Float32Array(4);
  43059. result[0] = Math.max(fovLeft, screenLeft);
  43060. result[1] = Math.min(fovTop, screenTop);
  43061. result[2] = Math.min(fovRight, screenRight);
  43062. result[3] = Math.max(fovBottom, screenBottom);
  43063. return result;
  43064. };
  43065. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  43066. var viewer = this.viewer;
  43067. var device = this.device;
  43068. var distortion = this.distortion;
  43069. var result = new Float32Array(4);
  43070. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  43071. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  43072. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  43073. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  43074. var halfWidth = device.widthMeters / 4;
  43075. var halfHeight = device.heightMeters / 2;
  43076. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  43077. var centerX = viewer.interLensDistance / 2 - halfWidth;
  43078. var centerY = -verticalLensOffset;
  43079. var centerZ = viewer.screenLensDistance;
  43080. var screenLeft = (centerX - halfWidth) / centerZ;
  43081. var screenTop = (centerY + halfHeight) / centerZ;
  43082. var screenRight = (centerX + halfWidth) / centerZ;
  43083. var screenBottom = (centerY - halfHeight) / centerZ;
  43084. result[0] = Math.max(fovLeft, screenLeft);
  43085. result[1] = Math.min(fovTop, screenTop);
  43086. result[2] = Math.min(fovRight, screenRight);
  43087. result[3] = Math.max(fovBottom, screenBottom);
  43088. return result;
  43089. };
  43090. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  43091. var viewer = this.viewer;
  43092. var device = this.device;
  43093. var dist = viewer.screenLensDistance;
  43094. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  43095. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  43096. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  43097. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  43098. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  43099. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  43100. return {
  43101. x: left,
  43102. y: bottom,
  43103. width: right - left,
  43104. height: top - bottom
  43105. };
  43106. };
  43107. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  43108. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  43109. };
  43110. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  43111. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  43112. return {
  43113. leftDegrees: fov.rightDegrees,
  43114. rightDegrees: fov.leftDegrees,
  43115. upDegrees: fov.upDegrees,
  43116. downDegrees: fov.downDegrees
  43117. };
  43118. };
  43119. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  43120. var p = this.getUndistortedParams_();
  43121. return {
  43122. leftDegrees: radToDeg * Math.atan(p.outerDist),
  43123. rightDegrees: radToDeg * Math.atan(p.innerDist),
  43124. downDegrees: radToDeg * Math.atan(p.bottomDist),
  43125. upDegrees: radToDeg * Math.atan(p.topDist)
  43126. };
  43127. };
  43128. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  43129. var p = this.getUndistortedParams_();
  43130. var viewer = this.viewer;
  43131. var device = this.device;
  43132. var eyeToScreenDistance = viewer.screenLensDistance;
  43133. var screenWidth = device.widthMeters / eyeToScreenDistance;
  43134. var screenHeight = device.heightMeters / eyeToScreenDistance;
  43135. var xPxPerTanAngle = device.width / screenWidth;
  43136. var yPxPerTanAngle = device.height / screenHeight;
  43137. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  43138. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  43139. return {
  43140. x: x,
  43141. y: y,
  43142. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  43143. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  43144. };
  43145. };
  43146. DeviceInfo.prototype.getUndistortedParams_ = function () {
  43147. var viewer = this.viewer;
  43148. var device = this.device;
  43149. var distortion = this.distortion;
  43150. var eyeToScreenDistance = viewer.screenLensDistance;
  43151. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  43152. var screenWidth = device.widthMeters / eyeToScreenDistance;
  43153. var screenHeight = device.heightMeters / eyeToScreenDistance;
  43154. var eyePosX = screenWidth / 2 - halfLensDistance;
  43155. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  43156. var maxFov = viewer.fov;
  43157. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  43158. var outerDist = Math.min(eyePosX, viewerMax);
  43159. var innerDist = Math.min(halfLensDistance, viewerMax);
  43160. var bottomDist = Math.min(eyePosY, viewerMax);
  43161. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  43162. return {
  43163. outerDist: outerDist,
  43164. innerDist: innerDist,
  43165. topDist: topDist,
  43166. bottomDist: bottomDist,
  43167. eyePosX: eyePosX,
  43168. eyePosY: eyePosY
  43169. };
  43170. };
  43171. function CardboardViewer(params) {
  43172. this.id = params.id;
  43173. this.label = params.label;
  43174. this.fov = params.fov;
  43175. this.interLensDistance = params.interLensDistance;
  43176. this.baselineLensDistance = params.baselineLensDistance;
  43177. this.screenLensDistance = params.screenLensDistance;
  43178. this.distortionCoefficients = params.distortionCoefficients;
  43179. this.inverseCoefficients = params.inverseCoefficients;
  43180. }
  43181. DeviceInfo.Viewers = Viewers;
  43182. var format = 1;
  43183. var last_updated = "2019-11-09T17:36:14Z";
  43184. var devices = [{"type":"android","rules":[{"mdmh":"asus/*/Nexus 7/*"},{"ua":"Nexus 7"}],"dpi":[320.8,323],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_X00PD/*"},{"ua":"ASUS_X00PD"}],"dpi":245,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_X008D/*"},{"ua":"ASUS_X008D"}],"dpi":282,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_Z00AD/*"},{"ua":"ASUS_Z00AD"}],"dpi":[403,404.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 2 XL/*"},{"ua":"Pixel 2 XL"}],"dpi":537.9,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 3 XL/*"},{"ua":"Pixel 3 XL"}],"dpi":[558.5,553.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel XL/*"},{"ua":"Pixel XL"}],"dpi":[537.9,533],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 3/*"},{"ua":"Pixel 3"}],"dpi":442.4,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 2/*"},{"ua":"Pixel 2"}],"dpi":441,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"Google/*/Pixel/*"},{"ua":"Pixel"}],"dpi":[432.6,436.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"HTC/*/HTC6435LVW/*"},{"ua":"HTC6435LVW"}],"dpi":[449.7,443.3],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One XL/*"},{"ua":"HTC One XL"}],"dpi":[315.3,314.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"htc/*/Nexus 9/*"},{"ua":"Nexus 9"}],"dpi":289,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One M9/*"},{"ua":"HTC One M9"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One_M8/*"},{"ua":"HTC One_M8"}],"dpi":[449.7,447.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One/*"},{"ua":"HTC One"}],"dpi":472.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/Nexus 6P/*"},{"ua":"Nexus 6P"}],"dpi":[515.1,518],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/BLN-L24/*"},{"ua":"HONORBLN-L24"}],"dpi":480,"bw":4,"ac":500},{"type":"android","rules":[{"mdmh":"Huawei/*/BKL-L09/*"},{"ua":"BKL-L09"}],"dpi":403,"bw":3.47,"ac":500},{"type":"android","rules":[{"mdmh":"LENOVO/*/Lenovo PB2-690Y/*"},{"ua":"Lenovo PB2-690Y"}],"dpi":[457.2,454.713],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 5X/*"},{"ua":"Nexus 5X"}],"dpi":[422,419.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGMS345/*"},{"ua":"LGMS345"}],"dpi":[221.7,219.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/LG-D800/*"},{"ua":"LG-D800"}],"dpi":[422,424.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/LG-D850/*"},{"ua":"LG-D850"}],"dpi":[537.9,541.9],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/VS985 4G/*"},{"ua":"VS985 4G"}],"dpi":[537.9,535.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 5/*"},{"ua":"Nexus 5 B"}],"dpi":[442.4,444.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 4/*"},{"ua":"Nexus 4"}],"dpi":[319.8,318.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LG-P769/*"},{"ua":"LG-P769"}],"dpi":[240.6,247.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGMS323/*"},{"ua":"LGMS323"}],"dpi":[206.6,204.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGLS996/*"},{"ua":"LGLS996"}],"dpi":[403.4,401.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/4560MMX/*"},{"ua":"4560MMX"}],"dpi":[240,219.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/A250/*"},{"ua":"Micromax A250"}],"dpi":[480,446.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/Micromax AQ4501/*"},{"ua":"Micromax AQ4501"}],"dpi":240,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/G5/*"},{"ua":"Moto G (5) Plus"}],"dpi":[403.4,403],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/DROID RAZR/*"},{"ua":"DROID RAZR"}],"dpi":[368.1,256.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT830C/*"},{"ua":"XT830C"}],"dpi":[254,255.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1021/*"},{"ua":"XT1021"}],"dpi":[254,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1023/*"},{"ua":"XT1023"}],"dpi":[254,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1028/*"},{"ua":"XT1028"}],"dpi":[326.6,327.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1034/*"},{"ua":"XT1034"}],"dpi":[326.6,328.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1053/*"},{"ua":"XT1053"}],"dpi":[315.3,316.1],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1562/*"},{"ua":"XT1562"}],"dpi":[403.4,402.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/Nexus 6/*"},{"ua":"Nexus 6 B"}],"dpi":[494.3,489.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1063/*"},{"ua":"XT1063"}],"dpi":[295,296.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1064/*"},{"ua":"XT1064"}],"dpi":[295,295.6],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1092/*"},{"ua":"XT1092"}],"dpi":[422,424.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1095/*"},{"ua":"XT1095"}],"dpi":[422,423.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/G4/*"},{"ua":"Moto G (4)"}],"dpi":401,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/A0001/*"},{"ua":"A0001"}],"dpi":[403.4,401],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1001/*"},{"ua":"ONE E1001"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1003/*"},{"ua":"ONE E1003"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1005/*"},{"ua":"ONE E1005"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2001/*"},{"ua":"ONE A2001"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2003/*"},{"ua":"ONE A2003"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2005/*"},{"ua":"ONE A2005"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A3000/*"},{"ua":"ONEPLUS A3000"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A3003/*"},{"ua":"ONEPLUS A3003"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A3010/*"},{"ua":"ONEPLUS A3010"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A5000/*"},{"ua":"ONEPLUS A5000 "}],"dpi":[403.411,399.737],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A5010/*"},{"ua":"ONEPLUS A5010"}],"dpi":[403,400],"bw":2,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6000/*"},{"ua":"ONEPLUS A6000"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6003/*"},{"ua":"ONEPLUS A6003"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6010/*"},{"ua":"ONEPLUS A6010"}],"dpi":401,"bw":2,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6013/*"},{"ua":"ONEPLUS A6013"}],"dpi":401,"bw":2,"ac":500},{"type":"android","rules":[{"mdmh":"OPPO/*/X909/*"},{"ua":"X909"}],"dpi":[442.4,444.1],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9082/*"},{"ua":"GT-I9082"}],"dpi":[184.7,185.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G360P/*"},{"ua":"SM-G360P"}],"dpi":[196.7,205.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/Nexus S/*"},{"ua":"Nexus S"}],"dpi":[234.5,229.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300/*"},{"ua":"GT-I9300"}],"dpi":[304.8,303.9],"bw":5,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-T230NU/*"},{"ua":"SM-T230NU"}],"dpi":216,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SGH-T399/*"},{"ua":"SGH-T399"}],"dpi":[217.7,231.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SGH-M919/*"},{"ua":"SGH-M919"}],"dpi":[440.8,437.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N9005/*"},{"ua":"SM-N9005"}],"dpi":[386.4,387],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SAMSUNG-SM-N900A/*"},{"ua":"SAMSUNG-SM-N900A"}],"dpi":[386.4,387.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9500/*"},{"ua":"GT-I9500"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9505/*"},{"ua":"GT-I9505"}],"dpi":439.4,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G900F/*"},{"ua":"SM-G900F"}],"dpi":[415.6,431.6],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G900M/*"},{"ua":"SM-G900M"}],"dpi":[415.6,431.6],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G800F/*"},{"ua":"SM-G800F"}],"dpi":326.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G906S/*"},{"ua":"SM-G906S"}],"dpi":[562.7,572.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300/*"},{"ua":"GT-I9300"}],"dpi":[306.7,304.8],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-T535/*"},{"ua":"SM-T535"}],"dpi":[142.6,136.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920C/*"},{"ua":"SM-N920C"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920P/*"},{"ua":"SM-N920P"}],"dpi":[386.3655,390.144],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920W8/*"},{"ua":"SM-N920W8"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300I/*"},{"ua":"GT-I9300I"}],"dpi":[304.8,305.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9195/*"},{"ua":"GT-I9195"}],"dpi":[249.4,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SPH-L520/*"},{"ua":"SPH-L520"}],"dpi":[249.4,255.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SAMSUNG-SGH-I717/*"},{"ua":"SAMSUNG-SGH-I717"}],"dpi":285.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SPH-D710/*"},{"ua":"SPH-D710"}],"dpi":[217.7,204.2],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-N7100/*"},{"ua":"GT-N7100"}],"dpi":265.1,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SCH-I605/*"},{"ua":"SCH-I605"}],"dpi":265.1,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/Galaxy Nexus/*"},{"ua":"Galaxy Nexus"}],"dpi":[315.3,314.2],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N910H/*"},{"ua":"SM-N910H"}],"dpi":[515.1,518],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N910C/*"},{"ua":"SM-N910C"}],"dpi":[515.2,520.2],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G130M/*"},{"ua":"SM-G130M"}],"dpi":[165.9,164.8],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G928I/*"},{"ua":"SM-G928I"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G920F/*"},{"ua":"SM-G920F"}],"dpi":580.6,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G920P/*"},{"ua":"SM-G920P"}],"dpi":[522.5,577],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G925F/*"},{"ua":"SM-G925F"}],"dpi":580.6,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G925V/*"},{"ua":"SM-G925V"}],"dpi":[522.5,576.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G930F/*"},{"ua":"SM-G930F"}],"dpi":576.6,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G935F/*"},{"ua":"SM-G935F"}],"dpi":533,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G950F/*"},{"ua":"SM-G950F"}],"dpi":[562.707,565.293],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G955U/*"},{"ua":"SM-G955U"}],"dpi":[522.514,525.762],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G955F/*"},{"ua":"SM-G955F"}],"dpi":[522.514,525.762],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960F/*"},{"ua":"SM-G960F"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G9600/*"},{"ua":"SM-G9600"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960T/*"},{"ua":"SM-G960T"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960N/*"},{"ua":"SM-G960N"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960U/*"},{"ua":"SM-G960U"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G9608/*"},{"ua":"SM-G9608"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960FD/*"},{"ua":"SM-G960FD"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960W/*"},{"ua":"SM-G960W"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G965F/*"},{"ua":"SM-G965F"}],"dpi":529,"bw":2,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/C6903/*"},{"ua":"C6903"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"Sony/*/D6653/*"},{"ua":"D6653"}],"dpi":[428.6,427.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/E6653/*"},{"ua":"E6653"}],"dpi":[428.6,425.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/E6853/*"},{"ua":"E6853"}],"dpi":[403.4,401.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/SGP321/*"},{"ua":"SGP321"}],"dpi":[224.7,224.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"TCT/*/ALCATEL ONE TOUCH Fierce/*"},{"ua":"ALCATEL ONE TOUCH Fierce"}],"dpi":[240,247.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"THL/*/thl 5000/*"},{"ua":"thl 5000"}],"dpi":[480,443.3],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Fly/*/IQ4412/*"},{"ua":"IQ4412"}],"dpi":307.9,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"ZTE/*/ZTE Blade L2/*"},{"ua":"ZTE Blade L2"}],"dpi":240,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"BENEVE/*/VR518/*"},{"ua":"VR518"}],"dpi":480,"bw":3,"ac":500},{"type":"ios","rules":[{"res":[640,960]}],"dpi":[325.1,328.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[640,1136]}],"dpi":[317.1,320.2],"bw":3,"ac":1000},{"type":"ios","rules":[{"res":[750,1334]}],"dpi":326.4,"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1242,2208]}],"dpi":[453.6,458.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1125,2001]}],"dpi":[410.9,415.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1125,2436]}],"dpi":458,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/EML-L29/*"},{"ua":"EML-L29"}],"dpi":428,"bw":3.45,"ac":500},{"type":"android","rules":[{"mdmh":"Nokia/*/Nokia 7.1/*"},{"ua":"Nokia 7.1"}],"dpi":[432,431.9],"bw":3,"ac":500},{"type":"ios","rules":[{"res":[1242,2688]}],"dpi":458,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G570M/*"},{"ua":"SM-G570M"}],"dpi":320,"bw":3.684,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G970F/*"},{"ua":"SM-G970F"}],"dpi":438,"bw":2.281,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G973F/*"},{"ua":"SM-G973F"}],"dpi":550,"bw":2.002,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G975F/*"},{"ua":"SM-G975F"}],"dpi":522,"bw":2.054,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G977F/*"},{"ua":"SM-G977F"}],"dpi":505,"bw":2.334,"ac":500},{"type":"ios","rules":[{"res":[828,1792]}],"dpi":326,"bw":5,"ac":500}];
  43185. var DPDB_CACHE = {
  43186. format: format,
  43187. last_updated: last_updated,
  43188. devices: devices
  43189. };
  43190. function Dpdb(url, onDeviceParamsUpdated) {
  43191. this.dpdb = DPDB_CACHE;
  43192. this.recalculateDeviceParams_();
  43193. if (url) {
  43194. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  43195. var xhr = new XMLHttpRequest();
  43196. var obj = this;
  43197. xhr.open('GET', url, true);
  43198. xhr.addEventListener('load', function () {
  43199. obj.loading = false;
  43200. if (xhr.status >= 200 && xhr.status <= 299) {
  43201. obj.dpdb = JSON.parse(xhr.response);
  43202. obj.recalculateDeviceParams_();
  43203. } else {
  43204. console.error('Error loading online DPDB!');
  43205. }
  43206. });
  43207. xhr.send();
  43208. }
  43209. }
  43210. Dpdb.prototype.getDeviceParams = function () {
  43211. return this.deviceParams;
  43212. };
  43213. Dpdb.prototype.recalculateDeviceParams_ = function () {
  43214. var newDeviceParams = this.calcDeviceParams_();
  43215. if (newDeviceParams) {
  43216. this.deviceParams = newDeviceParams;
  43217. if (this.onDeviceParamsUpdated) {
  43218. this.onDeviceParamsUpdated(this.deviceParams);
  43219. }
  43220. } else {
  43221. console.error('Failed to recalculate device parameters.');
  43222. }
  43223. };
  43224. Dpdb.prototype.calcDeviceParams_ = function () {
  43225. var db = this.dpdb;
  43226. if (!db) {
  43227. console.error('DPDB not available.');
  43228. return null;
  43229. }
  43230. if (db.format != 1) {
  43231. console.error('DPDB has unexpected format version.');
  43232. return null;
  43233. }
  43234. if (!db.devices || !db.devices.length) {
  43235. console.error('DPDB does not have a devices section.');
  43236. return null;
  43237. }
  43238. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  43239. var width = getScreenWidth();
  43240. var height = getScreenHeight();
  43241. if (!db.devices) {
  43242. console.error('DPDB has no devices section.');
  43243. return null;
  43244. }
  43245. for (var i = 0; i < db.devices.length; i++) {
  43246. var device = db.devices[i];
  43247. if (!device.rules) {
  43248. console.warn('Device[' + i + '] has no rules section.');
  43249. continue;
  43250. }
  43251. if (device.type != 'ios' && device.type != 'android') {
  43252. console.warn('Device[' + i + '] has invalid type.');
  43253. continue;
  43254. }
  43255. if (isIOS() != (device.type == 'ios')) continue;
  43256. var matched = false;
  43257. for (var j = 0; j < device.rules.length; j++) {
  43258. var rule = device.rules[j];
  43259. if (this.ruleMatches_(rule, userAgent, width, height)) {
  43260. matched = true;
  43261. break;
  43262. }
  43263. }
  43264. if (!matched) continue;
  43265. var xdpi = device.dpi[0] || device.dpi;
  43266. var ydpi = device.dpi[1] || device.dpi;
  43267. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  43268. }
  43269. console.warn('No DPDB device match.');
  43270. return null;
  43271. };
  43272. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  43273. if (!rule.ua && !rule.res) return false;
  43274. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  43275. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  43276. if (rule.res) {
  43277. if (!rule.res[0] || !rule.res[1]) return false;
  43278. var resX = rule.res[0];
  43279. var resY = rule.res[1];
  43280. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  43281. return false;
  43282. }
  43283. }
  43284. return true;
  43285. };
  43286. function DeviceParams(params) {
  43287. this.xdpi = params.xdpi;
  43288. this.ydpi = params.ydpi;
  43289. this.bevelMm = params.bevelMm;
  43290. }
  43291. function SensorSample(sample, timestampS) {
  43292. this.set(sample, timestampS);
  43293. }
  43294. SensorSample.prototype.set = function (sample, timestampS) {
  43295. this.sample = sample;
  43296. this.timestampS = timestampS;
  43297. };
  43298. SensorSample.prototype.copy = function (sensorSample) {
  43299. this.set(sensorSample.sample, sensorSample.timestampS);
  43300. };
  43301. function ComplementaryFilter(kFilter, isDebug) {
  43302. this.kFilter = kFilter;
  43303. this.isDebug = isDebug;
  43304. this.currentAccelMeasurement = new SensorSample();
  43305. this.currentGyroMeasurement = new SensorSample();
  43306. this.previousGyroMeasurement = new SensorSample();
  43307. if (isIOS()) {
  43308. this.filterQ = new Quaternion(-1, 0, 0, 1);
  43309. } else {
  43310. this.filterQ = new Quaternion(1, 0, 0, 1);
  43311. }
  43312. this.previousFilterQ = new Quaternion();
  43313. this.previousFilterQ.copy(this.filterQ);
  43314. this.accelQ = new Quaternion();
  43315. this.isOrientationInitialized = false;
  43316. this.estimatedGravity = new Vector3();
  43317. this.measuredGravity = new Vector3();
  43318. this.gyroIntegralQ = new Quaternion();
  43319. }
  43320. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  43321. this.currentAccelMeasurement.set(vector, timestampS);
  43322. };
  43323. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  43324. this.currentGyroMeasurement.set(vector, timestampS);
  43325. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  43326. if (isTimestampDeltaValid(deltaT)) {
  43327. this.run_();
  43328. }
  43329. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  43330. };
  43331. ComplementaryFilter.prototype.run_ = function () {
  43332. if (!this.isOrientationInitialized) {
  43333. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  43334. this.previousFilterQ.copy(this.accelQ);
  43335. this.isOrientationInitialized = true;
  43336. return;
  43337. }
  43338. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  43339. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  43340. this.gyroIntegralQ.multiply(gyroDeltaQ);
  43341. this.filterQ.copy(this.previousFilterQ);
  43342. this.filterQ.multiply(gyroDeltaQ);
  43343. var invFilterQ = new Quaternion();
  43344. invFilterQ.copy(this.filterQ);
  43345. invFilterQ.inverse();
  43346. this.estimatedGravity.set(0, 0, -1);
  43347. this.estimatedGravity.applyQuaternion(invFilterQ);
  43348. this.estimatedGravity.normalize();
  43349. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  43350. this.measuredGravity.normalize();
  43351. var deltaQ = new Quaternion();
  43352. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  43353. deltaQ.inverse();
  43354. if (this.isDebug) {
  43355. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)', radToDeg * getQuaternionAngle(deltaQ), this.estimatedGravity.x.toFixed(1), this.estimatedGravity.y.toFixed(1), this.estimatedGravity.z.toFixed(1), this.measuredGravity.x.toFixed(1), this.measuredGravity.y.toFixed(1), this.measuredGravity.z.toFixed(1));
  43356. }
  43357. var targetQ = new Quaternion();
  43358. targetQ.copy(this.filterQ);
  43359. targetQ.multiply(deltaQ);
  43360. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  43361. this.previousFilterQ.copy(this.filterQ);
  43362. };
  43363. ComplementaryFilter.prototype.getOrientation = function () {
  43364. return this.filterQ;
  43365. };
  43366. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  43367. var normAccel = new Vector3();
  43368. normAccel.copy(accel);
  43369. normAccel.normalize();
  43370. var quat = new Quaternion();
  43371. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  43372. quat.inverse();
  43373. return quat;
  43374. };
  43375. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  43376. var quat = new Quaternion();
  43377. var axis = new Vector3();
  43378. axis.copy(gyro);
  43379. axis.normalize();
  43380. quat.setFromAxisAngle(axis, gyro.length() * dt);
  43381. return quat;
  43382. };
  43383. function PosePredictor(predictionTimeS, isDebug) {
  43384. this.predictionTimeS = predictionTimeS;
  43385. this.isDebug = isDebug;
  43386. this.previousQ = new Quaternion();
  43387. this.previousTimestampS = null;
  43388. this.deltaQ = new Quaternion();
  43389. this.outQ = new Quaternion();
  43390. }
  43391. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  43392. if (!this.previousTimestampS) {
  43393. this.previousQ.copy(currentQ);
  43394. this.previousTimestampS = timestampS;
  43395. return currentQ;
  43396. }
  43397. var axis = new Vector3();
  43398. axis.copy(gyro);
  43399. axis.normalize();
  43400. var angularSpeed = gyro.length();
  43401. if (angularSpeed < degToRad * 20) {
  43402. if (this.isDebug) {
  43403. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  43404. }
  43405. this.outQ.copy(currentQ);
  43406. this.previousQ.copy(currentQ);
  43407. return this.outQ;
  43408. }
  43409. var predictAngle = angularSpeed * this.predictionTimeS;
  43410. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  43411. this.outQ.copy(this.previousQ);
  43412. this.outQ.multiply(this.deltaQ);
  43413. this.previousQ.copy(currentQ);
  43414. this.previousTimestampS = timestampS;
  43415. return this.outQ;
  43416. };
  43417. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  43418. this.yawOnly = yawOnly;
  43419. this.accelerometer = new Vector3();
  43420. this.gyroscope = new Vector3();
  43421. this.filter = new ComplementaryFilter(kFilter, isDebug);
  43422. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  43423. this.isFirefoxAndroid = isFirefoxAndroid();
  43424. this.isIOS = isIOS();
  43425. var chromeVersion = getChromeVersion();
  43426. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  43427. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion() || isSafariWithoutDeviceMotion();
  43428. this.filterToWorldQ = new Quaternion();
  43429. if (isIOS()) {
  43430. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  43431. } else {
  43432. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  43433. }
  43434. this.inverseWorldToScreenQ = new Quaternion();
  43435. this.worldToScreenQ = new Quaternion();
  43436. this.originalPoseAdjustQ = new Quaternion();
  43437. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  43438. this.setScreenTransform_();
  43439. if (isLandscapeMode()) {
  43440. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  43441. }
  43442. this.resetQ = new Quaternion();
  43443. this.orientationOut_ = new Float32Array(4);
  43444. this.start();
  43445. }
  43446. FusionPoseSensor.prototype.getPosition = function () {
  43447. return null;
  43448. };
  43449. FusionPoseSensor.prototype.getOrientation = function () {
  43450. var orientation = void 0;
  43451. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  43452. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  43453. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  43454. var y = new Quaternion();
  43455. if (window.orientation === -90) {
  43456. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  43457. } else {
  43458. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  43459. }
  43460. return z.multiply(y);
  43461. }();
  43462. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  43463. var q = new Quaternion();
  43464. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  43465. return q;
  43466. }();
  43467. orientation = this._deviceOrientationQ;
  43468. var out = new Quaternion();
  43469. out.copy(orientation);
  43470. out.multiply(this.deviceOrientationFilterToWorldQ);
  43471. out.multiply(this.resetQ);
  43472. out.multiply(this.worldToScreenQ);
  43473. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  43474. if (this.yawOnly) {
  43475. out.x = 0;
  43476. out.z = 0;
  43477. out.normalize();
  43478. }
  43479. this.orientationOut_[0] = out.x;
  43480. this.orientationOut_[1] = out.y;
  43481. this.orientationOut_[2] = out.z;
  43482. this.orientationOut_[3] = out.w;
  43483. return this.orientationOut_;
  43484. } else {
  43485. var filterOrientation = this.filter.getOrientation();
  43486. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  43487. }
  43488. var out = new Quaternion();
  43489. out.copy(this.filterToWorldQ);
  43490. out.multiply(this.resetQ);
  43491. out.multiply(orientation);
  43492. out.multiply(this.worldToScreenQ);
  43493. if (this.yawOnly) {
  43494. out.x = 0;
  43495. out.z = 0;
  43496. out.normalize();
  43497. }
  43498. this.orientationOut_[0] = out.x;
  43499. this.orientationOut_[1] = out.y;
  43500. this.orientationOut_[2] = out.z;
  43501. this.orientationOut_[3] = out.w;
  43502. return this.orientationOut_;
  43503. };
  43504. FusionPoseSensor.prototype.resetPose = function () {
  43505. this.resetQ.copy(this.filter.getOrientation());
  43506. this.resetQ.x = 0;
  43507. this.resetQ.y = 0;
  43508. this.resetQ.z *= -1;
  43509. this.resetQ.normalize();
  43510. if (isLandscapeMode()) {
  43511. this.resetQ.multiply(this.inverseWorldToScreenQ);
  43512. }
  43513. this.resetQ.multiply(this.originalPoseAdjustQ);
  43514. };
  43515. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  43516. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  43517. var alpha = e.alpha,
  43518. beta = e.beta,
  43519. gamma = e.gamma;
  43520. alpha = (alpha || 0) * Math.PI / 180;
  43521. beta = (beta || 0) * Math.PI / 180;
  43522. gamma = (gamma || 0) * Math.PI / 180;
  43523. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  43524. };
  43525. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  43526. this.updateDeviceMotion_(deviceMotion);
  43527. };
  43528. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  43529. var accGravity = deviceMotion.accelerationIncludingGravity;
  43530. var rotRate = deviceMotion.rotationRate;
  43531. var timestampS = deviceMotion.timeStamp / 1000;
  43532. var deltaS = timestampS - this.previousTimestampS;
  43533. if (deltaS < 0) {
  43534. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  43535. this.previousTimestampS = timestampS;
  43536. return;
  43537. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  43538. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  43539. this.previousTimestampS = timestampS;
  43540. return;
  43541. }
  43542. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  43543. if (rotRate) {
  43544. if (isR7()) {
  43545. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  43546. } else {
  43547. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  43548. }
  43549. if (!this.isDeviceMotionInRadians) {
  43550. this.gyroscope.multiplyScalar(Math.PI / 180);
  43551. }
  43552. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  43553. }
  43554. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  43555. this.previousTimestampS = timestampS;
  43556. };
  43557. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  43558. this.setScreenTransform_();
  43559. };
  43560. FusionPoseSensor.prototype.onMessage_ = function (event) {
  43561. var message = event.data;
  43562. if (!message || !message.type) {
  43563. return;
  43564. }
  43565. var type = message.type.toLowerCase();
  43566. if (type !== 'devicemotion') {
  43567. return;
  43568. }
  43569. this.updateDeviceMotion_(message.deviceMotionEvent);
  43570. };
  43571. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  43572. this.worldToScreenQ.set(0, 0, 0, 1);
  43573. switch (window.orientation) {
  43574. case 0:
  43575. break;
  43576. case 90:
  43577. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  43578. break;
  43579. case -90:
  43580. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  43581. break;
  43582. case 180:
  43583. break;
  43584. }
  43585. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  43586. this.inverseWorldToScreenQ.inverse();
  43587. };
  43588. FusionPoseSensor.prototype.start = function () {
  43589. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  43590. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  43591. this.onMessageCallback_ = this.onMessage_.bind(this);
  43592. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  43593. if (isIOS() && isInsideCrossOriginIFrame()) {
  43594. window.addEventListener('message', this.onMessageCallback_);
  43595. }
  43596. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  43597. if (this.isWithoutDeviceMotion) {
  43598. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  43599. } else {
  43600. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  43601. }
  43602. };
  43603. FusionPoseSensor.prototype.stop = function () {
  43604. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  43605. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  43606. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  43607. window.removeEventListener('message', this.onMessageCallback_);
  43608. };
  43609. var SENSOR_FREQUENCY = 60;
  43610. var X_AXIS = new Vector3(1, 0, 0);
  43611. var Z_AXIS = new Vector3(0, 0, 1);
  43612. var SENSOR_TO_VR = new Quaternion();
  43613. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  43614. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  43615. var PoseSensor = function () {
  43616. function PoseSensor(config) {
  43617. classCallCheck(this, PoseSensor);
  43618. this.config = config;
  43619. this.sensor = null;
  43620. this.fusionSensor = null;
  43621. this._out = new Float32Array(4);
  43622. this.api = null;
  43623. this.errors = [];
  43624. this._sensorQ = new Quaternion();
  43625. this._outQ = new Quaternion();
  43626. this._onSensorRead = this._onSensorRead.bind(this);
  43627. this._onSensorError = this._onSensorError.bind(this);
  43628. this.init();
  43629. }
  43630. createClass(PoseSensor, [{
  43631. key: 'init',
  43632. value: function init() {
  43633. var sensor = null;
  43634. try {
  43635. sensor = new RelativeOrientationSensor({
  43636. frequency: SENSOR_FREQUENCY,
  43637. referenceFrame: 'screen'
  43638. });
  43639. sensor.addEventListener('error', this._onSensorError);
  43640. } catch (error) {
  43641. this.errors.push(error);
  43642. if (error.name === 'SecurityError') {
  43643. console.error('Cannot construct sensors due to the Feature Policy');
  43644. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  43645. this.useDeviceMotion();
  43646. } else if (error.name === 'ReferenceError') {
  43647. this.useDeviceMotion();
  43648. } else {
  43649. console.error(error);
  43650. }
  43651. }
  43652. if (sensor) {
  43653. this.api = 'sensor';
  43654. this.sensor = sensor;
  43655. this.sensor.addEventListener('reading', this._onSensorRead);
  43656. this.sensor.start();
  43657. }
  43658. }
  43659. }, {
  43660. key: 'useDeviceMotion',
  43661. value: function useDeviceMotion() {
  43662. this.api = 'devicemotion';
  43663. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  43664. if (this.sensor) {
  43665. this.sensor.removeEventListener('reading', this._onSensorRead);
  43666. this.sensor.removeEventListener('error', this._onSensorError);
  43667. this.sensor = null;
  43668. }
  43669. }
  43670. }, {
  43671. key: 'getOrientation',
  43672. value: function getOrientation() {
  43673. if (this.fusionSensor) {
  43674. return this.fusionSensor.getOrientation();
  43675. }
  43676. if (!this.sensor || !this.sensor.quaternion) {
  43677. this._out[0] = this._out[1] = this._out[2] = 0;
  43678. this._out[3] = 1;
  43679. return this._out;
  43680. }
  43681. var q = this.sensor.quaternion;
  43682. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  43683. var out = this._outQ;
  43684. out.copy(SENSOR_TO_VR);
  43685. out.multiply(this._sensorQ);
  43686. if (this.config.YAW_ONLY) {
  43687. out.x = out.z = 0;
  43688. out.normalize();
  43689. }
  43690. this._out[0] = out.x;
  43691. this._out[1] = out.y;
  43692. this._out[2] = out.z;
  43693. this._out[3] = out.w;
  43694. return this._out;
  43695. }
  43696. }, {
  43697. key: '_onSensorError',
  43698. value: function _onSensorError(event) {
  43699. this.errors.push(event.error);
  43700. if (event.error.name === 'NotAllowedError') {
  43701. console.error('Permission to access sensor was denied');
  43702. } else if (event.error.name === 'NotReadableError') {
  43703. console.error('Sensor could not be read');
  43704. } else {
  43705. console.error(event.error);
  43706. }
  43707. this.useDeviceMotion();
  43708. }
  43709. }, {
  43710. key: '_onSensorRead',
  43711. value: function _onSensorRead() {}
  43712. }]);
  43713. return PoseSensor;
  43714. }();
  43715. var rotateInstructionsAsset = "<svg width='198' height='240' viewBox='0 0 198 240' xmlns='http://www.w3.org/2000/svg'><g fill='none' fill-rule='evenodd'><path d='M149.625 109.527l6.737 3.891v.886c0 .177.013.36.038.549.01.081.02.162.027.242.14 1.415.974 2.998 2.105 3.999l5.72 5.062.081-.09s4.382-2.53 5.235-3.024l25.97 14.993v54.001c0 .771-.386 1.217-.948 1.217-.233 0-.495-.076-.772-.236l-23.967-13.838-.014.024-27.322 15.775-.85-1.323c-4.731-1.529-9.748-2.74-14.951-3.61a.27.27 0 0 0-.007.024l-5.067 16.961-7.891 4.556-.037-.063v27.59c0 .772-.386 1.217-.948 1.217-.232 0-.495-.076-.772-.236l-42.473-24.522c-.95-.549-1.72-1.877-1.72-2.967v-1.035l-.021.047a5.111 5.111 0 0 0-1.816-.399 5.682 5.682 0 0 0-.546.001 13.724 13.724 0 0 1-1.918-.041c-1.655-.153-3.2-.6-4.404-1.296l-46.576-26.89.005.012-10.278-18.75c-1.001-1.827-.241-4.216 1.698-5.336l56.011-32.345a4.194 4.194 0 0 1 2.099-.572c1.326 0 2.572.659 3.227 1.853l.005-.003.227.413-.006.004a9.63 9.63 0 0 0 1.477 2.018l.277.27c1.914 1.85 4.468 2.801 7.113 2.801 1.949 0 3.948-.517 5.775-1.572.013 0 7.319-4.219 7.319-4.219a4.194 4.194 0 0 1 2.099-.572c1.326 0 2.572.658 3.226 1.853l3.25 5.928.022-.018 6.785 3.917-.105-.182 46.881-26.965m0-1.635c-.282 0-.563.073-.815.218l-46.169 26.556-5.41-3.124-3.005-5.481c-.913-1.667-2.699-2.702-4.66-2.703-1.011 0-2.02.274-2.917.792a3825 3825 0 0 1-7.275 4.195l-.044.024a9.937 9.937 0 0 1-4.957 1.353c-2.292 0-4.414-.832-5.976-2.342l-.252-.245a7.992 7.992 0 0 1-1.139-1.534 1.379 1.379 0 0 0-.06-.122l-.227-.414a1.718 1.718 0 0 0-.095-.154c-.938-1.574-2.673-2.545-4.571-2.545-1.011 0-2.02.274-2.917.792L3.125 155.502c-2.699 1.559-3.738 4.94-2.314 7.538l10.278 18.75c.177.323.448.563.761.704l46.426 26.804c1.403.81 3.157 1.332 5.072 1.508a15.661 15.661 0 0 0 2.146.046 4.766 4.766 0 0 1 .396 0c.096.004.19.011.283.022.109 1.593 1.159 3.323 2.529 4.114l42.472 24.522c.524.302 1.058.455 1.59.455 1.497 0 2.583-1.2 2.583-2.852v-26.562l7.111-4.105a1.64 1.64 0 0 0 .749-.948l4.658-15.593c4.414.797 8.692 1.848 12.742 3.128l.533.829a1.634 1.634 0 0 0 2.193.531l26.532-15.317L193 192.433c.523.302 1.058.455 1.59.455 1.497 0 2.583-1.199 2.583-2.852v-54.001c0-.584-.312-1.124-.818-1.416l-25.97-14.993a1.633 1.633 0 0 0-1.636.001c-.606.351-2.993 1.73-4.325 2.498l-4.809-4.255c-.819-.725-1.461-1.933-1.561-2.936a7.776 7.776 0 0 0-.033-.294 2.487 2.487 0 0 1-.023-.336v-.886c0-.584-.312-1.123-.817-1.416l-6.739-3.891a1.633 1.633 0 0 0-.817-.219' fill='#455A64'/><path d='M96.027 132.636l46.576 26.891c1.204.695 1.979 1.587 2.242 2.541l-.01.007-81.374 46.982h-.001c-1.654-.152-3.199-.6-4.403-1.295l-46.576-26.891 83.546-48.235' fill='#FAFAFA'/><path d='M63.461 209.174c-.008 0-.015 0-.022-.002-1.693-.156-3.228-.609-4.441-1.309l-46.576-26.89a.118.118 0 0 1 0-.203l83.546-48.235a.117.117 0 0 1 .117 0l46.576 26.891c1.227.708 2.021 1.612 2.296 2.611a.116.116 0 0 1-.042.124l-.021.016-81.375 46.981a.11.11 0 0 1-.058.016zm-50.747-28.303l46.401 26.79c1.178.68 2.671 1.121 4.32 1.276l81.272-46.922c-.279-.907-1.025-1.73-2.163-2.387l-46.517-26.857-83.313 48.1z' fill='#607D8B'/><path d='M148.327 165.471a5.85 5.85 0 0 1-.546.001c-1.894-.083-3.302-1.038-3.145-2.132a2.693 2.693 0 0 0-.072-1.105l-81.103 46.822c.628.058 1.272.073 1.918.042.182-.009.364-.009.546-.001 1.894.083 3.302 1.038 3.145 2.132l79.257-45.759' fill='#FFF'/><path d='M69.07 211.347a.118.118 0 0 1-.115-.134c.045-.317-.057-.637-.297-.925-.505-.61-1.555-1.022-2.738-1.074a5.966 5.966 0 0 0-.535.001 14.03 14.03 0 0 1-1.935-.041.117.117 0 0 1-.103-.092.116.116 0 0 1 .055-.126l81.104-46.822a.117.117 0 0 1 .171.07c.104.381.129.768.074 1.153-.045.316.057.637.296.925.506.61 1.555 1.021 2.739 1.073.178.008.357.008.535-.001a.117.117 0 0 1 .064.218l-79.256 45.759a.114.114 0 0 1-.059.016zm-3.405-2.372c.089 0 .177.002.265.006 1.266.056 2.353.488 2.908 1.158.227.274.35.575.36.882l78.685-45.429c-.036 0-.072-.001-.107-.003-1.267-.056-2.354-.489-2.909-1.158-.282-.34-.402-.724-.347-1.107a2.604 2.604 0 0 0-.032-.91L63.846 208.97a13.91 13.91 0 0 0 1.528.012c.097-.005.194-.007.291-.007z' fill='#607D8B'/><path d='M2.208 162.134c-1.001-1.827-.241-4.217 1.698-5.337l56.011-32.344c1.939-1.12 4.324-.546 5.326 1.281l.232.41a9.344 9.344 0 0 0 1.47 2.021l.278.27c3.325 3.214 8.583 3.716 12.888 1.23l7.319-4.22c1.94-1.119 4.324-.546 5.325 1.282l3.25 5.928-83.519 48.229-10.278-18.75z' fill='#FAFAFA'/><path d='M12.486 181.001a.112.112 0 0 1-.031-.005.114.114 0 0 1-.071-.056L2.106 162.19c-1.031-1.88-.249-4.345 1.742-5.494l56.01-32.344a4.328 4.328 0 0 1 2.158-.588c1.415 0 2.65.702 3.311 1.882.01.008.018.017.024.028l.227.414a.122.122 0 0 1 .013.038 9.508 9.508 0 0 0 1.439 1.959l.275.266c1.846 1.786 4.344 2.769 7.031 2.769 1.977 0 3.954-.538 5.717-1.557a.148.148 0 0 1 .035-.013l7.284-4.206a4.321 4.321 0 0 1 2.157-.588c1.427 0 2.672.716 3.329 1.914l3.249 5.929a.116.116 0 0 1-.044.157l-83.518 48.229a.116.116 0 0 1-.059.016zm49.53-57.004c-.704 0-1.41.193-2.041.557l-56.01 32.345c-1.882 1.086-2.624 3.409-1.655 5.179l10.221 18.645 83.317-48.112-3.195-5.829c-.615-1.122-1.783-1.792-3.124-1.792a4.08 4.08 0 0 0-2.04.557l-7.317 4.225a.148.148 0 0 1-.035.013 11.7 11.7 0 0 1-5.801 1.569c-2.748 0-5.303-1.007-7.194-2.835l-.278-.27a9.716 9.716 0 0 1-1.497-2.046.096.096 0 0 1-.013-.037l-.191-.347a.11.11 0 0 1-.023-.029c-.615-1.123-1.783-1.793-3.124-1.793z' fill='#607D8B'/><path d='M42.434 155.808c-2.51-.001-4.697-1.258-5.852-3.365-1.811-3.304-.438-7.634 3.059-9.654l12.291-7.098a7.599 7.599 0 0 1 3.789-1.033c2.51 0 4.697 1.258 5.852 3.365 1.811 3.304.439 7.634-3.059 9.654l-12.291 7.098a7.606 7.606 0 0 1-3.789 1.033zm13.287-20.683a7.128 7.128 0 0 0-3.555.971l-12.291 7.098c-3.279 1.893-4.573 5.942-2.883 9.024 1.071 1.955 3.106 3.122 5.442 3.122a7.13 7.13 0 0 0 3.556-.97l12.291-7.098c3.279-1.893 4.572-5.942 2.883-9.024-1.072-1.955-3.106-3.123-5.443-3.123z' fill='#607D8B'/><path d='M149.588 109.407l6.737 3.89v.887c0 .176.013.36.037.549.011.081.02.161.028.242.14 1.415.973 2.998 2.105 3.999l7.396 6.545c.177.156.358.295.541.415 1.579 1.04 2.95.466 3.062-1.282.049-.784.057-1.595.023-2.429l-.003-.16v-1.151l25.987 15.003v54c0 1.09-.77 1.53-1.72.982l-42.473-24.523c-.95-.548-1.72-1.877-1.72-2.966v-34.033' fill='#FAFAFA'/><path d='M194.553 191.25c-.257 0-.54-.085-.831-.253l-42.472-24.521c-.981-.567-1.779-1.943-1.779-3.068v-34.033h.234v34.033c0 1.051.745 2.336 1.661 2.866l42.473 24.521c.424.245.816.288 1.103.122.285-.164.442-.52.442-1.002v-53.933l-25.753-14.868.003 1.106c.034.832.026 1.654-.024 2.439-.054.844-.396 1.464-.963 1.746-.619.309-1.45.173-2.28-.373a5.023 5.023 0 0 1-.553-.426l-7.397-6.544c-1.158-1.026-1.999-2.625-2.143-4.076a9.624 9.624 0 0 0-.027-.238 4.241 4.241 0 0 1-.038-.564v-.82l-6.68-3.856.117-.202 6.738 3.89.058.034v.954c0 .171.012.351.036.533.011.083.021.165.029.246.138 1.395.948 2.935 2.065 3.923l7.397 6.545c.173.153.35.289.527.406.758.499 1.504.63 2.047.359.49-.243.786-.795.834-1.551.05-.778.057-1.591.024-2.417l-.004-.163v-1.355l.175.1 25.987 15.004.059.033v54.068c0 .569-.198.996-.559 1.204a1.002 1.002 0 0 1-.506.131' fill='#607D8B'/><path d='M145.685 163.161l24.115 13.922-25.978 14.998-1.462-.307c-6.534-2.17-13.628-3.728-21.019-4.616-4.365-.524-8.663 1.096-9.598 3.62a2.746 2.746 0 0 0-.011 1.928c1.538 4.267 4.236 8.363 7.995 12.135l.532.845-25.977 14.997-24.115-13.922 75.518-43.6' fill='#FFF'/><path d='M94.282 220.818l-.059-.033-24.29-14.024.175-.101 75.577-43.634.058.033 24.29 14.024-26.191 15.122-.045-.01-1.461-.307c-6.549-2.174-13.613-3.725-21.009-4.614a13.744 13.744 0 0 0-1.638-.097c-3.758 0-7.054 1.531-7.837 3.642a2.62 2.62 0 0 0-.01 1.848c1.535 4.258 4.216 8.326 7.968 12.091l.016.021.526.835.006.01.064.102-.105.061-25.977 14.998-.058.033zm-23.881-14.057l23.881 13.788 24.802-14.32c.546-.315.846-.489 1.017-.575l-.466-.74c-3.771-3.787-6.467-7.881-8.013-12.168a2.851 2.851 0 0 1 .011-2.008c.815-2.199 4.203-3.795 8.056-3.795.557 0 1.117.033 1.666.099 7.412.891 14.491 2.445 21.041 4.621.836.175 1.215.254 1.39.304l25.78-14.884-23.881-13.788-75.284 43.466z' fill='#607D8B'/><path d='M167.23 125.979v50.871l-27.321 15.773-6.461-14.167c-.91-1.996-3.428-1.738-5.624.574a10.238 10.238 0 0 0-2.33 4.018l-6.46 21.628-27.322 15.774v-50.871l75.518-43.6' fill='#FFF'/><path d='M91.712 220.567a.127.127 0 0 1-.059-.016.118.118 0 0 1-.058-.101v-50.871c0-.042.023-.08.058-.101l75.519-43.6a.117.117 0 0 1 .175.101v50.871c0 .041-.023.08-.059.1l-27.321 15.775a.118.118 0 0 1-.094.01.12.12 0 0 1-.071-.063l-6.46-14.168c-.375-.822-1.062-1.275-1.934-1.275-1.089 0-2.364.686-3.5 1.881a10.206 10.206 0 0 0-2.302 3.972l-6.46 21.627a.118.118 0 0 1-.054.068L91.77 220.551a.12.12 0 0 1-.058.016zm.117-50.92v50.601l27.106-15.65 6.447-21.583a10.286 10.286 0 0 1 2.357-4.065c1.18-1.242 2.517-1.954 3.669-1.954.969 0 1.731.501 2.146 1.411l6.407 14.051 27.152-15.676v-50.601l-75.284 43.466z' fill='#607D8B'/><path d='M168.543 126.213v50.87l-27.322 15.774-6.46-14.168c-.91-1.995-3.428-1.738-5.624.574a10.248 10.248 0 0 0-2.33 4.019l-6.461 21.627-27.321 15.774v-50.87l75.518-43.6' fill='#FFF'/><path d='M93.025 220.8a.123.123 0 0 1-.059-.015.12.12 0 0 1-.058-.101v-50.871c0-.042.023-.08.058-.101l75.518-43.6a.112.112 0 0 1 .117 0c.036.02.059.059.059.1v50.871a.116.116 0 0 1-.059.101l-27.321 15.774a.111.111 0 0 1-.094.01.115.115 0 0 1-.071-.062l-6.46-14.168c-.375-.823-1.062-1.275-1.935-1.275-1.088 0-2.363.685-3.499 1.881a10.19 10.19 0 0 0-2.302 3.971l-6.461 21.628a.108.108 0 0 1-.053.067l-27.322 15.775a.12.12 0 0 1-.058.015zm.117-50.919v50.6l27.106-15.649 6.447-21.584a10.293 10.293 0 0 1 2.357-4.065c1.179-1.241 2.516-1.954 3.668-1.954.969 0 1.732.502 2.147 1.412l6.407 14.051 27.152-15.676v-50.601l-75.284 43.466z' fill='#607D8B'/><path d='M169.8 177.083l-27.322 15.774-6.46-14.168c-.91-1.995-3.428-1.738-5.625.574a10.246 10.246 0 0 0-2.329 4.019l-6.461 21.627-27.321 15.774v-50.87l75.518-43.6v50.87z' fill='#FAFAFA'/><path d='M94.282 220.917a.234.234 0 0 1-.234-.233v-50.871c0-.083.045-.161.117-.202l75.518-43.601a.234.234 0 1 1 .35.202v50.871a.233.233 0 0 1-.116.202l-27.322 15.775a.232.232 0 0 1-.329-.106l-6.461-14.168c-.36-.789-.992-1.206-1.828-1.206-1.056 0-2.301.672-3.415 1.844a10.099 10.099 0 0 0-2.275 3.924l-6.46 21.628a.235.235 0 0 1-.107.136l-27.322 15.774a.23.23 0 0 1-.116.031zm.233-50.969v50.331l26.891-15.525 6.434-21.539a10.41 10.41 0 0 1 2.384-4.112c1.201-1.265 2.569-1.991 3.753-1.991 1.018 0 1.818.526 2.253 1.48l6.354 13.934 26.982-15.578v-50.331l-75.051 43.331z' fill='#607D8B'/><path d='M109.894 199.943c-1.774 0-3.241-.725-4.244-2.12a.224.224 0 0 1 .023-.294.233.233 0 0 1 .301-.023c.78.547 1.705.827 2.75.827 1.323 0 2.754-.439 4.256-1.306 5.311-3.067 9.631-10.518 9.631-16.611 0-1.927-.442-3.56-1.278-4.724a.232.232 0 0 1 .323-.327c1.671 1.172 2.591 3.381 2.591 6.219 0 6.242-4.426 13.863-9.865 17.003-1.574.908-3.084 1.356-4.488 1.356zm-2.969-1.542c.813.651 1.82.877 2.968.877h.001c1.321 0 2.753-.327 4.254-1.194 5.311-3.067 9.632-10.463 9.632-16.556 0-1.979-.463-3.599-1.326-4.761.411 1.035.625 2.275.625 3.635 0 6.243-4.426 13.883-9.865 17.023-1.574.909-3.084 1.317-4.49 1.317-.641 0-1.243-.149-1.799-.341z' fill='#607D8B'/><path d='M113.097 197.23c5.384-3.108 9.748-10.636 9.748-16.814 0-2.051-.483-3.692-1.323-4.86-1.784-1.252-4.374-1.194-7.257.47-5.384 3.108-9.748 10.636-9.748 16.814 0 2.051.483 3.692 1.323 4.86 1.784 1.252 4.374 1.194 7.257-.47' fill='#FAFAFA'/><path d='M108.724 198.614c-1.142 0-2.158-.213-3.019-.817-.021-.014-.04.014-.055-.007-.894-1.244-1.367-2.948-1.367-4.973 0-6.242 4.426-13.864 9.865-17.005 1.574-.908 3.084-1.363 4.49-1.363 1.142 0 2.158.309 3.018.913a.23.23 0 0 1 .056.056c.894 1.244 1.367 2.972 1.367 4.997 0 6.243-4.426 13.783-9.865 16.923-1.574.909-3.084 1.276-4.49 1.276zm-2.718-1.109c.774.532 1.688.776 2.718.776 1.323 0 2.754-.413 4.256-1.28 5.311-3.066 9.631-10.505 9.631-16.598 0-1.909-.434-3.523-1.255-4.685-.774-.533-1.688-.799-2.718-.799-1.323 0-2.755.441-4.256 1.308-5.311 3.066-9.631 10.506-9.631 16.599 0 1.909.434 3.517 1.255 4.679z' fill='#607D8B'/><path d='M149.318 114.262l-9.984 8.878 15.893 11.031 5.589-6.112-11.498-13.797' fill='#FAFAFA'/><path d='M169.676 120.84l-9.748 5.627c-3.642 2.103-9.528 2.113-13.147.024-3.62-2.089-3.601-5.488.041-7.591l9.495-5.608-6.729-3.885-81.836 47.071 45.923 26.514 3.081-1.779c.631-.365.869-.898.618-1.39-2.357-4.632-2.593-9.546-.683-14.262 5.638-13.92 24.509-24.815 48.618-28.07 8.169-1.103 16.68-.967 24.704.394.852.145 1.776.008 2.407-.357l3.081-1.778-25.825-14.91' fill='#FAFAFA'/><path d='M113.675 183.459a.47.47 0 0 1-.233-.062l-45.924-26.515a.468.468 0 0 1 .001-.809l81.836-47.071a.467.467 0 0 1 .466 0l6.729 3.885a.467.467 0 0 1-.467.809l-6.496-3.75-80.9 46.533 44.988 25.973 2.848-1.644c.192-.111.62-.409.435-.773-2.416-4.748-2.658-9.814-.7-14.65 2.806-6.927 8.885-13.242 17.582-18.263 8.657-4.998 19.518-8.489 31.407-10.094 8.198-1.107 16.79-.97 24.844.397.739.125 1.561.007 2.095-.301l2.381-1.374-25.125-14.506a.467.467 0 0 1 .467-.809l25.825 14.91a.467.467 0 0 1 0 .809l-3.081 1.779c-.721.417-1.763.575-2.718.413-7.963-1.351-16.457-1.486-24.563-.392-11.77 1.589-22.512 5.039-31.065 9.977-8.514 4.916-14.456 11.073-17.183 17.805-1.854 4.578-1.623 9.376.666 13.875.37.725.055 1.513-.8 2.006l-3.081 1.78a.476.476 0 0 1-.234.062' fill='#455A64'/><path d='M153.316 128.279c-2.413 0-4.821-.528-6.652-1.586-1.818-1.049-2.82-2.461-2.82-3.975 0-1.527 1.016-2.955 2.861-4.02l9.493-5.607a.233.233 0 1 1 .238.402l-9.496 5.609c-1.696.979-2.628 2.263-2.628 3.616 0 1.34.918 2.608 2.585 3.571 3.549 2.049 9.343 2.038 12.914-.024l9.748-5.628a.234.234 0 0 1 .234.405l-9.748 5.628c-1.858 1.072-4.296 1.609-6.729 1.609' fill='#607D8B'/><path d='M113.675 182.992l-45.913-26.508M113.675 183.342a.346.346 0 0 1-.175-.047l-45.913-26.508a.35.35 0 1 1 .35-.607l45.913 26.508a.35.35 0 0 1-.175.654' fill='#455A64'/><path d='M67.762 156.484v54.001c0 1.09.77 2.418 1.72 2.967l42.473 24.521c.95.549 1.72.11 1.72-.98v-54.001' fill='#FAFAFA'/><path d='M112.727 238.561c-.297 0-.62-.095-.947-.285l-42.473-24.521c-1.063-.613-1.895-2.05-1.895-3.27v-54.001a.35.35 0 1 1 .701 0v54.001c0 .96.707 2.18 1.544 2.663l42.473 24.522c.344.198.661.243.87.122.206-.119.325-.411.325-.799v-54.001a.35.35 0 1 1 .7 0v54.001c0 .655-.239 1.154-.675 1.406a1.235 1.235 0 0 1-.623.162' fill='#455A64'/><path d='M112.86 147.512h-.001c-2.318 0-4.499-.522-6.142-1.471-1.705-.984-2.643-2.315-2.643-3.749 0-1.445.952-2.791 2.68-3.788l12.041-6.953c1.668-.962 3.874-1.493 6.212-1.493 2.318 0 4.499.523 6.143 1.472 1.704.984 2.643 2.315 2.643 3.748 0 1.446-.952 2.791-2.68 3.789l-12.042 6.952c-1.668.963-3.874 1.493-6.211 1.493zm12.147-16.753c-2.217 0-4.298.497-5.861 1.399l-12.042 6.952c-1.502.868-2.33 1.998-2.33 3.182 0 1.173.815 2.289 2.293 3.142 1.538.889 3.596 1.378 5.792 1.378h.001c2.216 0 4.298-.497 5.861-1.399l12.041-6.953c1.502-.867 2.33-1.997 2.33-3.182 0-1.172-.814-2.288-2.292-3.142-1.539-.888-3.596-1.377-5.793-1.377z' fill='#607D8B'/><path d='M165.63 123.219l-5.734 3.311c-3.167 1.828-8.286 1.837-11.433.02-3.147-1.817-3.131-4.772.036-6.601l5.734-3.31 11.397 6.58' fill='#FAFAFA'/><path d='M154.233 117.448l9.995 5.771-4.682 2.704c-1.434.827-3.352 1.283-5.399 1.283-2.029 0-3.923-.449-5.333-1.263-1.29-.744-2-1.694-2-2.674 0-.991.723-1.955 2.036-2.713l5.383-3.108m0-.809l-5.734 3.31c-3.167 1.829-3.183 4.784-.036 6.601 1.568.905 3.623 1.357 5.684 1.357 2.077 0 4.159-.46 5.749-1.377l5.734-3.311-11.397-6.58M145.445 179.667c-1.773 0-3.241-.85-4.243-2.245-.067-.092-.057-.275.023-.356.08-.081.207-.12.3-.055.781.548 1.706.812 2.751.811 1.322 0 2.754-.446 4.256-1.313 5.31-3.066 9.631-10.522 9.631-16.615 0-1.927-.442-3.562-1.279-4.726a.235.235 0 0 1 .024-.301.232.232 0 0 1 .3-.027c1.67 1.172 2.59 3.38 2.59 6.219 0 6.242-4.425 13.987-9.865 17.127-1.573.908-3.083 1.481-4.488 1.481zM142.476 178c.814.651 1.82 1.002 2.969 1.002 1.322 0 2.753-.452 4.255-1.32 5.31-3.065 9.631-10.523 9.631-16.617 0-1.98-.463-3.63-1.325-4.793.411 1.035.624 2.26.624 3.62 0 6.242-4.425 13.875-9.865 17.015-1.573.909-3.084 1.376-4.489 1.376a5.49 5.49 0 0 1-1.8-.283z' fill='#607D8B'/><path d='M148.648 176.704c5.384-3.108 9.748-10.636 9.748-16.813 0-2.052-.483-3.693-1.322-4.861-1.785-1.252-4.375-1.194-7.258.471-5.383 3.108-9.748 10.636-9.748 16.813 0 2.051.484 3.692 1.323 4.86 1.785 1.253 4.374 1.195 7.257-.47' fill='#FAFAFA'/><path d='M144.276 178.276c-1.143 0-2.158-.307-3.019-.911a.217.217 0 0 1-.055-.054c-.895-1.244-1.367-2.972-1.367-4.997 0-6.241 4.425-13.875 9.865-17.016 1.573-.908 3.084-1.369 4.489-1.369 1.143 0 2.158.307 3.019.91a.24.24 0 0 1 .055.055c.894 1.244 1.367 2.971 1.367 4.997 0 6.241-4.425 13.875-9.865 17.016-1.573.908-3.084 1.369-4.489 1.369zm-2.718-1.172c.773.533 1.687.901 2.718.901 1.322 0 2.754-.538 4.256-1.405 5.31-3.066 9.631-10.567 9.631-16.661 0-1.908-.434-3.554-1.256-4.716-.774-.532-1.688-.814-2.718-.814-1.322 0-2.754.433-4.256 1.3-5.31 3.066-9.631 10.564-9.631 16.657 0 1.91.434 3.576 1.256 4.738z' fill='#607D8B'/><path d='M150.72 172.361l-.363-.295a24.105 24.105 0 0 0 2.148-3.128 24.05 24.05 0 0 0 1.977-4.375l.443.149a24.54 24.54 0 0 1-2.015 4.46 24.61 24.61 0 0 1-2.19 3.189M115.917 191.514l-.363-.294a24.174 24.174 0 0 0 2.148-3.128 24.038 24.038 0 0 0 1.976-4.375l.443.148a24.48 24.48 0 0 1-2.015 4.461 24.662 24.662 0 0 1-2.189 3.188M114 237.476V182.584 237.476' fill='#607D8B'/><g><path d='M81.822 37.474c.017-.135-.075-.28-.267-.392-.327-.188-.826-.21-1.109-.045l-6.012 3.471c-.131.076-.194.178-.191.285.002.132.002.461.002.578v.043l-.007.128-6.591 3.779c-.001 0-2.077 1.046-2.787 5.192 0 0-.912 6.961-.898 19.745.015 12.57.606 17.07 1.167 21.351.22 1.684 3.001 2.125 3.001 2.125.331.04.698-.027 1.08-.248l75.273-43.551c1.808-1.069 2.667-3.719 3.056-6.284 1.213-7.99 1.675-32.978-.275-39.878-.196-.693-.51-1.083-.868-1.282l-2.086-.79c-.727.028-1.416.467-1.534.535L82.032 37.072l-.21.402' fill='#FFF'/><path d='M144.311 1.701l2.085.79c.358.199.672.589.868 1.282 1.949 6.9 1.487 31.887.275 39.878-.39 2.565-1.249 5.215-3.056 6.284L69.21 93.486a1.78 1.78 0 0 1-.896.258l-.183-.011c0 .001-2.782-.44-3.003-2.124-.56-4.282-1.151-8.781-1.165-21.351-.015-12.784.897-19.745.897-19.745.71-4.146 2.787-5.192 2.787-5.192l6.591-3.779.007-.128v-.043c0-.117 0-.446-.002-.578-.003-.107.059-.21.191-.285l6.012-3.472a.98.98 0 0 1 .481-.11c.218 0 .449.053.627.156.193.112.285.258.268.392l.211-.402 60.744-34.836c.117-.068.806-.507 1.534-.535m0-.997l-.039.001c-.618.023-1.283.244-1.974.656l-.021.012-60.519 34.706a2.358 2.358 0 0 0-.831-.15c-.365 0-.704.084-.98.244l-6.012 3.471c-.442.255-.699.69-.689 1.166l.001.15-6.08 3.487c-.373.199-2.542 1.531-3.29 5.898l-.006.039c-.009.07-.92 7.173-.906 19.875.014 12.62.603 17.116 1.172 21.465l.002.015c.308 2.355 3.475 2.923 3.836 2.98l.034.004c.101.013.204.019.305.019a2.77 2.77 0 0 0 1.396-.392l75.273-43.552c1.811-1.071 2.999-3.423 3.542-6.997 1.186-7.814 1.734-33.096-.301-40.299-.253-.893-.704-1.527-1.343-1.882l-.132-.062-2.085-.789a.973.973 0 0 0-.353-.065' fill='#455A64'/><path d='M128.267 11.565l1.495.434-56.339 32.326' fill='#FFF'/><path d='M74.202 90.545a.5.5 0 0 1-.25-.931l18.437-10.645a.499.499 0 1 1 .499.864L74.451 90.478l-.249.067M75.764 42.654l-.108-.062.046-.171 5.135-2.964.17.045-.045.171-5.135 2.964-.063.017M70.52 90.375V46.421l.063-.036L137.84 7.554v43.954l-.062.036L70.52 90.375zm.25-43.811v43.38l66.821-38.579V7.985L70.77 46.564z' fill='#607D8B'/><path d='M86.986 83.182c-.23.149-.612.384-.849.523l-11.505 6.701c-.237.139-.206.252.068.252h.565c.275 0 .693-.113.93-.252L87.7 83.705c.237-.139.428-.253.425-.256a11.29 11.29 0 0 1-.006-.503c0-.274-.188-.377-.418-.227l-.715.463' fill='#607D8B'/><path d='M75.266 90.782H74.7c-.2 0-.316-.056-.346-.166-.03-.11.043-.217.215-.317l11.505-6.702c.236-.138.615-.371.844-.519l.715-.464a.488.488 0 0 1 .266-.089c.172 0 .345.13.345.421 0 .214.001.363.003.437l.006.004-.004.069c-.003.075-.003.075-.486.356l-11.505 6.702a2.282 2.282 0 0 1-.992.268zm-.6-.25l.034.001h.566c.252 0 .649-.108.866-.234l11.505-6.702c.168-.098.294-.173.361-.214-.004-.084-.004-.218-.004-.437l-.095-.171-.131.049-.714.463c-.232.15-.616.386-.854.525l-11.505 6.702-.029.018z' fill='#607D8B'/><path d='M75.266 89.871H74.7c-.2 0-.316-.056-.346-.166-.03-.11.043-.217.215-.317l11.505-6.702c.258-.151.694-.268.993-.268h.565c.2 0 .316.056.346.166.03.11-.043.217-.215.317l-11.505 6.702a2.282 2.282 0 0 1-.992.268zm-.6-.25l.034.001h.566c.252 0 .649-.107.866-.234l11.505-6.702.03-.018-.035-.001h-.565c-.252 0-.649.108-.867.234l-11.505 6.702-.029.018zM74.37 90.801v-1.247 1.247' fill='#607D8B'/><path d='M68.13 93.901c-.751-.093-1.314-.737-1.439-1.376-.831-4.238-1.151-8.782-1.165-21.352-.015-12.784.897-19.745.897-19.745.711-4.146 2.787-5.192 2.787-5.192l74.859-43.219c.223-.129 2.487-1.584 3.195.923 1.95 6.9 1.488 31.887.275 39.878-.389 2.565-1.248 5.215-3.056 6.283L69.21 93.653c-.382.221-.749.288-1.08.248 0 0-2.781-.441-3.001-2.125-.561-4.281-1.152-8.781-1.167-21.351-.014-12.784.898-19.745.898-19.745.71-4.146 2.787-5.191 2.787-5.191l6.598-3.81.871-.119 6.599-3.83.046-.461L68.13 93.901' fill='#FAFAFA'/><path d='M68.317 94.161l-.215-.013h-.001l-.244-.047c-.719-.156-2.772-.736-2.976-2.292-.568-4.34-1.154-8.813-1.168-21.384-.014-12.654.891-19.707.9-19.777.725-4.231 2.832-5.338 2.922-5.382l6.628-3.827.87-.119 6.446-3.742.034-.334a.248.248 0 0 1 .273-.223.248.248 0 0 1 .223.272l-.059.589-6.752 3.919-.87.118-6.556 3.785c-.031.016-1.99 1.068-2.666 5.018-.007.06-.908 7.086-.894 19.702.014 12.539.597 16.996 1.161 21.305.091.691.689 1.154 1.309 1.452a1.95 1.95 0 0 1-.236-.609c-.781-3.984-1.155-8.202-1.17-21.399-.014-12.653.891-19.707.9-19.777.725-4.231 2.832-5.337 2.922-5.382-.004.001 74.444-42.98 74.846-43.212l.028-.017c.904-.538 1.72-.688 2.36-.433.555.221.949.733 1.172 1.52 2.014 7.128 1.46 32.219.281 39.983-.507 3.341-1.575 5.515-3.175 6.462L69.335 93.869a2.023 2.023 0 0 1-1.018.292zm-.147-.507c.293.036.604-.037.915-.217l75.273-43.551c1.823-1.078 2.602-3.915 2.934-6.106 1.174-7.731 1.731-32.695-.268-39.772-.178-.631-.473-1.032-.876-1.192-.484-.193-1.166-.052-1.921.397l-.034.021-74.858 43.218c-.031.017-1.989 1.069-2.666 5.019-.007.059-.908 7.085-.894 19.702.015 13.155.386 17.351 1.161 21.303.09.461.476.983 1.037 1.139.114.025.185.037.196.039h.001z' fill='#455A64'/><path d='M69.317 68.982c.489-.281.885-.056.885.505 0 .56-.396 1.243-.885 1.525-.488.282-.884.057-.884-.504 0-.56.396-1.243.884-1.526' fill='#FFF'/><path d='M68.92 71.133c-.289 0-.487-.228-.487-.625 0-.56.396-1.243.884-1.526a.812.812 0 0 1 .397-.121c.289 0 .488.229.488.626 0 .56-.396 1.243-.885 1.525a.812.812 0 0 1-.397.121m.794-2.459a.976.976 0 0 0-.49.147c-.548.317-.978 1.058-.978 1.687 0 .486.271.812.674.812a.985.985 0 0 0 .491-.146c.548-.317.978-1.057.978-1.687 0-.486-.272-.813-.675-.813' fill='#8097A2'/><path d='M68.92 70.947c-.271 0-.299-.307-.299-.439 0-.491.361-1.116.79-1.363a.632.632 0 0 1 .303-.096c.272 0 .301.306.301.438 0 .491-.363 1.116-.791 1.364a.629.629 0 0 1-.304.096m.794-2.086a.812.812 0 0 0-.397.121c-.488.283-.884.966-.884 1.526 0 .397.198.625.487.625a.812.812 0 0 0 .397-.121c.489-.282.885-.965.885-1.525 0-.397-.199-.626-.488-.626' fill='#8097A2'/><path d='M69.444 85.35c.264-.152.477-.031.477.272 0 .303-.213.67-.477.822-.263.153-.477.031-.477-.271 0-.302.214-.671.477-.823' fill='#FFF'/><path d='M69.23 86.51c-.156 0-.263-.123-.263-.337 0-.302.214-.671.477-.823a.431.431 0 0 1 .214-.066c.156 0 .263.124.263.338 0 .303-.213.67-.477.822a.431.431 0 0 1-.214.066m.428-1.412c-.1 0-.203.029-.307.09-.32.185-.57.618-.57.985 0 .309.185.524.449.524a.63.63 0 0 0 .308-.09c.32-.185.57-.618.57-.985 0-.309-.185-.524-.45-.524' fill='#8097A2'/><path d='M69.23 86.322l-.076-.149c0-.235.179-.544.384-.661l.12-.041.076.151c0 .234-.179.542-.383.66l-.121.04m.428-1.038a.431.431 0 0 0-.214.066c-.263.152-.477.521-.477.823 0 .214.107.337.263.337a.431.431 0 0 0 .214-.066c.264-.152.477-.519.477-.822 0-.214-.107-.338-.263-.338' fill='#8097A2'/><path d='M139.278 7.769v43.667L72.208 90.16V46.493l67.07-38.724' fill='#455A64'/><path d='M72.083 90.375V46.421l.063-.036 67.257-38.831v43.954l-.062.036-67.258 38.831zm.25-43.811v43.38l66.821-38.579V7.985L72.333 46.564z' fill='#607D8B'/></g><path d='M125.737 88.647l-7.639 3.334V84l-11.459 4.713v8.269L99 100.315l13.369 3.646 13.368-15.314' fill='#455A64'/></g></svg>";
  43716. function RotateInstructions() {
  43717. this.loadIcon_();
  43718. var overlay = document.createElement('div');
  43719. var s = overlay.style;
  43720. s.position = 'fixed';
  43721. s.top = 0;
  43722. s.right = 0;
  43723. s.bottom = 0;
  43724. s.left = 0;
  43725. s.backgroundColor = 'gray';
  43726. s.fontFamily = 'sans-serif';
  43727. s.zIndex = 1000000;
  43728. var img = document.createElement('img');
  43729. img.src = this.icon;
  43730. var s = img.style;
  43731. s.marginLeft = '25%';
  43732. s.marginTop = '25%';
  43733. s.width = '50%';
  43734. overlay.appendChild(img);
  43735. var text = document.createElement('div');
  43736. var s = text.style;
  43737. s.textAlign = 'center';
  43738. s.fontSize = '16px';
  43739. s.lineHeight = '24px';
  43740. s.margin = '24px 25%';
  43741. s.width = '50%';
  43742. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  43743. overlay.appendChild(text);
  43744. var snackbar = document.createElement('div');
  43745. var s = snackbar.style;
  43746. s.backgroundColor = '#CFD8DC';
  43747. s.position = 'fixed';
  43748. s.bottom = 0;
  43749. s.width = '100%';
  43750. s.height = '48px';
  43751. s.padding = '14px 24px';
  43752. s.boxSizing = 'border-box';
  43753. s.color = '#656A6B';
  43754. overlay.appendChild(snackbar);
  43755. var snackbarText = document.createElement('div');
  43756. snackbarText.style.float = 'left';
  43757. snackbarText.innerHTML = 'No Cardboard viewer?';
  43758. var snackbarButton = document.createElement('a');
  43759. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  43760. snackbarButton.innerHTML = 'get one';
  43761. snackbarButton.target = '_blank';
  43762. var s = snackbarButton.style;
  43763. s.float = 'right';
  43764. s.fontWeight = 600;
  43765. s.textTransform = 'uppercase';
  43766. s.borderLeft = '1px solid gray';
  43767. s.paddingLeft = '24px';
  43768. s.textDecoration = 'none';
  43769. s.color = '#656A6B';
  43770. snackbar.appendChild(snackbarText);
  43771. snackbar.appendChild(snackbarButton);
  43772. this.overlay = overlay;
  43773. this.text = text;
  43774. this.hide();
  43775. }
  43776. RotateInstructions.prototype.show = function (parent) {
  43777. if (!parent && !this.overlay.parentElement) {
  43778. document.body.appendChild(this.overlay);
  43779. } else if (parent) {
  43780. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  43781. parent.appendChild(this.overlay);
  43782. }
  43783. this.overlay.style.display = 'block';
  43784. var img = this.overlay.querySelector('img');
  43785. var s = img.style;
  43786. if (isLandscapeMode()) {
  43787. s.width = '20%';
  43788. s.marginLeft = '40%';
  43789. s.marginTop = '3%';
  43790. } else {
  43791. s.width = '50%';
  43792. s.marginLeft = '25%';
  43793. s.marginTop = '25%';
  43794. }
  43795. };
  43796. RotateInstructions.prototype.hide = function () {
  43797. this.overlay.style.display = 'none';
  43798. };
  43799. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  43800. this.show(parent);
  43801. this.timer = setTimeout(this.hide.bind(this), ms);
  43802. };
  43803. RotateInstructions.prototype.disableShowTemporarily = function () {
  43804. clearTimeout(this.timer);
  43805. };
  43806. RotateInstructions.prototype.update = function () {
  43807. this.disableShowTemporarily();
  43808. if (!isLandscapeMode() && isMobile()) {
  43809. this.show();
  43810. } else {
  43811. this.hide();
  43812. }
  43813. };
  43814. RotateInstructions.prototype.loadIcon_ = function () {
  43815. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  43816. };
  43817. var DEFAULT_VIEWER = 'CardboardV1';
  43818. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  43819. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  43820. function ViewerSelector(defaultViewer) {
  43821. try {
  43822. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  43823. } catch (error) {
  43824. console.error('Failed to load viewer profile: %s', error);
  43825. }
  43826. if (!this.selectedKey) {
  43827. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  43828. }
  43829. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  43830. this.root = null;
  43831. this.onChangeCallbacks_ = [];
  43832. }
  43833. ViewerSelector.prototype.show = function (root) {
  43834. this.root = root;
  43835. root.appendChild(this.dialog);
  43836. var selected = this.dialog.querySelector('#' + this.selectedKey);
  43837. selected.checked = true;
  43838. this.dialog.style.display = 'block';
  43839. };
  43840. ViewerSelector.prototype.hide = function () {
  43841. if (this.root && this.root.contains(this.dialog)) {
  43842. this.root.removeChild(this.dialog);
  43843. }
  43844. this.dialog.style.display = 'none';
  43845. };
  43846. ViewerSelector.prototype.getCurrentViewer = function () {
  43847. return DeviceInfo.Viewers[this.selectedKey];
  43848. };
  43849. ViewerSelector.prototype.getSelectedKey_ = function () {
  43850. var input = this.dialog.querySelector('input[name=field]:checked');
  43851. if (input) {
  43852. return input.id;
  43853. }
  43854. return null;
  43855. };
  43856. ViewerSelector.prototype.onChange = function (cb) {
  43857. this.onChangeCallbacks_.push(cb);
  43858. };
  43859. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  43860. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  43861. this.onChangeCallbacks_[i](viewer);
  43862. }
  43863. };
  43864. ViewerSelector.prototype.onSave_ = function () {
  43865. this.selectedKey = this.getSelectedKey_();
  43866. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  43867. console.error('ViewerSelector.onSave_: this should never happen!');
  43868. return;
  43869. }
  43870. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  43871. try {
  43872. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  43873. } catch (error) {
  43874. console.error('Failed to save viewer profile: %s', error);
  43875. }
  43876. this.hide();
  43877. };
  43878. ViewerSelector.prototype.createDialog_ = function (options) {
  43879. var container = document.createElement('div');
  43880. container.classList.add(CLASS_NAME);
  43881. container.style.display = 'none';
  43882. var overlay = document.createElement('div');
  43883. var s = overlay.style;
  43884. s.position = 'fixed';
  43885. s.left = 0;
  43886. s.top = 0;
  43887. s.width = '100%';
  43888. s.height = '100%';
  43889. s.background = 'rgba(0, 0, 0, 0.3)';
  43890. overlay.addEventListener('click', this.hide.bind(this));
  43891. var width = 280;
  43892. var dialog = document.createElement('div');
  43893. var s = dialog.style;
  43894. s.boxSizing = 'border-box';
  43895. s.position = 'fixed';
  43896. s.top = '24px';
  43897. s.left = '50%';
  43898. s.marginLeft = -width / 2 + 'px';
  43899. s.width = width + 'px';
  43900. s.padding = '24px';
  43901. s.overflow = 'hidden';
  43902. s.background = '#fafafa';
  43903. s.fontFamily = "'Roboto', sans-serif";
  43904. s.boxShadow = '0px 5px 20px #666';
  43905. dialog.appendChild(this.createH1_('Select your viewer'));
  43906. for (var id in options) {
  43907. dialog.appendChild(this.createChoice_(id, options[id].label));
  43908. }
  43909. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  43910. container.appendChild(overlay);
  43911. container.appendChild(dialog);
  43912. return container;
  43913. };
  43914. ViewerSelector.prototype.createH1_ = function (name) {
  43915. var h1 = document.createElement('h1');
  43916. var s = h1.style;
  43917. s.color = 'black';
  43918. s.fontSize = '20px';
  43919. s.fontWeight = 'bold';
  43920. s.marginTop = 0;
  43921. s.marginBottom = '24px';
  43922. h1.innerHTML = name;
  43923. return h1;
  43924. };
  43925. ViewerSelector.prototype.createChoice_ = function (id, name) {
  43926. var div = document.createElement('div');
  43927. div.style.marginTop = '8px';
  43928. div.style.color = 'black';
  43929. var input = document.createElement('input');
  43930. input.style.fontSize = '30px';
  43931. input.setAttribute('id', id);
  43932. input.setAttribute('type', 'radio');
  43933. input.setAttribute('value', id);
  43934. input.setAttribute('name', 'field');
  43935. var label = document.createElement('label');
  43936. label.style.marginLeft = '4px';
  43937. label.setAttribute('for', id);
  43938. label.innerHTML = name;
  43939. div.appendChild(input);
  43940. div.appendChild(label);
  43941. return div;
  43942. };
  43943. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  43944. var button = document.createElement('button');
  43945. button.innerHTML = label;
  43946. var s = button.style;
  43947. s.float = 'right';
  43948. s.textTransform = 'uppercase';
  43949. s.color = '#1094f7';
  43950. s.fontSize = '14px';
  43951. s.letterSpacing = 0;
  43952. s.border = 0;
  43953. s.background = 'none';
  43954. s.marginTop = '16px';
  43955. button.addEventListener('click', onclick);
  43956. return button;
  43957. };
  43958. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  43959. function unwrapExports$$1 (x) {
  43960. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  43961. }
  43962. function createCommonjsModule$$1(fn, module) {
  43963. return module = { exports: {} }, fn(module, module.exports), module.exports;
  43964. }
  43965. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  43966. (function webpackUniversalModuleDefinition(root, factory) {
  43967. module.exports = factory();
  43968. })(commonjsGlobal$$1, function() {
  43969. return (function(modules) {
  43970. var installedModules = {};
  43971. function __webpack_require__(moduleId) {
  43972. if(installedModules[moduleId]) {
  43973. return installedModules[moduleId].exports;
  43974. }
  43975. var module = installedModules[moduleId] = {
  43976. i: moduleId,
  43977. l: false,
  43978. exports: {}
  43979. };
  43980. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  43981. module.l = true;
  43982. return module.exports;
  43983. }
  43984. __webpack_require__.m = modules;
  43985. __webpack_require__.c = installedModules;
  43986. __webpack_require__.d = function(exports, name, getter) {
  43987. if(!__webpack_require__.o(exports, name)) {
  43988. Object.defineProperty(exports, name, {
  43989. configurable: false,
  43990. enumerable: true,
  43991. get: getter
  43992. });
  43993. }
  43994. };
  43995. __webpack_require__.n = function(module) {
  43996. var getter = module && module.__esModule ?
  43997. function getDefault() { return module['default']; } :
  43998. function getModuleExports() { return module; };
  43999. __webpack_require__.d(getter, 'a', getter);
  44000. return getter;
  44001. };
  44002. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  44003. __webpack_require__.p = "";
  44004. return __webpack_require__(__webpack_require__.s = 0);
  44005. })
  44006. ([
  44007. (function(module, exports, __webpack_require__) {
  44008. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  44009. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  44010. var mediaFile = __webpack_require__(1);
  44011. var oldIOS = typeof navigator !== 'undefined' && parseFloat(('' + (/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0, ''])[1]).replace('undefined', '3_2').replace('_', '.').replace('_', '')) < 10 && !window.MSStream;
  44012. var NoSleep = function () {
  44013. function NoSleep() {
  44014. _classCallCheck(this, NoSleep);
  44015. if (oldIOS) {
  44016. this.noSleepTimer = null;
  44017. } else {
  44018. this.noSleepVideo = document.createElement('video');
  44019. this.noSleepVideo.setAttribute('playsinline', '');
  44020. this.noSleepVideo.setAttribute('src', mediaFile);
  44021. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  44022. if (this.noSleepVideo.currentTime > 0.5) {
  44023. this.noSleepVideo.currentTime = Math.random();
  44024. }
  44025. }.bind(this));
  44026. }
  44027. }
  44028. _createClass(NoSleep, [{
  44029. key: 'enable',
  44030. value: function enable() {
  44031. if (oldIOS) {
  44032. this.disable();
  44033. this.noSleepTimer = window.setInterval(function () {
  44034. window.location.href = '/';
  44035. window.setTimeout(window.stop, 0);
  44036. }, 15000);
  44037. } else {
  44038. this.noSleepVideo.play();
  44039. }
  44040. }
  44041. }, {
  44042. key: 'disable',
  44043. value: function disable() {
  44044. if (oldIOS) {
  44045. if (this.noSleepTimer) {
  44046. window.clearInterval(this.noSleepTimer);
  44047. this.noSleepTimer = null;
  44048. }
  44049. } else {
  44050. this.noSleepVideo.pause();
  44051. }
  44052. }
  44053. }]);
  44054. return NoSleep;
  44055. }();
  44056. module.exports = NoSleep;
  44057. }),
  44058. (function(module, exports, __webpack_require__) {
  44059. module.exports = 'data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACKBtZGF0AAAC8wYF///v3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0MiByMjQ3OSBkZDc5YTYxIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDExMSBtZT1oZXggc3VibWU9MiBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0wIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MCA4eDhkY3Q9MCBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0wIHRocmVhZHM9NiBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVjdD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MzAwIGtleWludF9taW49MzAgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IHZidl9tYXhyYXRlPTIwMDAwIHZidl9idWZzaXplPTI1MDAwIGNyZl9tYXg9MC4wIG5hbF9ocmQ9bm9uZSBmaWxsZXI9MCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAOWWIhAA3//p+C7v8tDDSTjf97w55i3SbRPO4ZY+hkjD5hbkAkL3zpJ6h/LR1CAABzgB1kqqzUorlhQAAAAxBmiQYhn/+qZYADLgAAAAJQZ5CQhX/AAj5IQADQGgcIQADQGgcAAAACQGeYUQn/wALKCEAA0BoHAAAAAkBnmNEJ/8ACykhAANAaBwhAANAaBwAAAANQZpoNExDP/6plgAMuSEAA0BoHAAAAAtBnoZFESwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBnqVEJ/8ACykhAANAaBwAAAAJAZ6nRCf/AAsoIQADQGgcIQADQGgcAAAADUGarDRMQz/+qZYADLghAANAaBwAAAALQZ7KRRUsK/8ACPkhAANAaBwAAAAJAZ7pRCf/AAsoIQADQGgcIQADQGgcAAAACQGe60Qn/wALKCEAA0BoHAAAAA1BmvA0TEM//qmWAAy5IQADQGgcIQADQGgcAAAAC0GfDkUVLCv/AAj5IQADQGgcAAAACQGfLUQn/wALKSEAA0BoHCEAA0BoHAAAAAkBny9EJ/8ACyghAANAaBwAAAANQZs0NExDP/6plgAMuCEAA0BoHAAAAAtBn1JFFSwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBn3FEJ/8ACyghAANAaBwAAAAJAZ9zRCf/AAsoIQADQGgcIQADQGgcAAAADUGbeDRMQz/+qZYADLkhAANAaBwAAAALQZ+WRRUsK/8ACPghAANAaBwhAANAaBwAAAAJAZ+1RCf/AAspIQADQGgcAAAACQGft0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bm7w0TEM//qmWAAy4IQADQGgcAAAAC0Gf2kUVLCv/AAj5IQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHAAAAAkBn/tEJ/8ACykhAANAaBwAAAANQZvgNExDP/6plgAMuSEAA0BoHCEAA0BoHAAAAAtBnh5FFSwr/wAI+CEAA0BoHAAAAAkBnj1EJ/8ACyghAANAaBwhAANAaBwAAAAJAZ4/RCf/AAspIQADQGgcAAAADUGaJDRMQz/+qZYADLghAANAaBwAAAALQZ5CRRUsK/8ACPkhAANAaBwhAANAaBwAAAAJAZ5hRCf/AAsoIQADQGgcAAAACQGeY0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bmmg0TEM//qmWAAy5IQADQGgcAAAAC0GehkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGepUQn/wALKSEAA0BoHAAAAAkBnqdEJ/8ACyghAANAaBwAAAANQZqsNExDP/6plgAMuCEAA0BoHCEAA0BoHAAAAAtBnspFFSwr/wAI+SEAA0BoHAAAAAkBnulEJ/8ACyghAANAaBwhAANAaBwAAAAJAZ7rRCf/AAsoIQADQGgcAAAADUGa8DRMQz/+qZYADLkhAANAaBwhAANAaBwAAAALQZ8ORRUsK/8ACPkhAANAaBwAAAAJAZ8tRCf/AAspIQADQGgcIQADQGgcAAAACQGfL0Qn/wALKCEAA0BoHAAAAA1BmzQ0TEM//qmWAAy4IQADQGgcAAAAC0GfUkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGfcUQn/wALKCEAA0BoHAAAAAkBn3NEJ/8ACyghAANAaBwhAANAaBwAAAANQZt4NExC//6plgAMuSEAA0BoHAAAAAtBn5ZFFSwr/wAI+CEAA0BoHCEAA0BoHAAAAAkBn7VEJ/8ACykhAANAaBwAAAAJAZ+3RCf/AAspIQADQGgcAAAADUGbuzRMQn/+nhAAYsAhAANAaBwhAANAaBwAAAAJQZ/aQhP/AAspIQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHAAACiFtb292AAAAbG12aGQAAAAA1YCCX9WAgl8AAAPoAAAH/AABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAGGlvZHMAAAAAEICAgAcAT////v7/AAAF+XRyYWsAAABcdGtoZAAAAAPVgIJf1YCCXwAAAAEAAAAAAAAH0AAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAygAAAMoAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAB9AAABdwAAEAAAAABXFtZGlhAAAAIG1kaGQAAAAA1YCCX9WAgl8AAV+QAAK/IFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAUcbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAE3HN0YmwAAACYc3RzZAAAAAAAAAABAAAAiGF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAygDKAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAyYXZjQwFNQCj/4QAbZ01AKOyho3ySTUBAQFAAAAMAEAAr8gDxgxlgAQAEaO+G8gAAABhzdHRzAAAAAAAAAAEAAAA8AAALuAAAABRzdHNzAAAAAAAAAAEAAAABAAAB8GN0dHMAAAAAAAAAPAAAAAEAABdwAAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAAC7gAAAAAQAAF3AAAAABAAAAAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAEEc3RzegAAAAAAAAAAAAAAPAAAAzQAAAAQAAAADQAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAANAAAADQAAAQBzdGNvAAAAAAAAADwAAAAwAAADZAAAA3QAAAONAAADoAAAA7kAAAPQAAAD6wAAA/4AAAQXAAAELgAABEMAAARcAAAEbwAABIwAAAShAAAEugAABM0AAATkAAAE/wAABRIAAAUrAAAFQgAABV0AAAVwAAAFiQAABaAAAAW1AAAFzgAABeEAAAX+AAAGEwAABiwAAAY/AAAGVgAABnEAAAaEAAAGnQAABrQAAAbPAAAG4gAABvUAAAcSAAAHJwAAB0AAAAdTAAAHcAAAB4UAAAeeAAAHsQAAB8gAAAfjAAAH9gAACA8AAAgmAAAIQQAACFQAAAhnAAAIhAAACJcAAAMsdHJhawAAAFx0a2hkAAAAA9WAgl/VgIJfAAAAAgAAAAAAAAf8AAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAACsm1kaWEAAAAgbWRoZAAAAADVgIJf1YCCXwAArEQAAWAAVcQAAAAAACdoZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU3RlcmVvAAAAAmNtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAidzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAADDUAAAAAABYCAgAISEAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAABYAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAAGAAAAWAAAAXBzdGNvAAAAAAAAAFgAAAOBAAADhwAAA5oAAAOtAAADswAAA8oAAAPfAAAD5QAAA/gAAAQLAAAEEQAABCgAAAQ9AAAEUAAABFYAAARpAAAEgAAABIYAAASbAAAErgAABLQAAATHAAAE3gAABPMAAAT5AAAFDAAABR8AAAUlAAAFPAAABVEAAAVXAAAFagAABX0AAAWDAAAFmgAABa8AAAXCAAAFyAAABdsAAAXyAAAF+AAABg0AAAYgAAAGJgAABjkAAAZQAAAGZQAABmsAAAZ+AAAGkQAABpcAAAauAAAGwwAABskAAAbcAAAG7wAABwYAAAcMAAAHIQAABzQAAAc6AAAHTQAAB2QAAAdqAAAHfwAAB5IAAAeYAAAHqwAAB8IAAAfXAAAH3QAAB/AAAAgDAAAICQAACCAAAAg1AAAIOwAACE4AAAhhAAAIeAAACH4AAAiRAAAIpAAACKoAAAiwAAAItgAACLwAAAjCAAAAFnVkdGEAAAAObmFtZVN0ZXJlbwAAAHB1ZHRhAAAAaG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAO2lsc3QAAAAzqXRvbwAAACtkYXRhAAAAAQAAAABIYW5kQnJha2UgMC4xMC4yIDIwMTUwNjExMDA=';
  44060. })
  44061. ]);
  44062. });
  44063. });
  44064. var NoSleep$1 = unwrapExports$$1(NoSleep);
  44065. var nextDisplayId = 1000;
  44066. var defaultLeftBounds = [0, 0, 0.5, 1];
  44067. var defaultRightBounds = [0.5, 0, 0.5, 1];
  44068. var raf = window.requestAnimationFrame;
  44069. var caf = window.cancelAnimationFrame;
  44070. function VRFrameData() {
  44071. this.leftProjectionMatrix = new Float32Array(16);
  44072. this.leftViewMatrix = new Float32Array(16);
  44073. this.rightProjectionMatrix = new Float32Array(16);
  44074. this.rightViewMatrix = new Float32Array(16);
  44075. this.pose = null;
  44076. }
  44077. function VRDisplayCapabilities(config) {
  44078. Object.defineProperties(this, {
  44079. hasPosition: {
  44080. writable: false, enumerable: true, value: config.hasPosition
  44081. },
  44082. hasExternalDisplay: {
  44083. writable: false, enumerable: true, value: config.hasExternalDisplay
  44084. },
  44085. canPresent: {
  44086. writable: false, enumerable: true, value: config.canPresent
  44087. },
  44088. maxLayers: {
  44089. writable: false, enumerable: true, value: config.maxLayers
  44090. },
  44091. hasOrientation: {
  44092. enumerable: true, get: function get() {
  44093. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  44094. return config.hasOrientation;
  44095. }
  44096. }
  44097. });
  44098. }
  44099. function VRDisplay(config) {
  44100. config = config || {};
  44101. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  44102. this.isPolyfilled = true;
  44103. this.displayId = nextDisplayId++;
  44104. this.displayName = '';
  44105. this.depthNear = 0.01;
  44106. this.depthFar = 10000.0;
  44107. this.isPresenting = false;
  44108. Object.defineProperty(this, 'isConnected', {
  44109. get: function get() {
  44110. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  44111. return false;
  44112. }
  44113. });
  44114. this.capabilities = new VRDisplayCapabilities({
  44115. hasPosition: false,
  44116. hasOrientation: false,
  44117. hasExternalDisplay: false,
  44118. canPresent: false,
  44119. maxLayers: 1
  44120. });
  44121. this.stageParameters = null;
  44122. this.waitingForPresent_ = false;
  44123. this.layer_ = null;
  44124. this.originalParent_ = null;
  44125. this.fullscreenElement_ = null;
  44126. this.fullscreenWrapper_ = null;
  44127. this.fullscreenElementCachedStyle_ = null;
  44128. this.fullscreenEventTarget_ = null;
  44129. this.fullscreenChangeHandler_ = null;
  44130. this.fullscreenErrorHandler_ = null;
  44131. if (USE_WAKELOCK && isMobile()) {
  44132. this.wakelock_ = new NoSleep$1();
  44133. }
  44134. }
  44135. VRDisplay.prototype.getFrameData = function (frameData) {
  44136. return frameDataFromPose(frameData, this._getPose(), this);
  44137. };
  44138. VRDisplay.prototype.getPose = function () {
  44139. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  44140. return this._getPose();
  44141. };
  44142. VRDisplay.prototype.resetPose = function () {
  44143. deprecateWarning('VRDisplay.prototype.resetPose');
  44144. return this._resetPose();
  44145. };
  44146. VRDisplay.prototype.getImmediatePose = function () {
  44147. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  44148. return this._getPose();
  44149. };
  44150. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  44151. return raf(callback);
  44152. };
  44153. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  44154. return caf(id);
  44155. };
  44156. VRDisplay.prototype.wrapForFullscreen = function (element) {
  44157. if (isIOS()) {
  44158. return element;
  44159. }
  44160. if (!this.fullscreenWrapper_) {
  44161. this.fullscreenWrapper_ = document.createElement('div');
  44162. var cssProperties = ['height: ' + Math.min(screen.height, screen.width) + 'px !important', 'top: 0 !important', 'left: 0 !important', 'right: 0 !important', 'border: 0', 'margin: 0', 'padding: 0', 'z-index: 999999 !important', 'position: fixed'];
  44163. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  44164. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  44165. }
  44166. if (this.fullscreenElement_ == element) {
  44167. return this.fullscreenWrapper_;
  44168. }
  44169. if (this.fullscreenElement_) {
  44170. if (this.originalParent_) {
  44171. this.originalParent_.appendChild(this.fullscreenElement_);
  44172. } else {
  44173. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  44174. }
  44175. }
  44176. this.fullscreenElement_ = element;
  44177. this.originalParent_ = element.parentElement;
  44178. if (!this.originalParent_) {
  44179. document.body.appendChild(element);
  44180. }
  44181. if (!this.fullscreenWrapper_.parentElement) {
  44182. var parent = this.fullscreenElement_.parentElement;
  44183. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  44184. parent.removeChild(this.fullscreenElement_);
  44185. }
  44186. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  44187. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  44188. var self = this;
  44189. function applyFullscreenElementStyle() {
  44190. if (!self.fullscreenElement_) {
  44191. return;
  44192. }
  44193. var cssProperties = ['position: absolute', 'top: 0', 'left: 0', 'width: ' + Math.max(screen.width, screen.height) + 'px', 'height: ' + Math.min(screen.height, screen.width) + 'px', 'border: 0', 'margin: 0', 'padding: 0'];
  44194. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  44195. }
  44196. applyFullscreenElementStyle();
  44197. return this.fullscreenWrapper_;
  44198. };
  44199. VRDisplay.prototype.removeFullscreenWrapper = function () {
  44200. if (!this.fullscreenElement_) {
  44201. return;
  44202. }
  44203. var element = this.fullscreenElement_;
  44204. if (this.fullscreenElementCachedStyle_) {
  44205. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  44206. } else {
  44207. element.removeAttribute('style');
  44208. }
  44209. this.fullscreenElement_ = null;
  44210. this.fullscreenElementCachedStyle_ = null;
  44211. var parent = this.fullscreenWrapper_.parentElement;
  44212. this.fullscreenWrapper_.removeChild(element);
  44213. if (this.originalParent_ === parent) {
  44214. parent.insertBefore(element, this.fullscreenWrapper_);
  44215. }
  44216. else if (this.originalParent_) {
  44217. this.originalParent_.appendChild(element);
  44218. }
  44219. parent.removeChild(this.fullscreenWrapper_);
  44220. return element;
  44221. };
  44222. VRDisplay.prototype.requestPresent = function (layers) {
  44223. var wasPresenting = this.isPresenting;
  44224. var self = this;
  44225. if (!(layers instanceof Array)) {
  44226. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  44227. layers = [layers];
  44228. }
  44229. return new Promise(function (resolve, reject) {
  44230. if (!self.capabilities.canPresent) {
  44231. reject(new Error('VRDisplay is not capable of presenting.'));
  44232. return;
  44233. }
  44234. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  44235. reject(new Error('Invalid number of layers.'));
  44236. return;
  44237. }
  44238. var incomingLayer = layers[0];
  44239. if (!incomingLayer.source) {
  44240. resolve();
  44241. return;
  44242. }
  44243. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  44244. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  44245. if (wasPresenting) {
  44246. var layer = self.layer_;
  44247. if (layer.source !== incomingLayer.source) {
  44248. layer.source = incomingLayer.source;
  44249. }
  44250. for (var i = 0; i < 4; i++) {
  44251. layer.leftBounds[i] = leftBounds[i];
  44252. layer.rightBounds[i] = rightBounds[i];
  44253. }
  44254. self.wrapForFullscreen(self.layer_.source);
  44255. self.updatePresent_();
  44256. resolve();
  44257. return;
  44258. }
  44259. self.layer_ = {
  44260. predistorted: incomingLayer.predistorted,
  44261. source: incomingLayer.source,
  44262. leftBounds: leftBounds.slice(0),
  44263. rightBounds: rightBounds.slice(0)
  44264. };
  44265. self.waitingForPresent_ = false;
  44266. if (self.layer_ && self.layer_.source) {
  44267. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  44268. var onFullscreenChange = function onFullscreenChange() {
  44269. var actualFullscreenElement = getFullscreenElement();
  44270. self.isPresenting = fullscreenElement === actualFullscreenElement;
  44271. if (self.isPresenting) {
  44272. if (screen.orientation && screen.orientation.lock) {
  44273. screen.orientation.lock('landscape-primary').catch(function (error) {
  44274. console.error('screen.orientation.lock() failed due to', error.message);
  44275. });
  44276. }
  44277. self.waitingForPresent_ = false;
  44278. self.beginPresent_();
  44279. resolve();
  44280. } else {
  44281. if (screen.orientation && screen.orientation.unlock) {
  44282. screen.orientation.unlock();
  44283. }
  44284. self.removeFullscreenWrapper();
  44285. self.disableWakeLock();
  44286. self.endPresent_();
  44287. self.removeFullscreenListeners_();
  44288. }
  44289. self.fireVRDisplayPresentChange_();
  44290. };
  44291. var onFullscreenError = function onFullscreenError() {
  44292. if (!self.waitingForPresent_) {
  44293. return;
  44294. }
  44295. self.removeFullscreenWrapper();
  44296. self.removeFullscreenListeners_();
  44297. self.disableWakeLock();
  44298. self.waitingForPresent_ = false;
  44299. self.isPresenting = false;
  44300. reject(new Error('Unable to present.'));
  44301. };
  44302. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  44303. if (requestFullscreen(fullscreenElement)) {
  44304. self.enableWakeLock();
  44305. self.waitingForPresent_ = true;
  44306. } else if (isIOS() || isWebViewAndroid()) {
  44307. self.enableWakeLock();
  44308. self.isPresenting = true;
  44309. self.beginPresent_();
  44310. self.fireVRDisplayPresentChange_();
  44311. resolve();
  44312. }
  44313. }
  44314. if (!self.waitingForPresent_ && !isIOS()) {
  44315. exitFullscreen();
  44316. reject(new Error('Unable to present.'));
  44317. }
  44318. });
  44319. };
  44320. VRDisplay.prototype.exitPresent = function () {
  44321. var wasPresenting = this.isPresenting;
  44322. var self = this;
  44323. this.isPresenting = false;
  44324. this.layer_ = null;
  44325. this.disableWakeLock();
  44326. return new Promise(function (resolve, reject) {
  44327. if (wasPresenting) {
  44328. if (!exitFullscreen() && isIOS()) {
  44329. self.endPresent_();
  44330. self.fireVRDisplayPresentChange_();
  44331. }
  44332. if (isWebViewAndroid()) {
  44333. self.removeFullscreenWrapper();
  44334. self.removeFullscreenListeners_();
  44335. self.endPresent_();
  44336. self.fireVRDisplayPresentChange_();
  44337. }
  44338. resolve();
  44339. } else {
  44340. reject(new Error('Was not presenting to VRDisplay.'));
  44341. }
  44342. });
  44343. };
  44344. VRDisplay.prototype.getLayers = function () {
  44345. if (this.layer_) {
  44346. return [this.layer_];
  44347. }
  44348. return [];
  44349. };
  44350. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  44351. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  44352. window.dispatchEvent(event);
  44353. };
  44354. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  44355. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  44356. window.dispatchEvent(event);
  44357. };
  44358. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  44359. this.removeFullscreenListeners_();
  44360. this.fullscreenEventTarget_ = element;
  44361. this.fullscreenChangeHandler_ = changeHandler;
  44362. this.fullscreenErrorHandler_ = errorHandler;
  44363. if (changeHandler) {
  44364. if (document.fullscreenEnabled) {
  44365. element.addEventListener('fullscreenchange', changeHandler, false);
  44366. } else if (document.webkitFullscreenEnabled) {
  44367. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  44368. } else if (document.mozFullScreenEnabled) {
  44369. document.addEventListener('mozfullscreenchange', changeHandler, false);
  44370. } else if (document.msFullscreenEnabled) {
  44371. element.addEventListener('msfullscreenchange', changeHandler, false);
  44372. }
  44373. }
  44374. if (errorHandler) {
  44375. if (document.fullscreenEnabled) {
  44376. element.addEventListener('fullscreenerror', errorHandler, false);
  44377. } else if (document.webkitFullscreenEnabled) {
  44378. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  44379. } else if (document.mozFullScreenEnabled) {
  44380. document.addEventListener('mozfullscreenerror', errorHandler, false);
  44381. } else if (document.msFullscreenEnabled) {
  44382. element.addEventListener('msfullscreenerror', errorHandler, false);
  44383. }
  44384. }
  44385. };
  44386. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  44387. if (!this.fullscreenEventTarget_) return;
  44388. var element = this.fullscreenEventTarget_;
  44389. if (this.fullscreenChangeHandler_) {
  44390. var changeHandler = this.fullscreenChangeHandler_;
  44391. element.removeEventListener('fullscreenchange', changeHandler, false);
  44392. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  44393. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  44394. element.removeEventListener('msfullscreenchange', changeHandler, false);
  44395. }
  44396. if (this.fullscreenErrorHandler_) {
  44397. var errorHandler = this.fullscreenErrorHandler_;
  44398. element.removeEventListener('fullscreenerror', errorHandler, false);
  44399. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  44400. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  44401. element.removeEventListener('msfullscreenerror', errorHandler, false);
  44402. }
  44403. this.fullscreenEventTarget_ = null;
  44404. this.fullscreenChangeHandler_ = null;
  44405. this.fullscreenErrorHandler_ = null;
  44406. };
  44407. VRDisplay.prototype.enableWakeLock = function () {
  44408. if (this.wakelock_) {
  44409. this.wakelock_.enable();
  44410. }
  44411. };
  44412. VRDisplay.prototype.disableWakeLock = function () {
  44413. if (this.wakelock_) {
  44414. this.wakelock_.disable();
  44415. }
  44416. };
  44417. VRDisplay.prototype.beginPresent_ = function () {
  44418. };
  44419. VRDisplay.prototype.endPresent_ = function () {
  44420. };
  44421. VRDisplay.prototype.submitFrame = function (pose) {
  44422. };
  44423. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  44424. return null;
  44425. };
  44426. var config = {
  44427. ADDITIONAL_VIEWERS: [],
  44428. DEFAULT_VIEWER: '',
  44429. MOBILE_WAKE_LOCK: true,
  44430. DEBUG: false,
  44431. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  44432. K_FILTER: 0.98,
  44433. PREDICTION_TIME_S: 0.040,
  44434. CARDBOARD_UI_DISABLED: false,
  44435. ROTATE_INSTRUCTIONS_DISABLED: false,
  44436. YAW_ONLY: false,
  44437. BUFFER_SCALE: 0.5,
  44438. DIRTY_SUBMIT_FRAME_BINDINGS: false
  44439. };
  44440. var Eye = {
  44441. LEFT: 'left',
  44442. RIGHT: 'right'
  44443. };
  44444. function CardboardVRDisplay(config$$1) {
  44445. var defaults = extend({}, config);
  44446. config$$1 = extend(defaults, config$$1 || {});
  44447. VRDisplay.call(this, {
  44448. wakelock: config$$1.MOBILE_WAKE_LOCK
  44449. });
  44450. this.config = config$$1;
  44451. this.displayName = 'Cardboard VRDisplay';
  44452. this.capabilities = new VRDisplayCapabilities({
  44453. hasPosition: false,
  44454. hasOrientation: true,
  44455. hasExternalDisplay: false,
  44456. canPresent: true,
  44457. maxLayers: 1
  44458. });
  44459. this.stageParameters = null;
  44460. this.bufferScale_ = this.config.BUFFER_SCALE;
  44461. this.poseSensor_ = new PoseSensor(this.config);
  44462. this.distorter_ = null;
  44463. this.cardboardUI_ = null;
  44464. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  44465. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  44466. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  44467. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  44468. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  44469. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  44470. this.rotateInstructions_ = new RotateInstructions();
  44471. }
  44472. if (isIOS()) {
  44473. window.addEventListener('resize', this.onResize_.bind(this));
  44474. }
  44475. }
  44476. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  44477. CardboardVRDisplay.prototype._getPose = function () {
  44478. return {
  44479. position: null,
  44480. orientation: this.poseSensor_.getOrientation(),
  44481. linearVelocity: null,
  44482. linearAcceleration: null,
  44483. angularVelocity: null,
  44484. angularAcceleration: null
  44485. };
  44486. };
  44487. CardboardVRDisplay.prototype._resetPose = function () {
  44488. if (this.poseSensor_.resetPose) {
  44489. this.poseSensor_.resetPose();
  44490. }
  44491. };
  44492. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  44493. var fieldOfView;
  44494. if (whichEye == Eye.LEFT) {
  44495. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  44496. } else if (whichEye == Eye.RIGHT) {
  44497. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  44498. } else {
  44499. console.error('Invalid eye provided: %s', whichEye);
  44500. return null;
  44501. }
  44502. return fieldOfView;
  44503. };
  44504. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  44505. var offset;
  44506. if (whichEye == Eye.LEFT) {
  44507. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  44508. } else if (whichEye == Eye.RIGHT) {
  44509. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  44510. } else {
  44511. console.error('Invalid eye provided: %s', whichEye);
  44512. return null;
  44513. }
  44514. return offset;
  44515. };
  44516. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  44517. var offset = this._getEyeOffset(whichEye);
  44518. var fieldOfView = this._getFieldOfView(whichEye);
  44519. var eyeParams = {
  44520. offset: offset,
  44521. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  44522. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  44523. };
  44524. Object.defineProperty(eyeParams, 'fieldOfView', {
  44525. enumerable: true,
  44526. get: function get() {
  44527. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  44528. return fieldOfView;
  44529. }
  44530. });
  44531. return eyeParams;
  44532. };
  44533. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  44534. if (this.config.DEBUG) {
  44535. console.log('DPDB reported that device params were updated.');
  44536. }
  44537. this.deviceInfo_.updateDeviceParams(newParams);
  44538. if (this.distorter_) {
  44539. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44540. }
  44541. };
  44542. CardboardVRDisplay.prototype.updateBounds_ = function () {
  44543. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  44544. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  44545. }
  44546. };
  44547. CardboardVRDisplay.prototype.beginPresent_ = function () {
  44548. var gl = this.layer_.source.getContext('webgl');
  44549. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44550. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44551. if (!gl) return;
  44552. if (this.layer_.predistorted) {
  44553. if (!this.config.CARDBOARD_UI_DISABLED) {
  44554. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  44555. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  44556. this.cardboardUI_ = new CardboardUI(gl);
  44557. }
  44558. } else {
  44559. if (!this.config.CARDBOARD_UI_DISABLED) {
  44560. this.cardboardUI_ = new CardboardUI(gl);
  44561. }
  44562. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  44563. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44564. }
  44565. if (this.cardboardUI_) {
  44566. this.cardboardUI_.listen(function (e) {
  44567. this.viewerSelector_.show(this.layer_.source.parentElement);
  44568. e.stopPropagation();
  44569. e.preventDefault();
  44570. }.bind(this), function (e) {
  44571. this.exitPresent();
  44572. e.stopPropagation();
  44573. e.preventDefault();
  44574. }.bind(this));
  44575. }
  44576. if (this.rotateInstructions_) {
  44577. if (isLandscapeMode() && isMobile()) {
  44578. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  44579. } else {
  44580. this.rotateInstructions_.update();
  44581. }
  44582. }
  44583. this.orientationHandler = this.onOrientationChange_.bind(this);
  44584. window.addEventListener('orientationchange', this.orientationHandler);
  44585. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  44586. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  44587. this.fireVRDisplayDeviceParamsChange_();
  44588. };
  44589. CardboardVRDisplay.prototype.endPresent_ = function () {
  44590. if (this.distorter_) {
  44591. this.distorter_.destroy();
  44592. this.distorter_ = null;
  44593. }
  44594. if (this.cardboardUI_) {
  44595. this.cardboardUI_.destroy();
  44596. this.cardboardUI_ = null;
  44597. }
  44598. if (this.rotateInstructions_) {
  44599. this.rotateInstructions_.hide();
  44600. }
  44601. this.viewerSelector_.hide();
  44602. window.removeEventListener('orientationchange', this.orientationHandler);
  44603. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  44604. };
  44605. CardboardVRDisplay.prototype.updatePresent_ = function () {
  44606. this.endPresent_();
  44607. this.beginPresent_();
  44608. };
  44609. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  44610. if (this.distorter_) {
  44611. this.updateBounds_();
  44612. this.distorter_.submitFrame();
  44613. } else if (this.cardboardUI_ && this.layer_) {
  44614. var gl = this.layer_.source.getContext('webgl');
  44615. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44616. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44617. var canvas = gl.canvas;
  44618. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  44619. this.cardboardUI_.onResize();
  44620. }
  44621. this.lastWidth = canvas.width;
  44622. this.lastHeight = canvas.height;
  44623. this.cardboardUI_.render();
  44624. }
  44625. };
  44626. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  44627. this.viewerSelector_.hide();
  44628. if (this.rotateInstructions_) {
  44629. this.rotateInstructions_.update();
  44630. }
  44631. this.onResize_();
  44632. };
  44633. CardboardVRDisplay.prototype.onResize_ = function (e) {
  44634. if (this.layer_) {
  44635. var gl = this.layer_.source.getContext('webgl');
  44636. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44637. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44638. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  44639. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  44640. 'padding: 0px', 'box-sizing: content-box'];
  44641. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  44642. safariCssSizeWorkaround(gl.canvas);
  44643. }
  44644. };
  44645. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  44646. this.deviceInfo_.setViewer(viewer);
  44647. if (this.distorter_) {
  44648. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44649. }
  44650. this.fireVRDisplayDeviceParamsChange_();
  44651. };
  44652. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  44653. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  44654. detail: {
  44655. vrdisplay: this,
  44656. deviceInfo: this.deviceInfo_
  44657. }
  44658. });
  44659. window.dispatchEvent(event);
  44660. };
  44661. CardboardVRDisplay.VRFrameData = VRFrameData;
  44662. CardboardVRDisplay.VRDisplay = VRDisplay;
  44663. return CardboardVRDisplay;
  44664. })));
  44665. });
  44666. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  44667. var version = "0.10.12";
  44668. var DefaultConfig = {
  44669. ADDITIONAL_VIEWERS: [],
  44670. DEFAULT_VIEWER: '',
  44671. PROVIDE_MOBILE_VRDISPLAY: true,
  44672. MOBILE_WAKE_LOCK: true,
  44673. DEBUG: false,
  44674. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  44675. K_FILTER: 0.98,
  44676. PREDICTION_TIME_S: 0.040,
  44677. CARDBOARD_UI_DISABLED: false,
  44678. ROTATE_INSTRUCTIONS_DISABLED: false,
  44679. YAW_ONLY: false,
  44680. BUFFER_SCALE: 0.5,
  44681. DIRTY_SUBMIT_FRAME_BINDINGS: false
  44682. };
  44683. function WebVRPolyfill(config) {
  44684. this.config = extend(extend({}, DefaultConfig), config);
  44685. this.polyfillDisplays = [];
  44686. this.enabled = false;
  44687. this.hasNative = 'getVRDisplays' in navigator;
  44688. this.native = {};
  44689. this.native.getVRDisplays = navigator.getVRDisplays;
  44690. this.native.VRFrameData = window.VRFrameData;
  44691. this.native.VRDisplay = window.VRDisplay;
  44692. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  44693. this.enable();
  44694. this.getVRDisplays().then(function (displays) {
  44695. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  44696. displays[0].fireVRDisplayConnect_();
  44697. }
  44698. });
  44699. }
  44700. }
  44701. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  44702. if (this._polyfillDisplaysPopulated) {
  44703. return this.polyfillDisplays;
  44704. }
  44705. if (isMobile()) {
  44706. var vrDisplay = new CardboardVRDisplay({
  44707. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  44708. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  44709. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  44710. DEBUG: this.config.DEBUG,
  44711. DPDB_URL: this.config.DPDB_URL,
  44712. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  44713. K_FILTER: this.config.K_FILTER,
  44714. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  44715. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  44716. YAW_ONLY: this.config.YAW_ONLY,
  44717. BUFFER_SCALE: this.config.BUFFER_SCALE,
  44718. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  44719. });
  44720. this.polyfillDisplays.push(vrDisplay);
  44721. }
  44722. this._polyfillDisplaysPopulated = true;
  44723. return this.polyfillDisplays;
  44724. };
  44725. WebVRPolyfill.prototype.enable = function () {
  44726. this.enabled = true;
  44727. if (this.hasNative && this.native.VRFrameData) {
  44728. var NativeVRFrameData = this.native.VRFrameData;
  44729. var nativeFrameData = new this.native.VRFrameData();
  44730. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  44731. window.VRDisplay.prototype.getFrameData = function (frameData) {
  44732. if (frameData instanceof NativeVRFrameData) {
  44733. nativeGetFrameData.call(this, frameData);
  44734. return;
  44735. }
  44736. nativeGetFrameData.call(this, nativeFrameData);
  44737. frameData.pose = nativeFrameData.pose;
  44738. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  44739. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  44740. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  44741. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  44742. };
  44743. }
  44744. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  44745. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  44746. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  44747. };
  44748. WebVRPolyfill.prototype.getVRDisplays = function () {
  44749. var _this = this;
  44750. var config = this.config;
  44751. if (!this.hasNative) {
  44752. return Promise.resolve(this.getPolyfillDisplays());
  44753. }
  44754. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  44755. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  44756. });
  44757. };
  44758. WebVRPolyfill.version = version;
  44759. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  44760. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  44761. var webvrPolyfill = Object.freeze({
  44762. default: WebVRPolyfill
  44763. });
  44764. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  44765. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  44766. if (!commonjsGlobal.document) {
  44767. commonjsGlobal.document = commonjsGlobal.window.document;
  44768. }
  44769. if (!commonjsGlobal.navigator) {
  44770. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  44771. }
  44772. }
  44773. var src = require$$0;
  44774. return src;
  44775. })));
  44776. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  44777. },{}],68:[function(_dereq_,module,exports){
  44778. var newline = /\n/
  44779. var newlineChar = '\n'
  44780. var whitespace = /\s/
  44781. module.exports = function(text, opt) {
  44782. var lines = module.exports.lines(text, opt)
  44783. return lines.map(function(line) {
  44784. return text.substring(line.start, line.end)
  44785. }).join('\n')
  44786. }
  44787. module.exports.lines = function wordwrap(text, opt) {
  44788. opt = opt||{}
  44789. //zero width results in nothing visible
  44790. if (opt.width === 0 && opt.mode !== 'nowrap')
  44791. return []
  44792. text = text||''
  44793. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  44794. var start = Math.max(0, opt.start||0)
  44795. var end = typeof opt.end === 'number' ? opt.end : text.length
  44796. var mode = opt.mode
  44797. var measure = opt.measure || monospace
  44798. if (mode === 'pre')
  44799. return pre(measure, text, start, end, width)
  44800. else
  44801. return greedy(measure, text, start, end, width, mode)
  44802. }
  44803. function idxOf(text, chr, start, end) {
  44804. var idx = text.indexOf(chr, start)
  44805. if (idx === -1 || idx > end)
  44806. return end
  44807. return idx
  44808. }
  44809. function isWhitespace(chr) {
  44810. return whitespace.test(chr)
  44811. }
  44812. function pre(measure, text, start, end, width) {
  44813. var lines = []
  44814. var lineStart = start
  44815. for (var i=start; i<end && i<text.length; i++) {
  44816. var chr = text.charAt(i)
  44817. var isNewline = newline.test(chr)
  44818. //If we've reached a newline, then step down a line
  44819. //Or if we've reached the EOF
  44820. if (isNewline || i===end-1) {
  44821. var lineEnd = isNewline ? i : i+1
  44822. var measured = measure(text, lineStart, lineEnd, width)
  44823. lines.push(measured)
  44824. lineStart = i+1
  44825. }
  44826. }
  44827. return lines
  44828. }
  44829. function greedy(measure, text, start, end, width, mode) {
  44830. //A greedy word wrapper based on LibGDX algorithm
  44831. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  44832. var lines = []
  44833. var testWidth = width
  44834. //if 'nowrap' is specified, we only wrap on newline chars
  44835. if (mode === 'nowrap')
  44836. testWidth = Number.MAX_VALUE
  44837. while (start < end && start < text.length) {
  44838. //get next newline position
  44839. var newLine = idxOf(text, newlineChar, start, end)
  44840. //eat whitespace at start of line
  44841. while (start < newLine) {
  44842. if (!isWhitespace( text.charAt(start) ))
  44843. break
  44844. start++
  44845. }
  44846. //determine visible # of glyphs for the available width
  44847. var measured = measure(text, start, newLine, testWidth)
  44848. var lineEnd = start + (measured.end-measured.start)
  44849. var nextStart = lineEnd + newlineChar.length
  44850. //if we had to cut the line before the next newline...
  44851. if (lineEnd < newLine) {
  44852. //find char to break on
  44853. while (lineEnd > start) {
  44854. if (isWhitespace(text.charAt(lineEnd)))
  44855. break
  44856. lineEnd--
  44857. }
  44858. if (lineEnd === start) {
  44859. if (nextStart > start + newlineChar.length) nextStart--
  44860. lineEnd = nextStart // If no characters to break, show all.
  44861. } else {
  44862. nextStart = lineEnd
  44863. //eat whitespace at end of line
  44864. while (lineEnd > start) {
  44865. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  44866. break
  44867. lineEnd--
  44868. }
  44869. }
  44870. }
  44871. if (lineEnd >= start) {
  44872. var result = measure(text, start, lineEnd, testWidth)
  44873. lines.push(result)
  44874. }
  44875. start = nextStart
  44876. }
  44877. return lines
  44878. }
  44879. //determines the visible number of glyphs within a given width
  44880. function monospace(text, start, end, width) {
  44881. var glyphs = Math.min(width, end-start)
  44882. return {
  44883. start: start,
  44884. end: start+glyphs
  44885. }
  44886. }
  44887. },{}],69:[function(_dereq_,module,exports){
  44888. "use strict";
  44889. var window = _dereq_("global/window")
  44890. var isFunction = _dereq_("is-function")
  44891. var parseHeaders = _dereq_("parse-headers")
  44892. var xtend = _dereq_("xtend")
  44893. module.exports = createXHR
  44894. // Allow use of default import syntax in TypeScript
  44895. module.exports.default = createXHR;
  44896. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  44897. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  44898. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  44899. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  44900. options = initParams(uri, options, callback)
  44901. options.method = method.toUpperCase()
  44902. return _createXHR(options)
  44903. }
  44904. })
  44905. function forEachArray(array, iterator) {
  44906. for (var i = 0; i < array.length; i++) {
  44907. iterator(array[i])
  44908. }
  44909. }
  44910. function isEmpty(obj){
  44911. for(var i in obj){
  44912. if(obj.hasOwnProperty(i)) return false
  44913. }
  44914. return true
  44915. }
  44916. function initParams(uri, options, callback) {
  44917. var params = uri
  44918. if (isFunction(options)) {
  44919. callback = options
  44920. if (typeof uri === "string") {
  44921. params = {uri:uri}
  44922. }
  44923. } else {
  44924. params = xtend(options, {uri: uri})
  44925. }
  44926. params.callback = callback
  44927. return params
  44928. }
  44929. function createXHR(uri, options, callback) {
  44930. options = initParams(uri, options, callback)
  44931. return _createXHR(options)
  44932. }
  44933. function _createXHR(options) {
  44934. if(typeof options.callback === "undefined"){
  44935. throw new Error("callback argument missing")
  44936. }
  44937. var called = false
  44938. var callback = function cbOnce(err, response, body){
  44939. if(!called){
  44940. called = true
  44941. options.callback(err, response, body)
  44942. }
  44943. }
  44944. function readystatechange() {
  44945. if (xhr.readyState === 4) {
  44946. setTimeout(loadFunc, 0)
  44947. }
  44948. }
  44949. function getBody() {
  44950. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  44951. var body = undefined
  44952. if (xhr.response) {
  44953. body = xhr.response
  44954. } else {
  44955. body = xhr.responseText || getXml(xhr)
  44956. }
  44957. if (isJson) {
  44958. try {
  44959. body = JSON.parse(body)
  44960. } catch (e) {}
  44961. }
  44962. return body
  44963. }
  44964. function errorFunc(evt) {
  44965. clearTimeout(timeoutTimer)
  44966. if(!(evt instanceof Error)){
  44967. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  44968. }
  44969. evt.statusCode = 0
  44970. return callback(evt, failureResponse)
  44971. }
  44972. // will load the data & process the response in a special response object
  44973. function loadFunc() {
  44974. if (aborted) return
  44975. var status
  44976. clearTimeout(timeoutTimer)
  44977. if(options.useXDR && xhr.status===undefined) {
  44978. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  44979. status = 200
  44980. } else {
  44981. status = (xhr.status === 1223 ? 204 : xhr.status)
  44982. }
  44983. var response = failureResponse
  44984. var err = null
  44985. if (status !== 0){
  44986. response = {
  44987. body: getBody(),
  44988. statusCode: status,
  44989. method: method,
  44990. headers: {},
  44991. url: uri,
  44992. rawRequest: xhr
  44993. }
  44994. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  44995. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  44996. }
  44997. } else {
  44998. err = new Error("Internal XMLHttpRequest Error")
  44999. }
  45000. return callback(err, response, response.body)
  45001. }
  45002. var xhr = options.xhr || null
  45003. if (!xhr) {
  45004. if (options.cors || options.useXDR) {
  45005. xhr = new createXHR.XDomainRequest()
  45006. }else{
  45007. xhr = new createXHR.XMLHttpRequest()
  45008. }
  45009. }
  45010. var key
  45011. var aborted
  45012. var uri = xhr.url = options.uri || options.url
  45013. var method = xhr.method = options.method || "GET"
  45014. var body = options.body || options.data
  45015. var headers = xhr.headers = options.headers || {}
  45016. var sync = !!options.sync
  45017. var isJson = false
  45018. var timeoutTimer
  45019. var failureResponse = {
  45020. body: undefined,
  45021. headers: {},
  45022. statusCode: 0,
  45023. method: method,
  45024. url: uri,
  45025. rawRequest: xhr
  45026. }
  45027. if ("json" in options && options.json !== false) {
  45028. isJson = true
  45029. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  45030. if (method !== "GET" && method !== "HEAD") {
  45031. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  45032. body = JSON.stringify(options.json === true ? body : options.json)
  45033. }
  45034. }
  45035. xhr.onreadystatechange = readystatechange
  45036. xhr.onload = loadFunc
  45037. xhr.onerror = errorFunc
  45038. // IE9 must have onprogress be set to a unique function.
  45039. xhr.onprogress = function () {
  45040. // IE must die
  45041. }
  45042. xhr.onabort = function(){
  45043. aborted = true;
  45044. }
  45045. xhr.ontimeout = errorFunc
  45046. xhr.open(method, uri, !sync, options.username, options.password)
  45047. //has to be after open
  45048. if(!sync) {
  45049. xhr.withCredentials = !!options.withCredentials
  45050. }
  45051. // Cannot set timeout with sync request
  45052. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  45053. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  45054. if (!sync && options.timeout > 0 ) {
  45055. timeoutTimer = setTimeout(function(){
  45056. if (aborted) return
  45057. aborted = true//IE9 may still call readystatechange
  45058. xhr.abort("timeout")
  45059. var e = new Error("XMLHttpRequest timeout")
  45060. e.code = "ETIMEDOUT"
  45061. errorFunc(e)
  45062. }, options.timeout )
  45063. }
  45064. if (xhr.setRequestHeader) {
  45065. for(key in headers){
  45066. if(headers.hasOwnProperty(key)){
  45067. xhr.setRequestHeader(key, headers[key])
  45068. }
  45069. }
  45070. } else if (options.headers && !isEmpty(options.headers)) {
  45071. throw new Error("Headers cannot be set on an XDomainRequest object")
  45072. }
  45073. if ("responseType" in options) {
  45074. xhr.responseType = options.responseType
  45075. }
  45076. if ("beforeSend" in options &&
  45077. typeof options.beforeSend === "function"
  45078. ) {
  45079. options.beforeSend(xhr)
  45080. }
  45081. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  45082. // XMLHttpRequest spec says to pass null as body to indicate no body
  45083. // See https://github.com/naugtur/xhr/issues/100.
  45084. xhr.send(body || null)
  45085. return xhr
  45086. }
  45087. function getXml(xhr) {
  45088. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  45089. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  45090. try {
  45091. if (xhr.responseType === "document") {
  45092. return xhr.responseXML
  45093. }
  45094. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  45095. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  45096. return xhr.responseXML
  45097. }
  45098. } catch (e) {}
  45099. return null
  45100. }
  45101. function noop() {}
  45102. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":71}],70:[function(_dereq_,module,exports){
  45103. module.exports = (function xmlparser() {
  45104. //common browsers
  45105. if (typeof self.DOMParser !== 'undefined') {
  45106. return function(str) {
  45107. var parser = new self.DOMParser()
  45108. return parser.parseFromString(str, 'application/xml')
  45109. }
  45110. }
  45111. //IE8 fallback
  45112. if (typeof self.ActiveXObject !== 'undefined'
  45113. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  45114. return function(str) {
  45115. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  45116. xmlDoc.async = "false"
  45117. xmlDoc.loadXML(str)
  45118. return xmlDoc
  45119. }
  45120. }
  45121. //last resort fallback
  45122. return function(str) {
  45123. var div = document.createElement('div')
  45124. div.innerHTML = str
  45125. return div
  45126. }
  45127. })()
  45128. },{}],71:[function(_dereq_,module,exports){
  45129. module.exports = extend
  45130. var hasOwnProperty = Object.prototype.hasOwnProperty;
  45131. function extend() {
  45132. var target = {}
  45133. for (var i = 0; i < arguments.length; i++) {
  45134. var source = arguments[i]
  45135. for (var key in source) {
  45136. if (hasOwnProperty.call(source, key)) {
  45137. target[key] = source[key]
  45138. }
  45139. }
  45140. }
  45141. return target
  45142. }
  45143. },{}],72:[function(_dereq_,module,exports){
  45144. module.exports={
  45145. "name": "aframe",
  45146. "version": "1.1.0",
  45147. "description": "A web framework for building virtual reality experiences.",
  45148. "homepage": "https://aframe.io/",
  45149. "main": "dist/aframe-master.js",
  45150. "scripts": {
  45151. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  45152. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [ envify --INSPECTOR_VERSION dev ] -o build/aframe.js",
  45153. "codecov": "codecov",
  45154. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  45155. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  45156. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  45157. "dist:min": "npm run browserify -s -- --debug -p [ minifyify --map aframe-master.min.js.map --output dist/aframe-master.min.js.map ] -o dist/aframe-master.min.js",
  45158. "docs": "markserv --dir docs --port 9001",
  45159. "preghpages": "node ./scripts/preghpages.js",
  45160. "ghpages": "ghpages -p gh-pages/",
  45161. "lint": "semistandard -v | snazzy",
  45162. "lint:fix": "semistandard --fix",
  45163. "precommit": "npm run lint",
  45164. "prepush": "node scripts/testOnlyCheck.js",
  45165. "prerelease": "node scripts/release.js 1.0.4 1.1.0",
  45166. "start": "npm run dev",
  45167. "start:https": "cross-env SSL=true npm run dev",
  45168. "test": "karma start ./tests/karma.conf.js",
  45169. "test:docs": "node scripts/docsLint.js",
  45170. "test:firefox": "npm test -- --browsers Firefox",
  45171. "test:chrome": "npm test -- --browsers Chrome",
  45172. "test:nobrowser": "NO_BROWSER=true npm test",
  45173. "test:node": "mocha --ui tdd tests/node"
  45174. },
  45175. "repository": "aframevr/aframe",
  45176. "license": "MIT",
  45177. "files": [
  45178. "dist/*",
  45179. "docs/**/*",
  45180. "src/**/*",
  45181. "vendor/**/*"
  45182. ],
  45183. "dependencies": {
  45184. "custom-event-polyfill": "^1.0.6",
  45185. "debug": "ngokevin/debug#noTimestamp",
  45186. "deep-assign": "^2.0.0",
  45187. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  45188. "load-bmfont": "^1.2.3",
  45189. "object-assign": "^4.0.1",
  45190. "present": "0.0.6",
  45191. "promise-polyfill": "^3.1.0",
  45192. "super-animejs": "^3.1.0",
  45193. "super-three": "^0.123.1",
  45194. "three-bmfont-text": "dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e",
  45195. "webvr-polyfill": "^0.10.12"
  45196. },
  45197. "devDependencies": {
  45198. "browserify": "^13.1.0",
  45199. "browserify-css": "^0.8.4",
  45200. "browserify-derequire": "^0.9.4",
  45201. "browserify-istanbul": "^2.0.0",
  45202. "budo": "^9.2.0",
  45203. "chai": "^3.5.0",
  45204. "chai-shallow-deep-equal": "^1.4.0",
  45205. "chalk": "^1.1.3",
  45206. "codecov": "^1.0.1",
  45207. "cross-env": "^5.0.1",
  45208. "envify": "^3.4.1",
  45209. "exorcist": "^0.4.0",
  45210. "ghpages": "0.0.8",
  45211. "git-rev": "^0.2.1",
  45212. "glob": "^7.1.1",
  45213. "husky": "^0.11.7",
  45214. "istanbul": "^0.4.5",
  45215. "jsdom": "^9.11.0",
  45216. "karma": "1.4.1",
  45217. "karma-browserify": "^5.1.0",
  45218. "karma-chai-shallow-deep-equal": "0.0.4",
  45219. "karma-chrome-launcher": "^2.0.0",
  45220. "karma-coverage": "^1.1.1",
  45221. "karma-env-preprocessor": "^0.1.1",
  45222. "karma-firefox-launcher": "^1.2.0",
  45223. "karma-mocha": "^1.1.1",
  45224. "karma-mocha-reporter": "^2.1.0",
  45225. "karma-sinon-chai": "1.2.4",
  45226. "lolex": "^1.5.1",
  45227. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  45228. "minifyify": "^7.3.3",
  45229. "mocha": "^3.0.2",
  45230. "mozilla-download": "^1.1.1",
  45231. "replace-in-file": "^2.5.3",
  45232. "semistandard": "^9.0.0",
  45233. "shelljs": "^0.7.7",
  45234. "shx": "^0.2.2",
  45235. "sinon": "^1.17.5",
  45236. "sinon-chai": "2.8.0",
  45237. "snazzy": "^5.0.0",
  45238. "too-wordy": "ngokevin/too-wordy",
  45239. "uglifyjs": "^2.4.10",
  45240. "write-good": "^0.9.1"
  45241. },
  45242. "link": true,
  45243. "browserify": {
  45244. "transform": [
  45245. "browserify-css",
  45246. "envify"
  45247. ]
  45248. },
  45249. "semistandard": {
  45250. "ignore": [
  45251. "build/**",
  45252. "dist/**",
  45253. "examples/**/shaders/*.js",
  45254. "**/vendor/**"
  45255. ]
  45256. },
  45257. "keywords": [
  45258. "3d",
  45259. "aframe",
  45260. "cardboard",
  45261. "components",
  45262. "oculus",
  45263. "three",
  45264. "three.js",
  45265. "rift",
  45266. "vive",
  45267. "vr",
  45268. "web-components",
  45269. "webvr"
  45270. ],
  45271. "browserify-css": {
  45272. "minify": true
  45273. },
  45274. "engines": {
  45275. "node": ">= 4.6.0",
  45276. "npm": "^2.15.9"
  45277. }
  45278. }
  45279. },{}],73:[function(_dereq_,module,exports){
  45280. var anime = _dereq_('super-animejs');
  45281. var components = _dereq_('../core/component').components;
  45282. var registerComponent = _dereq_('../core/component').registerComponent;
  45283. var THREE = _dereq_('../lib/three');
  45284. var utils = _dereq_('../utils');
  45285. var colorHelperFrom = new THREE.Color();
  45286. var colorHelperTo = new THREE.Color();
  45287. var getComponentProperty = utils.entity.getComponentProperty;
  45288. var setComponentProperty = utils.entity.setComponentProperty;
  45289. var splitCache = {};
  45290. var TYPE_COLOR = 'color';
  45291. var PROP_POSITION = 'position';
  45292. var PROP_ROTATION = 'rotation';
  45293. var PROP_SCALE = 'scale';
  45294. var STRING_COMPONENTS = 'components';
  45295. var STRING_OBJECT3D = 'object3D';
  45296. /**
  45297. * Animation component for A-Frame using anime.js.
  45298. *
  45299. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  45300. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  45301. * boolean * flag * `isAnimationPlaying`.
  45302. *
  45303. * anime.js animation config for tweenining Javascript objects and values works as:
  45304. *
  45305. * config = {
  45306. * targets: {foo: 0.0, bar: '#000'},
  45307. * foo: 1.0,
  45308. * bar: '#FFF'
  45309. * }
  45310. *
  45311. * The above will tween each property in `targets`. The `to` values are set in the root of
  45312. * the config.
  45313. *
  45314. * @member {object} animation - anime.js instance.
  45315. * @member {boolean} animationIsPlaying - Control if animation is playing.
  45316. */
  45317. module.exports.Component = registerComponent('animation', {
  45318. schema: {
  45319. autoplay: {default: true},
  45320. delay: {default: 0},
  45321. dir: {default: ''},
  45322. dur: {default: 1000},
  45323. easing: {default: 'easeInQuad'},
  45324. elasticity: {default: 400},
  45325. enabled: {default: true},
  45326. from: {default: ''},
  45327. loop: {
  45328. default: 0,
  45329. parse: function (value) {
  45330. // Boolean or integer.
  45331. if (value === true || value === 'true') { return true; }
  45332. if (value === false || value === 'false') { return false; }
  45333. return parseInt(value, 10);
  45334. }
  45335. },
  45336. property: {default: ''},
  45337. startEvents: {type: 'array'},
  45338. pauseEvents: {type: 'array'},
  45339. resumeEvents: {type: 'array'},
  45340. round: {default: false},
  45341. to: {default: ''},
  45342. type: {default: ''},
  45343. isRawProperty: {default: false}
  45344. },
  45345. multiple: true,
  45346. init: function () {
  45347. var self = this;
  45348. this.eventDetail = {name: this.attrName};
  45349. this.time = 0;
  45350. this.animation = null;
  45351. this.animationIsPlaying = false;
  45352. this.onStartEvent = this.onStartEvent.bind(this);
  45353. this.beginAnimation = this.beginAnimation.bind(this);
  45354. this.pauseAnimation = this.pauseAnimation.bind(this);
  45355. this.resumeAnimation = this.resumeAnimation.bind(this);
  45356. this.fromColor = {};
  45357. this.toColor = {};
  45358. this.targets = {};
  45359. this.targetsArray = [];
  45360. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  45361. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  45362. this.config = {
  45363. complete: function () {
  45364. self.animationIsPlaying = false;
  45365. self.el.emit('animationcomplete', self.eventDetail, false);
  45366. if (self.id) {
  45367. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  45368. }
  45369. }
  45370. };
  45371. },
  45372. update: function (oldData) {
  45373. var config = this.config;
  45374. var data = this.data;
  45375. this.animationIsPlaying = false;
  45376. if (!this.data.enabled) { return; }
  45377. if (!data.property) { return; }
  45378. // Base config.
  45379. config.autoplay = false;
  45380. config.direction = data.dir;
  45381. config.duration = data.dur;
  45382. config.easing = data.easing;
  45383. config.elasticity = data.elasticity;
  45384. config.loop = data.loop;
  45385. config.round = data.round;
  45386. // Start new animation.
  45387. this.createAndStartAnimation();
  45388. },
  45389. tick: function (t, dt) {
  45390. if (!this.animationIsPlaying) { return; }
  45391. this.time += dt;
  45392. this.animation.tick(this.time);
  45393. },
  45394. remove: function () {
  45395. this.pauseAnimation();
  45396. this.removeEventListeners();
  45397. },
  45398. pause: function () {
  45399. this.paused = true;
  45400. this.pausedWasPlaying = this.animationIsPlaying;
  45401. this.pauseAnimation();
  45402. this.removeEventListeners();
  45403. },
  45404. /**
  45405. * `play` handler only for resuming scene.
  45406. */
  45407. play: function () {
  45408. if (!this.paused) { return; }
  45409. this.paused = false;
  45410. this.addEventListeners();
  45411. if (this.pausedWasPlaying) {
  45412. this.resumeAnimation();
  45413. this.pausedWasPlaying = false;
  45414. }
  45415. },
  45416. /**
  45417. * Start animation from scratch.
  45418. */
  45419. createAndStartAnimation: function () {
  45420. var data = this.data;
  45421. this.updateConfig();
  45422. this.animationIsPlaying = false;
  45423. this.animation = anime(this.config);
  45424. this.animation.began = true;
  45425. this.removeEventListeners();
  45426. this.addEventListeners();
  45427. // Wait for start events for animation.
  45428. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  45429. // Delay animation.
  45430. if (data.delay) {
  45431. setTimeout(this.beginAnimation, data.delay);
  45432. return;
  45433. }
  45434. // Play animation.
  45435. this.beginAnimation();
  45436. },
  45437. /**
  45438. * This is before animation start (including from startEvents).
  45439. * Set to initial state (config.from, time = 0, seekTime = 0).
  45440. */
  45441. beginAnimation: function () {
  45442. this.updateConfig();
  45443. this.animation.began = true;
  45444. this.time = 0;
  45445. this.animationIsPlaying = true;
  45446. this.stopRelatedAnimations();
  45447. this.el.emit('animationbegin', this.eventDetail, false);
  45448. },
  45449. pauseAnimation: function () {
  45450. this.animationIsPlaying = false;
  45451. },
  45452. resumeAnimation: function () {
  45453. this.animationIsPlaying = true;
  45454. },
  45455. /**
  45456. * startEvents callback.
  45457. */
  45458. onStartEvent: function () {
  45459. if (!this.data.enabled) { return; }
  45460. this.updateConfig();
  45461. if (this.animation) {
  45462. this.animation.pause();
  45463. }
  45464. this.animation = anime(this.config);
  45465. // Include the delay before each start event.
  45466. if (this.data.delay) {
  45467. setTimeout(this.beginAnimation, this.data.delay);
  45468. return;
  45469. }
  45470. this.beginAnimation();
  45471. },
  45472. /**
  45473. * rawProperty: true and type: color;
  45474. */
  45475. updateConfigForRawColor: function () {
  45476. var config = this.config;
  45477. var data = this.data;
  45478. var el = this.el;
  45479. var from;
  45480. var key;
  45481. var to;
  45482. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  45483. return;
  45484. }
  45485. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  45486. to = data.to;
  45487. // Use r/g/b vector for color type.
  45488. this.setColorConfig(from, to);
  45489. from = this.fromColor;
  45490. to = this.toColor;
  45491. this.targetsArray.length = 0;
  45492. this.targetsArray.push(from);
  45493. config.targets = this.targetsArray;
  45494. for (key in to) { config[key] = to[key]; }
  45495. config.update = (function () {
  45496. var lastValue = {};
  45497. return function (anim) {
  45498. var value;
  45499. value = anim.animatables[0].target;
  45500. // For animation timeline.
  45501. if (value.r === lastValue.r &&
  45502. value.g === lastValue.g &&
  45503. value.b === lastValue.b) { return; }
  45504. setRawProperty(el, data.property, value, data.type);
  45505. };
  45506. })();
  45507. },
  45508. /**
  45509. * Stuff property into generic `property` key.
  45510. */
  45511. updateConfigForDefault: function () {
  45512. var config = this.config;
  45513. var data = this.data;
  45514. var el = this.el;
  45515. var from;
  45516. var isBoolean;
  45517. var isNumber;
  45518. var to;
  45519. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  45520. return;
  45521. }
  45522. if (data.from === '') {
  45523. // Infer from.
  45524. from = isRawProperty(data)
  45525. ? getRawProperty(el, data.property)
  45526. : getComponentProperty(el, data.property);
  45527. } else {
  45528. // Explicit from.
  45529. from = data.from;
  45530. }
  45531. to = data.to;
  45532. isNumber = !isNaN(from || to);
  45533. if (isNumber) {
  45534. from = parseFloat(from);
  45535. to = parseFloat(to);
  45536. } else {
  45537. from = from ? from.toString() : from;
  45538. to = to ? to.toString() : to;
  45539. }
  45540. // Convert booleans to integer to allow boolean flipping.
  45541. isBoolean = data.to === 'true' || data.to === 'false' ||
  45542. data.to === true || data.to === false;
  45543. if (isBoolean) {
  45544. from = data.from === 'true' || data.from === true ? 1 : 0;
  45545. to = data.to === 'true' || data.to === true ? 1 : 0;
  45546. }
  45547. this.targets.aframeProperty = from;
  45548. config.targets = this.targets;
  45549. config.aframeProperty = to;
  45550. config.update = (function () {
  45551. var lastValue;
  45552. return function (anim) {
  45553. var value;
  45554. value = anim.animatables[0].target.aframeProperty;
  45555. // Need to do a last value check for animation timeline since all the tweening
  45556. // begins simultaenously even if the value has not changed. Also better for perf
  45557. // anyways.
  45558. if (value === lastValue) { return; }
  45559. lastValue = value;
  45560. if (isBoolean) { value = value >= 1; }
  45561. if (isRawProperty(data)) {
  45562. setRawProperty(el, data.property, value, data.type);
  45563. } else {
  45564. setComponentProperty(el, data.property, value);
  45565. }
  45566. };
  45567. })();
  45568. },
  45569. /**
  45570. * Extend x/y/z/w onto the config.
  45571. * Update vector by modifying object3D.
  45572. */
  45573. updateConfigForVector: function () {
  45574. var config = this.config;
  45575. var data = this.data;
  45576. var el = this.el;
  45577. var key;
  45578. var from;
  45579. var to;
  45580. // Parse coordinates.
  45581. from = data.from !== ''
  45582. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  45583. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  45584. to = utils.coordinates.parse(data.to);
  45585. if (data.property === PROP_ROTATION) {
  45586. toRadians(from);
  45587. toRadians(to);
  45588. }
  45589. // Set to and from.
  45590. this.targetsArray.length = 0;
  45591. this.targetsArray.push(from);
  45592. config.targets = this.targetsArray;
  45593. for (key in to) { config[key] = to[key]; }
  45594. // If animating object3D transformation, run more optimized updater.
  45595. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  45596. data.property === PROP_SCALE) {
  45597. config.update = (function () {
  45598. var lastValue = {};
  45599. return function (anim) {
  45600. var value = anim.animatables[0].target;
  45601. if (data.property === PROP_SCALE) {
  45602. value.x = Math.max(0.0001, value.x);
  45603. value.y = Math.max(0.0001, value.y);
  45604. value.z = Math.max(0.0001, value.z);
  45605. }
  45606. // For animation timeline.
  45607. if (value.x === lastValue.x &&
  45608. value.y === lastValue.y &&
  45609. value.z === lastValue.z) { return; }
  45610. lastValue.x = value.x;
  45611. lastValue.y = value.y;
  45612. lastValue.z = value.z;
  45613. el.object3D[data.property].set(value.x, value.y, value.z);
  45614. };
  45615. })();
  45616. return;
  45617. }
  45618. // Animating some vector.
  45619. config.update = (function () {
  45620. var lastValue = {};
  45621. return function (anim) {
  45622. var value = anim.animatables[0].target;
  45623. // Animate rotation through radians.
  45624. // For animation timeline.
  45625. if (value.x === lastValue.x &&
  45626. value.y === lastValue.y &&
  45627. value.z === lastValue.z) { return; }
  45628. lastValue.x = value.x;
  45629. lastValue.y = value.y;
  45630. lastValue.z = value.z;
  45631. setComponentProperty(el, data.property, value);
  45632. };
  45633. })();
  45634. },
  45635. /**
  45636. * Update the config before each run.
  45637. */
  45638. updateConfig: function () {
  45639. var propType;
  45640. // Route config type.
  45641. propType = getPropertyType(this.el, this.data.property);
  45642. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  45643. this.updateConfigForRawColor();
  45644. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  45645. this.updateConfigForVector();
  45646. } else {
  45647. this.updateConfigForDefault();
  45648. }
  45649. },
  45650. /**
  45651. * Wait for component to initialize.
  45652. */
  45653. waitComponentInitRawProperty: function (cb) {
  45654. var componentName;
  45655. var data = this.data;
  45656. var el = this.el;
  45657. var self = this;
  45658. if (data.from !== '') { return false; }
  45659. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  45660. componentName = splitDot(data.property)[1];
  45661. if (el.components[componentName]) { return false; }
  45662. el.addEventListener('componentinitialized', function wait (evt) {
  45663. if (evt.detail.name !== componentName) { return; }
  45664. cb();
  45665. // Since the config was created async, create the animation now since we missed it
  45666. // earlier.
  45667. self.animation = anime(self.config);
  45668. el.removeEventListener('componentinitialized', wait);
  45669. });
  45670. return true;
  45671. },
  45672. /**
  45673. * Make sure two animations on the same property don't fight each other.
  45674. * e.g., animation__mouseenter="property: material.opacity"
  45675. * animation__mouseleave="property: material.opacity"
  45676. */
  45677. stopRelatedAnimations: function () {
  45678. var component;
  45679. var componentName;
  45680. for (componentName in this.el.components) {
  45681. component = this.el.components[componentName];
  45682. if (componentName === this.attrName) { continue; }
  45683. if (component.name !== 'animation') { continue; }
  45684. if (!component.animationIsPlaying) { continue; }
  45685. if (component.data.property !== this.data.property) { continue; }
  45686. component.animationIsPlaying = false;
  45687. }
  45688. },
  45689. addEventListeners: function () {
  45690. var data = this.data;
  45691. var el = this.el;
  45692. addEventListeners(el, data.startEvents, this.onStartEvent);
  45693. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  45694. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  45695. },
  45696. removeEventListeners: function () {
  45697. var data = this.data;
  45698. var el = this.el;
  45699. removeEventListeners(el, data.startEvents, this.onStartEvent);
  45700. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  45701. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  45702. },
  45703. setColorConfig: function (from, to) {
  45704. colorHelperFrom.set(from);
  45705. colorHelperTo.set(to);
  45706. from = this.fromColor;
  45707. to = this.toColor;
  45708. from.r = colorHelperFrom.r;
  45709. from.g = colorHelperFrom.g;
  45710. from.b = colorHelperFrom.b;
  45711. to.r = colorHelperTo.r;
  45712. to.g = colorHelperTo.g;
  45713. to.b = colorHelperTo.b;
  45714. }
  45715. });
  45716. /**
  45717. * Given property name, check schema to see what type we are animating.
  45718. * We just care whether the property is a vector.
  45719. */
  45720. function getPropertyType (el, property) {
  45721. var component;
  45722. var componentName;
  45723. var split;
  45724. var propertyName;
  45725. split = property.split('.');
  45726. componentName = split[0];
  45727. propertyName = split[1];
  45728. component = el.components[componentName] || components[componentName];
  45729. // Primitives.
  45730. if (!component) { return null; }
  45731. // Dynamic schema. We only care about vectors anyways.
  45732. if (propertyName && !component.schema[propertyName]) { return null; }
  45733. // Multi-prop.
  45734. if (propertyName) { return component.schema[propertyName].type; }
  45735. // Single-prop.
  45736. return component.schema.type;
  45737. }
  45738. /**
  45739. * Convert object to radians.
  45740. */
  45741. function toRadians (obj) {
  45742. obj.x = THREE.Math.degToRad(obj.x);
  45743. obj.y = THREE.Math.degToRad(obj.y);
  45744. obj.z = THREE.Math.degToRad(obj.z);
  45745. }
  45746. function addEventListeners (el, eventNames, handler) {
  45747. var i;
  45748. for (i = 0; i < eventNames.length; i++) {
  45749. el.addEventListener(eventNames[i], handler);
  45750. }
  45751. }
  45752. function removeEventListeners (el, eventNames, handler) {
  45753. var i;
  45754. for (i = 0; i < eventNames.length; i++) {
  45755. el.removeEventListener(eventNames[i], handler);
  45756. }
  45757. }
  45758. function getRawProperty (el, path) {
  45759. var i;
  45760. var split;
  45761. var value;
  45762. split = splitDot(path);
  45763. value = el;
  45764. for (i = 0; i < split.length; i++) {
  45765. value = value[split[i]];
  45766. }
  45767. if (value === undefined) {
  45768. console.log(el);
  45769. throw new Error('[animation] property (' + path + ') could not be found');
  45770. }
  45771. return value;
  45772. }
  45773. function setRawProperty (el, path, value, type) {
  45774. var i;
  45775. var split;
  45776. var propertyName;
  45777. var targetValue;
  45778. if (path.startsWith('object3D.rotation')) {
  45779. value = THREE.Math.degToRad(value);
  45780. }
  45781. // Walk.
  45782. split = splitDot(path);
  45783. targetValue = el;
  45784. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  45785. propertyName = split[split.length - 1];
  45786. // Raw color.
  45787. if (type === TYPE_COLOR) {
  45788. if ('r' in targetValue[propertyName]) {
  45789. targetValue[propertyName].r = value.r;
  45790. targetValue[propertyName].g = value.g;
  45791. targetValue[propertyName].b = value.b;
  45792. } else {
  45793. targetValue[propertyName].x = value.r;
  45794. targetValue[propertyName].y = value.g;
  45795. targetValue[propertyName].z = value.b;
  45796. }
  45797. return;
  45798. }
  45799. targetValue[propertyName] = value;
  45800. }
  45801. function splitDot (path) {
  45802. if (path in splitCache) { return splitCache[path]; }
  45803. splitCache[path] = path.split('.');
  45804. return splitCache[path];
  45805. }
  45806. function isRawProperty (data) {
  45807. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  45808. data.property.startsWith(STRING_OBJECT3D);
  45809. }
  45810. },{"../core/component":130,"../lib/three":178,"../utils":204,"super-animejs":56}],74:[function(_dereq_,module,exports){
  45811. var registerComponent = _dereq_('../core/component').registerComponent;
  45812. var THREE = _dereq_('../lib/three');
  45813. /**
  45814. * Camera component.
  45815. * Pairs along with camera system to handle tracking the active camera.
  45816. */
  45817. module.exports.Component = registerComponent('camera', {
  45818. schema: {
  45819. active: {default: true},
  45820. far: {default: 10000},
  45821. fov: {default: 80, min: 0},
  45822. near: {default: 0.005, min: 0},
  45823. spectator: {default: false},
  45824. zoom: {default: 1, min: 0}
  45825. },
  45826. /**
  45827. * Initialize three.js camera and add it to the entity.
  45828. * Add reference from scene to this entity as the camera.
  45829. */
  45830. init: function () {
  45831. var camera;
  45832. var el = this.el;
  45833. // Create camera.
  45834. camera = this.camera = new THREE.PerspectiveCamera();
  45835. el.setObject3D('camera', camera);
  45836. },
  45837. /**
  45838. * Update three.js camera.
  45839. */
  45840. update: function (oldData) {
  45841. var data = this.data;
  45842. var camera = this.camera;
  45843. // Update properties.
  45844. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  45845. camera.far = data.far;
  45846. camera.fov = data.fov;
  45847. camera.near = data.near;
  45848. camera.zoom = data.zoom;
  45849. camera.updateProjectionMatrix();
  45850. this.updateActiveCamera(oldData);
  45851. this.updateSpectatorCamera(oldData);
  45852. },
  45853. updateActiveCamera: function (oldData) {
  45854. var data = this.data;
  45855. var el = this.el;
  45856. var system = this.system;
  45857. // Active property did not change.
  45858. if (oldData && oldData.active === data.active || data.spectator) { return; }
  45859. // If `active` property changes, or first update, handle active camera with system.
  45860. if (data.active && system.activeCameraEl !== el) {
  45861. // Camera enabled. Set camera to this camera.
  45862. system.setActiveCamera(el);
  45863. } else if (!data.active && system.activeCameraEl === el) {
  45864. // Camera disabled. Set camera to another camera.
  45865. system.disableActiveCamera();
  45866. }
  45867. },
  45868. updateSpectatorCamera: function (oldData) {
  45869. var data = this.data;
  45870. var el = this.el;
  45871. var system = this.system;
  45872. // spectator property did not change.
  45873. if (oldData && oldData.spectator === data.spectator) { return; }
  45874. // If `spectator` property changes, or first update, handle spectator camera with system.
  45875. if (data.spectator && system.spectatorCameraEl !== el) {
  45876. // Camera enabled. Set camera to this camera.
  45877. system.setSpectatorCamera(el);
  45878. } else if (!data.spectator && system.spectatorCameraEl === el) {
  45879. // Camera disabled. Set camera to another camera.
  45880. system.disableSpectatorCamera();
  45881. }
  45882. },
  45883. /**
  45884. * Remove camera on remove (callback).
  45885. */
  45886. remove: function () {
  45887. this.el.removeObject3D('camera');
  45888. }
  45889. });
  45890. },{"../core/component":130,"../lib/three":178}],75:[function(_dereq_,module,exports){
  45891. /* global THREE */
  45892. var registerComponent = _dereq_('../core/component').registerComponent;
  45893. var utils = _dereq_('../utils/');
  45894. var bind = utils.bind;
  45895. var EVENTS = {
  45896. CLICK: 'click',
  45897. FUSING: 'fusing',
  45898. MOUSEENTER: 'mouseenter',
  45899. MOUSEDOWN: 'mousedown',
  45900. MOUSELEAVE: 'mouseleave',
  45901. MOUSEUP: 'mouseup'
  45902. };
  45903. var STATES = {
  45904. FUSING: 'cursor-fusing',
  45905. HOVERING: 'cursor-hovering',
  45906. HOVERED: 'cursor-hovered'
  45907. };
  45908. var CANVAS_EVENTS = {
  45909. DOWN: ['mousedown', 'touchstart'],
  45910. UP: ['mouseup', 'touchend']
  45911. };
  45912. var WEBXR_EVENTS = {
  45913. DOWN: ['selectstart'],
  45914. UP: ['selectend']
  45915. };
  45916. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  45917. /**
  45918. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  45919. * from the camera and pointing from camera's facing direction, and then only returning the
  45920. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  45921. *
  45922. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  45923. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  45924. * @member {object} intersection - Attributes of the current intersection event, including
  45925. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  45926. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  45927. * emit events when unintersecting.
  45928. */
  45929. module.exports.Component = registerComponent('cursor', {
  45930. dependencies: ['raycaster'],
  45931. schema: {
  45932. downEvents: {default: []},
  45933. fuse: {default: utils.device.isMobile()},
  45934. fuseTimeout: {default: 1500, min: 0},
  45935. mouseCursorStylesEnabled: {default: true},
  45936. upEvents: {default: []},
  45937. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  45938. },
  45939. init: function () {
  45940. var self = this;
  45941. this.fuseTimeout = undefined;
  45942. this.cursorDownEl = null;
  45943. this.intersectedEl = null;
  45944. this.canvasBounds = document.body.getBoundingClientRect();
  45945. this.isCursorDown = false;
  45946. // Debounce.
  45947. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  45948. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  45949. }, 500);
  45950. this.eventDetail = {};
  45951. this.intersectedEventDetail = {cursorEl: this.el};
  45952. // Bind methods.
  45953. this.onCursorDown = bind(this.onCursorDown, this);
  45954. this.onCursorUp = bind(this.onCursorUp, this);
  45955. this.onIntersection = bind(this.onIntersection, this);
  45956. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  45957. this.onMouseMove = bind(this.onMouseMove, this);
  45958. this.onEnterVR = bind(this.onEnterVR, this);
  45959. },
  45960. update: function (oldData) {
  45961. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  45962. this.updateMouseEventListeners();
  45963. },
  45964. play: function () {
  45965. this.addEventListeners();
  45966. },
  45967. pause: function () {
  45968. this.removeEventListeners();
  45969. },
  45970. remove: function () {
  45971. var el = this.el;
  45972. el.removeState(STATES.HOVERING);
  45973. el.removeState(STATES.FUSING);
  45974. clearTimeout(this.fuseTimeout);
  45975. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  45976. this.removeEventListeners();
  45977. },
  45978. addEventListeners: function () {
  45979. var canvas;
  45980. var data = this.data;
  45981. var el = this.el;
  45982. var self = this;
  45983. function addCanvasListeners () {
  45984. canvas = el.sceneEl.canvas;
  45985. if (data.downEvents.length || data.upEvents.length) { return; }
  45986. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  45987. canvas.addEventListener(downEvent, self.onCursorDown);
  45988. });
  45989. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  45990. canvas.addEventListener(upEvent, self.onCursorUp);
  45991. });
  45992. }
  45993. canvas = el.sceneEl.canvas;
  45994. if (canvas) {
  45995. addCanvasListeners();
  45996. } else {
  45997. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  45998. }
  45999. data.downEvents.forEach(function (downEvent) {
  46000. el.addEventListener(downEvent, self.onCursorDown);
  46001. });
  46002. data.upEvents.forEach(function (upEvent) {
  46003. el.addEventListener(upEvent, self.onCursorUp);
  46004. });
  46005. el.addEventListener('raycaster-intersection', this.onIntersection);
  46006. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  46007. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  46008. el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  46009. window.addEventListener('resize', this.updateCanvasBounds);
  46010. window.addEventListener('scroll', this.updateCanvasBounds);
  46011. this.updateMouseEventListeners();
  46012. },
  46013. removeEventListeners: function () {
  46014. var canvas;
  46015. var data = this.data;
  46016. var el = this.el;
  46017. var self = this;
  46018. canvas = el.sceneEl.canvas;
  46019. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  46020. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  46021. canvas.removeEventListener(downEvent, self.onCursorDown);
  46022. });
  46023. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  46024. canvas.removeEventListener(upEvent, self.onCursorUp);
  46025. });
  46026. }
  46027. data.downEvents.forEach(function (downEvent) {
  46028. el.removeEventListener(downEvent, self.onCursorDown);
  46029. });
  46030. data.upEvents.forEach(function (upEvent) {
  46031. el.removeEventListener(upEvent, self.onCursorUp);
  46032. });
  46033. el.removeEventListener('raycaster-intersection', this.onIntersection);
  46034. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  46035. canvas.removeEventListener('mousemove', this.onMouseMove);
  46036. canvas.removeEventListener('touchstart', this.onMouseMove);
  46037. canvas.removeEventListener('touchmove', this.onMouseMove);
  46038. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  46039. el.sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  46040. window.removeEventListener('resize', this.updateCanvasBounds);
  46041. window.removeEventListener('scroll', this.updateCanvasBounds);
  46042. },
  46043. updateMouseEventListeners: function () {
  46044. var canvas;
  46045. var el = this.el;
  46046. canvas = el.sceneEl.canvas;
  46047. canvas.removeEventListener('mousemove', this.onMouseMove);
  46048. canvas.removeEventListener('touchmove', this.onMouseMove);
  46049. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  46050. if (this.data.rayOrigin !== 'mouse') { return; }
  46051. canvas.addEventListener('mousemove', this.onMouseMove, false);
  46052. canvas.addEventListener('touchmove', this.onMouseMove, false);
  46053. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  46054. this.updateCanvasBounds();
  46055. },
  46056. onMouseMove: (function () {
  46057. var direction = new THREE.Vector3();
  46058. var mouse = new THREE.Vector2();
  46059. var origin = new THREE.Vector3();
  46060. var rayCasterConfig = {origin: origin, direction: direction};
  46061. return function (evt) {
  46062. var bounds = this.canvasBounds;
  46063. var camera = this.el.sceneEl.camera;
  46064. var left;
  46065. var point;
  46066. var top;
  46067. camera.parent.updateMatrixWorld();
  46068. // Calculate mouse position based on the canvas element
  46069. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  46070. // Track the first touch for simplicity.
  46071. point = evt.touches.item(0);
  46072. } else {
  46073. point = evt;
  46074. }
  46075. left = point.clientX - bounds.left;
  46076. top = point.clientY - bounds.top;
  46077. mouse.x = (left / bounds.width) * 2 - 1;
  46078. mouse.y = -(top / bounds.height) * 2 + 1;
  46079. origin.setFromMatrixPosition(camera.matrixWorld);
  46080. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  46081. this.el.setAttribute('raycaster', rayCasterConfig);
  46082. if (evt.type === 'touchmove') { evt.preventDefault(); }
  46083. };
  46084. })(),
  46085. /**
  46086. * Trigger mousedown and keep track of the mousedowned entity.
  46087. */
  46088. onCursorDown: function (evt) {
  46089. this.isCursorDown = true;
  46090. // Raycast again for touch.
  46091. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  46092. this.onMouseMove(evt);
  46093. this.el.components.raycaster.checkIntersections();
  46094. evt.preventDefault();
  46095. }
  46096. this.twoWayEmit(EVENTS.MOUSEDOWN);
  46097. this.cursorDownEl = this.intersectedEl;
  46098. },
  46099. /**
  46100. * Trigger mouseup if:
  46101. * - Not fusing (mobile has no mouse).
  46102. * - Currently intersecting an entity.
  46103. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  46104. * in case user mousedowned one entity, dragged to another, and mouseupped.
  46105. */
  46106. onCursorUp: function (evt) {
  46107. if (!this.isCursorDown) { return; }
  46108. this.isCursorDown = false;
  46109. var data = this.data;
  46110. this.twoWayEmit(EVENTS.MOUSEUP);
  46111. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  46112. // previously cursorUp entity.
  46113. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  46114. this.intersectedEventDetail.intersection = null;
  46115. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  46116. }
  46117. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  46118. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  46119. this.twoWayEmit(EVENTS.CLICK);
  46120. }
  46121. this.cursorDownEl = null;
  46122. if (evt.type === 'touchend') { evt.preventDefault(); }
  46123. },
  46124. /**
  46125. * Handle intersection.
  46126. */
  46127. onIntersection: function (evt) {
  46128. var currentIntersection;
  46129. var cursorEl = this.el;
  46130. var index;
  46131. var intersectedEl;
  46132. var intersection;
  46133. // Select closest object, excluding the cursor.
  46134. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  46135. intersection = evt.detail.intersections[index];
  46136. intersectedEl = evt.detail.els[index];
  46137. // If cursor is the only intersected object, ignore the event.
  46138. if (!intersectedEl) { return; }
  46139. // Already intersecting this entity.
  46140. if (this.intersectedEl === intersectedEl) { return; }
  46141. // Ignore events further away than active intersection.
  46142. if (this.intersectedEl) {
  46143. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  46144. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  46145. }
  46146. // Unset current intersection.
  46147. this.clearCurrentIntersection(true);
  46148. this.setIntersection(intersectedEl, intersection);
  46149. },
  46150. /**
  46151. * Handle intersection cleared.
  46152. */
  46153. onIntersectionCleared: function (evt) {
  46154. var clearedEls = evt.detail.clearedEls;
  46155. // Check if the current intersection has ended
  46156. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  46157. this.clearCurrentIntersection();
  46158. },
  46159. onEnterVR: function () {
  46160. this.clearCurrentIntersection(true);
  46161. var xrSession = this.el.sceneEl.xrSession;
  46162. var self = this;
  46163. if (!xrSession) { return; }
  46164. if (this.data.rayOrigin === 'mouse') { return; }
  46165. WEBXR_EVENTS.DOWN.forEach(function (downEvent) {
  46166. xrSession.addEventListener(downEvent, self.onCursorDown);
  46167. });
  46168. WEBXR_EVENTS.UP.forEach(function (upEvent) {
  46169. xrSession.addEventListener(upEvent, self.onCursorUp);
  46170. });
  46171. },
  46172. setIntersection: function (intersectedEl, intersection) {
  46173. var cursorEl = this.el;
  46174. var data = this.data;
  46175. var self = this;
  46176. // Already intersecting.
  46177. if (this.intersectedEl === intersectedEl) { return; }
  46178. // Set new intersection.
  46179. this.intersectedEl = intersectedEl;
  46180. // Hovering.
  46181. cursorEl.addState(STATES.HOVERING);
  46182. intersectedEl.addState(STATES.HOVERED);
  46183. this.twoWayEmit(EVENTS.MOUSEENTER);
  46184. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  46185. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  46186. }
  46187. // Begin fuse if necessary.
  46188. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  46189. cursorEl.addState(STATES.FUSING);
  46190. this.twoWayEmit(EVENTS.FUSING);
  46191. this.fuseTimeout = setTimeout(function fuse () {
  46192. cursorEl.removeState(STATES.FUSING);
  46193. self.twoWayEmit(EVENTS.CLICK);
  46194. }, data.fuseTimeout);
  46195. },
  46196. clearCurrentIntersection: function (ignoreRemaining) {
  46197. var index;
  46198. var intersection;
  46199. var intersections;
  46200. var cursorEl = this.el;
  46201. // Nothing to be cleared.
  46202. if (!this.intersectedEl) { return; }
  46203. // No longer hovering (or fusing).
  46204. this.intersectedEl.removeState(STATES.HOVERED);
  46205. cursorEl.removeState(STATES.HOVERING);
  46206. cursorEl.removeState(STATES.FUSING);
  46207. this.twoWayEmit(EVENTS.MOUSELEAVE);
  46208. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  46209. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  46210. }
  46211. // Unset intersected entity (after emitting the event).
  46212. this.intersectedEl = null;
  46213. // Clear fuseTimeout.
  46214. clearTimeout(this.fuseTimeout);
  46215. // Set intersection to another raycasted element if any.
  46216. if (ignoreRemaining === true) { return; }
  46217. intersections = this.el.components.raycaster.intersections;
  46218. if (intersections.length === 0) { return; }
  46219. // Exclude the cursor.
  46220. index = intersections[0].object.el === cursorEl ? 1 : 0;
  46221. intersection = intersections[index];
  46222. if (!intersection) { return; }
  46223. this.setIntersection(intersection.object.el, intersection);
  46224. },
  46225. /**
  46226. * Helper to emit on both the cursor and the intersected entity (if exists).
  46227. */
  46228. twoWayEmit: function (evtName) {
  46229. var el = this.el;
  46230. var intersectedEl = this.intersectedEl;
  46231. var intersection;
  46232. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  46233. this.eventDetail.intersectedEl = intersectedEl;
  46234. this.eventDetail.intersection = intersection;
  46235. el.emit(evtName, this.eventDetail);
  46236. if (!intersectedEl) { return; }
  46237. this.intersectedEventDetail.intersection = intersection;
  46238. intersectedEl.emit(evtName, this.intersectedEventDetail);
  46239. }
  46240. });
  46241. },{"../core/component":130,"../utils/":204}],76:[function(_dereq_,module,exports){
  46242. var registerComponent = _dereq_('../core/component').registerComponent;
  46243. var bind = _dereq_('../utils/bind');
  46244. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46245. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46246. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46247. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46248. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  46249. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  46250. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  46251. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  46252. var GAMEPAD_ID_WEBXR = 'google-daydream';
  46253. var GAMEPAD_ID_WEBVR = 'Daydream Controller';
  46254. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  46255. /**
  46256. * Button indices:
  46257. * 0 - trackpad
  46258. * 1 - menu (never dispatched on this layer)
  46259. * 2 - system (never dispatched on this layer)
  46260. *
  46261. * Axis:
  46262. * 0 - trackpad x
  46263. * 1 - trackpad y
  46264. */
  46265. var INPUT_MAPPING_WEBVR = {
  46266. axes: {trackpad: [0, 1]},
  46267. buttons: ['trackpad', 'menu', 'system']
  46268. };
  46269. /**
  46270. * Button indices:
  46271. * 0 - none
  46272. * 1 - none
  46273. * 2 - touchpad
  46274. *
  46275. * Axis:
  46276. * 0 - touchpad x
  46277. * 1 - touchpad y
  46278. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/google/google-daydream.json
  46279. */
  46280. var INPUT_MAPPING_WEBXR = {
  46281. axes: {touchpad: [0, 1]},
  46282. buttons: ['none', 'none', 'touchpad', 'menu', 'system']
  46283. };
  46284. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  46285. /**
  46286. * Daydream controls.
  46287. * Interface with Daydream controller and map Gamepad events to
  46288. * controller buttons: trackpad, menu, system
  46289. * Load a controller model and highlight the pressed buttons.
  46290. */
  46291. module.exports.Component = registerComponent('daydream-controls', {
  46292. schema: {
  46293. hand: {default: ''}, // This informs the degenerate arm model.
  46294. buttonColor: {type: 'color', default: '#000000'},
  46295. buttonTouchedColor: {type: 'color', default: '#777777'},
  46296. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  46297. model: {default: true},
  46298. orientationOffset: {type: 'vec3'},
  46299. armModel: {default: true}
  46300. },
  46301. mapping: INPUT_MAPPING,
  46302. bindMethods: function () {
  46303. this.onModelLoaded = bind(this.onModelLoaded, this);
  46304. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46305. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46306. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46307. this.onAxisMoved = bind(this.onAxisMoved, this);
  46308. },
  46309. init: function () {
  46310. var self = this;
  46311. this.onButtonChanged = bind(this.onButtonChanged, this);
  46312. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46313. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46314. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46315. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46316. this.controllerPresent = false;
  46317. this.lastControllerCheck = 0;
  46318. this.bindMethods();
  46319. },
  46320. addEventListeners: function () {
  46321. var el = this.el;
  46322. el.addEventListener('buttonchanged', this.onButtonChanged);
  46323. el.addEventListener('buttondown', this.onButtonDown);
  46324. el.addEventListener('buttonup', this.onButtonUp);
  46325. el.addEventListener('touchstart', this.onButtonTouchStart);
  46326. el.addEventListener('touchend', this.onButtonTouchEnd);
  46327. el.addEventListener('model-loaded', this.onModelLoaded);
  46328. el.addEventListener('axismove', this.onAxisMoved);
  46329. this.controllerEventsActive = true;
  46330. },
  46331. removeEventListeners: function () {
  46332. var el = this.el;
  46333. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46334. el.removeEventListener('buttondown', this.onButtonDown);
  46335. el.removeEventListener('buttonup', this.onButtonUp);
  46336. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46337. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46338. el.removeEventListener('model-loaded', this.onModelLoaded);
  46339. el.removeEventListener('axismove', this.onAxisMoved);
  46340. this.controllerEventsActive = false;
  46341. },
  46342. checkIfControllerPresent: function () {
  46343. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46344. this.data.hand ? {hand: this.data.hand} : {});
  46345. },
  46346. play: function () {
  46347. this.checkIfControllerPresent();
  46348. this.addControllersUpdateListener();
  46349. },
  46350. pause: function () {
  46351. this.removeEventListeners();
  46352. this.removeControllersUpdateListener();
  46353. },
  46354. injectTrackedControls: function () {
  46355. var el = this.el;
  46356. var data = this.data;
  46357. el.setAttribute('tracked-controls', {
  46358. armModel: data.armModel,
  46359. hand: data.hand,
  46360. idPrefix: GAMEPAD_ID_PREFIX,
  46361. id: GAMEPAD_ID_PREFIX,
  46362. orientationOffset: data.orientationOffset
  46363. });
  46364. if (!this.data.model) { return; }
  46365. this.el.setAttribute('obj-model', {
  46366. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  46367. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  46368. });
  46369. },
  46370. addControllersUpdateListener: function () {
  46371. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46372. },
  46373. removeControllersUpdateListener: function () {
  46374. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46375. },
  46376. onControllersUpdate: function () {
  46377. this.checkIfControllerPresent();
  46378. },
  46379. onModelLoaded: function (evt) {
  46380. var controllerObject3D = evt.detail.model;
  46381. var buttonMeshes;
  46382. if (!this.data.model) { return; }
  46383. buttonMeshes = this.buttonMeshes = {};
  46384. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  46385. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  46386. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  46387. buttonMeshes.touchpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  46388. // Offset pivot point.
  46389. controllerObject3D.position.set(0, 0, -0.04);
  46390. },
  46391. onAxisMoved: function (evt) {
  46392. emitIfAxesChanged(this, this.mapping.axes, evt);
  46393. },
  46394. onButtonChanged: function (evt) {
  46395. var button = this.mapping.buttons[evt.detail.id];
  46396. if (!button) return;
  46397. // Pass along changed event with button state, using button mapping for convenience.
  46398. this.el.emit(button + 'changed', evt.detail.state);
  46399. },
  46400. updateModel: function (buttonName, evtName) {
  46401. if (!this.data.model) { return; }
  46402. this.updateButtonModel(buttonName, evtName);
  46403. },
  46404. updateButtonModel: function (buttonName, state) {
  46405. var buttonMeshes = this.buttonMeshes;
  46406. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46407. var color;
  46408. switch (state) {
  46409. case 'down':
  46410. color = this.data.buttonHighlightColor;
  46411. break;
  46412. case 'touchstart':
  46413. color = this.data.buttonTouchedColor;
  46414. break;
  46415. default:
  46416. color = this.data.buttonColor;
  46417. }
  46418. buttonMeshes[buttonName].material.color.set(color);
  46419. }
  46420. });
  46421. },{"../core/component":130,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],77:[function(_dereq_,module,exports){
  46422. var registerComponent = _dereq_('../core/component').registerComponent;
  46423. var bind = _dereq_('../utils/bind');
  46424. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46425. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46426. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46427. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46428. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  46429. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  46430. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  46431. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  46432. var GAMEPAD_ID_WEBXR = 'samsung-gearvr';
  46433. var GAMEPAD_ID_WEBVR = 'Gear VR';
  46434. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  46435. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  46436. /**
  46437. * Button indices:
  46438. * 0 - trackpad
  46439. * 1 - trigger
  46440. *
  46441. * Axis:
  46442. * 0 - trackpad x
  46443. * 1 - trackpad y
  46444. */
  46445. var INPUT_MAPPING_WEBVR = {
  46446. axes: {trackpad: [0, 1]},
  46447. buttons: ['trackpad', 'trigger']
  46448. };
  46449. /**
  46450. * Button indices:
  46451. * 0 - trigger
  46452. * 1 - none
  46453. * 2 - touchpad
  46454. * 3 - menu
  46455. *
  46456. * Axis:
  46457. * 0 - touchpad x
  46458. * 1 - touchpad y
  46459. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/samsung/samsung-gearvr.json
  46460. */
  46461. var INPUT_MAPPING_WEBXR = {
  46462. axes: {touchpad: [0, 1]},
  46463. buttons: ['trigger', 'none', 'touchpad', 'none', 'menu']
  46464. };
  46465. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  46466. /**
  46467. * Gear VR controls.
  46468. * Interface with Gear VR controller and map Gamepad events to
  46469. * controller buttons: trackpad, trigger
  46470. * Load a controller model and highlight the pressed buttons.
  46471. */
  46472. module.exports.Component = registerComponent('gearvr-controls', {
  46473. schema: {
  46474. hand: {default: ''}, // This informs the degenerate arm model.
  46475. buttonColor: {type: 'color', default: '#000000'},
  46476. buttonTouchedColor: {type: 'color', default: '#777777'},
  46477. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  46478. model: {default: true},
  46479. orientationOffset: {type: 'vec3'},
  46480. armModel: {default: true}
  46481. },
  46482. mapping: INPUT_MAPPING,
  46483. bindMethods: function () {
  46484. this.onModelLoaded = bind(this.onModelLoaded, this);
  46485. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46486. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46487. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46488. this.onAxisMoved = bind(this.onAxisMoved, this);
  46489. },
  46490. init: function () {
  46491. var self = this;
  46492. this.onButtonChanged = bind(this.onButtonChanged, this);
  46493. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46494. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46495. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46496. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46497. this.controllerPresent = false;
  46498. this.lastControllerCheck = 0;
  46499. this.bindMethods();
  46500. },
  46501. addEventListeners: function () {
  46502. var el = this.el;
  46503. el.addEventListener('buttonchanged', this.onButtonChanged);
  46504. el.addEventListener('buttondown', this.onButtonDown);
  46505. el.addEventListener('buttonup', this.onButtonUp);
  46506. el.addEventListener('touchstart', this.onButtonTouchStart);
  46507. el.addEventListener('touchend', this.onButtonTouchEnd);
  46508. el.addEventListener('model-loaded', this.onModelLoaded);
  46509. el.addEventListener('axismove', this.onAxisMoved);
  46510. this.controllerEventsActive = true;
  46511. },
  46512. removeEventListeners: function () {
  46513. var el = this.el;
  46514. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46515. el.removeEventListener('buttondown', this.onButtonDown);
  46516. el.removeEventListener('buttonup', this.onButtonUp);
  46517. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46518. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46519. el.removeEventListener('model-loaded', this.onModelLoaded);
  46520. el.removeEventListener('axismove', this.onAxisMoved);
  46521. this.controllerEventsActive = false;
  46522. },
  46523. checkIfControllerPresent: function () {
  46524. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46525. this.data.hand ? {hand: this.data.hand} : {});
  46526. },
  46527. play: function () {
  46528. this.checkIfControllerPresent();
  46529. this.addControllersUpdateListener();
  46530. },
  46531. pause: function () {
  46532. this.removeEventListeners();
  46533. this.removeControllersUpdateListener();
  46534. },
  46535. injectTrackedControls: function () {
  46536. var el = this.el;
  46537. var data = this.data;
  46538. el.setAttribute('tracked-controls', {
  46539. armModel: data.armModel,
  46540. hand: data.hand,
  46541. idPrefix: GAMEPAD_ID_PREFIX,
  46542. id: GAMEPAD_ID_PREFIX,
  46543. orientationOffset: data.orientationOffset
  46544. });
  46545. if (!this.data.model) { return; }
  46546. this.el.setAttribute('obj-model', {
  46547. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  46548. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  46549. });
  46550. },
  46551. addControllersUpdateListener: function () {
  46552. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46553. },
  46554. removeControllersUpdateListener: function () {
  46555. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46556. },
  46557. onControllersUpdate: function () {
  46558. this.checkIfControllerPresent();
  46559. },
  46560. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  46561. onModelLoaded: function (evt) {
  46562. var controllerObject3D = evt.detail.model;
  46563. var buttonMeshes;
  46564. if (!this.data.model) { return; }
  46565. buttonMeshes = this.buttonMeshes = {};
  46566. buttonMeshes.trigger = controllerObject3D.children[2];
  46567. buttonMeshes.trackpad = controllerObject3D.children[1];
  46568. buttonMeshes.touchpad = controllerObject3D.children[1];
  46569. },
  46570. onButtonChanged: function (evt) {
  46571. var button = this.mapping.buttons[evt.detail.id];
  46572. if (!button) return;
  46573. // Pass along changed event with button state, using button mapping for convenience.
  46574. this.el.emit(button + 'changed', evt.detail.state);
  46575. },
  46576. onAxisMoved: function (evt) {
  46577. emitIfAxesChanged(this, this.mapping.axes, evt);
  46578. },
  46579. updateModel: function (buttonName, evtName) {
  46580. if (!this.data.model) { return; }
  46581. this.updateButtonModel(buttonName, evtName);
  46582. },
  46583. updateButtonModel: function (buttonName, state) {
  46584. var buttonMeshes = this.buttonMeshes;
  46585. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46586. var color;
  46587. switch (state) {
  46588. case 'down':
  46589. color = this.data.buttonHighlightColor;
  46590. break;
  46591. case 'touchstart':
  46592. color = this.data.buttonTouchedColor;
  46593. break;
  46594. default:
  46595. color = this.data.buttonColor;
  46596. }
  46597. buttonMeshes[buttonName].material.color.set(color);
  46598. }
  46599. });
  46600. },{"../core/component":130,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],78:[function(_dereq_,module,exports){
  46601. var registerComponent = _dereq_('../core/component').registerComponent;
  46602. var bind = _dereq_('../utils/bind');
  46603. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46604. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46605. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46606. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46607. var GAMEPAD_ID_PREFIX = 'generic';
  46608. /**
  46609. * Button indices:
  46610. * 0 - trigger
  46611. * 1 - squeeze
  46612. * 2 - touchpad
  46613. * 3 - thumbstick
  46614. *
  46615. * Axis:
  46616. * 0 - touchpad
  46617. * 1 - thumbstick
  46618. *
  46619. */
  46620. var INPUT_MAPPING = {
  46621. axes: {
  46622. touchpad: [0, 1],
  46623. thumbstick: [2, 3]
  46624. },
  46625. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick']
  46626. };
  46627. /**
  46628. * Oculus Go controls.
  46629. * Interface with Oculus Go controller and map Gamepad events to
  46630. * controller buttons: trackpad, trigger
  46631. * Load a controller model and highlight the pressed buttons.
  46632. */
  46633. module.exports.Component = registerComponent('generic-tracked-controller-controls', {
  46634. schema: {
  46635. hand: {default: ''}, // This informs the degenerate arm model.
  46636. defaultModel: {default: true},
  46637. defaultModelColor: {default: 'gray'},
  46638. orientationOffset: {type: 'vec3'}
  46639. },
  46640. /**
  46641. * Button IDs:
  46642. * 0 - trackpad
  46643. * 1 - trigger
  46644. */
  46645. mapping: INPUT_MAPPING,
  46646. bindMethods: function () {
  46647. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46648. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46649. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46650. this.onAxisMoved = bind(this.onAxisMoved, this);
  46651. },
  46652. init: function () {
  46653. var self = this;
  46654. this.onButtonChanged = bind(this.onButtonChanged, this);
  46655. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46656. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46657. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46658. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46659. this.controllerPresent = false;
  46660. this.lastControllerCheck = 0;
  46661. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46662. this.bindMethods();
  46663. },
  46664. addEventListeners: function () {
  46665. var el = this.el;
  46666. el.addEventListener('buttonchanged', this.onButtonChanged);
  46667. el.addEventListener('buttondown', this.onButtonDown);
  46668. el.addEventListener('buttonup', this.onButtonUp);
  46669. el.addEventListener('touchstart', this.onButtonTouchStart);
  46670. el.addEventListener('touchend', this.onButtonTouchEnd);
  46671. el.addEventListener('axismove', this.onAxisMoved);
  46672. this.controllerEventsActive = true;
  46673. },
  46674. removeEventListeners: function () {
  46675. var el = this.el;
  46676. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46677. el.removeEventListener('buttondown', this.onButtonDown);
  46678. el.removeEventListener('buttonup', this.onButtonUp);
  46679. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46680. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46681. el.removeEventListener('axismove', this.onAxisMoved);
  46682. this.controllerEventsActive = false;
  46683. },
  46684. checkIfControllerPresent: function () {
  46685. var data = this.data;
  46686. var hand = data.hand ? data.hand : undefined;
  46687. checkControllerPresentAndSetup(
  46688. this, GAMEPAD_ID_PREFIX,
  46689. {hand: hand, iterateControllerProfiles: true});
  46690. },
  46691. play: function () {
  46692. this.checkIfControllerPresent();
  46693. this.addControllersUpdateListener();
  46694. },
  46695. pause: function () {
  46696. this.removeEventListeners();
  46697. this.removeControllersUpdateListener();
  46698. },
  46699. injectTrackedControls: function () {
  46700. var el = this.el;
  46701. var data = this.data;
  46702. // Do nothing if tracked-controls already set.
  46703. // Generic controls have the lowest precedence.
  46704. if (this.el.components['tracked-controls']) {
  46705. this.removeEventListeners();
  46706. return;
  46707. }
  46708. el.setAttribute('tracked-controls', {
  46709. hand: data.hand,
  46710. idPrefix: GAMEPAD_ID_PREFIX,
  46711. orientationOffset: data.orientationOffset,
  46712. iterateControllerProfiles: true
  46713. });
  46714. if (!this.data.defaultModel) { return; }
  46715. this.initDefaultModel();
  46716. },
  46717. addControllersUpdateListener: function () {
  46718. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46719. },
  46720. removeControllersUpdateListener: function () {
  46721. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46722. },
  46723. onControllersUpdate: function () {
  46724. this.checkIfControllerPresent();
  46725. },
  46726. onButtonChanged: function (evt) {
  46727. var button = this.mapping.buttons[evt.detail.id];
  46728. if (!button) return;
  46729. // Pass along changed event with button state, using button mapping for convenience.
  46730. this.el.emit(button + 'changed', evt.detail.state);
  46731. },
  46732. onAxisMoved: function (evt) {
  46733. emitIfAxesChanged(this, this.mapping.axes, evt);
  46734. },
  46735. initDefaultModel: function () {
  46736. var modelEl = this.modelEl = document.createElement('a-entity');
  46737. modelEl.setAttribute('geometry', {
  46738. primitive: 'sphere',
  46739. radius: 0.03
  46740. });
  46741. modelEl.setAttribute('material', {color: this.data.color});
  46742. this.el.appendChild(modelEl);
  46743. }
  46744. });
  46745. },{"../core/component":130,"../utils/bind":198,"../utils/tracked-controls":213}],79:[function(_dereq_,module,exports){
  46746. var geometries = _dereq_('../core/geometry').geometries;
  46747. var geometryNames = _dereq_('../core/geometry').geometryNames;
  46748. var registerComponent = _dereq_('../core/component').registerComponent;
  46749. var THREE = _dereq_('../lib/three');
  46750. var dummyGeometry = new THREE.Geometry();
  46751. /**
  46752. * Geometry component. Combined with material component to make a mesh in 3D object.
  46753. * Extended with registered geometries.
  46754. */
  46755. module.exports.Component = registerComponent('geometry', {
  46756. schema: {
  46757. buffer: {default: true},
  46758. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  46759. skipCache: {default: false}
  46760. },
  46761. init: function () {
  46762. this.geometry = null;
  46763. },
  46764. /**
  46765. * Talk to geometry system to get or create geometry.
  46766. */
  46767. update: function (previousData) {
  46768. var data = this.data;
  46769. var el = this.el;
  46770. var mesh;
  46771. var system = this.system;
  46772. // Dispose old geometry if we created one.
  46773. if (this.geometry) {
  46774. system.unuseGeometry(previousData);
  46775. this.geometry = null;
  46776. }
  46777. // Create new geometry.
  46778. this.geometry = system.getOrCreateGeometry(data);
  46779. // Set on mesh. If mesh does not exist, create it.
  46780. mesh = el.getObject3D('mesh');
  46781. if (mesh) {
  46782. mesh.geometry = this.geometry;
  46783. } else {
  46784. mesh = new THREE.Mesh();
  46785. mesh.geometry = this.geometry;
  46786. el.setObject3D('mesh', mesh);
  46787. }
  46788. },
  46789. /**
  46790. * Tell geometry system that entity is no longer using the geometry.
  46791. * Unset the geometry on the mesh
  46792. */
  46793. remove: function () {
  46794. this.system.unuseGeometry(this.data);
  46795. this.el.getObject3D('mesh').geometry = dummyGeometry;
  46796. this.geometry = null;
  46797. },
  46798. /**
  46799. * Update geometry component schema based on geometry type.
  46800. */
  46801. updateSchema: function (data) {
  46802. var currentGeometryType = this.oldData && this.oldData.primitive;
  46803. var newGeometryType = data.primitive;
  46804. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  46805. // Geometry has no schema.
  46806. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  46807. // Nothing has changed.
  46808. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  46809. this.extendSchema(schema);
  46810. }
  46811. });
  46812. },{"../core/component":130,"../core/geometry":131,"../lib/three":178}],80:[function(_dereq_,module,exports){
  46813. var registerComponent = _dereq_('../core/component').registerComponent;
  46814. var THREE = _dereq_('../lib/three');
  46815. var utils = _dereq_('../utils/');
  46816. var warn = utils.debug('components:gltf-model:warn');
  46817. /**
  46818. * glTF model loader.
  46819. */
  46820. module.exports.Component = registerComponent('gltf-model', {
  46821. schema: {type: 'model'},
  46822. init: function () {
  46823. var dracoLoader = this.system.getDRACOLoader();
  46824. this.model = null;
  46825. this.loader = new THREE.GLTFLoader();
  46826. if (dracoLoader) {
  46827. this.loader.setDRACOLoader(dracoLoader);
  46828. }
  46829. },
  46830. update: function () {
  46831. var self = this;
  46832. var el = this.el;
  46833. var src = this.data;
  46834. if (!src) { return; }
  46835. this.remove();
  46836. this.loader.load(src, function gltfLoaded (gltfModel) {
  46837. self.model = gltfModel.scene || gltfModel.scenes[0];
  46838. self.model.animations = gltfModel.animations;
  46839. el.setObject3D('mesh', self.model);
  46840. el.emit('model-loaded', {format: 'gltf', model: self.model});
  46841. }, undefined /* onProgress */, function gltfFailed (error) {
  46842. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  46843. warn(message);
  46844. el.emit('model-error', {format: 'gltf', src: src});
  46845. });
  46846. },
  46847. remove: function () {
  46848. if (!this.model) { return; }
  46849. this.el.removeObject3D('mesh');
  46850. }
  46851. });
  46852. },{"../core/component":130,"../lib/three":178,"../utils/":204}],81:[function(_dereq_,module,exports){
  46853. /* global THREE */
  46854. var registerComponent = _dereq_('../core/component').registerComponent;
  46855. // Found at https://github.com/aframevr/assets.
  46856. var MODEL_URLS = {
  46857. toonLeft: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  46858. toonRight: 'https://cdn.aframe.io/controllers/hands/rightHand.glb',
  46859. lowPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandLow.glb',
  46860. lowPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandLow.glb',
  46861. highPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandHigh.glb',
  46862. highPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandHigh.glb'
  46863. };
  46864. // Poses.
  46865. var ANIMATIONS = {
  46866. open: 'Open',
  46867. // point: grip active, trackpad surface active, trigger inactive.
  46868. point: 'Point',
  46869. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  46870. pointThumb: 'Point + Thumb',
  46871. // fist: grip active, trigger active, trackpad surface active.
  46872. fist: 'Fist',
  46873. // hold: trigger active, grip inactive.
  46874. hold: 'Hold',
  46875. // thumbUp: grip active, trigger active, trackpad surface inactive.
  46876. thumbUp: 'Thumb Up'
  46877. };
  46878. // Map animation to public events for the API.
  46879. var EVENTS = {};
  46880. EVENTS[ANIMATIONS.fist] = 'grip';
  46881. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  46882. EVENTS[ANIMATIONS.point] = 'pointing';
  46883. /**
  46884. * Hand controls component that abstracts 6DoF controls:
  46885. * oculus-touch-controls, vive-controls, windows-motion-controls.
  46886. *
  46887. * Originally meant to be a sample implementation of applications-specific controls that
  46888. * abstracts multiple types of controllers.
  46889. *
  46890. * Auto-detect appropriate controller.
  46891. * Handle common events coming from the detected vendor-specific controls.
  46892. * Translate button events to semantic hand-related event names:
  46893. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  46894. * Load hand model with gestures that are applied based on the button pressed.
  46895. *
  46896. * @property {string} Hand mapping (`left`, `right`).
  46897. */
  46898. module.exports.Component = registerComponent('hand-controls', {
  46899. schema: {
  46900. color: {default: 'white', type: 'color'},
  46901. hand: { default: 'left' },
  46902. handModelStyle: {default: 'lowPoly', oneOf: ['lowPoly', 'highPoly', 'toon']}
  46903. },
  46904. init: function () {
  46905. var self = this;
  46906. var el = this.el;
  46907. // Current pose.
  46908. this.gesture = ANIMATIONS.open;
  46909. // Active buttons populated by events provided by the attached controls.
  46910. this.pressedButtons = {};
  46911. this.touchedButtons = {};
  46912. this.loader = new THREE.GLTFLoader();
  46913. this.loader.setCrossOrigin('anonymous');
  46914. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  46915. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  46916. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  46917. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  46918. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  46919. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  46920. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  46921. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  46922. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  46923. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  46924. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  46925. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  46926. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  46927. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  46928. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  46929. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  46930. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  46931. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  46932. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  46933. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  46934. this.onControllerConnected = this.onControllerConnected.bind(this);
  46935. this.onControllerDisconnected = this.onControllerDisconnected.bind(this);
  46936. el.addEventListener('controllerconnected', this.onControllerConnected);
  46937. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  46938. // Hidden by default.
  46939. el.object3D.visible = false;
  46940. },
  46941. play: function () {
  46942. this.addEventListeners();
  46943. },
  46944. pause: function () {
  46945. this.removeEventListeners();
  46946. },
  46947. tick: function (time, delta) {
  46948. var mesh = this.el.getObject3D('mesh');
  46949. if (!mesh || !mesh.mixer) { return; }
  46950. mesh.mixer.update(delta / 1000);
  46951. },
  46952. onControllerConnected: function () {
  46953. this.el.object3D.visible = true;
  46954. },
  46955. onControllerDisconnected: function () {
  46956. this.el.object3D.visible = false;
  46957. },
  46958. addEventListeners: function () {
  46959. var el = this.el;
  46960. el.addEventListener('gripdown', this.onGripDown);
  46961. el.addEventListener('gripup', this.onGripUp);
  46962. el.addEventListener('trackpaddown', this.onTrackpadDown);
  46963. el.addEventListener('trackpadup', this.onTrackpadUp);
  46964. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  46965. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  46966. el.addEventListener('triggerdown', this.onTriggerDown);
  46967. el.addEventListener('triggerup', this.onTriggerUp);
  46968. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  46969. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  46970. el.addEventListener('griptouchstart', this.onGripTouchStart);
  46971. el.addEventListener('griptouchend', this.onGripTouchEnd);
  46972. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  46973. el.addEventListener('thumbstickup', this.onThumbstickUp);
  46974. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  46975. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  46976. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  46977. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  46978. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  46979. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  46980. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  46981. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  46982. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  46983. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  46984. },
  46985. removeEventListeners: function () {
  46986. var el = this.el;
  46987. el.removeEventListener('gripdown', this.onGripDown);
  46988. el.removeEventListener('gripup', this.onGripUp);
  46989. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  46990. el.removeEventListener('trackpadup', this.onTrackpadUp);
  46991. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  46992. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  46993. el.removeEventListener('triggerdown', this.onTriggerDown);
  46994. el.removeEventListener('triggerup', this.onTriggerUp);
  46995. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  46996. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  46997. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  46998. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  46999. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  47000. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  47001. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  47002. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  47003. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  47004. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  47005. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  47006. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  47007. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  47008. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  47009. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  47010. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  47011. },
  47012. /**
  47013. * Update handler. More like the `init` handler since the only property is the hand, and
  47014. * that won't be changing much.
  47015. */
  47016. update: function (previousHand) {
  47017. var controlConfiguration;
  47018. var el = this.el;
  47019. var hand = this.data.hand;
  47020. var handModelStyle = this.data.handModelStyle;
  47021. var handColor = this.data.color;
  47022. var self = this;
  47023. // Get common configuration to abstract different vendor controls.
  47024. controlConfiguration = {
  47025. hand: hand,
  47026. model: false
  47027. };
  47028. // Set model.
  47029. if (hand !== previousHand) {
  47030. var handmodelUrl = MODEL_URLS[handModelStyle + hand.charAt(0).toUpperCase() + hand.slice(1)];
  47031. this.loader.load(handmodelUrl, function (gltf) {
  47032. var mesh = gltf.scene.children[0];
  47033. var handModelOrientation = hand === 'left' ? Math.PI / 2 : -Math.PI / 2;
  47034. mesh.mixer = new THREE.AnimationMixer(mesh);
  47035. self.clips = gltf.animations;
  47036. el.setObject3D('mesh', mesh);
  47037. var handMaterial = mesh.children[1].material;
  47038. handMaterial.color = new THREE.Color(handColor);
  47039. mesh.position.set(0, 0, 0);
  47040. mesh.rotation.set(0, 0, handModelOrientation);
  47041. el.setAttribute('magicleap-controls', controlConfiguration);
  47042. el.setAttribute('vive-controls', controlConfiguration);
  47043. el.setAttribute('oculus-touch-controls', controlConfiguration);
  47044. el.setAttribute('windows-motion-controls', controlConfiguration);
  47045. });
  47046. }
  47047. },
  47048. remove: function () {
  47049. this.el.removeObject3D('mesh');
  47050. },
  47051. /**
  47052. * Play model animation, based on which button was pressed and which kind of event.
  47053. *
  47054. * 1. Process buttons.
  47055. * 2. Determine gesture (this.determineGesture()).
  47056. * 3. Animation gesture (this.animationGesture()).
  47057. * 4. Emit gesture events (this.emitGestureEvents()).
  47058. *
  47059. * @param {string} button - Name of the button.
  47060. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  47061. */
  47062. handleButton: function (button, evt) {
  47063. var lastGesture;
  47064. var isPressed = evt === 'down';
  47065. var isTouched = evt === 'touchstart';
  47066. // Update objects.
  47067. if (evt.indexOf('touch') === 0) {
  47068. // Update touch object.
  47069. if (isTouched === this.touchedButtons[button]) { return; }
  47070. this.touchedButtons[button] = isTouched;
  47071. } else {
  47072. // Update button object.
  47073. if (isPressed === this.pressedButtons[button]) { return; }
  47074. this.pressedButtons[button] = isPressed;
  47075. }
  47076. // Determine the gesture.
  47077. lastGesture = this.gesture;
  47078. this.gesture = this.determineGesture();
  47079. // Same gesture.
  47080. if (this.gesture === lastGesture) { return; }
  47081. // Animate gesture.
  47082. this.animateGesture(this.gesture, lastGesture);
  47083. // Emit events.
  47084. this.emitGestureEvents(this.gesture, lastGesture);
  47085. },
  47086. /**
  47087. * Determine which pose hand should be in considering active and touched buttons.
  47088. */
  47089. determineGesture: function () {
  47090. var gesture;
  47091. var isGripActive = this.pressedButtons.grip;
  47092. var isSurfaceActive = this.pressedButtons.surface || this.touchedButtons.surface;
  47093. var isTrackpadActive = this.pressedButtons.trackpad || this.touchedButtons.trackpad;
  47094. var isTriggerActive = this.pressedButtons.trigger || this.touchedButtons.trigger;
  47095. var isABXYActive = this.touchedButtons.AorX || this.touchedButtons.BorY;
  47096. var isVive = isViveController(this.el.components['tracked-controls']);
  47097. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  47098. if (isVive) {
  47099. if (isGripActive || isTriggerActive) {
  47100. gesture = ANIMATIONS.fist;
  47101. } else if (isTrackpadActive) {
  47102. gesture = ANIMATIONS.point;
  47103. }
  47104. } else {
  47105. if (isGripActive) {
  47106. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  47107. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  47108. } else {
  47109. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  47110. }
  47111. } else if (isTriggerActive) {
  47112. gesture = ANIMATIONS.hold;
  47113. }
  47114. }
  47115. return gesture;
  47116. },
  47117. /**
  47118. * Play corresponding clip to a gesture
  47119. */
  47120. getClip: function (gesture) {
  47121. var clip;
  47122. var i;
  47123. for (i = 0; i < this.clips.length; i++) {
  47124. clip = this.clips[i];
  47125. if (clip.name !== gesture) { continue; }
  47126. return clip;
  47127. }
  47128. },
  47129. /**
  47130. * Play gesture animation.
  47131. *
  47132. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  47133. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  47134. */
  47135. animateGesture: function (gesture, lastGesture) {
  47136. if (gesture) {
  47137. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  47138. return;
  47139. }
  47140. // If no gesture, then reverse the current gesture back to open pose.
  47141. this.playAnimation(lastGesture, lastGesture, true);
  47142. },
  47143. /**
  47144. * Emit `hand-controls`-specific events.
  47145. */
  47146. emitGestureEvents: function (gesture, lastGesture) {
  47147. var el = this.el;
  47148. var eventName;
  47149. if (lastGesture === gesture) { return; }
  47150. // Emit event for lastGesture not inactive.
  47151. eventName = getGestureEventName(lastGesture, false);
  47152. if (eventName) { el.emit(eventName); }
  47153. // Emit event for current gesture now active.
  47154. eventName = getGestureEventName(gesture, true);
  47155. if (eventName) { el.emit(eventName); }
  47156. },
  47157. /**
  47158. * Play hand animation based on button state.
  47159. *
  47160. * @param {string} gesture - Name of the animation as specified by the model.
  47161. * @param {string} lastGesture - Previous pose.
  47162. * @param {boolean} reverse - Whether animation should play in reverse.
  47163. */
  47164. playAnimation: function (gesture, lastGesture, reverse) {
  47165. var clip;
  47166. var fromAction;
  47167. var mesh = this.el.getObject3D('mesh');
  47168. var toAction;
  47169. if (!mesh) { return; }
  47170. // Stop all current animations.
  47171. mesh.mixer.stopAllAction();
  47172. // Grab clip action.
  47173. clip = this.getClip(gesture);
  47174. toAction = mesh.mixer.clipAction(clip);
  47175. toAction.clampWhenFinished = true;
  47176. toAction.loop = THREE.LoopRepeat;
  47177. toAction.repetitions = 0;
  47178. toAction.timeScale = reverse ? -1 : 1;
  47179. toAction.time = reverse ? clip.duration : 0;
  47180. toAction.weight = 1;
  47181. // No gesture to gesture or gesture to no gesture.
  47182. if (!lastGesture || gesture === lastGesture) {
  47183. // Stop all current animations.
  47184. mesh.mixer.stopAllAction();
  47185. // Play animation.
  47186. toAction.play();
  47187. return;
  47188. }
  47189. // Animate or crossfade from gesture to gesture.
  47190. clip = this.getClip(lastGesture);
  47191. fromAction = mesh.mixer.clipAction(clip);
  47192. fromAction.weight = 0.15;
  47193. fromAction.play();
  47194. toAction.play();
  47195. fromAction.crossFadeTo(toAction, 0.15, true);
  47196. }
  47197. });
  47198. /**
  47199. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  47200. *
  47201. * @param {string} gesture
  47202. * @param {boolean} active
  47203. */
  47204. function getGestureEventName (gesture, active) {
  47205. var eventName;
  47206. if (!gesture) { return; }
  47207. eventName = EVENTS[gesture];
  47208. if (eventName === 'grip') {
  47209. return eventName + (active ? 'close' : 'open');
  47210. }
  47211. if (eventName === 'point') {
  47212. return eventName + (active ? 'up' : 'down');
  47213. }
  47214. if (eventName === 'pointing' || eventName === 'pistol') {
  47215. return eventName + (active ? 'start' : 'end');
  47216. }
  47217. }
  47218. function isViveController (trackedControls) {
  47219. var controller = trackedControls && trackedControls.controller;
  47220. var isVive = controller && (controller.id && controller.id.indexOf('OpenVR ') === 0 ||
  47221. (controller.profiles &&
  47222. controller.profiles[0] &&
  47223. controller.profiles[0] === 'htc-vive-controller-mv'));
  47224. return isVive;
  47225. }
  47226. },{"../core/component":130}],82:[function(_dereq_,module,exports){
  47227. /* global THREE, XRRigidTransform, XRHand */
  47228. var registerComponent = _dereq_('../core/component').registerComponent;
  47229. var bind = _dereq_('../utils/bind');
  47230. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47231. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47232. var JOINTS_NUMBER = 25;
  47233. var LEFT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/unity/left.glb';
  47234. var RIGHT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/unity/right.glb';
  47235. var BONE_PREFIX = {
  47236. left: 'b_l_',
  47237. right: 'b_r_'
  47238. };
  47239. var BONE_MAPPING = [
  47240. 'wrist',
  47241. 'thumb1',
  47242. 'thumb2',
  47243. 'thumb3',
  47244. 'thumb_null',
  47245. null,
  47246. 'index1',
  47247. 'index2',
  47248. 'index3',
  47249. 'index_null',
  47250. null,
  47251. 'middle1',
  47252. 'middle2',
  47253. 'middle3',
  47254. 'middle_null',
  47255. null,
  47256. 'ring1',
  47257. 'ring2',
  47258. 'ring3',
  47259. 'ring_null',
  47260. 'pinky0',
  47261. 'pinky1',
  47262. 'pinky2',
  47263. 'pinky3',
  47264. 'pinky_null'
  47265. ];
  47266. var PINCH_START_DISTANCE = 0.015;
  47267. var PINCH_END_DISTANCE = 0.03;
  47268. var PINCH_POSITION_INTERPOLATION = 0.5;
  47269. /**
  47270. * Controls for hand tracking
  47271. */
  47272. module.exports.Component = registerComponent('hand-tracking-controls', {
  47273. schema: {
  47274. hand: {default: 'right', oneOf: ['left', 'right']},
  47275. modelStyle: {default: 'mesh', oneOf: ['dots', 'mesh']},
  47276. modelColor: {default: 'white'}
  47277. },
  47278. bindMethods: function () {
  47279. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47280. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47281. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47282. },
  47283. addEventListeners: function () {
  47284. this.el.addEventListener('model-loaded', this.onModelLoaded);
  47285. for (var i = 0; i < this.jointEls.length; ++i) {
  47286. this.jointEls[i].object3D.visible = true;
  47287. }
  47288. },
  47289. removeEventListeners: function () {
  47290. this.el.removeEventListener('model-loaded', this.onModelLoaded);
  47291. for (var i = 0; i < this.jointEls.length; ++i) {
  47292. this.jointEls[i].object3D.visible = false;
  47293. }
  47294. },
  47295. init: function () {
  47296. var sceneEl = this.el.sceneEl;
  47297. var webXROptionalAttributes = sceneEl.getAttribute('webxr').optionalFeatures;
  47298. webXROptionalAttributes.push('hand-tracking');
  47299. sceneEl.setAttribute('webxr', {optionalFeatures: webXROptionalAttributes});
  47300. this.onModelLoaded = this.onModelLoaded.bind(this);
  47301. this.jointEls = [];
  47302. this.controllerPresent = false;
  47303. this.isPinched = false;
  47304. this.pinchEventDetail = {position: new THREE.Vector3()};
  47305. this.indexTipPosition = new THREE.Vector3();
  47306. this.bindMethods();
  47307. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  47308. this.el.sceneEl.addEventListener('enter-vr', this.updateReferenceSpace);
  47309. this.el.sceneEl.addEventListener('exit-vr', this.updateReferenceSpace);
  47310. },
  47311. updateReferenceSpace: function () {
  47312. var self = this;
  47313. var xrSession = this.el.sceneEl.xrSession;
  47314. this.referenceSpace = undefined;
  47315. if (!xrSession) { return; }
  47316. var referenceSpaceType = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  47317. xrSession.requestReferenceSpace(referenceSpaceType).then(function (referenceSpace) {
  47318. self.referenceSpace = referenceSpace.getOffsetReferenceSpace(new XRRigidTransform({x: 0, y: 1.5, z: 0}));
  47319. }).catch(function (error) {
  47320. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(referenceSpaceType, 'tracked-controls-webxr uses reference space ' + referenceSpaceType);
  47321. throw error;
  47322. });
  47323. },
  47324. checkIfControllerPresent: function () {
  47325. var data = this.data;
  47326. var hand = data.hand ? data.hand : undefined;
  47327. checkControllerPresentAndSetup(
  47328. this, '',
  47329. {hand: hand, iterateControllerProfiles: true, handTracking: true});
  47330. },
  47331. play: function () {
  47332. this.checkIfControllerPresent();
  47333. this.addControllersUpdateListener();
  47334. },
  47335. tick: function () {
  47336. var sceneEl = this.el.sceneEl;
  47337. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47338. var frame = sceneEl.frame;
  47339. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47340. if (!controller || !frame || !trackedControlsWebXR) { return; }
  47341. if (controller.hand) {
  47342. this.el.object3D.position.set(0, 0, 0);
  47343. this.el.object3D.rotation.set(0, 0, 0);
  47344. if (frame.getJointPose) { this.updateHandModel(); }
  47345. this.detectGesture();
  47346. }
  47347. },
  47348. updateHandModel: function () {
  47349. if (this.data.modelStyle === 'dots') {
  47350. this.updateHandDotsModel();
  47351. }
  47352. if (this.data.modelStyle === 'mesh') {
  47353. this.updateHandMeshModel();
  47354. }
  47355. },
  47356. updateHandMeshModel: function () {
  47357. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47358. var referenceSpace = this.referenceSpace;
  47359. if (!controller || !this.mesh || !referenceSpace) { return; }
  47360. this.mesh.visible = false;
  47361. for (var i = 0; i < controller.hand.length; i++) {
  47362. var bone;
  47363. var jointPose;
  47364. var jointTransform;
  47365. if (!controller.hand[i]) { continue; }
  47366. jointPose = this.el.sceneEl.frame.getJointPose(controller.hand[i], referenceSpace);
  47367. if (BONE_MAPPING[i] == null) { continue; }
  47368. bone = this.getBone(BONE_PREFIX[this.data.hand] + BONE_MAPPING[i]);
  47369. if (bone != null && jointPose) {
  47370. jointTransform = jointPose.transform;
  47371. this.mesh.visible = true;
  47372. bone.position.copy(jointTransform.position).multiplyScalar(100);
  47373. bone.quaternion.set(jointTransform.orientation.x, jointTransform.orientation.y, jointTransform.orientation.z, jointTransform.orientation.w);
  47374. }
  47375. }
  47376. },
  47377. getBone: function (name) {
  47378. var bones = this.bones;
  47379. for (var i = 0; i < bones.length; i++) {
  47380. if (bones[i].name === name) { return bones[i]; }
  47381. }
  47382. return null;
  47383. },
  47384. updateHandDotsModel: function () {
  47385. var frame = this.el.sceneEl.frame;
  47386. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47387. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47388. var referenceSpace = trackedControlsWebXR.system.referenceSpace;
  47389. for (var i = 0; i < this.jointEls.length; ++i) {
  47390. var jointEl = this.jointEls[i];
  47391. jointEl.object3D.visible = !!controller.hand[i];
  47392. if (controller.hand[i]) {
  47393. var object3D = jointEl.object3D;
  47394. var pose = frame.getJointPose(controller.hand[i], referenceSpace);
  47395. jointEl.object3D.visible = !!pose;
  47396. if (!pose) { continue; }
  47397. object3D.matrix.elements = pose.transform.matrix;
  47398. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  47399. jointEl.setAttribute('scale', {x: pose.radius, y: pose.radius, z: pose.radius});
  47400. }
  47401. }
  47402. },
  47403. detectGesture: function () {
  47404. this.detectPinch();
  47405. },
  47406. detectPinch: (function () {
  47407. var thumbTipPosition = new THREE.Vector3();
  47408. return function () {
  47409. var frame = this.el.sceneEl.frame;
  47410. var indexTipPosition = this.indexTipPosition;
  47411. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47412. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47413. var referenceSpace = this.referenceSpace || trackedControlsWebXR.system.referenceSpace;
  47414. if (!controller.hand[XRHand.INDEX_PHALANX_TIP] ||
  47415. !controller.hand[XRHand.THUMB_PHALANX_TIP]) { return; }
  47416. var indexTipPose = frame.getJointPose(controller.hand[XRHand.INDEX_PHALANX_TIP], referenceSpace);
  47417. var thumbTipPose = frame.getJointPose(controller.hand[XRHand.THUMB_PHALANX_TIP], referenceSpace);
  47418. if (!indexTipPose || !thumbTipPose) { return; }
  47419. thumbTipPosition.copy(thumbTipPose.transform.position);
  47420. indexTipPosition.copy(indexTipPose.transform.position);
  47421. var distance = indexTipPosition.distanceTo(thumbTipPosition);
  47422. if (distance < PINCH_START_DISTANCE && this.isPinched === false) {
  47423. this.isPinched = true;
  47424. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47425. this.pinchEventDetail.position.y += 1.5;
  47426. this.el.emit('pinchstarted', this.pinchEventDetail);
  47427. }
  47428. if (distance > PINCH_END_DISTANCE && this.isPinched === true) {
  47429. this.isPinched = false;
  47430. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47431. this.pinchEventDetail.position.y += 1.5;
  47432. this.el.emit('pinchended', this.pinchEventDetail);
  47433. }
  47434. if (this.isPinched) {
  47435. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47436. this.pinchEventDetail.position.y += 1.5;
  47437. this.el.emit('pinchmoved', this.pinchEventDetail);
  47438. }
  47439. indexTipPosition.y += 1.5;
  47440. };
  47441. })(),
  47442. pause: function () {
  47443. this.removeEventListeners();
  47444. this.removeControllersUpdateListener();
  47445. },
  47446. injectTrackedControls: function () {
  47447. var el = this.el;
  47448. var data = this.data;
  47449. el.setAttribute('tracked-controls', {
  47450. hand: data.hand,
  47451. iterateControllerProfiles: true,
  47452. handTrackingEnabled: true
  47453. });
  47454. this.initDefaultModel();
  47455. },
  47456. addControllersUpdateListener: function () {
  47457. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47458. },
  47459. removeControllersUpdateListener: function () {
  47460. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47461. },
  47462. onControllersUpdate: function () {
  47463. var controller;
  47464. this.checkIfControllerPresent();
  47465. controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47466. if (!this.el.getObject3D('mesh')) { return; }
  47467. if (!controller || !controller.hand || !controller.hand[0]) {
  47468. this.el.removeObject3D('mesh');
  47469. }
  47470. },
  47471. initDefaultModel: function () {
  47472. if (this.data.modelStyle === 'dots') {
  47473. this.initDotsModel();
  47474. }
  47475. if (this.data.modelStyle === 'mesh') {
  47476. this.initMeshHandModel();
  47477. }
  47478. },
  47479. initDotsModel: function () {
  47480. // Add models just once.
  47481. if (this.jointEls.length !== 0) { return; }
  47482. for (var i = 0; i < JOINTS_NUMBER; ++i) {
  47483. var jointEl = this.jointEl = document.createElement('a-entity');
  47484. jointEl.setAttribute('geometry', {
  47485. primitive: 'sphere',
  47486. radius: 1.0
  47487. });
  47488. jointEl.setAttribute('material', {color: this.data.modelColor});
  47489. jointEl.object3D.visible = false;
  47490. this.el.appendChild(jointEl);
  47491. this.jointEls.push(jointEl);
  47492. }
  47493. },
  47494. initMeshHandModel: function () {
  47495. var modelURL = this.data.hand === 'left' ? LEFT_HAND_MODEL_URL : RIGHT_HAND_MODEL_URL;
  47496. this.el.setAttribute('gltf-model', modelURL);
  47497. },
  47498. onModelLoaded: function () {
  47499. var mesh = this.mesh = this.el.getObject3D('mesh').children[0];
  47500. var skinnedMesh = this.skinnedMesh = mesh.children[24];
  47501. if (!this.skinnedMesh) { return; }
  47502. this.bones = skinnedMesh.skeleton.bones;
  47503. this.el.removeObject3D('mesh');
  47504. mesh.position.set(0, 1.5, 0);
  47505. mesh.rotation.set(0, 0, 0);
  47506. skinnedMesh.frustumCulled = false;
  47507. skinnedMesh.material = new THREE.MeshStandardMaterial({skinning: true, color: this.data.modelColor});
  47508. this.el.setObject3D('mesh', mesh);
  47509. }
  47510. });
  47511. },{"../core/component":130,"../utils/bind":198,"../utils/tracked-controls":213}],83:[function(_dereq_,module,exports){
  47512. _dereq_('./animation');
  47513. _dereq_('./camera');
  47514. _dereq_('./cursor');
  47515. _dereq_('./daydream-controls');
  47516. _dereq_('./gearvr-controls');
  47517. _dereq_('./geometry');
  47518. _dereq_('./generic-tracked-controller-controls');
  47519. _dereq_('./gltf-model');
  47520. _dereq_('./hand-tracking-controls');
  47521. _dereq_('./hand-controls');
  47522. _dereq_('./layer');
  47523. _dereq_('./laser-controls');
  47524. _dereq_('./light');
  47525. _dereq_('./line');
  47526. _dereq_('./link');
  47527. _dereq_('./look-controls');
  47528. _dereq_('./magicleap-controls');
  47529. _dereq_('./material');
  47530. _dereq_('./obj-model');
  47531. _dereq_('./oculus-go-controls');
  47532. _dereq_('./oculus-touch-controls');
  47533. _dereq_('./position');
  47534. _dereq_('./raycaster');
  47535. _dereq_('./rotation');
  47536. _dereq_('./scale');
  47537. _dereq_('./shadow');
  47538. _dereq_('./sound');
  47539. _dereq_('./text');
  47540. _dereq_('./tracked-controls');
  47541. _dereq_('./tracked-controls-webvr');
  47542. _dereq_('./tracked-controls-webxr');
  47543. _dereq_('./visible');
  47544. _dereq_('./valve-index-controls');
  47545. _dereq_('./vive-controls');
  47546. _dereq_('./vive-focus-controls');
  47547. _dereq_('./wasd-controls');
  47548. _dereq_('./windows-motion-controls');
  47549. _dereq_('./scene/background');
  47550. _dereq_('./scene/debug');
  47551. _dereq_('./scene/device-orientation-permission-ui');
  47552. _dereq_('./scene/embedded');
  47553. _dereq_('./scene/inspector');
  47554. _dereq_('./scene/fog');
  47555. _dereq_('./scene/keyboard-shortcuts');
  47556. _dereq_('./scene/pool');
  47557. _dereq_('./scene/screenshot');
  47558. _dereq_('./scene/stats');
  47559. _dereq_('./scene/vr-mode-ui');
  47560. },{"./animation":73,"./camera":74,"./cursor":75,"./daydream-controls":76,"./gearvr-controls":77,"./generic-tracked-controller-controls":78,"./geometry":79,"./gltf-model":80,"./hand-controls":81,"./hand-tracking-controls":82,"./laser-controls":84,"./layer":85,"./light":86,"./line":87,"./link":88,"./look-controls":89,"./magicleap-controls":90,"./material":91,"./obj-model":92,"./oculus-go-controls":93,"./oculus-touch-controls":94,"./position":95,"./raycaster":96,"./rotation":97,"./scale":98,"./scene/background":99,"./scene/debug":100,"./scene/device-orientation-permission-ui":101,"./scene/embedded":102,"./scene/fog":103,"./scene/inspector":104,"./scene/keyboard-shortcuts":105,"./scene/pool":106,"./scene/screenshot":107,"./scene/stats":108,"./scene/vr-mode-ui":109,"./shadow":110,"./sound":111,"./text":112,"./tracked-controls":115,"./tracked-controls-webvr":113,"./tracked-controls-webxr":114,"./valve-index-controls":116,"./visible":117,"./vive-controls":118,"./vive-focus-controls":119,"./wasd-controls":120,"./windows-motion-controls":121}],84:[function(_dereq_,module,exports){
  47561. var registerComponent = _dereq_('../core/component').registerComponent;
  47562. var utils = _dereq_('../utils/');
  47563. registerComponent('laser-controls', {
  47564. schema: {
  47565. hand: {default: 'right'},
  47566. model: {default: true},
  47567. defaultModelColor: {type: 'color', default: 'grey'}
  47568. },
  47569. init: function () {
  47570. var config = this.config;
  47571. var data = this.data;
  47572. var el = this.el;
  47573. var self = this;
  47574. var controlsConfiguration = {hand: data.hand, model: data.model};
  47575. // Set all controller models.
  47576. el.setAttribute('daydream-controls', controlsConfiguration);
  47577. el.setAttribute('gearvr-controls', controlsConfiguration);
  47578. el.setAttribute('magicleap-controls', controlsConfiguration);
  47579. el.setAttribute('oculus-go-controls', controlsConfiguration);
  47580. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  47581. el.setAttribute('valve-index-controls', controlsConfiguration);
  47582. el.setAttribute('vive-controls', controlsConfiguration);
  47583. el.setAttribute('vive-focus-controls', controlsConfiguration);
  47584. el.setAttribute('windows-motion-controls', controlsConfiguration);
  47585. el.setAttribute('generic-tracked-controller-controls', controlsConfiguration);
  47586. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  47587. el.addEventListener('controllerconnected', createRay);
  47588. el.addEventListener('controllerdisconnected', hideRay);
  47589. el.addEventListener('controllermodelready', function (evt) {
  47590. createRay(evt);
  47591. self.modelReady = true;
  47592. });
  47593. function createRay (evt) {
  47594. var controllerConfig = config[evt.detail.name];
  47595. if (!controllerConfig) { return; }
  47596. // Show the line unless a particular config opts to hide it, until a controllermodelready
  47597. // event comes through.
  47598. var raycasterConfig = utils.extend({
  47599. showLine: true
  47600. }, controllerConfig.raycaster || {});
  47601. // The controllermodelready event contains a rayOrigin that takes into account
  47602. // offsets specific to the loaded model.
  47603. if (evt.detail.rayOrigin) {
  47604. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  47605. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  47606. raycasterConfig.showLine = true;
  47607. }
  47608. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  47609. // config applied from a controllermodelready event.
  47610. if (evt.detail.rayOrigin || !self.modelReady) {
  47611. el.setAttribute('raycaster', raycasterConfig);
  47612. } else {
  47613. el.setAttribute('raycaster', 'showLine', true);
  47614. }
  47615. el.setAttribute('cursor', utils.extend({
  47616. fuse: false
  47617. }, controllerConfig.cursor));
  47618. }
  47619. function hideRay () {
  47620. el.setAttribute('raycaster', 'showLine', false);
  47621. }
  47622. },
  47623. config: {
  47624. 'daydream-controls': {
  47625. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47626. },
  47627. 'gearvr-controls': {
  47628. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47629. raycaster: {origin: {x: 0, y: 0.0010, z: 0}}
  47630. },
  47631. 'generic-tracked-controller-controls': {
  47632. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47633. },
  47634. 'magicleap-controls': {
  47635. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47636. },
  47637. 'oculus-go-controls': {
  47638. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47639. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  47640. },
  47641. 'oculus-touch-controls': {
  47642. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47643. raycaster: {origin: {x: 0, y: 0, z: 0}}
  47644. },
  47645. 'valve-index-controls': {
  47646. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47647. },
  47648. 'vive-controls': {
  47649. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47650. },
  47651. 'vive-focus-controls': {
  47652. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47653. },
  47654. 'windows-motion-controls': {
  47655. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47656. raycaster: {showLine: false}
  47657. }
  47658. }
  47659. });
  47660. },{"../core/component":130,"../utils/":204}],85:[function(_dereq_,module,exports){
  47661. /* global THREE, XRRigidTransform, XRWebGLBinding */
  47662. var registerComponent = _dereq_('../core/component').registerComponent;
  47663. var utils = _dereq_('../utils/');
  47664. var warn = utils.debug('components:layer:warn');
  47665. module.exports.Component = registerComponent('layer', {
  47666. schema: {
  47667. type: {default: 'quad', oneOf: ['quad', 'monocubemap', 'stereocubemap']},
  47668. src: {type: 'map'},
  47669. rotateCubemap: {default: false},
  47670. width: {default: 0},
  47671. height: {default: 0}
  47672. },
  47673. init: function () {
  47674. var gl = this.el.sceneEl.renderer.getContext();
  47675. this.quaternion = new THREE.Quaternion();
  47676. this.position = new THREE.Vector3();
  47677. this.bindMethods();
  47678. this.needsRedraw = false;
  47679. this.frameBuffer = gl.createFramebuffer();
  47680. var requiredFeatures = this.el.sceneEl.getAttribute('webxr').requiredFeatures;
  47681. requiredFeatures.push('layers');
  47682. this.el.sceneEl.getAttribute('webxr', 'requiredFeatures', requiredFeatures);
  47683. this.el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  47684. this.el.sceneEl.addEventListener('exit-vr', this.onExitVR);
  47685. },
  47686. bindMethods: function () {
  47687. this.onRequestedReferenceSpace = this.onRequestedReferenceSpace.bind(this);
  47688. this.onEnterVR = this.onEnterVR.bind(this);
  47689. this.onExitVR = this.onExitVR.bind(this);
  47690. },
  47691. update: function (oldData) {
  47692. if (this.data.src !== oldData.src) { this.updateSrc(); }
  47693. },
  47694. updateSrc: function () {
  47695. var type = this.data.type;
  47696. this.texture = undefined;
  47697. if (type === 'quad') {
  47698. this.loadQuadImage();
  47699. return;
  47700. }
  47701. if (type === 'monocubemap' || type === 'stereocubemap') {
  47702. this.loadCubeMapImages();
  47703. return;
  47704. }
  47705. },
  47706. loadCubeMapImages: function () {
  47707. var type = this.data.type;
  47708. var glayer;
  47709. var xrGLFactory = this.xrGLFactory;
  47710. var frame = this.el.sceneEl.frame;
  47711. var src = this.data.src;
  47712. this.visibilityChanged = false;
  47713. if (!this.layer) { return; }
  47714. if (!src.complete) {
  47715. this.pendingCubeMapUpdate = true;
  47716. } else {
  47717. this.pendingCubeMapUpdate = false;
  47718. }
  47719. if (!this.loadingScreen) {
  47720. this.loadingScreen = true;
  47721. } else {
  47722. this.loadingScreen = false;
  47723. }
  47724. if (type === 'monocubemap') {
  47725. glayer = xrGLFactory.getSubImage(this.layer, frame);
  47726. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  47727. } else {
  47728. glayer = xrGLFactory.getSubImage(this.layer, frame, 'left');
  47729. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  47730. glayer = xrGLFactory.getSubImage(this.layer, frame, 'right');
  47731. this.loadCubeMapImage(glayer.colorTexture, src, 6);
  47732. }
  47733. },
  47734. loadQuadImage: function () {
  47735. var src = this.data.src;
  47736. var self = this;
  47737. this.el.sceneEl.systems.material.loadTexture(src, {src: src}, function textureLoaded (texture) {
  47738. self.el.sceneEl.renderer.initTexture(texture);
  47739. self.texture = texture;
  47740. if (src.tagName === 'VIDEO') { setTimeout(function () { self.textureIsVideo = true; }, 1000); }
  47741. if (self.layer) {
  47742. self.layer.height = self.data.height / 2 || self.texture.image.height / 1000;
  47743. self.layer.width = self.data.width / 2 || self.texture.image.width / 1000;
  47744. self.needsRedraw = true;
  47745. }
  47746. self.updateQuadPanel();
  47747. });
  47748. },
  47749. preGenerateCubeMapTextures: function (src, callback) {
  47750. if (this.data.type === 'monocubemap') {
  47751. this.generateCubeMapTextures(src, 0, callback);
  47752. } else {
  47753. this.generateCubeMapTextures(src, 0, callback);
  47754. this.generateCubeMapTextures(src, 6, callback);
  47755. }
  47756. },
  47757. generateCubeMapTextures: function (src, faceOffset, callback) {
  47758. var data = this.data;
  47759. var cubeFaceSize = this.cubeFaceSize;
  47760. var textureSourceCubeFaceSize = Math.min(src.width, src.height);
  47761. var cubefaceTextures = [];
  47762. var imgTmp0;
  47763. var imgTmp2;
  47764. for (var i = 0; i < 6; i++) {
  47765. var tempCanvas = document.createElement('CANVAS');
  47766. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47767. var tempCanvasContext = tempCanvas.getContext('2d');
  47768. if (data.rotateCubemap) {
  47769. if (i === 2 || i === 3) {
  47770. tempCanvasContext.save();
  47771. tempCanvasContext.translate(cubeFaceSize, cubeFaceSize);
  47772. tempCanvasContext.rotate(Math.PI);
  47773. }
  47774. }
  47775. // Note that this call to drawImage will not only copy the bytes to the
  47776. // canvas but also could resized the image if our cube face size is
  47777. // smaller than the source image due to GL max texture size.
  47778. tempCanvasContext.drawImage(
  47779. src,
  47780. (i + faceOffset) * textureSourceCubeFaceSize, // top left x coord in source
  47781. 0, // top left y coord in source
  47782. textureSourceCubeFaceSize, // x pixel count from source
  47783. textureSourceCubeFaceSize, // y pixel count from source
  47784. 0, // dest x offset in the canvas
  47785. 0, // dest y offset in the canvas
  47786. cubeFaceSize, // x pixel count in dest
  47787. cubeFaceSize // y pixel count in dest
  47788. );
  47789. tempCanvasContext.restore();
  47790. if (callback) { callback(); }
  47791. cubefaceTextures.push(tempCanvas);
  47792. }
  47793. if (data.rotateCubemap) {
  47794. imgTmp0 = cubefaceTextures[0];
  47795. imgTmp2 = cubefaceTextures[1];
  47796. cubefaceTextures[0] = imgTmp2;
  47797. cubefaceTextures[1] = imgTmp0;
  47798. imgTmp0 = cubefaceTextures[4];
  47799. imgTmp2 = cubefaceTextures[5];
  47800. cubefaceTextures[4] = imgTmp2;
  47801. cubefaceTextures[5] = imgTmp0;
  47802. }
  47803. if (callback) { callback(); }
  47804. return cubefaceTextures;
  47805. },
  47806. loadCubeMapImage: function (layerColorTexture, src, faceOffset) {
  47807. var gl = this.el.sceneEl.renderer.getContext();
  47808. var cubefaceTextures;
  47809. // dont flip the pixels as we load them into the texture buffer.
  47810. // TEXTURE_CUBE_MAP expects the Y to be flipped for the faces and it already
  47811. // is flipped in our texture image.
  47812. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  47813. gl.bindTexture(gl.TEXTURE_CUBE_MAP, layerColorTexture);
  47814. if (!src.complete || this.loadingScreen) {
  47815. cubefaceTextures = this.loadingScreenImages;
  47816. } else {
  47817. cubefaceTextures = this.generateCubeMapTextures(src, faceOffset);
  47818. }
  47819. var errorCode = 0;
  47820. cubefaceTextures.forEach(function (canvas, i) {
  47821. gl.texSubImage2D(
  47822. gl.TEXTURE_CUBE_MAP_POSITIVE_X + i,
  47823. 0,
  47824. 0, 0,
  47825. gl.RGBA,
  47826. gl.UNSIGNED_BYTE,
  47827. canvas
  47828. );
  47829. errorCode = gl.getError();
  47830. });
  47831. if (errorCode !== 0) {
  47832. console.log('renderingError, WebGL Error Code: ' + errorCode);
  47833. }
  47834. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  47835. },
  47836. tick: function () {
  47837. if (!this.el.sceneEl.xrSession) { return; }
  47838. if (!this.layer && this.el.sceneEl.is('vr-mode')) { this.initLayer(); }
  47839. this.updateTransform();
  47840. if (this.data.src.complete && (this.pendingCubeMapUpdate || this.loadingScreen || this.visibilityChanged)) { this.loadCubeMapImages(); }
  47841. if (!this.needsRedraw && !this.layer.needsRedraw && !this.textureIsVideo) { return; }
  47842. if (this.data.type === 'quad') { this.draw(); }
  47843. this.needsRedraw = false;
  47844. },
  47845. initLayer: function () {
  47846. var self = this;
  47847. var type = this.data.type;
  47848. this.el.sceneEl.xrSession.onvisibilitychange = function (evt) {
  47849. self.visibilityChanged = evt.session.visibilityState !== 'hidden';
  47850. };
  47851. if (type === 'quad') {
  47852. this.initQuadLayer();
  47853. return;
  47854. }
  47855. if (type === 'monocubemap' || type === 'stereocubemap') {
  47856. this.initCubeMapLayer();
  47857. return;
  47858. }
  47859. },
  47860. initQuadLayer: function () {
  47861. var sceneEl = this.el.sceneEl;
  47862. var gl = sceneEl.renderer.getContext();
  47863. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  47864. if (!this.texture) { return; }
  47865. this.layer = xrGLFactory.createQuadLayer({
  47866. space: this.referenceSpace,
  47867. viewPixelHeight: 2048,
  47868. viewPixelWidth: 2048,
  47869. height: this.data.height / 2 || this.texture.image.height / 1000,
  47870. width: this.data.width / 2 || this.texture.image.width / 1000
  47871. });
  47872. sceneEl.renderer.xr.addLayer(this.layer);
  47873. },
  47874. initCubeMapLayer: function () {
  47875. var src = this.data.src;
  47876. var sceneEl = this.el.sceneEl;
  47877. var gl = sceneEl.renderer.getContext();
  47878. var glSizeLimit = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  47879. var cubeFaceSize = this.cubeFaceSize = Math.min(glSizeLimit, Math.min(src.width, src.height));
  47880. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  47881. this.layer = xrGLFactory.createCubeLayer({
  47882. space: this.referenceSpace,
  47883. viewPixelWidth: cubeFaceSize,
  47884. viewPixelHeight: cubeFaceSize,
  47885. layout: this.data.type === 'monocubemap' ? 'mono' : 'stereo',
  47886. isStatic: false
  47887. });
  47888. this.initLoadingScreenImages();
  47889. this.loadCubeMapImages();
  47890. sceneEl.renderer.xr.addLayer(this.layer);
  47891. },
  47892. initLoadingScreenImages: function () {
  47893. var cubeFaceSize = this.cubeFaceSize;
  47894. var loadingScreenImages = this.loadingScreenImages = [];
  47895. for (var i = 0; i < 6; i++) {
  47896. var tempCanvas = document.createElement('CANVAS');
  47897. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47898. var tempCanvasContext = tempCanvas.getContext('2d');
  47899. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47900. tempCanvasContext.fillStyle = 'black';
  47901. tempCanvasContext.fillRect(0, 0, cubeFaceSize, cubeFaceSize);
  47902. if (i !== 2 && i !== 3) {
  47903. tempCanvasContext.translate(cubeFaceSize, 0);
  47904. tempCanvasContext.scale(-1, 1);
  47905. tempCanvasContext.fillStyle = 'white';
  47906. tempCanvasContext.font = '30px Arial';
  47907. tempCanvasContext.fillText('Loading', cubeFaceSize / 2, cubeFaceSize / 2);
  47908. }
  47909. loadingScreenImages.push(tempCanvas);
  47910. }
  47911. },
  47912. destroyLayer: function () {
  47913. if (!this.layer) { return; }
  47914. this.el.sceneEl.renderer.xr.removeLayer(this.layer);
  47915. this.layer.destroy();
  47916. this.layer = undefined;
  47917. },
  47918. toggleCompositorLayer: function () {
  47919. this.enableCompositorLayer(!this.layerEnabled);
  47920. },
  47921. enableCompositorLayer: function (enable) {
  47922. this.layerEnabled = enable;
  47923. this.quadPanelEl.object3D.visible = !this.layerEnabled;
  47924. },
  47925. updateQuadPanel: function () {
  47926. var quadPanelEl = this.quadPanelEl;
  47927. if (!this.quadPanelEl) {
  47928. quadPanelEl = this.quadPanelEl = document.createElement('a-entity');
  47929. this.el.appendChild(quadPanelEl);
  47930. }
  47931. quadPanelEl.setAttribute('material', {
  47932. shader: 'flat',
  47933. src: this.data.src,
  47934. transparent: true
  47935. });
  47936. quadPanelEl.setAttribute('geometry', {
  47937. primitive: 'plane',
  47938. height: this.data.height || this.texture.image.height / 1000,
  47939. width: this.data.width || this.texture.image.height / 1000
  47940. });
  47941. },
  47942. draw: function () {
  47943. var sceneEl = this.el.sceneEl;
  47944. var gl = this.el.sceneEl.renderer.getContext();
  47945. var glayer = this.xrGLFactory.getSubImage(this.layer, sceneEl.frame);
  47946. var texture = sceneEl.renderer.properties.get(this.texture).__webglTexture;
  47947. var previousFrameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  47948. gl.viewport(glayer.viewport.x, glayer.viewport.y, glayer.viewport.width, glayer.viewport.height);
  47949. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer);
  47950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glayer.colorTexture, 0);
  47951. blitTexture(gl, texture, glayer, this.data.src);
  47952. gl.bindFramebuffer(gl.FRAMEBUFFER, previousFrameBuffer);
  47953. },
  47954. updateTransform: function () {
  47955. var el = this.el;
  47956. var position = this.position;
  47957. var quaternion = this.quaternion;
  47958. el.object3D.updateMatrixWorld();
  47959. position.setFromMatrixPosition(el.object3D.matrixWorld);
  47960. quaternion.setFromRotationMatrix(el.object3D.matrixWorld);
  47961. if (!this.layerEnabled) { position.set(0, 0, 100000000); }
  47962. this.layer.transform = new XRRigidTransform(position, quaternion);
  47963. },
  47964. onEnterVR: function () {
  47965. var sceneEl = this.el.sceneEl;
  47966. var xrSession = sceneEl.xrSession;
  47967. if (!sceneEl.hasWebXR || !XRWebGLBinding || !xrSession) {
  47968. warn('The layer component requires WebXR and the layers API enabled');
  47969. return;
  47970. }
  47971. xrSession.requestReferenceSpace('local').then(this.onRequestedReferenceSpace);
  47972. this.needsRedraw = true;
  47973. this.layerEnabled = true;
  47974. if (this.quadPanelEl) {
  47975. this.quadPanelEl.object3D.visible = false;
  47976. }
  47977. if (this.data.src.play) { this.data.src.play(); }
  47978. },
  47979. onExitVR: function () {
  47980. if (this.quadPanelEl) {
  47981. this.quadPanelEl.object3D.visible = true;
  47982. }
  47983. this.destroyLayer();
  47984. },
  47985. onRequestedReferenceSpace: function (referenceSpace) {
  47986. this.referenceSpace = referenceSpace;
  47987. }
  47988. });
  47989. function blitTexture (gl, texture, subImage, textureEl) {
  47990. var xrReadFramebuffer = gl.createFramebuffer();
  47991. let x1offset = subImage.viewport.x;
  47992. let y1offset = subImage.viewport.y;
  47993. let x2offset = subImage.viewport.x + subImage.viewport.width;
  47994. let y2offset = subImage.viewport.y + subImage.viewport.height;
  47995. // Update video texture.
  47996. if (textureEl.tagName === 'VIDEO') {
  47997. gl.bindTexture(gl.TEXTURE_2D, texture);
  47998. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, textureEl.width, textureEl.height, gl.RGB, gl.UNSIGNED_BYTE, textureEl);
  47999. }
  48000. // Bind texture to read framebuffer.
  48001. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, xrReadFramebuffer);
  48002. gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  48003. // Blit into layer buffer.
  48004. gl.readBuffer(gl.COLOR_ATTACHMENT0);
  48005. gl.blitFramebuffer(0, 0, textureEl.width, textureEl.height, x1offset, y1offset, x2offset, y2offset, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  48006. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  48007. gl.deleteFramebuffer(xrReadFramebuffer);
  48008. }
  48009. },{"../core/component":130,"../utils/":204}],86:[function(_dereq_,module,exports){
  48010. var bind = _dereq_('../utils/bind');
  48011. var diff = _dereq_('../utils').diff;
  48012. var debug = _dereq_('../utils/debug');
  48013. var registerComponent = _dereq_('../core/component').registerComponent;
  48014. var THREE = _dereq_('../lib/three');
  48015. var degToRad = THREE.Math.degToRad;
  48016. var warn = debug('components:light:warn');
  48017. /**
  48018. * Light component.
  48019. */
  48020. module.exports.Component = registerComponent('light', {
  48021. schema: {
  48022. angle: {default: 60, if: {type: ['spot']}},
  48023. color: {type: 'color'},
  48024. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  48025. decay: {default: 1, if: {type: ['point', 'spot']}},
  48026. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  48027. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  48028. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  48029. type: {
  48030. default: 'directional',
  48031. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  48032. schemaChange: true
  48033. },
  48034. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  48035. // Shadows.
  48036. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  48037. shadowBias: {default: 0, if: {castShadow: true}},
  48038. shadowCameraFar: {default: 500, if: {castShadow: true}},
  48039. shadowCameraFov: {default: 90, if: {castShadow: true}},
  48040. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  48041. shadowCameraTop: {default: 5, if: {castShadow: true}},
  48042. shadowCameraRight: {default: 5, if: {castShadow: true}},
  48043. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  48044. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  48045. shadowCameraVisible: {default: false, if: {castShadow: true}},
  48046. shadowMapHeight: {default: 512, if: {castShadow: true}},
  48047. shadowMapWidth: {default: 512, if: {castShadow: true}},
  48048. shadowRadius: {default: 1, if: {castShadow: true}}
  48049. },
  48050. /**
  48051. * Notifies scene a light has been added to remove default lighting.
  48052. */
  48053. init: function () {
  48054. var el = this.el;
  48055. this.light = null;
  48056. this.defaultTarget = null;
  48057. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48058. this.system.registerLight(el);
  48059. },
  48060. /**
  48061. * (Re)create or update light.
  48062. */
  48063. update: function (oldData) {
  48064. var data = this.data;
  48065. var diffData = diff(data, oldData);
  48066. var light = this.light;
  48067. var rendererSystem = this.rendererSystem;
  48068. var self = this;
  48069. // Existing light.
  48070. if (light && !('type' in diffData)) {
  48071. var shadowsLoaded = false;
  48072. // Light type has not changed. Update light.
  48073. Object.keys(diffData).forEach(function (key) {
  48074. var value = data[key];
  48075. switch (key) {
  48076. case 'color': {
  48077. light.color.set(value);
  48078. rendererSystem.applyColorCorrection(light.color);
  48079. break;
  48080. }
  48081. case 'groundColor': {
  48082. light.groundColor.set(value);
  48083. rendererSystem.applyColorCorrection(light.groundColor);
  48084. break;
  48085. }
  48086. case 'angle': {
  48087. light.angle = degToRad(value);
  48088. break;
  48089. }
  48090. case 'target': {
  48091. // Reset target if selector is null.
  48092. if (value === null) {
  48093. if (data.type === 'spot' || data.type === 'directional') {
  48094. light.target = self.defaultTarget;
  48095. }
  48096. } else {
  48097. // Target specified, set target to entity's `object3D` when it is loaded.
  48098. if (value.hasLoaded) {
  48099. self.onSetTarget(value, light);
  48100. } else {
  48101. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  48102. }
  48103. }
  48104. break;
  48105. }
  48106. case 'castShadow':
  48107. case 'shadowBias':
  48108. case 'shadowCameraFar':
  48109. case 'shadowCameraFov':
  48110. case 'shadowCameraNear':
  48111. case 'shadowCameraTop':
  48112. case 'shadowCameraRight':
  48113. case 'shadowCameraBottom':
  48114. case 'shadowCameraLeft':
  48115. case 'shadowCameraVisible':
  48116. case 'shadowMapHeight':
  48117. case 'shadowMapWidth':
  48118. case 'shadowRadius':
  48119. if (!shadowsLoaded) {
  48120. self.updateShadow();
  48121. shadowsLoaded = true;
  48122. }
  48123. break;
  48124. default: {
  48125. light[key] = value;
  48126. }
  48127. }
  48128. });
  48129. return;
  48130. }
  48131. // No light yet or light type has changed. Create and add light.
  48132. this.setLight(this.data);
  48133. this.updateShadow();
  48134. },
  48135. setLight: function (data) {
  48136. var el = this.el;
  48137. var newLight = this.getLight(data);
  48138. if (newLight) {
  48139. if (this.light) {
  48140. el.removeObject3D('light');
  48141. }
  48142. this.light = newLight;
  48143. this.light.el = el;
  48144. el.setObject3D('light', this.light);
  48145. // HACK solution for issue #1624
  48146. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  48147. el.getObject3D('light').translateY(-1);
  48148. }
  48149. // set and position default lighttarget as a child to enable spotlight orientation
  48150. if (data.type === 'spot') {
  48151. el.setObject3D('light-target', this.defaultTarget);
  48152. el.getObject3D('light-target').position.set(0, 0, -1);
  48153. }
  48154. }
  48155. },
  48156. /**
  48157. * Updates shadow-related properties on the current light.
  48158. */
  48159. updateShadow: function () {
  48160. var el = this.el;
  48161. var data = this.data;
  48162. var light = this.light;
  48163. light.castShadow = data.castShadow;
  48164. // Shadow camera helper.
  48165. var cameraHelper = el.getObject3D('cameraHelper');
  48166. if (data.shadowCameraVisible && !cameraHelper) {
  48167. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  48168. } else if (!data.shadowCameraVisible && cameraHelper) {
  48169. el.removeObject3D('cameraHelper');
  48170. }
  48171. if (!data.castShadow) { return light; }
  48172. // Shadow appearance.
  48173. light.shadow.bias = data.shadowBias;
  48174. light.shadow.radius = data.shadowRadius;
  48175. light.shadow.mapSize.height = data.shadowMapHeight;
  48176. light.shadow.mapSize.width = data.shadowMapWidth;
  48177. // Shadow camera.
  48178. light.shadow.camera.near = data.shadowCameraNear;
  48179. light.shadow.camera.far = data.shadowCameraFar;
  48180. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  48181. light.shadow.camera.top = data.shadowCameraTop;
  48182. light.shadow.camera.right = data.shadowCameraRight;
  48183. light.shadow.camera.bottom = data.shadowCameraBottom;
  48184. light.shadow.camera.left = data.shadowCameraLeft;
  48185. } else {
  48186. light.shadow.camera.fov = data.shadowCameraFov;
  48187. }
  48188. light.shadow.camera.updateProjectionMatrix();
  48189. if (cameraHelper) { cameraHelper.update(); }
  48190. },
  48191. /**
  48192. * Creates a new three.js light object given data object defining the light.
  48193. *
  48194. * @param {object} data
  48195. */
  48196. getLight: function (data) {
  48197. var angle = data.angle;
  48198. var color = new THREE.Color(data.color);
  48199. this.rendererSystem.applyColorCorrection(color);
  48200. color = color.getHex();
  48201. var decay = data.decay;
  48202. var distance = data.distance;
  48203. var groundColor = new THREE.Color(data.groundColor);
  48204. this.rendererSystem.applyColorCorrection(groundColor);
  48205. groundColor = groundColor.getHex();
  48206. var intensity = data.intensity;
  48207. var type = data.type;
  48208. var target = data.target;
  48209. var light = null;
  48210. switch (type.toLowerCase()) {
  48211. case 'ambient': {
  48212. return new THREE.AmbientLight(color, intensity);
  48213. }
  48214. case 'directional': {
  48215. light = new THREE.DirectionalLight(color, intensity);
  48216. this.defaultTarget = light.target;
  48217. if (target) {
  48218. if (target.hasLoaded) {
  48219. this.onSetTarget(target, light);
  48220. } else {
  48221. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  48222. }
  48223. }
  48224. return light;
  48225. }
  48226. case 'hemisphere': {
  48227. return new THREE.HemisphereLight(color, groundColor, intensity);
  48228. }
  48229. case 'point': {
  48230. return new THREE.PointLight(color, intensity, distance, decay);
  48231. }
  48232. case 'spot': {
  48233. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  48234. this.defaultTarget = light.target;
  48235. if (target) {
  48236. if (target.hasLoaded) {
  48237. this.onSetTarget(target, light);
  48238. } else {
  48239. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  48240. }
  48241. }
  48242. return light;
  48243. }
  48244. default: {
  48245. warn('%s is not a valid light type. ' +
  48246. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  48247. }
  48248. }
  48249. },
  48250. onSetTarget: function (targetEl, light) {
  48251. light.target = targetEl.object3D;
  48252. },
  48253. /**
  48254. * Remove light on remove (callback).
  48255. */
  48256. remove: function () {
  48257. var el = this.el;
  48258. el.removeObject3D('light');
  48259. if (el.getObject3D('cameraHelper')) {
  48260. el.removeObject3D('cameraHelper');
  48261. }
  48262. }
  48263. });
  48264. },{"../core/component":130,"../lib/three":178,"../utils":204,"../utils/bind":198,"../utils/debug":200}],87:[function(_dereq_,module,exports){
  48265. /* global THREE */
  48266. var registerComponent = _dereq_('../core/component').registerComponent;
  48267. module.exports.Component = registerComponent('line', {
  48268. schema: {
  48269. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  48270. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  48271. color: {type: 'color', default: '#74BEC1'},
  48272. opacity: {type: 'number', default: 1},
  48273. visible: {default: true}
  48274. },
  48275. multiple: true,
  48276. init: function () {
  48277. var data = this.data;
  48278. var geometry;
  48279. var material;
  48280. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48281. material = this.material = new THREE.LineBasicMaterial({
  48282. color: data.color,
  48283. opacity: data.opacity,
  48284. transparent: data.opacity < 1,
  48285. visible: data.visible
  48286. });
  48287. geometry = this.geometry = new THREE.BufferGeometry();
  48288. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  48289. this.rendererSystem.applyColorCorrection(material.color);
  48290. this.line = new THREE.Line(geometry, material);
  48291. this.el.setObject3D(this.attrName, this.line);
  48292. },
  48293. update: function (oldData) {
  48294. var data = this.data;
  48295. var geometry = this.geometry;
  48296. var geoNeedsUpdate = false;
  48297. var material = this.material;
  48298. var positionArray = geometry.attributes.position.array;
  48299. // Update geometry.
  48300. if (!isEqualVec3(data.start, oldData.start)) {
  48301. positionArray[0] = data.start.x;
  48302. positionArray[1] = data.start.y;
  48303. positionArray[2] = data.start.z;
  48304. geoNeedsUpdate = true;
  48305. }
  48306. if (!isEqualVec3(data.end, oldData.end)) {
  48307. positionArray[3] = data.end.x;
  48308. positionArray[4] = data.end.y;
  48309. positionArray[5] = data.end.z;
  48310. geoNeedsUpdate = true;
  48311. }
  48312. if (geoNeedsUpdate) {
  48313. geometry.attributes.position.needsUpdate = true;
  48314. geometry.computeBoundingSphere();
  48315. }
  48316. material.color.setStyle(data.color);
  48317. this.rendererSystem.applyColorCorrection(material.color);
  48318. material.opacity = data.opacity;
  48319. material.transparent = data.opacity < 1;
  48320. material.visible = data.visible;
  48321. },
  48322. remove: function () {
  48323. this.el.removeObject3D('line', this.line);
  48324. }
  48325. });
  48326. function isEqualVec3 (a, b) {
  48327. if (!a || !b) { return false; }
  48328. return (a.x === b.x && a.y === b.y && a.z === b.z);
  48329. }
  48330. },{"../core/component":130}],88:[function(_dereq_,module,exports){
  48331. var registerComponent = _dereq_('../core/component').registerComponent;
  48332. var registerShader = _dereq_('../core/shader').registerShader;
  48333. var THREE = _dereq_('../lib/three');
  48334. /**
  48335. * Link component. Connect experiences and traverse between them in VR
  48336. *
  48337. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  48338. */
  48339. module.exports.Component = registerComponent('link', {
  48340. schema: {
  48341. backgroundColor: {default: 'red', type: 'color'},
  48342. borderColor: {default: 'white', type: 'color'},
  48343. highlighted: {default: false},
  48344. highlightedColor: {default: '#24CAFF', type: 'color'},
  48345. href: {default: ''},
  48346. image: {type: 'asset'},
  48347. on: {default: 'click'},
  48348. peekMode: {default: false},
  48349. title: {default: ''},
  48350. titleColor: {default: 'white', type: 'color'},
  48351. visualAspectEnabled: {default: false}
  48352. },
  48353. init: function () {
  48354. this.navigate = this.navigate.bind(this);
  48355. this.previousQuaternion = undefined;
  48356. this.quaternionClone = new THREE.Quaternion();
  48357. // Store hidden elements during peek mode so we can show them again later.
  48358. this.hiddenEls = [];
  48359. },
  48360. update: function (oldData) {
  48361. var data = this.data;
  48362. var el = this.el;
  48363. var backgroundColor;
  48364. var strokeColor;
  48365. if (!data.visualAspectEnabled) { return; }
  48366. this.initVisualAspect();
  48367. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  48368. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  48369. el.setAttribute('material', 'backgroundColor', backgroundColor);
  48370. el.setAttribute('material', 'strokeColor', strokeColor);
  48371. if (data.on !== oldData.on) { this.updateEventListener(); }
  48372. if (oldData.peekMode !== undefined &&
  48373. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  48374. if (!data.image || oldData.image === data.image) { return; }
  48375. el.setAttribute('material', 'pano',
  48376. typeof data.image === 'string' ? data.image : data.image.src);
  48377. },
  48378. /*
  48379. * Toggle all elements and full 360 preview of the linked page.
  48380. */
  48381. updatePeekMode: function () {
  48382. var el = this.el;
  48383. var sphereEl = this.sphereEl;
  48384. if (this.data.peekMode) {
  48385. this.hideAll();
  48386. el.getObject3D('mesh').visible = false;
  48387. sphereEl.setAttribute('visible', true);
  48388. } else {
  48389. this.showAll();
  48390. el.getObject3D('mesh').visible = true;
  48391. sphereEl.setAttribute('visible', false);
  48392. }
  48393. },
  48394. play: function () {
  48395. this.updateEventListener();
  48396. },
  48397. pause: function () {
  48398. this.removeEventListener();
  48399. },
  48400. updateEventListener: function () {
  48401. var el = this.el;
  48402. if (!el.isPlaying) { return; }
  48403. this.removeEventListener();
  48404. el.addEventListener(this.data.on, this.navigate);
  48405. },
  48406. removeEventListener: function () {
  48407. var on = this.data.on;
  48408. if (!on) { return; }
  48409. this.el.removeEventListener(on, this.navigate);
  48410. },
  48411. initVisualAspect: function () {
  48412. var el = this.el;
  48413. var semiSphereEl;
  48414. var sphereEl;
  48415. var textEl;
  48416. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  48417. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  48418. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  48419. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  48420. // Set portal.
  48421. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  48422. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  48423. // Set text that displays the link title and URL.
  48424. textEl.setAttribute('text', {
  48425. color: this.data.titleColor,
  48426. align: 'center',
  48427. font: 'kelsonsans',
  48428. value: this.data.title || this.data.href,
  48429. width: 4
  48430. });
  48431. textEl.setAttribute('position', '0 1.5 0');
  48432. el.appendChild(textEl);
  48433. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  48434. semiSphereEl.setAttribute('geometry', {
  48435. primitive: 'sphere',
  48436. radius: 1.0,
  48437. phiStart: 0,
  48438. segmentsWidth: 64,
  48439. segmentsHeight: 64,
  48440. phiLength: 180,
  48441. thetaStart: 0,
  48442. thetaLength: 360
  48443. });
  48444. semiSphereEl.setAttribute('material', {
  48445. shader: 'portal',
  48446. borderEnabled: 0.0,
  48447. pano: this.data.image,
  48448. side: 'back'
  48449. });
  48450. semiSphereEl.setAttribute('rotation', '0 180 0');
  48451. semiSphereEl.setAttribute('position', '0 0 0');
  48452. semiSphereEl.setAttribute('visible', false);
  48453. el.appendChild(semiSphereEl);
  48454. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  48455. sphereEl.setAttribute('geometry', {
  48456. primitive: 'sphere',
  48457. radius: 10,
  48458. segmentsWidth: 64,
  48459. segmentsHeight: 64
  48460. });
  48461. sphereEl.setAttribute('material', {
  48462. shader: 'portal',
  48463. borderEnabled: 0.0,
  48464. pano: this.data.image,
  48465. side: 'back'
  48466. });
  48467. sphereEl.setAttribute('visible', false);
  48468. el.appendChild(sphereEl);
  48469. this.visualAspectInitialized = true;
  48470. },
  48471. navigate: function () {
  48472. window.location = this.data.href;
  48473. },
  48474. /**
  48475. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  48476. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  48477. * from where user enters.
  48478. * 2. Place the url/title above or inside portal depending on distance to camera.
  48479. * 3. Face portal to camera when far away from user.
  48480. */
  48481. tick: (function () {
  48482. var cameraWorldPosition = new THREE.Vector3();
  48483. var elWorldPosition = new THREE.Vector3();
  48484. var quaternion = new THREE.Quaternion();
  48485. var scale = new THREE.Vector3();
  48486. return function () {
  48487. var el = this.el;
  48488. var object3D = el.object3D;
  48489. var camera = el.sceneEl.camera;
  48490. var cameraPortalOrientation;
  48491. var distance;
  48492. var textEl = this.textEl;
  48493. if (!this.data.visualAspectEnabled) { return; }
  48494. // Update matrices
  48495. object3D.updateMatrixWorld();
  48496. camera.parent.updateMatrixWorld();
  48497. camera.updateMatrixWorld();
  48498. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  48499. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  48500. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  48501. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  48502. if (distance > 20) {
  48503. // Store original orientation to be restored when the portal stops facing the camera.
  48504. if (!this.previousQuaternion) {
  48505. this.quaternionClone.copy(quaternion);
  48506. this.previousQuaternion = this.quaternionClone;
  48507. }
  48508. // If the portal is far away from the user, face portal to camera.
  48509. object3D.lookAt(cameraWorldPosition);
  48510. } else {
  48511. // When portal is close to the user/camera.
  48512. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  48513. // If user gets very close to portal, replace with holed sphere they can peek in.
  48514. if (distance < 0.5) {
  48515. // Configure text size and sphere orientation depending side user approaches portal.
  48516. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  48517. textEl.setAttribute('text', 'width', 1.5);
  48518. if (cameraPortalOrientation <= 0.0) {
  48519. textEl.setAttribute('position', '0 0 0.75');
  48520. textEl.setAttribute('rotation', '0 180 0');
  48521. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  48522. } else {
  48523. textEl.setAttribute('position', '0 0 -0.75');
  48524. textEl.setAttribute('rotation', '0 0 0');
  48525. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  48526. }
  48527. el.getObject3D('mesh').visible = false;
  48528. this.semiSphereEl.setAttribute('visible', true);
  48529. this.peekCameraPortalOrientation = cameraPortalOrientation;
  48530. } else {
  48531. // Calculate wich side the camera is approaching the camera (back / front).
  48532. // Adjust text orientation based on camera position.
  48533. if (cameraPortalOrientation <= 0.0) {
  48534. textEl.setAttribute('rotation', '0 180 0');
  48535. } else {
  48536. textEl.setAttribute('rotation', '0 0 0');
  48537. }
  48538. textEl.setAttribute('text', 'width', 5);
  48539. textEl.setAttribute('position', '0 1.5 0');
  48540. el.getObject3D('mesh').visible = true;
  48541. this.semiSphereEl.setAttribute('visible', false);
  48542. this.peekCameraPortalOrientation = undefined;
  48543. }
  48544. if (this.previousQuaternion) {
  48545. object3D.quaternion.copy(this.previousQuaternion);
  48546. this.previousQuaternion = undefined;
  48547. }
  48548. }
  48549. };
  48550. })(),
  48551. hideAll: function () {
  48552. var el = this.el;
  48553. var hiddenEls = this.hiddenEls;
  48554. var self = this;
  48555. if (hiddenEls.length > 0) { return; }
  48556. el.sceneEl.object3D.traverse(function (object) {
  48557. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  48558. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  48559. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  48560. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  48561. object.el === self.semiSphereEl) {
  48562. return;
  48563. }
  48564. object.el.setAttribute('visible', false);
  48565. hiddenEls.push(object.el);
  48566. });
  48567. },
  48568. showAll: function () {
  48569. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  48570. this.hiddenEls = [];
  48571. },
  48572. /**
  48573. * Calculate whether the camera faces the front or back face of the portal.
  48574. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  48575. */
  48576. calculateCameraPortalOrientation: (function () {
  48577. var mat4 = new THREE.Matrix4();
  48578. var cameraPosition = new THREE.Vector3();
  48579. var portalNormal = new THREE.Vector3(0, 0, 1);
  48580. var portalPosition = new THREE.Vector3(0, 0, 0);
  48581. return function () {
  48582. var el = this.el;
  48583. var camera = el.sceneEl.camera;
  48584. // Reset tmp variables.
  48585. cameraPosition.set(0, 0, 0);
  48586. portalNormal.set(0, 0, 1);
  48587. portalPosition.set(0, 0, 0);
  48588. // Apply portal orientation to the normal.
  48589. el.object3D.matrixWorld.extractRotation(mat4);
  48590. portalNormal.applyMatrix4(mat4);
  48591. // Calculate portal world position.
  48592. el.object3D.updateMatrixWorld();
  48593. el.object3D.localToWorld(portalPosition);
  48594. // Calculate camera world position.
  48595. camera.parent.parent.updateMatrixWorld();
  48596. camera.parent.updateMatrixWorld();
  48597. camera.updateMatrixWorld();
  48598. camera.localToWorld(cameraPosition);
  48599. // Calculate vector from portal to camera.
  48600. // (portal) -------> (camera)
  48601. cameraPosition.sub(portalPosition).normalize();
  48602. portalNormal.normalize();
  48603. // Side where camera approaches portal is given by sign of dot product of portal normal
  48604. // and portal to camera vectors.
  48605. return Math.sign(portalNormal.dot(cameraPosition));
  48606. };
  48607. })(),
  48608. remove: function () {
  48609. this.removeEventListener();
  48610. }
  48611. });
  48612. /* eslint-disable */
  48613. registerShader('portal', {
  48614. schema: {
  48615. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  48616. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  48617. pano: {type: 'map', is: 'uniform'},
  48618. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  48619. },
  48620. vertexShader: [
  48621. 'vec3 portalPosition;',
  48622. 'varying vec3 vWorldPosition;',
  48623. 'varying float vDistanceToCenter;',
  48624. 'varying float vDistance;',
  48625. 'void main() {',
  48626. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  48627. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  48628. 'vDistance = length(portalPosition - cameraPosition);',
  48629. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  48630. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  48631. '}'
  48632. ].join('\n'),
  48633. fragmentShader: [
  48634. '#define RECIPROCAL_PI2 0.15915494',
  48635. 'uniform sampler2D pano;',
  48636. 'uniform vec3 strokeColor;',
  48637. 'uniform vec3 backgroundColor;',
  48638. 'uniform float borderEnabled;',
  48639. 'varying float vDistanceToCenter;',
  48640. 'varying float vDistance;',
  48641. 'varying vec3 vWorldPosition;',
  48642. 'void main() {',
  48643. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  48644. 'vec2 sampleUV;',
  48645. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  48646. 'sampleUV.y = clamp(direction.y * 0.5 + 0.5, 0.0, 1.0);',
  48647. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  48648. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  48649. 'gl_FragColor = vec4(strokeColor, 1.0);',
  48650. '} else {',
  48651. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  48652. '}',
  48653. '}'
  48654. ].join('\n')
  48655. });
  48656. /* eslint-enable */
  48657. },{"../core/component":130,"../core/shader":140,"../lib/three":178}],89:[function(_dereq_,module,exports){
  48658. /* global DeviceOrientationEvent */
  48659. var registerComponent = _dereq_('../core/component').registerComponent;
  48660. var THREE = _dereq_('../lib/three');
  48661. var utils = _dereq_('../utils/');
  48662. var bind = utils.bind;
  48663. // To avoid recalculation at every mouse movement tick
  48664. var PI_2 = Math.PI / 2;
  48665. /**
  48666. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  48667. */
  48668. module.exports.Component = registerComponent('look-controls', {
  48669. dependencies: ['position', 'rotation'],
  48670. schema: {
  48671. enabled: {default: true},
  48672. magicWindowTrackingEnabled: {default: true},
  48673. pointerLockEnabled: {default: false},
  48674. reverseMouseDrag: {default: false},
  48675. reverseTouchDrag: {default: false},
  48676. touchEnabled: {default: true},
  48677. mouseEnabled: {default: true}
  48678. },
  48679. init: function () {
  48680. this.deltaYaw = 0;
  48681. this.previousHMDPosition = new THREE.Vector3();
  48682. this.hmdQuaternion = new THREE.Quaternion();
  48683. this.magicWindowAbsoluteEuler = new THREE.Euler();
  48684. this.magicWindowDeltaEuler = new THREE.Euler();
  48685. this.position = new THREE.Vector3();
  48686. this.magicWindowObject = new THREE.Object3D();
  48687. this.rotation = {};
  48688. this.deltaRotation = {};
  48689. this.savedPose = null;
  48690. this.pointerLocked = false;
  48691. this.setupMouseControls();
  48692. this.bindMethods();
  48693. this.previousMouseEvent = {};
  48694. this.setupMagicWindowControls();
  48695. // To save / restore camera pose
  48696. this.savedPose = {
  48697. position: new THREE.Vector3(),
  48698. rotation: new THREE.Euler()
  48699. };
  48700. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  48701. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  48702. },
  48703. setupMagicWindowControls: function () {
  48704. var magicWindowControls;
  48705. var data = this.data;
  48706. // Only on mobile devices and only enabled if DeviceOrientation permission has been granted.
  48707. if (utils.device.isMobile()) {
  48708. magicWindowControls = this.magicWindowControls = new THREE.DeviceOrientationControls(this.magicWindowObject);
  48709. if (typeof DeviceOrientationEvent !== 'undefined' && DeviceOrientationEvent.requestPermission) {
  48710. magicWindowControls.enabled = false;
  48711. if (this.el.sceneEl.components['device-orientation-permission-ui'].permissionGranted) {
  48712. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48713. } else {
  48714. this.el.sceneEl.addEventListener('deviceorientationpermissiongranted', function () {
  48715. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48716. });
  48717. }
  48718. }
  48719. }
  48720. },
  48721. update: function (oldData) {
  48722. var data = this.data;
  48723. // Disable grab cursor classes if no longer enabled.
  48724. if (data.enabled !== oldData.enabled) {
  48725. this.updateGrabCursor(data.enabled);
  48726. }
  48727. // Reset magic window eulers if tracking is disabled.
  48728. if (oldData && !data.magicWindowTrackingEnabled && oldData.magicWindowTrackingEnabled) {
  48729. this.magicWindowAbsoluteEuler.set(0, 0, 0);
  48730. this.magicWindowDeltaEuler.set(0, 0, 0);
  48731. }
  48732. // Pass on magic window tracking setting to magicWindowControls.
  48733. if (this.magicWindowControls) {
  48734. this.magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48735. }
  48736. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  48737. this.removeEventListeners();
  48738. this.addEventListeners();
  48739. if (this.pointerLocked) { this.exitPointerLock(); }
  48740. }
  48741. },
  48742. tick: function (t) {
  48743. var data = this.data;
  48744. if (!data.enabled) { return; }
  48745. this.updateOrientation();
  48746. },
  48747. play: function () {
  48748. this.addEventListeners();
  48749. },
  48750. pause: function () {
  48751. this.removeEventListeners();
  48752. if (this.pointerLocked) { this.exitPointerLock(); }
  48753. },
  48754. remove: function () {
  48755. this.removeEventListeners();
  48756. if (this.pointerLocked) { this.exitPointerLock(); }
  48757. },
  48758. bindMethods: function () {
  48759. this.onMouseDown = bind(this.onMouseDown, this);
  48760. this.onMouseMove = bind(this.onMouseMove, this);
  48761. this.onMouseUp = bind(this.onMouseUp, this);
  48762. this.onTouchStart = bind(this.onTouchStart, this);
  48763. this.onTouchMove = bind(this.onTouchMove, this);
  48764. this.onTouchEnd = bind(this.onTouchEnd, this);
  48765. this.onEnterVR = bind(this.onEnterVR, this);
  48766. this.onExitVR = bind(this.onExitVR, this);
  48767. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  48768. this.onPointerLockError = bind(this.onPointerLockError, this);
  48769. },
  48770. /**
  48771. * Set up states and Object3Ds needed to store rotation data.
  48772. */
  48773. setupMouseControls: function () {
  48774. this.mouseDown = false;
  48775. this.pitchObject = new THREE.Object3D();
  48776. this.yawObject = new THREE.Object3D();
  48777. this.yawObject.position.y = 10;
  48778. this.yawObject.add(this.pitchObject);
  48779. },
  48780. /**
  48781. * Add mouse and touch event listeners to canvas.
  48782. */
  48783. addEventListeners: function () {
  48784. var sceneEl = this.el.sceneEl;
  48785. var canvasEl = sceneEl.canvas;
  48786. // Wait for canvas to load.
  48787. if (!canvasEl) {
  48788. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  48789. return;
  48790. }
  48791. // Mouse events.
  48792. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  48793. window.addEventListener('mousemove', this.onMouseMove, false);
  48794. window.addEventListener('mouseup', this.onMouseUp, false);
  48795. // Touch events.
  48796. canvasEl.addEventListener('touchstart', this.onTouchStart);
  48797. window.addEventListener('touchmove', this.onTouchMove);
  48798. window.addEventListener('touchend', this.onTouchEnd);
  48799. // sceneEl events.
  48800. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  48801. sceneEl.addEventListener('exit-vr', this.onExitVR);
  48802. // Pointer Lock events.
  48803. if (this.data.pointerLockEnabled) {
  48804. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  48805. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  48806. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  48807. }
  48808. },
  48809. /**
  48810. * Remove mouse and touch event listeners from canvas.
  48811. */
  48812. removeEventListeners: function () {
  48813. var sceneEl = this.el.sceneEl;
  48814. var canvasEl = sceneEl && sceneEl.canvas;
  48815. if (!canvasEl) { return; }
  48816. // Mouse events.
  48817. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  48818. window.removeEventListener('mousemove', this.onMouseMove);
  48819. window.removeEventListener('mouseup', this.onMouseUp);
  48820. // Touch events.
  48821. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  48822. window.removeEventListener('touchmove', this.onTouchMove);
  48823. window.removeEventListener('touchend', this.onTouchEnd);
  48824. // sceneEl events.
  48825. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  48826. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  48827. // Pointer Lock events.
  48828. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  48829. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  48830. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  48831. },
  48832. /**
  48833. * Update orientation for mobile, mouse drag, and headset.
  48834. * Mouse-drag only enabled if HMD is not active.
  48835. */
  48836. updateOrientation: (function () {
  48837. var poseMatrix = new THREE.Matrix4();
  48838. return function () {
  48839. var object3D = this.el.object3D;
  48840. var pitchObject = this.pitchObject;
  48841. var yawObject = this.yawObject;
  48842. var pose;
  48843. var sceneEl = this.el.sceneEl;
  48844. // In VR mode, THREE is in charge of updating the camera pose.
  48845. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) {
  48846. // With WebXR THREE applies headset pose to the object3D matrixWorld internally.
  48847. // Reflect values back on position, rotation, scale for getAttribute to return the expected values.
  48848. if (sceneEl.hasWebXR) {
  48849. pose = sceneEl.renderer.xr.getCameraPose();
  48850. if (pose) {
  48851. poseMatrix.elements = pose.transform.matrix;
  48852. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  48853. }
  48854. }
  48855. return;
  48856. }
  48857. this.updateMagicWindowOrientation();
  48858. // On mobile, do camera rotation with touch events and sensors.
  48859. object3D.rotation.x = this.magicWindowDeltaEuler.x + pitchObject.rotation.x;
  48860. object3D.rotation.y = this.magicWindowDeltaEuler.y + yawObject.rotation.y;
  48861. object3D.rotation.z = this.magicWindowDeltaEuler.z;
  48862. };
  48863. })(),
  48864. updateMagicWindowOrientation: function () {
  48865. var magicWindowAbsoluteEuler = this.magicWindowAbsoluteEuler;
  48866. var magicWindowDeltaEuler = this.magicWindowDeltaEuler;
  48867. // Calculate magic window HMD quaternion.
  48868. if (this.magicWindowControls && this.magicWindowControls.enabled) {
  48869. this.magicWindowControls.update();
  48870. magicWindowAbsoluteEuler.setFromQuaternion(this.magicWindowObject.quaternion, 'YXZ');
  48871. if (!this.previousMagicWindowYaw && magicWindowAbsoluteEuler.y !== 0) {
  48872. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  48873. }
  48874. if (this.previousMagicWindowYaw) {
  48875. magicWindowDeltaEuler.x = magicWindowAbsoluteEuler.x;
  48876. magicWindowDeltaEuler.y += magicWindowAbsoluteEuler.y - this.previousMagicWindowYaw;
  48877. magicWindowDeltaEuler.z = magicWindowAbsoluteEuler.z;
  48878. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  48879. }
  48880. }
  48881. },
  48882. /**
  48883. * Translate mouse drag into rotation.
  48884. *
  48885. * Dragging up and down rotates the camera around the X-axis (yaw).
  48886. * Dragging left and right rotates the camera around the Y-axis (pitch).
  48887. */
  48888. onMouseMove: function (evt) {
  48889. var direction;
  48890. var movementX;
  48891. var movementY;
  48892. var pitchObject = this.pitchObject;
  48893. var previousMouseEvent = this.previousMouseEvent;
  48894. var yawObject = this.yawObject;
  48895. // Not dragging or not enabled.
  48896. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  48897. // Calculate delta.
  48898. if (this.pointerLocked) {
  48899. movementX = evt.movementX || evt.mozMovementX || 0;
  48900. movementY = evt.movementY || evt.mozMovementY || 0;
  48901. } else {
  48902. movementX = evt.screenX - previousMouseEvent.screenX;
  48903. movementY = evt.screenY - previousMouseEvent.screenY;
  48904. }
  48905. this.previousMouseEvent.screenX = evt.screenX;
  48906. this.previousMouseEvent.screenY = evt.screenY;
  48907. // Calculate rotation.
  48908. direction = this.data.reverseMouseDrag ? 1 : -1;
  48909. yawObject.rotation.y += movementX * 0.002 * direction;
  48910. pitchObject.rotation.x += movementY * 0.002 * direction;
  48911. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  48912. },
  48913. /**
  48914. * Register mouse down to detect mouse drag.
  48915. */
  48916. onMouseDown: function (evt) {
  48917. var sceneEl = this.el.sceneEl;
  48918. if (!this.data.enabled || !this.data.mouseEnabled || (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected())) { return; }
  48919. // Handle only primary button.
  48920. if (evt.button !== 0) { return; }
  48921. var canvasEl = sceneEl && sceneEl.canvas;
  48922. this.mouseDown = true;
  48923. this.previousMouseEvent.screenX = evt.screenX;
  48924. this.previousMouseEvent.screenY = evt.screenY;
  48925. this.showGrabbingCursor();
  48926. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  48927. if (canvasEl.requestPointerLock) {
  48928. canvasEl.requestPointerLock();
  48929. } else if (canvasEl.mozRequestPointerLock) {
  48930. canvasEl.mozRequestPointerLock();
  48931. }
  48932. }
  48933. },
  48934. /**
  48935. * Shows grabbing cursor on scene
  48936. */
  48937. showGrabbingCursor: function () {
  48938. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  48939. },
  48940. /**
  48941. * Hides grabbing cursor on scene
  48942. */
  48943. hideGrabbingCursor: function () {
  48944. this.el.sceneEl.canvas.style.cursor = '';
  48945. },
  48946. /**
  48947. * Register mouse up to detect release of mouse drag.
  48948. */
  48949. onMouseUp: function () {
  48950. this.mouseDown = false;
  48951. this.hideGrabbingCursor();
  48952. },
  48953. /**
  48954. * Register touch down to detect touch drag.
  48955. */
  48956. onTouchStart: function (evt) {
  48957. if (evt.touches.length !== 1 ||
  48958. !this.data.touchEnabled ||
  48959. this.el.sceneEl.is('vr-mode')) { return; }
  48960. this.touchStart = {
  48961. x: evt.touches[0].pageX,
  48962. y: evt.touches[0].pageY
  48963. };
  48964. this.touchStarted = true;
  48965. },
  48966. /**
  48967. * Translate touch move to Y-axis rotation.
  48968. */
  48969. onTouchMove: function (evt) {
  48970. var direction;
  48971. var canvas = this.el.sceneEl.canvas;
  48972. var deltaY;
  48973. var yawObject = this.yawObject;
  48974. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  48975. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  48976. direction = this.data.reverseTouchDrag ? 1 : -1;
  48977. // Limit touch orientaion to to yaw (y axis).
  48978. yawObject.rotation.y -= deltaY * 0.5 * direction;
  48979. this.touchStart = {
  48980. x: evt.touches[0].pageX,
  48981. y: evt.touches[0].pageY
  48982. };
  48983. },
  48984. /**
  48985. * Register touch end to detect release of touch drag.
  48986. */
  48987. onTouchEnd: function () {
  48988. this.touchStarted = false;
  48989. },
  48990. /**
  48991. * Save pose.
  48992. */
  48993. onEnterVR: function () {
  48994. var sceneEl = this.el.sceneEl;
  48995. if (!sceneEl.checkHeadsetConnected()) { return; }
  48996. this.saveCameraPose();
  48997. this.el.object3D.position.set(0, 0, 0);
  48998. this.el.object3D.rotation.set(0, 0, 0);
  48999. if (sceneEl.hasWebXR) {
  49000. this.el.object3D.matrixAutoUpdate = false;
  49001. this.el.object3D.updateMatrix();
  49002. }
  49003. },
  49004. /**
  49005. * Restore the pose.
  49006. */
  49007. onExitVR: function () {
  49008. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  49009. this.restoreCameraPose();
  49010. this.previousHMDPosition.set(0, 0, 0);
  49011. this.el.object3D.matrixAutoUpdate = true;
  49012. },
  49013. /**
  49014. * Update Pointer Lock state.
  49015. */
  49016. onPointerLockChange: function () {
  49017. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  49018. },
  49019. /**
  49020. * Recover from Pointer Lock error.
  49021. */
  49022. onPointerLockError: function () {
  49023. this.pointerLocked = false;
  49024. },
  49025. // Exits pointer-locked mode.
  49026. exitPointerLock: function () {
  49027. document.exitPointerLock();
  49028. this.pointerLocked = false;
  49029. },
  49030. /**
  49031. * Toggle the feature of showing/hiding the grab cursor.
  49032. */
  49033. updateGrabCursor: function (enabled) {
  49034. var sceneEl = this.el.sceneEl;
  49035. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  49036. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  49037. if (!sceneEl.canvas) {
  49038. if (enabled) {
  49039. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  49040. } else {
  49041. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  49042. }
  49043. return;
  49044. }
  49045. if (enabled) {
  49046. enableGrabCursor();
  49047. return;
  49048. }
  49049. disableGrabCursor();
  49050. },
  49051. /**
  49052. * Save camera pose before entering VR to restore later if exiting.
  49053. */
  49054. saveCameraPose: function () {
  49055. var el = this.el;
  49056. this.savedPose.position.copy(el.object3D.position);
  49057. this.savedPose.rotation.copy(el.object3D.rotation);
  49058. this.hasSavedPose = true;
  49059. },
  49060. /**
  49061. * Reset camera pose to before entering VR.
  49062. */
  49063. restoreCameraPose: function () {
  49064. var el = this.el;
  49065. var savedPose = this.savedPose;
  49066. if (!this.hasSavedPose) { return; }
  49067. // Reset camera orientation.
  49068. el.object3D.position.copy(savedPose.position);
  49069. el.object3D.rotation.copy(savedPose.rotation);
  49070. this.hasSavedPose = false;
  49071. }
  49072. });
  49073. },{"../core/component":130,"../lib/three":178,"../utils/":204}],90:[function(_dereq_,module,exports){
  49074. var bind = _dereq_('../utils/bind');
  49075. var registerComponent = _dereq_('../core/component').registerComponent;
  49076. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49077. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49078. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49079. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49080. // See Profiles Registry:
  49081. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  49082. // TODO: Add a more robust system for deriving gamepad name.
  49083. var GAMEPAD_ID_PREFIX = 'magicleap';
  49084. var GAMEPAD_ID_SUFFIX = '-one';
  49085. var GAMEPAD_ID_COMPOSITE = GAMEPAD_ID_PREFIX + GAMEPAD_ID_SUFFIX;
  49086. var MAGICLEAP_CONTROLLER_MODEL_GLB_URL = 'https://cdn.aframe.io/controllers/magicleap/magicleap-one-controller.glb';
  49087. /**
  49088. * Button IDs:
  49089. * 0 - trigger
  49090. * 1 - grip
  49091. * 2 - touchpad
  49092. * 3 - menu (never dispatched on this layer)
  49093. *
  49094. * Axis:
  49095. * 0 - touchpad x axis
  49096. * 1 - touchpad y axis
  49097. */
  49098. var INPUT_MAPPING_WEBXR = {
  49099. axes: {touchpad: [0, 1]},
  49100. buttons: ['trigger', 'grip', 'touchpad', 'menu']
  49101. };
  49102. /**
  49103. * Magic Leap Controls
  49104. * Interface with Magic Leap control and map Gamepad events to controller
  49105. * buttons: trigger, grip, touchpad, and menu.
  49106. * Load a controller model.
  49107. */
  49108. module.exports.Component = registerComponent('magicleap-controls', {
  49109. schema: {
  49110. hand: {default: 'none'},
  49111. model: {default: true},
  49112. orientationOffset: {type: 'vec3'}
  49113. },
  49114. mapping: INPUT_MAPPING_WEBXR,
  49115. init: function () {
  49116. var self = this;
  49117. this.controllerPresent = false;
  49118. this.lastControllerCheck = 0;
  49119. this.onButtonChanged = bind(this.onButtonChanged, this);
  49120. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49121. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49122. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49123. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49124. this.previousButtonValues = {};
  49125. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49126. this.bindMethods();
  49127. },
  49128. update: function () {
  49129. var data = this.data;
  49130. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  49131. },
  49132. play: function () {
  49133. this.checkIfControllerPresent();
  49134. this.addControllersUpdateListener();
  49135. },
  49136. pause: function () {
  49137. this.removeEventListeners();
  49138. this.removeControllersUpdateListener();
  49139. },
  49140. bindMethods: function () {
  49141. this.onModelLoaded = bind(this.onModelLoaded, this);
  49142. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49143. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49144. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  49145. this.onAxisMoved = bind(this.onAxisMoved, this);
  49146. },
  49147. addEventListeners: function () {
  49148. var el = this.el;
  49149. el.addEventListener('buttonchanged', this.onButtonChanged);
  49150. el.addEventListener('buttondown', this.onButtonDown);
  49151. el.addEventListener('buttonup', this.onButtonUp);
  49152. el.addEventListener('touchstart', this.onButtonTouchStart);
  49153. el.addEventListener('touchend', this.onButtonTouchEnd);
  49154. el.addEventListener('axismove', this.onAxisMoved);
  49155. el.addEventListener('model-loaded', this.onModelLoaded);
  49156. this.controllerEventsActive = true;
  49157. },
  49158. removeEventListeners: function () {
  49159. var el = this.el;
  49160. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49161. el.removeEventListener('buttondown', this.onButtonDown);
  49162. el.removeEventListener('buttonup', this.onButtonUp);
  49163. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49164. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49165. el.removeEventListener('axismove', this.onAxisMoved);
  49166. el.removeEventListener('model-loaded', this.onModelLoaded);
  49167. this.controllerEventsActive = false;
  49168. },
  49169. checkIfControllerPresent: function () {
  49170. var data = this.data;
  49171. checkControllerPresentAndSetup(this, GAMEPAD_ID_COMPOSITE,
  49172. {index: this.controllerIndex, hand: data.hand});
  49173. },
  49174. injectTrackedControls: function () {
  49175. var el = this.el;
  49176. var data = this.data;
  49177. el.setAttribute('tracked-controls', {
  49178. // TODO: verify expected behavior between reserved prefixes.
  49179. idPrefix: GAMEPAD_ID_COMPOSITE,
  49180. hand: data.hand,
  49181. controller: this.controllerIndex,
  49182. orientationOffset: data.orientationOffset
  49183. });
  49184. // Load model.
  49185. if (!this.data.model) { return; }
  49186. this.el.setAttribute('gltf-model', MAGICLEAP_CONTROLLER_MODEL_GLB_URL);
  49187. },
  49188. addControllersUpdateListener: function () {
  49189. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49190. },
  49191. removeControllersUpdateListener: function () {
  49192. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49193. },
  49194. onControllersUpdate: function () {
  49195. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  49196. this.checkIfControllerPresent();
  49197. },
  49198. /**
  49199. * Rotate the trigger button based on how hard the trigger is pressed.
  49200. */
  49201. onButtonChanged: function (evt) {
  49202. var button = this.mapping.buttons[evt.detail.id];
  49203. var analogValue;
  49204. if (!button) { return; }
  49205. if (button === 'trigger') {
  49206. analogValue = evt.detail.state.value;
  49207. console.log('analog value of trigger press: ' + analogValue);
  49208. }
  49209. // Pass along changed event with button state, using button mapping for convenience.
  49210. this.el.emit(button + 'changed', evt.detail.state);
  49211. },
  49212. onModelLoaded: function (evt) {
  49213. var controllerObject3D = evt.detail.model;
  49214. // our glb scale is too large.
  49215. controllerObject3D.scale.set(0.01, 0.01, 0.01);
  49216. },
  49217. onAxisMoved: function (evt) {
  49218. emitIfAxesChanged(this, this.mapping.axes, evt);
  49219. },
  49220. updateModel: function (buttonName, evtName) {},
  49221. setButtonColor: function (buttonName, color) {}
  49222. });
  49223. },{"../core/component":130,"../utils/bind":198,"../utils/tracked-controls":213}],91:[function(_dereq_,module,exports){
  49224. /* global Promise */
  49225. var utils = _dereq_('../utils/');
  49226. var component = _dereq_('../core/component');
  49227. var THREE = _dereq_('../lib/three');
  49228. var shader = _dereq_('../core/shader');
  49229. var error = utils.debug('components:material:error');
  49230. var registerComponent = component.registerComponent;
  49231. var shaders = shader.shaders;
  49232. var shaderNames = shader.shaderNames;
  49233. /**
  49234. * Material component.
  49235. *
  49236. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  49237. * three.js's implementation of PBR. Another standard shading model is `flat` which
  49238. * uses MeshBasicMaterial.
  49239. */
  49240. module.exports.Component = registerComponent('material', {
  49241. schema: {
  49242. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  49243. depthTest: {default: true},
  49244. depthWrite: {default: true},
  49245. flatShading: {default: false},
  49246. npot: {default: false},
  49247. offset: {type: 'vec2', default: {x: 0, y: 0}},
  49248. opacity: {default: 1.0, min: 0.0, max: 1.0},
  49249. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  49250. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  49251. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  49252. transparent: {default: false},
  49253. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  49254. visible: {default: true},
  49255. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']},
  49256. dithering: {default: true}
  49257. },
  49258. init: function () {
  49259. this.material = null;
  49260. },
  49261. /**
  49262. * Update or create material.
  49263. *
  49264. * @param {object|null} oldData
  49265. */
  49266. update: function (oldData) {
  49267. var data = this.data;
  49268. if (!this.shader || data.shader !== oldData.shader) {
  49269. this.updateShader(data.shader);
  49270. }
  49271. this.shader.update(this.data);
  49272. this.updateMaterial(oldData);
  49273. },
  49274. updateSchema: function (data) {
  49275. var currentShader;
  49276. var newShader;
  49277. var schema;
  49278. var shader;
  49279. newShader = data && data.shader;
  49280. currentShader = this.oldData && this.oldData.shader;
  49281. shader = newShader || currentShader;
  49282. schema = shaders[shader] && shaders[shader].schema;
  49283. if (!schema) { error('Unknown shader schema ' + shader); }
  49284. if (currentShader && newShader === currentShader) { return; }
  49285. this.extendSchema(schema);
  49286. this.updateBehavior();
  49287. },
  49288. updateBehavior: function () {
  49289. var key;
  49290. var sceneEl = this.el.sceneEl;
  49291. var schema = this.schema;
  49292. var self = this;
  49293. var tickProperties;
  49294. function tickTime (time, delta) {
  49295. var key;
  49296. for (key in tickProperties) {
  49297. tickProperties[key] = time;
  49298. }
  49299. self.shader.update(tickProperties);
  49300. }
  49301. this.tick = undefined;
  49302. tickProperties = {};
  49303. for (key in schema) {
  49304. if (schema[key].type === 'time') {
  49305. this.tick = tickTime;
  49306. tickProperties[key] = true;
  49307. }
  49308. }
  49309. if (!sceneEl) { return; }
  49310. if (this.tick) {
  49311. sceneEl.addBehavior(this);
  49312. } else {
  49313. sceneEl.removeBehavior(this);
  49314. }
  49315. },
  49316. updateShader: function (shaderName) {
  49317. var data = this.data;
  49318. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  49319. var shaderInstance;
  49320. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  49321. // Get material from A-Frame shader.
  49322. shaderInstance = this.shader = new Shader();
  49323. shaderInstance.el = this.el;
  49324. shaderInstance.init(data);
  49325. this.setMaterial(shaderInstance.material);
  49326. this.updateSchema(data);
  49327. },
  49328. /**
  49329. * Set and update base material properties.
  49330. * Set `needsUpdate` when needed.
  49331. */
  49332. updateMaterial: function (oldData) {
  49333. var data = this.data;
  49334. var material = this.material;
  49335. var oldDataHasKeys;
  49336. // Base material properties.
  49337. material.alphaTest = data.alphaTest;
  49338. material.depthTest = data.depthTest !== false;
  49339. material.depthWrite = data.depthWrite !== false;
  49340. material.opacity = data.opacity;
  49341. material.flatShading = data.flatShading;
  49342. material.side = parseSide(data.side);
  49343. material.transparent = data.transparent !== false || data.opacity < 1.0;
  49344. material.vertexColors = parseVertexColors(data.vertexColors);
  49345. material.visible = data.visible;
  49346. material.blending = parseBlending(data.blending);
  49347. material.dithering = data.dithering;
  49348. // Check if material needs update.
  49349. for (oldDataHasKeys in oldData) { break; }
  49350. if (oldDataHasKeys &&
  49351. (oldData.alphaTest !== data.alphaTest ||
  49352. oldData.side !== data.side ||
  49353. oldData.vertexColors !== data.vertexColors)) {
  49354. material.needsUpdate = true;
  49355. }
  49356. },
  49357. /**
  49358. * Remove material on remove (callback).
  49359. * Dispose of it from memory and unsubscribe from scene updates.
  49360. */
  49361. remove: function () {
  49362. var defaultMaterial = new THREE.MeshBasicMaterial();
  49363. var material = this.material;
  49364. var object3D = this.el.getObject3D('mesh');
  49365. if (object3D) { object3D.material = defaultMaterial; }
  49366. disposeMaterial(material, this.system);
  49367. },
  49368. /**
  49369. * (Re)create new material. Has side-effects of setting `this.material` and updating
  49370. * material registration in scene.
  49371. *
  49372. * @param {object} data - Material component data.
  49373. * @param {object} type - Material type to create.
  49374. * @returns {object} Material.
  49375. */
  49376. setMaterial: function (material) {
  49377. var el = this.el;
  49378. var mesh;
  49379. var system = this.system;
  49380. if (this.material) { disposeMaterial(this.material, system); }
  49381. this.material = material;
  49382. system.registerMaterial(material);
  49383. // Set on mesh. If mesh does not exist, wait for it.
  49384. mesh = el.getObject3D('mesh');
  49385. if (mesh) {
  49386. mesh.material = material;
  49387. } else {
  49388. el.addEventListener('object3dset', function waitForMesh (evt) {
  49389. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  49390. el.getObject3D('mesh').material = material;
  49391. el.removeEventListener('object3dset', waitForMesh);
  49392. });
  49393. }
  49394. }
  49395. });
  49396. /**
  49397. * Return a three.js constant determining which material face sides to render
  49398. * based on the side parameter (passed as a component property).
  49399. *
  49400. * @param {string} [side=front] - `front`, `back`, or `double`.
  49401. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  49402. */
  49403. function parseSide (side) {
  49404. switch (side) {
  49405. case 'back': {
  49406. return THREE.BackSide;
  49407. }
  49408. case 'double': {
  49409. return THREE.DoubleSide;
  49410. }
  49411. default: {
  49412. // Including case `front`.
  49413. return THREE.FrontSide;
  49414. }
  49415. }
  49416. }
  49417. /**
  49418. * Return a three.js constant determining vertex coloring.
  49419. */
  49420. function parseVertexColors (coloring) {
  49421. switch (coloring) {
  49422. case 'face': {
  49423. return THREE.FaceColors;
  49424. }
  49425. case 'vertex': {
  49426. return THREE.VertexColors;
  49427. }
  49428. default: {
  49429. return THREE.NoColors;
  49430. }
  49431. }
  49432. }
  49433. /**
  49434. * Return a three.js constant determining blending
  49435. *
  49436. * @param {string} [blending=normal]
  49437. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  49438. * @returns {number}
  49439. */
  49440. function parseBlending (blending) {
  49441. switch (blending) {
  49442. case 'none': {
  49443. return THREE.NoBlending;
  49444. }
  49445. case 'additive': {
  49446. return THREE.AdditiveBlending;
  49447. }
  49448. case 'subtractive': {
  49449. return THREE.SubtractiveBlending;
  49450. }
  49451. case 'multiply': {
  49452. return THREE.MultiplyBlending;
  49453. }
  49454. default: {
  49455. return THREE.NormalBlending;
  49456. }
  49457. }
  49458. }
  49459. /**
  49460. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  49461. */
  49462. function disposeMaterial (material, system) {
  49463. material.dispose();
  49464. system.unregisterMaterial(material);
  49465. }
  49466. },{"../core/component":130,"../core/shader":140,"../lib/three":178,"../utils/":204}],92:[function(_dereq_,module,exports){
  49467. var debug = _dereq_('../utils/debug');
  49468. var registerComponent = _dereq_('../core/component').registerComponent;
  49469. var THREE = _dereq_('../lib/three');
  49470. var warn = debug('components:obj-model:warn');
  49471. module.exports.Component = registerComponent('obj-model', {
  49472. schema: {
  49473. mtl: {type: 'model'},
  49474. obj: {type: 'model'}
  49475. },
  49476. init: function () {
  49477. var self = this;
  49478. this.model = null;
  49479. this.objLoader = new THREE.OBJLoader();
  49480. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  49481. // Allow cross-origin images to be loaded.
  49482. this.mtlLoader.crossOrigin = '';
  49483. this.el.addEventListener('componentinitialized', function (evt) {
  49484. if (!self.model) { return; }
  49485. if (evt.detail.name !== 'material') { return; }
  49486. self.applyMaterial();
  49487. });
  49488. },
  49489. update: function () {
  49490. var data = this.data;
  49491. if (!data.obj) { return; }
  49492. this.resetMesh();
  49493. this.loadObj(data.obj, data.mtl);
  49494. },
  49495. remove: function () {
  49496. if (!this.model) { return; }
  49497. this.resetMesh();
  49498. },
  49499. resetMesh: function () {
  49500. this.el.removeObject3D('mesh');
  49501. },
  49502. loadObj: function (objUrl, mtlUrl) {
  49503. var self = this;
  49504. var el = this.el;
  49505. var mtlLoader = this.mtlLoader;
  49506. var objLoader = this.objLoader;
  49507. var rendererSystem = this.el.sceneEl.systems.renderer;
  49508. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  49509. if (mtlUrl) {
  49510. // .OBJ with an .MTL.
  49511. if (el.hasAttribute('material')) {
  49512. warn('Material component properties are ignored when a .MTL is provided');
  49513. }
  49514. mtlLoader.setResourcePath(BASE_PATH);
  49515. mtlLoader.load(mtlUrl, function (materials) {
  49516. materials.preload();
  49517. objLoader.setMaterials(materials);
  49518. objLoader.load(objUrl, function (objModel) {
  49519. self.model = objModel;
  49520. self.model.traverse(function (object) {
  49521. if (object.isMesh) {
  49522. var material = object.material;
  49523. if (material.color) rendererSystem.applyColorCorrection(material.color);
  49524. if (material.map) rendererSystem.applyColorCorrection(material.map);
  49525. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  49526. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  49527. }
  49528. });
  49529. el.setObject3D('mesh', objModel);
  49530. el.emit('model-loaded', {format: 'obj', model: objModel});
  49531. });
  49532. });
  49533. return;
  49534. }
  49535. // .OBJ only.
  49536. objLoader.load(objUrl, function loadObjOnly (objModel) {
  49537. self.model = objModel;
  49538. self.applyMaterial();
  49539. el.setObject3D('mesh', objModel);
  49540. el.emit('model-loaded', {format: 'obj', model: objModel});
  49541. });
  49542. },
  49543. /**
  49544. * Apply material from material component recursively.
  49545. */
  49546. applyMaterial: function () {
  49547. var material = this.el.components.material;
  49548. if (!material) { return; }
  49549. this.model.traverse(function (child) {
  49550. if (child instanceof THREE.Mesh) {
  49551. child.material = material.material;
  49552. }
  49553. });
  49554. }
  49555. });
  49556. },{"../core/component":130,"../lib/three":178,"../utils/debug":200}],93:[function(_dereq_,module,exports){
  49557. var registerComponent = _dereq_('../core/component').registerComponent;
  49558. var bind = _dereq_('../utils/bind');
  49559. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49560. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49561. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49562. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49563. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  49564. var GAMEPAD_ID_WEBXR = 'oculus-go';
  49565. var GAMEPAD_ID_WEBVR = 'Oculus Go';
  49566. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  49567. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  49568. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  49569. /**
  49570. * Button indices:
  49571. * 0 - trackpad
  49572. * 1 - trigger
  49573. *
  49574. * Axis:
  49575. * 0 - trackpad x
  49576. * 1 - trackpad y
  49577. */
  49578. var INPUT_MAPPING_WEBVR = {
  49579. axes: {trackpad: [0, 1]},
  49580. buttons: ['trackpad', 'trigger']
  49581. };
  49582. /**
  49583. * Button indices:
  49584. * 0 - trigger
  49585. * 1 - none
  49586. * 2 - touchpad
  49587. *
  49588. * Axis:
  49589. * 0 - touchpad x
  49590. * 1 - touchpad y
  49591. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  49592. */
  49593. var INPUT_MAPPING_WEBXR = {
  49594. axes: {touchpad: [0, 1]},
  49595. buttons: ['trigger', 'none', 'touchpad']
  49596. };
  49597. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  49598. /**
  49599. * Oculus Go controls.
  49600. * Interface with Oculus Go controller and map Gamepad events to
  49601. * controller buttons: trackpad, trigger
  49602. * Load a controller model and highlight the pressed buttons.
  49603. */
  49604. module.exports.Component = registerComponent('oculus-go-controls', {
  49605. schema: {
  49606. hand: {default: ''}, // This informs the degenerate arm model.
  49607. buttonColor: {type: 'color', default: '#FFFFFF'},
  49608. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  49609. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  49610. model: {default: true},
  49611. orientationOffset: {type: 'vec3'},
  49612. armModel: {default: true}
  49613. },
  49614. mapping: INPUT_MAPPING,
  49615. bindMethods: function () {
  49616. this.onModelLoaded = bind(this.onModelLoaded, this);
  49617. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49618. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49619. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  49620. this.onAxisMoved = bind(this.onAxisMoved, this);
  49621. },
  49622. init: function () {
  49623. var self = this;
  49624. this.onButtonChanged = bind(this.onButtonChanged, this);
  49625. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49626. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49627. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49628. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49629. this.controllerPresent = false;
  49630. this.lastControllerCheck = 0;
  49631. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49632. this.bindMethods();
  49633. },
  49634. addEventListeners: function () {
  49635. var el = this.el;
  49636. el.addEventListener('buttonchanged', this.onButtonChanged);
  49637. el.addEventListener('buttondown', this.onButtonDown);
  49638. el.addEventListener('buttonup', this.onButtonUp);
  49639. el.addEventListener('touchstart', this.onButtonTouchStart);
  49640. el.addEventListener('touchend', this.onButtonTouchEnd);
  49641. el.addEventListener('model-loaded', this.onModelLoaded);
  49642. el.addEventListener('axismove', this.onAxisMoved);
  49643. this.controllerEventsActive = true;
  49644. },
  49645. removeEventListeners: function () {
  49646. var el = this.el;
  49647. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49648. el.removeEventListener('buttondown', this.onButtonDown);
  49649. el.removeEventListener('buttonup', this.onButtonUp);
  49650. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49651. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49652. el.removeEventListener('model-loaded', this.onModelLoaded);
  49653. el.removeEventListener('axismove', this.onAxisMoved);
  49654. this.controllerEventsActive = false;
  49655. },
  49656. checkIfControllerPresent: function () {
  49657. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  49658. this.data.hand ? {hand: this.data.hand} : {});
  49659. },
  49660. play: function () {
  49661. this.checkIfControllerPresent();
  49662. this.addControllersUpdateListener();
  49663. },
  49664. pause: function () {
  49665. this.removeEventListeners();
  49666. this.removeControllersUpdateListener();
  49667. },
  49668. injectTrackedControls: function () {
  49669. var el = this.el;
  49670. var data = this.data;
  49671. el.setAttribute('tracked-controls', {
  49672. armModel: data.armModel,
  49673. hand: data.hand,
  49674. idPrefix: GAMEPAD_ID_PREFIX,
  49675. orientationOffset: data.orientationOffset
  49676. });
  49677. if (!this.data.model) { return; }
  49678. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  49679. },
  49680. addControllersUpdateListener: function () {
  49681. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49682. },
  49683. removeControllersUpdateListener: function () {
  49684. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49685. },
  49686. onControllersUpdate: function () {
  49687. this.checkIfControllerPresent();
  49688. },
  49689. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  49690. onModelLoaded: function (evt) {
  49691. var controllerObject3D = evt.detail.model;
  49692. var buttonMeshes;
  49693. if (!this.data.model) { return; }
  49694. buttonMeshes = this.buttonMeshes = {};
  49695. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  49696. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  49697. buttonMeshes.touchpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  49698. },
  49699. onButtonChanged: function (evt) {
  49700. var button = this.mapping.buttons[evt.detail.id];
  49701. if (!button) return;
  49702. // Pass along changed event with button state, using button mapping for convenience.
  49703. this.el.emit(button + 'changed', evt.detail.state);
  49704. },
  49705. onAxisMoved: function (evt) {
  49706. emitIfAxesChanged(this, this.mapping.axes, evt);
  49707. },
  49708. updateModel: function (buttonName, evtName) {
  49709. if (!this.data.model) { return; }
  49710. this.updateButtonModel(buttonName, evtName);
  49711. },
  49712. updateButtonModel: function (buttonName, state) {
  49713. var buttonMeshes = this.buttonMeshes;
  49714. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  49715. var color;
  49716. var button;
  49717. switch (state) {
  49718. case 'down':
  49719. color = this.data.buttonHighlightColor;
  49720. break;
  49721. case 'touchstart':
  49722. color = this.data.buttonTouchedColor;
  49723. break;
  49724. default:
  49725. color = this.data.buttonColor;
  49726. }
  49727. button = buttonMeshes[buttonName];
  49728. button.material.color.set(color);
  49729. this.rendererSystem.applyColorCorrection(button.material.color);
  49730. }
  49731. });
  49732. },{"../core/component":130,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],94:[function(_dereq_,module,exports){
  49733. var bind = _dereq_('../utils/bind');
  49734. var registerComponent = _dereq_('../core/component').registerComponent;
  49735. var THREE = _dereq_('../lib/three');
  49736. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49737. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49738. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49739. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49740. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  49741. var GAMEPAD_ID_WEBXR = 'oculus-touch';
  49742. var GAMEPAD_ID_WEBVR = 'Oculus Touch';
  49743. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  49744. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  49745. // First generation model URL.
  49746. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  49747. var OCULUS_TOUCH_WEBVR = {
  49748. left: {
  49749. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  49750. rayOrigin: {origin: {x: 0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  49751. modelPivotOffset: new THREE.Vector3(-0.005, 0.003, -0.055),
  49752. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49753. },
  49754. right: {
  49755. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  49756. rayOrigin: {origin: {x: -0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  49757. modelPivotOffset: new THREE.Vector3(0.005, 0.003, -0.055),
  49758. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49759. }
  49760. };
  49761. var OCULUS_TOUCH_WEBXR = {
  49762. left: {
  49763. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  49764. rayOrigin: {origin: {x: 0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  49765. modelPivotOffset: new THREE.Vector3(-0.005, 0.036, -0.037),
  49766. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  49767. },
  49768. right: {
  49769. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  49770. rayOrigin: {origin: {x: -0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  49771. modelPivotOffset: new THREE.Vector3(0.005, 0.036, -0.037),
  49772. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  49773. }
  49774. };
  49775. var OCULUS_TOUCH_CONFIG = isWebXRAvailable ? OCULUS_TOUCH_WEBXR : OCULUS_TOUCH_WEBVR;
  49776. var CONTROLLER_DEFAULT = 'oculus-touch';
  49777. var CONTROLLER_PROPERTIES = {
  49778. 'oculus-touch': OCULUS_TOUCH_CONFIG,
  49779. 'oculus-touch-v2': {
  49780. left: {
  49781. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-left.gltf',
  49782. rayOrigin: {origin: {x: -0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  49783. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  49784. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49785. },
  49786. right: {
  49787. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-right.gltf',
  49788. rayOrigin: {origin: {x: 0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  49789. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  49790. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49791. }
  49792. },
  49793. 'oculus-touch-v3': {
  49794. left: {
  49795. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-left.glb',
  49796. rayOrigin: {origin: {x: 0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  49797. modelPivotOffset: new THREE.Vector3(0.01, -0.01, 0.05),
  49798. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  49799. },
  49800. right: {
  49801. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-right.glb',
  49802. rayOrigin: {origin: {x: -0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  49803. modelPivotOffset: new THREE.Vector3(-0.01, -0.01, 0.05),
  49804. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  49805. }
  49806. }
  49807. };
  49808. /**
  49809. * Button indices:
  49810. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  49811. * 1 - trigger (with analog value, which goes up to 1)
  49812. * 2 - grip (with analog value, which goes up to 1)
  49813. * 3 - X (left) or A (right)
  49814. * 4 - Y (left) or B (right)
  49815. * 5 - surface (touch only)
  49816. */
  49817. var INPUT_MAPPING_WEBVR = {
  49818. left: {
  49819. axes: {thumbstick: [0, 1]},
  49820. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  49821. },
  49822. right: {
  49823. axes: {thumbstick: [0, 1]},
  49824. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  49825. }
  49826. };
  49827. /**
  49828. * Button indices:
  49829. * 0 - trigger
  49830. * 1 - grip
  49831. * 2 - none
  49832. * 3 - thumbstick
  49833. * 4 - X or A button
  49834. * 5 - Y or B button
  49835. * 6 - surface
  49836. *
  49837. * Axis:
  49838. * 0 - none
  49839. * 1 - none
  49840. * 2 - thumbstick
  49841. * 3 - thumbstick
  49842. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-touch.json
  49843. */
  49844. var INPUT_MAPPING_WEBXR = {
  49845. left: {
  49846. axes: {thumbstick: [2, 3]},
  49847. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton', 'surface']
  49848. },
  49849. right: {
  49850. axes: {thumbstick: [2, 3]},
  49851. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton', 'surface']
  49852. }
  49853. };
  49854. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  49855. /**
  49856. * Oculus Touch controls.
  49857. * Interface with Oculus Touch controllers and map Gamepad events to
  49858. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  49859. * Load a controller model and highlight the pressed buttons.
  49860. */
  49861. module.exports.Component = registerComponent('oculus-touch-controls', {
  49862. schema: {
  49863. hand: {default: 'left'},
  49864. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  49865. buttonTouchColor: {type: 'color', default: '#8AB'},
  49866. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  49867. model: {default: true},
  49868. controllerType: {default: 'auto', oneOf: ['auto', 'oculus-touch', 'oculus-touch-v2', 'oculus-touch-v3']},
  49869. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  49870. },
  49871. mapping: INPUT_MAPPING,
  49872. bindMethods: function () {
  49873. this.onModelLoaded = bind(this.onModelLoaded, this);
  49874. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49875. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49876. this.onAxisMoved = bind(this.onAxisMoved, this);
  49877. },
  49878. init: function () {
  49879. var self = this;
  49880. this.onButtonChanged = bind(this.onButtonChanged, this);
  49881. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  49882. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  49883. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  49884. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  49885. this.controllerPresent = false;
  49886. this.lastControllerCheck = 0;
  49887. this.previousButtonValues = {};
  49888. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49889. this.bindMethods();
  49890. },
  49891. addEventListeners: function () {
  49892. var el = this.el;
  49893. el.addEventListener('buttonchanged', this.onButtonChanged);
  49894. el.addEventListener('buttondown', this.onButtonDown);
  49895. el.addEventListener('buttonup', this.onButtonUp);
  49896. el.addEventListener('touchstart', this.onButtonTouchStart);
  49897. el.addEventListener('touchend', this.onButtonTouchEnd);
  49898. el.addEventListener('axismove', this.onAxisMoved);
  49899. el.addEventListener('model-loaded', this.onModelLoaded);
  49900. this.controllerEventsActive = true;
  49901. },
  49902. removeEventListeners: function () {
  49903. var el = this.el;
  49904. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49905. el.removeEventListener('buttondown', this.onButtonDown);
  49906. el.removeEventListener('buttonup', this.onButtonUp);
  49907. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49908. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49909. el.removeEventListener('axismove', this.onAxisMoved);
  49910. el.removeEventListener('model-loaded', this.onModelLoaded);
  49911. this.controllerEventsActive = false;
  49912. },
  49913. checkIfControllerPresent: function () {
  49914. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  49915. hand: this.data.hand
  49916. });
  49917. },
  49918. play: function () {
  49919. this.checkIfControllerPresent();
  49920. this.addControllersUpdateListener();
  49921. },
  49922. pause: function () {
  49923. this.removeEventListeners();
  49924. this.removeControllersUpdateListener();
  49925. },
  49926. loadModel: function (controller) {
  49927. var data = this.data;
  49928. var controllerId;
  49929. if (!data.model) { return; }
  49930. // Set the controller display model based on the data passed in.
  49931. this.displayModel = CONTROLLER_PROPERTIES[data.controllerType] || CONTROLLER_PROPERTIES[CONTROLLER_DEFAULT];
  49932. // If the developer is asking for auto-detection, see if the displayName can be retrieved to identify the specific unit.
  49933. // This only works for WebVR currently.
  49934. if (data.controllerType === 'auto') {
  49935. var trackedControlsSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
  49936. // WebVR
  49937. if (trackedControlsSystem && trackedControlsSystem.vrDisplay) {
  49938. var displayName = trackedControlsSystem.vrDisplay.displayName;
  49939. // The Oculus Quest uses the updated generation 2 inside-out tracked controllers so update the displayModel.
  49940. if (/^Oculus Quest$/.test(displayName)) {
  49941. this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2'];
  49942. }
  49943. } else { // WebXR
  49944. controllerId = CONTROLLER_DEFAULT;
  49945. controllerId = controller.profiles.indexOf('oculus-touch-v2') !== -1 ? 'oculus-touch-v2' : controllerId;
  49946. controllerId = controller.profiles.indexOf('oculus-touch-v3') !== -1 ? 'oculus-touch-v3' : controllerId;
  49947. this.displayModel = CONTROLLER_PROPERTIES[controllerId];
  49948. }
  49949. }
  49950. var modelUrl = this.displayModel[data.hand].modelUrl;
  49951. this.el.setAttribute('gltf-model', modelUrl);
  49952. },
  49953. injectTrackedControls: function (controller) {
  49954. var data = this.data;
  49955. var webXRId = GAMEPAD_ID_WEBXR;
  49956. var webVRId = data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)';
  49957. var id = isWebXRAvailable ? webXRId : webVRId;
  49958. this.el.setAttribute('tracked-controls', {
  49959. id: id,
  49960. hand: data.hand,
  49961. orientationOffset: data.orientationOffset,
  49962. handTrackingEnabled: false
  49963. });
  49964. this.loadModel(controller);
  49965. },
  49966. addControllersUpdateListener: function () {
  49967. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49968. },
  49969. removeControllersUpdateListener: function () {
  49970. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49971. },
  49972. onControllersUpdate: function () {
  49973. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  49974. this.checkIfControllerPresent();
  49975. },
  49976. onButtonChanged: function (evt) {
  49977. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  49978. var buttonMeshes = this.buttonMeshes;
  49979. var analogValue;
  49980. if (!button) { return; }
  49981. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  49982. // Update trigger and/or grip meshes, if any.
  49983. if (buttonMeshes) {
  49984. if (button === 'trigger' && buttonMeshes.trigger) {
  49985. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  49986. }
  49987. if (button === 'grip' && buttonMeshes.grip) {
  49988. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  49989. }
  49990. }
  49991. // Pass along changed event with button state, using the buttom mapping for convenience.
  49992. this.el.emit(button + 'changed', evt.detail.state);
  49993. },
  49994. onModelLoaded: function (evt) {
  49995. var controllerObject3D = this.controllerObject3D = evt.detail.model;
  49996. var buttonMeshes;
  49997. if (!this.data.model) { return; }
  49998. buttonMeshes = this.buttonMeshes = {};
  49999. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  50000. this.originalXPositionGrip = buttonMeshes.grip && buttonMeshes.grip.position.x;
  50001. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  50002. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  50003. this.originalXRotationTrigger = buttonMeshes.trigger && buttonMeshes.trigger.rotation.x;
  50004. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  50005. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  50006. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  50007. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  50008. // Offset pivot point
  50009. controllerObject3D.position.copy(this.displayModel[this.data.hand].modelPivotOffset);
  50010. controllerObject3D.rotation.copy(this.displayModel[this.data.hand].modelPivotRotation);
  50011. this.el.emit('controllermodelready', {
  50012. name: 'oculus-touch-controls',
  50013. model: this.data.model,
  50014. rayOrigin: this.displayModel[this.data.hand].rayOrigin
  50015. });
  50016. },
  50017. onAxisMoved: function (evt) {
  50018. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  50019. },
  50020. updateModel: function (buttonName, evtName) {
  50021. if (!this.data.model) { return; }
  50022. this.updateButtonModel(buttonName, evtName);
  50023. },
  50024. updateButtonModel: function (buttonName, state) {
  50025. var button;
  50026. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  50027. var buttonMeshes = this.buttonMeshes;
  50028. if (!this.data.model) { return; }
  50029. if (buttonMeshes && buttonMeshes[buttonName]) {
  50030. button = buttonMeshes[buttonName];
  50031. button.material.color.set(color);
  50032. this.rendererSystem.applyColorCorrection(button.material.color);
  50033. }
  50034. }
  50035. });
  50036. },{"../core/component":130,"../lib/three":178,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],95:[function(_dereq_,module,exports){
  50037. var registerComponent = _dereq_('../core/component').registerComponent;
  50038. module.exports.Component = registerComponent('position', {
  50039. schema: {type: 'vec3'},
  50040. update: function () {
  50041. var object3D = this.el.object3D;
  50042. var data = this.data;
  50043. object3D.position.set(data.x, data.y, data.z);
  50044. },
  50045. remove: function () {
  50046. // Pretty much for mixins.
  50047. this.el.object3D.position.set(0, 0, 0);
  50048. }
  50049. });
  50050. },{"../core/component":130}],96:[function(_dereq_,module,exports){
  50051. /* global MutationObserver */
  50052. var registerComponent = _dereq_('../core/component').registerComponent;
  50053. var THREE = _dereq_('../lib/three');
  50054. var utils = _dereq_('../utils/');
  50055. var warn = utils.debug('components:raycaster:warn');
  50056. // Defines selectors that should be 'safe' for the MutationObserver used to
  50057. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  50058. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  50059. // reliably detected and are therefore disallowed.
  50060. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  50061. // Configuration for the MutationObserver used to refresh the whitelist.
  50062. // Listens for addition/removal of elements and attributes within the scene.
  50063. var OBSERVER_CONFIG = {
  50064. childList: true,
  50065. attributes: true,
  50066. subtree: true
  50067. };
  50068. var EVENTS = {
  50069. INTERSECT: 'raycaster-intersected',
  50070. INTERSECTION: 'raycaster-intersection',
  50071. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  50072. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  50073. };
  50074. /**
  50075. * Raycaster component.
  50076. *
  50077. * Pass options to three.js Raycaster including which objects to test.
  50078. * Poll for intersections.
  50079. * Emit event on origin entity and on target entity on intersect.
  50080. *
  50081. * @member {array} intersectedEls - List of currently intersected entities.
  50082. * @member {array} objects - Cached list of meshes to intersect.
  50083. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  50084. * @member {object} raycaster - three.js Raycaster.
  50085. */
  50086. module.exports.Component = registerComponent('raycaster', {
  50087. schema: {
  50088. autoRefresh: {default: true},
  50089. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  50090. enabled: {default: true},
  50091. far: {default: 1000},
  50092. interval: {default: 0},
  50093. near: {default: 0},
  50094. objects: {default: ''},
  50095. origin: {type: 'vec3'},
  50096. showLine: {default: false},
  50097. lineColor: {default: 'white'},
  50098. lineOpacity: {default: 1},
  50099. useWorldCoordinates: {default: false}
  50100. },
  50101. multiple: true,
  50102. init: function () {
  50103. this.clearedIntersectedEls = [];
  50104. this.unitLineEndVec3 = new THREE.Vector3();
  50105. this.intersectedEls = [];
  50106. this.intersections = [];
  50107. this.newIntersectedEls = [];
  50108. this.newIntersections = [];
  50109. this.objects = [];
  50110. this.prevCheckTime = undefined;
  50111. this.prevIntersectedEls = [];
  50112. this.rawIntersections = [];
  50113. this.raycaster = new THREE.Raycaster();
  50114. this.updateOriginDirection();
  50115. this.setDirty = this.setDirty.bind(this);
  50116. this.updateLine = this.updateLine.bind(this);
  50117. this.observer = new MutationObserver(this.setDirty);
  50118. this.dirty = true;
  50119. this.lineEndVec3 = new THREE.Vector3();
  50120. this.otherLineEndVec3 = new THREE.Vector3();
  50121. this.lineData = {end: this.lineEndVec3};
  50122. this.getIntersection = this.getIntersection.bind(this);
  50123. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  50124. this.intersectedClearedDetail = {el: this.el};
  50125. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  50126. this.intersectionDetail = {};
  50127. },
  50128. /**
  50129. * Create or update raycaster object.
  50130. */
  50131. update: function (oldData) {
  50132. var data = this.data;
  50133. var el = this.el;
  50134. var raycaster = this.raycaster;
  50135. // Set raycaster properties.
  50136. raycaster.far = data.far;
  50137. raycaster.near = data.near;
  50138. // Draw line.
  50139. if (data.showLine &&
  50140. (data.far !== oldData.far || data.origin !== oldData.origin ||
  50141. data.direction !== oldData.direction || !oldData.showLine)) {
  50142. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  50143. // adjust line length.
  50144. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  50145. this.drawLine();
  50146. }
  50147. if (!data.showLine && oldData.showLine) {
  50148. el.removeAttribute('line');
  50149. }
  50150. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  50151. warn('[raycaster] Selector "' + data.objects +
  50152. '" may not update automatically with DOM changes.');
  50153. }
  50154. if (!data.objects) {
  50155. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  50156. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  50157. 'e.g., raycaster="objects: [data-raycastable]".');
  50158. }
  50159. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  50160. data.autoRefresh
  50161. ? this.addEventListeners()
  50162. : this.removeEventListeners();
  50163. }
  50164. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  50165. this.setDirty();
  50166. },
  50167. play: function () {
  50168. this.addEventListeners();
  50169. },
  50170. pause: function () {
  50171. this.removeEventListeners();
  50172. },
  50173. remove: function () {
  50174. if (this.data.showLine) {
  50175. this.el.removeAttribute('line');
  50176. }
  50177. this.clearAllIntersections();
  50178. },
  50179. addEventListeners: function () {
  50180. if (!this.data.autoRefresh) { return; }
  50181. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  50182. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  50183. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  50184. },
  50185. removeEventListeners: function () {
  50186. this.observer.disconnect();
  50187. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  50188. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  50189. },
  50190. /**
  50191. * Mark the object list as dirty, to be refreshed before next raycast.
  50192. */
  50193. setDirty: function () {
  50194. this.dirty = true;
  50195. },
  50196. /**
  50197. * Update list of objects to test for intersection.
  50198. */
  50199. refreshObjects: function () {
  50200. var data = this.data;
  50201. var els;
  50202. // If objects not defined, intersect with everything.
  50203. els = data.objects
  50204. ? this.el.sceneEl.querySelectorAll(data.objects)
  50205. : this.el.sceneEl.querySelectorAll('*');
  50206. this.objects = this.flattenObject3DMaps(els);
  50207. this.dirty = false;
  50208. },
  50209. /**
  50210. * Check for intersections and cleared intersections on an interval.
  50211. */
  50212. tock: function (time) {
  50213. var data = this.data;
  50214. var prevCheckTime = this.prevCheckTime;
  50215. if (!data.enabled) { return; }
  50216. // Only check for intersection if interval time has passed.
  50217. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  50218. // Update check time.
  50219. this.prevCheckTime = time;
  50220. this.checkIntersections();
  50221. },
  50222. /**
  50223. * Raycast for intersections and emit events for current and cleared intersections.
  50224. */
  50225. checkIntersections: function () {
  50226. var clearedIntersectedEls = this.clearedIntersectedEls;
  50227. var el = this.el;
  50228. var data = this.data;
  50229. var i;
  50230. var intersectedEls = this.intersectedEls;
  50231. var intersection;
  50232. var intersections = this.intersections;
  50233. var newIntersectedEls = this.newIntersectedEls;
  50234. var newIntersections = this.newIntersections;
  50235. var prevIntersectedEls = this.prevIntersectedEls;
  50236. var rawIntersections = this.rawIntersections;
  50237. // Refresh the object whitelist if needed.
  50238. if (this.dirty) { this.refreshObjects(); }
  50239. // Store old previously intersected entities.
  50240. copyArray(this.prevIntersectedEls, this.intersectedEls);
  50241. // Raycast.
  50242. this.updateOriginDirection();
  50243. rawIntersections.length = 0;
  50244. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  50245. // Only keep intersections against objects that have a reference to an entity.
  50246. intersections.length = 0;
  50247. intersectedEls.length = 0;
  50248. for (i = 0; i < rawIntersections.length; i++) {
  50249. intersection = rawIntersections[i];
  50250. // Don't intersect with own line.
  50251. if (data.showLine && intersection.object === el.getObject3D('line')) {
  50252. continue;
  50253. }
  50254. if (intersection.object.el) {
  50255. intersections.push(intersection);
  50256. intersectedEls.push(intersection.object.el);
  50257. }
  50258. }
  50259. // Get newly intersected entities.
  50260. newIntersections.length = 0;
  50261. newIntersectedEls.length = 0;
  50262. for (i = 0; i < intersections.length; i++) {
  50263. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  50264. newIntersections.push(intersections[i]);
  50265. newIntersectedEls.push(intersections[i].object.el);
  50266. }
  50267. }
  50268. // Emit intersection cleared on both entities per formerly intersected entity.
  50269. clearedIntersectedEls.length = 0;
  50270. for (i = 0; i < prevIntersectedEls.length; i++) {
  50271. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  50272. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  50273. this.intersectedClearedDetail);
  50274. clearedIntersectedEls.push(prevIntersectedEls[i]);
  50275. }
  50276. if (clearedIntersectedEls.length) {
  50277. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  50278. }
  50279. // Emit intersected on intersected entity per intersected entity.
  50280. for (i = 0; i < newIntersectedEls.length; i++) {
  50281. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  50282. }
  50283. // Emit all intersections at once on raycasting entity.
  50284. if (newIntersections.length) {
  50285. this.intersectionDetail.els = newIntersectedEls;
  50286. this.intersectionDetail.intersections = newIntersections;
  50287. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  50288. }
  50289. // Update line length.
  50290. if (data.showLine) { setTimeout(this.updateLine); }
  50291. },
  50292. updateLine: function () {
  50293. var el = this.el;
  50294. var intersections = this.intersections;
  50295. var lineLength;
  50296. if (intersections.length) {
  50297. if (intersections[0].object.el === el && intersections[1]) {
  50298. lineLength = intersections[1].distance;
  50299. } else {
  50300. lineLength = intersections[0].distance;
  50301. }
  50302. }
  50303. this.drawLine(lineLength);
  50304. },
  50305. /**
  50306. * Return the most recent intersection details for a given entity, if any.
  50307. * @param {AEntity} el
  50308. * @return {Object}
  50309. */
  50310. getIntersection: function (el) {
  50311. var i;
  50312. var intersection;
  50313. for (i = 0; i < this.intersections.length; i++) {
  50314. intersection = this.intersections[i];
  50315. if (intersection.object.el === el) { return intersection; }
  50316. }
  50317. return null;
  50318. },
  50319. /**
  50320. * Update origin and direction of raycaster using entity transforms and supplied origin or
  50321. * direction offsets.
  50322. */
  50323. updateOriginDirection: (function () {
  50324. var direction = new THREE.Vector3();
  50325. var originVec3 = new THREE.Vector3();
  50326. // Closure to make quaternion/vector3 objects private.
  50327. return function updateOriginDirection () {
  50328. var el = this.el;
  50329. var data = this.data;
  50330. if (data.useWorldCoordinates) {
  50331. this.raycaster.set(data.origin, data.direction);
  50332. return;
  50333. }
  50334. el.object3D.updateMatrixWorld();
  50335. originVec3.setFromMatrixPosition(el.object3D.matrixWorld);
  50336. // If non-zero origin, translate the origin into world space.
  50337. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  50338. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  50339. }
  50340. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  50341. // provide. Apply the offset to the direction, then rotation from the object,
  50342. // and normalize.
  50343. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  50344. // Apply offset and direction, in world coordinates.
  50345. this.raycaster.set(originVec3, direction);
  50346. };
  50347. })(),
  50348. /**
  50349. * Create or update line to give raycaster visual representation.
  50350. * Customize the line through through line component.
  50351. * We draw the line in the raycaster component to customize the line to the
  50352. * raycaster's origin, direction, and far.
  50353. *
  50354. * Unlike the raycaster, we create the line as a child of the object. The line will
  50355. * be affected by the transforms of the objects, so we don't have to calculate transforms
  50356. * like we do with the raycaster.
  50357. *
  50358. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  50359. * point. If not provided, length will default to the max length, `raycaster.far`.
  50360. */
  50361. drawLine: function (length) {
  50362. var data = this.data;
  50363. var el = this.el;
  50364. var endVec3;
  50365. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  50366. endVec3 = this.lineData.end === this.lineEndVec3
  50367. ? this.otherLineEndVec3
  50368. : this.lineEndVec3;
  50369. // Treat Infinity as 1000m for the line.
  50370. if (length === undefined) {
  50371. length = data.far === Infinity ? 1000 : data.far;
  50372. }
  50373. // Update the length of the line if given. `unitLineEndVec3` is the direction
  50374. // given by data.direction, then we apply a scalar to give it a length.
  50375. this.lineData.start = data.origin;
  50376. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  50377. this.lineData.color = data.lineColor;
  50378. this.lineData.opacity = data.lineOpacity;
  50379. el.setAttribute('line', this.lineData);
  50380. },
  50381. /**
  50382. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  50383. * Children are flattened by one level, removing the THREE.Group wrapper,
  50384. * so that non-recursive raycasting remains useful.
  50385. *
  50386. * Only push children defined as component attachements (e.g., setObject3D),
  50387. * NOT actual children in the scene graph hierarchy.
  50388. *
  50389. * @param {Array<Element>} els
  50390. * @return {Array<THREE.Object3D>}
  50391. */
  50392. flattenObject3DMaps: function (els) {
  50393. var key;
  50394. var i;
  50395. var objects = this.objects;
  50396. // Push meshes and other attachments onto list of objects to intersect.
  50397. objects.length = 0;
  50398. for (i = 0; i < els.length; i++) {
  50399. if (els[i].isEntity && els[i].object3D) {
  50400. for (key in els[i].object3DMap) {
  50401. objects.push(els[i].getObject3D(key));
  50402. }
  50403. }
  50404. }
  50405. return objects;
  50406. },
  50407. clearAllIntersections: function () {
  50408. var i;
  50409. for (i = 0; i < this.intersectedEls.length; i++) {
  50410. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  50411. this.intersectedClearedDetail);
  50412. }
  50413. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  50414. this.intersectedEls.length = 0;
  50415. this.intersections.length = 0;
  50416. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  50417. }
  50418. });
  50419. /**
  50420. * Copy contents of one array to another without allocating new array.
  50421. */
  50422. function copyArray (a, b) {
  50423. var i;
  50424. a.length = b.length;
  50425. for (i = 0; i < b.length; i++) {
  50426. a[i] = b[i];
  50427. }
  50428. }
  50429. },{"../core/component":130,"../lib/three":178,"../utils/":204}],97:[function(_dereq_,module,exports){
  50430. var degToRad = _dereq_('../lib/three').Math.degToRad;
  50431. var registerComponent = _dereq_('../core/component').registerComponent;
  50432. module.exports.Component = registerComponent('rotation', {
  50433. schema: {type: 'vec3'},
  50434. /**
  50435. * Updates object3D rotation.
  50436. */
  50437. update: function () {
  50438. var data = this.data;
  50439. var object3D = this.el.object3D;
  50440. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  50441. object3D.rotation.order = 'YXZ';
  50442. },
  50443. remove: function () {
  50444. // Pretty much for mixins.
  50445. this.el.object3D.rotation.set(0, 0, 0);
  50446. }
  50447. });
  50448. },{"../core/component":130,"../lib/three":178}],98:[function(_dereq_,module,exports){
  50449. var registerComponent = _dereq_('../core/component').registerComponent;
  50450. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  50451. var zeroScale = 0.00001;
  50452. module.exports.Component = registerComponent('scale', {
  50453. schema: {
  50454. type: 'vec3',
  50455. default: {x: 1, y: 1, z: 1}
  50456. },
  50457. update: function () {
  50458. var data = this.data;
  50459. var object3D = this.el.object3D;
  50460. var x = data.x === 0 ? zeroScale : data.x;
  50461. var y = data.y === 0 ? zeroScale : data.y;
  50462. var z = data.z === 0 ? zeroScale : data.z;
  50463. object3D.scale.set(x, y, z);
  50464. },
  50465. remove: function () {
  50466. // Pretty much for mixins.
  50467. this.el.object3D.scale.set(1, 1, 1);
  50468. }
  50469. });
  50470. },{"../core/component":130}],99:[function(_dereq_,module,exports){
  50471. /* global THREE */
  50472. var register = _dereq_('../../core/component').registerComponent;
  50473. var COMPONENTS = _dereq_('../../core/component').components;
  50474. module.exports.Component = register('background', {
  50475. schema: {
  50476. color: {type: 'color', default: 'black'},
  50477. transparent: {default: false}
  50478. },
  50479. update: function () {
  50480. var data = this.data;
  50481. var object3D = this.el.object3D;
  50482. if (data.transparent) {
  50483. object3D.background = null;
  50484. return;
  50485. }
  50486. object3D.background = new THREE.Color(data.color);
  50487. },
  50488. remove: function () {
  50489. var data = this.data;
  50490. var object3D = this.el.object3D;
  50491. if (data.transparent) {
  50492. object3D.background = null;
  50493. return;
  50494. }
  50495. object3D.background = COMPONENTS[this.name].schema.color.default;
  50496. }
  50497. });
  50498. },{"../../core/component":130}],100:[function(_dereq_,module,exports){
  50499. var register = _dereq_('../../core/component').registerComponent;
  50500. module.exports.Component = register('debug', {
  50501. schema: {default: true}
  50502. });
  50503. },{"../../core/component":130}],101:[function(_dereq_,module,exports){
  50504. /* global DeviceOrientationEvent, location */
  50505. var registerComponent = _dereq_('../../core/component').registerComponent;
  50506. var utils = _dereq_('../../utils/');
  50507. var bind = utils.bind;
  50508. var constants = _dereq_('../../constants/');
  50509. var MODAL_CLASS = 'a-modal';
  50510. var DIALOG_CLASS = 'a-dialog';
  50511. var DIALOG_TEXT_CLASS = 'a-dialog-text';
  50512. var DIALOG_TEXT_CONTAINER_CLASS = 'a-dialog-text-container';
  50513. var DIALOG_BUTTONS_CONTAINER_CLASS = 'a-dialog-buttons-container';
  50514. var DIALOG_BUTTON_CLASS = 'a-dialog-button';
  50515. var DIALOG_ALLOW_BUTTON_CLASS = 'a-dialog-allow-button';
  50516. var DIALOG_DENY_BUTTON_CLASS = 'a-dialog-deny-button';
  50517. var DIALOG_OK_BUTTON_CLASS = 'a-dialog-ok-button';
  50518. /**
  50519. * UI for enabling device motion permission
  50520. */
  50521. module.exports.Component = registerComponent('device-orientation-permission-ui', {
  50522. schema: {
  50523. enabled: {default: true},
  50524. deviceMotionMessage: {
  50525. default: 'This immersive website requires access to your device motion sensors.'
  50526. },
  50527. mobileDesktopMessage: {
  50528. default: 'Set your browser to request the mobile version of the site and reload the page to enjoy immersive mode.'
  50529. },
  50530. httpsMessage: {
  50531. default: 'Access this site over HTTPS to enter VR mode and grant access to the device sensors.'
  50532. },
  50533. denyButtonText: {default: 'Deny'},
  50534. allowButtonText: {default: 'Allow'},
  50535. cancelButtonText: {default: 'Cancel'}
  50536. },
  50537. init: function () {
  50538. var self = this;
  50539. if (!this.data.enabled) { return; }
  50540. if (location.hostname !== 'localhost' &&
  50541. location.hostname !== '127.0.0.1' &&
  50542. location.protocol === 'http:') {
  50543. this.showHTTPAlert();
  50544. }
  50545. // Show alert on iPad if Safari is on desktop mode.
  50546. if (utils.device.isMobileDeviceRequestingDesktopSite()) {
  50547. this.showMobileDesktopModeAlert();
  50548. return;
  50549. }
  50550. // Browser doesn't support or doesn't require permission to DeviceOrientationEvent API.
  50551. if (typeof DeviceOrientationEvent === 'undefined' || !DeviceOrientationEvent.requestPermission) {
  50552. this.permissionGranted = true;
  50553. return;
  50554. }
  50555. this.onDeviceMotionDialogAllowClicked = bind(this.onDeviceMotionDialogAllowClicked, this);
  50556. this.onDeviceMotionDialogDenyClicked = bind(this.onDeviceMotionDialogDenyClicked, this);
  50557. // Show dialog only if permission has not yet been granted.
  50558. DeviceOrientationEvent.requestPermission().catch(function () {
  50559. self.devicePermissionDialogEl = createPermissionDialog(
  50560. self.data.denyButtonText,
  50561. self.data.allowButtonText,
  50562. self.data.deviceMotionMessage,
  50563. self.onDeviceMotionDialogAllowClicked,
  50564. self.onDeviceMotionDialogDenyClicked);
  50565. self.el.appendChild(self.devicePermissionDialogEl);
  50566. }).then(function () {
  50567. self.el.emit('deviceorientationpermissiongranted');
  50568. self.permissionGranted = true;
  50569. });
  50570. },
  50571. remove: function () {
  50572. // This removes the modal screen
  50573. if (this.devicePermissionDialogEl) { this.el.removeChild(this.devicePermissionDialogEl); }
  50574. },
  50575. onDeviceMotionDialogDenyClicked: function () {
  50576. this.remove();
  50577. },
  50578. showMobileDesktopModeAlert: function () {
  50579. var self = this;
  50580. var safariIpadAlertEl = createAlertDialog(
  50581. self.data.cancelButtonText,
  50582. self.data.mobileDesktopMessage,
  50583. function () { self.el.removeChild(safariIpadAlertEl); });
  50584. this.el.appendChild(safariIpadAlertEl);
  50585. },
  50586. showHTTPAlert: function () {
  50587. var self = this;
  50588. var httpAlertEl = createAlertDialog(
  50589. self.data.cancelButtonText,
  50590. self.data.httpsMessage,
  50591. function () { self.el.removeChild(httpAlertEl); });
  50592. this.el.appendChild(httpAlertEl);
  50593. },
  50594. /**
  50595. * Enable device motion permission when clicked.
  50596. */
  50597. onDeviceMotionDialogAllowClicked: function () {
  50598. var self = this;
  50599. this.el.emit('deviceorientationpermissionrequested');
  50600. DeviceOrientationEvent.requestPermission().then(function (response) {
  50601. if (response === 'granted') {
  50602. self.el.emit('deviceorientationpermissiongranted');
  50603. self.permissionGranted = true;
  50604. } else {
  50605. self.el.emit('deviceorientationpermissionrejected');
  50606. }
  50607. self.remove();
  50608. }).catch(console.error);
  50609. }
  50610. });
  50611. /**
  50612. * Create a modal dialog that request users permission to access the Device Motion API.
  50613. *
  50614. * @param {function} onAllowClicked - click event handler
  50615. * @param {function} onDenyClicked - click event handler
  50616. *
  50617. * @returns {Element} Wrapper <div>.
  50618. */
  50619. function createPermissionDialog (
  50620. denyText, allowText, dialogText, onAllowClicked, onDenyClicked) {
  50621. var buttonsContainer;
  50622. var denyButton;
  50623. var acceptButton;
  50624. buttonsContainer = document.createElement('div');
  50625. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50626. // Buttons
  50627. denyButton = document.createElement('button');
  50628. denyButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_DENY_BUTTON_CLASS);
  50629. denyButton.setAttribute(constants.AFRAME_INJECTED, '');
  50630. denyButton.innerHTML = denyText;
  50631. buttonsContainer.appendChild(denyButton);
  50632. acceptButton = document.createElement('button');
  50633. acceptButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_ALLOW_BUTTON_CLASS);
  50634. acceptButton.setAttribute(constants.AFRAME_INJECTED, '');
  50635. acceptButton.innerHTML = allowText;
  50636. buttonsContainer.appendChild(acceptButton);
  50637. // Ask for sensor events to be used
  50638. acceptButton.addEventListener('click', function (evt) {
  50639. evt.stopPropagation();
  50640. onAllowClicked();
  50641. });
  50642. denyButton.addEventListener('click', function (evt) {
  50643. evt.stopPropagation();
  50644. onDenyClicked();
  50645. });
  50646. return createDialog(dialogText, buttonsContainer);
  50647. }
  50648. function createAlertDialog (closeText, dialogText, onOkClicked) {
  50649. var buttonsContainer;
  50650. var okButton;
  50651. buttonsContainer = document.createElement('div');
  50652. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50653. // Buttons
  50654. okButton = document.createElement('button');
  50655. okButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_OK_BUTTON_CLASS);
  50656. okButton.setAttribute(constants.AFRAME_INJECTED, '');
  50657. okButton.innerHTML = closeText;
  50658. buttonsContainer.appendChild(okButton);
  50659. // Ask for sensor events to be used
  50660. okButton.addEventListener('click', function (evt) {
  50661. evt.stopPropagation();
  50662. onOkClicked();
  50663. });
  50664. return createDialog(dialogText, buttonsContainer);
  50665. }
  50666. function createDialog (text, buttonsContainerEl) {
  50667. var modalContainer;
  50668. var dialog;
  50669. var dialogTextContainer;
  50670. var dialogText;
  50671. modalContainer = document.createElement('div');
  50672. modalContainer.classList.add(MODAL_CLASS);
  50673. modalContainer.setAttribute(constants.AFRAME_INJECTED, '');
  50674. dialog = document.createElement('div');
  50675. dialog.className = DIALOG_CLASS;
  50676. dialog.setAttribute(constants.AFRAME_INJECTED, '');
  50677. modalContainer.appendChild(dialog);
  50678. dialogTextContainer = document.createElement('div');
  50679. dialogTextContainer.classList.add(DIALOG_TEXT_CONTAINER_CLASS);
  50680. dialog.appendChild(dialogTextContainer);
  50681. dialogText = document.createElement('div');
  50682. dialogText.classList.add(DIALOG_TEXT_CLASS);
  50683. dialogText.innerHTML = text;
  50684. dialogTextContainer.appendChild(dialogText);
  50685. dialog.appendChild(buttonsContainerEl);
  50686. return modalContainer;
  50687. }
  50688. },{"../../constants/":122,"../../core/component":130,"../../utils/":204}],102:[function(_dereq_,module,exports){
  50689. var registerComponent = _dereq_('../../core/component').registerComponent;
  50690. /**
  50691. * Component to embed an a-frame scene within the layout of a 2D page.
  50692. */
  50693. module.exports.Component = registerComponent('embedded', {
  50694. dependencies: ['vr-mode-ui'],
  50695. schema: {default: true},
  50696. update: function () {
  50697. var sceneEl = this.el;
  50698. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  50699. if (this.data === true) {
  50700. if (enterVREl) { enterVREl.classList.add('embedded'); }
  50701. sceneEl.removeFullScreenStyles();
  50702. } else {
  50703. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  50704. sceneEl.addFullScreenStyles();
  50705. }
  50706. }
  50707. });
  50708. },{"../../core/component":130}],103:[function(_dereq_,module,exports){
  50709. var register = _dereq_('../../core/component').registerComponent;
  50710. var THREE = _dereq_('../../lib/three');
  50711. var debug = _dereq_('../../utils/debug');
  50712. var warn = debug('components:fog:warn');
  50713. /**
  50714. * Fog component.
  50715. * Applies only to the scene entity.
  50716. */
  50717. module.exports.Component = register('fog', {
  50718. schema: {
  50719. color: {type: 'color', default: '#000'},
  50720. density: {default: 0.00025},
  50721. far: {default: 1000, min: 0},
  50722. near: {default: 1, min: 0},
  50723. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  50724. },
  50725. update: function () {
  50726. var data = this.data;
  50727. var el = this.el;
  50728. var fog = this.el.object3D.fog;
  50729. if (!el.isScene) {
  50730. warn('Fog component can only be applied to <a-scene>');
  50731. return;
  50732. }
  50733. // (Re)create fog if fog doesn't exist or fog type changed.
  50734. if (!fog || data.type !== fog.name) {
  50735. el.object3D.fog = getFog(data);
  50736. el.systems.material.updateMaterials();
  50737. return;
  50738. }
  50739. // Fog data changed. Update fog.
  50740. Object.keys(this.schema).forEach(function (key) {
  50741. var value = data[key];
  50742. if (key === 'color') { value = new THREE.Color(value); }
  50743. fog[key] = value;
  50744. });
  50745. },
  50746. /**
  50747. * Remove fog on remove (callback).
  50748. */
  50749. remove: function () {
  50750. var fog = this.el.object3D.fog;
  50751. if (!fog) { return; }
  50752. fog.far = 0;
  50753. fog.near = 0.1;
  50754. }
  50755. });
  50756. /**
  50757. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  50758. *
  50759. * @param {object} data - Fog data.
  50760. * @returns {object} fog
  50761. */
  50762. function getFog (data) {
  50763. var fog;
  50764. if (data.type === 'exponential') {
  50765. fog = new THREE.FogExp2(data.color, data.density);
  50766. } else {
  50767. fog = new THREE.Fog(data.color, data.near, data.far);
  50768. }
  50769. fog.name = data.type;
  50770. return fog;
  50771. }
  50772. },{"../../core/component":130,"../../lib/three":178,"../../utils/debug":200}],104:[function(_dereq_,module,exports){
  50773. (function (process){
  50774. /* global AFRAME */
  50775. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  50776. var pkg = _dereq_('../../../package');
  50777. var registerComponent = _dereq_('../../core/component').registerComponent;
  50778. var utils = _dereq_('../../utils/');
  50779. /**
  50780. * 0.4.2 to 0.4.x
  50781. * Will need to update this when A-Frame goes to 1.x.x.
  50782. */
  50783. function getFuzzyPatchVersion (version) {
  50784. var split = version.split('.');
  50785. split[2] = 'x';
  50786. return split.join('.');
  50787. }
  50788. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  50789. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  50790. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  50791. var LOADING_MESSAGE = 'Loading Inspector';
  50792. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  50793. module.exports.Component = registerComponent('inspector', {
  50794. schema: {
  50795. url: {default: INSPECTOR_URL}
  50796. },
  50797. init: function () {
  50798. this.firstPlay = true;
  50799. this.onKeydown = this.onKeydown.bind(this);
  50800. this.onMessage = this.onMessage.bind(this);
  50801. this.initOverlay();
  50802. window.addEventListener('keydown', this.onKeydown);
  50803. window.addEventListener('message', this.onMessage);
  50804. },
  50805. play: function () {
  50806. var urlParam;
  50807. if (!this.firstPlay) { return; }
  50808. urlParam = utils.getUrlParameter('inspector');
  50809. if (urlParam !== 'false' && !!urlParam) {
  50810. this.openInspector();
  50811. this.firstPlay = false;
  50812. }
  50813. },
  50814. initOverlay: function () {
  50815. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  50816. this.loadingMessageEl = document.createElement('div');
  50817. this.loadingMessageEl.classList.add('a-inspector-loader');
  50818. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  50819. },
  50820. remove: function () {
  50821. this.removeEventListeners();
  50822. },
  50823. /**
  50824. * <ctrl> + <alt> + i keyboard shortcut.
  50825. */
  50826. onKeydown: function (evt) {
  50827. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  50828. if (!shortcutPressed) { return; }
  50829. this.openInspector();
  50830. },
  50831. showLoader: function () {
  50832. document.body.appendChild(this.loadingMessageEl);
  50833. },
  50834. hideLoader: function () {
  50835. document.body.removeChild(this.loadingMessageEl);
  50836. },
  50837. /**
  50838. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  50839. */
  50840. onMessage: function (evt) {
  50841. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  50842. },
  50843. openInspector: function (focusEl) {
  50844. var self = this;
  50845. var script;
  50846. // Already injected. Open.
  50847. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  50848. AFRAME.INSPECTOR.open(focusEl);
  50849. return;
  50850. }
  50851. this.showLoader();
  50852. // Inject.
  50853. script = document.createElement('script');
  50854. script.src = this.data.url;
  50855. script.setAttribute('data-name', 'aframe-inspector');
  50856. script.setAttribute(AFRAME_INJECTED, '');
  50857. script.onload = function () {
  50858. AFRAME.INSPECTOR.open(focusEl);
  50859. self.hideLoader();
  50860. self.removeEventListeners();
  50861. };
  50862. script.onerror = function () {
  50863. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  50864. };
  50865. document.head.appendChild(script);
  50866. AFRAME.inspectorInjected = true;
  50867. },
  50868. removeEventListeners: function () {
  50869. window.removeEventListener('keydown', this.onKeydown);
  50870. window.removeEventListener('message', this.onMessage);
  50871. }
  50872. });
  50873. }).call(this,_dereq_('_process'))
  50874. },{"../../../package":72,"../../constants":122,"../../core/component":130,"../../utils/":204,"_process":49}],105:[function(_dereq_,module,exports){
  50875. var registerComponent = _dereq_('../../core/component').registerComponent;
  50876. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  50877. module.exports.Component = registerComponent('keyboard-shortcuts', {
  50878. schema: {
  50879. enterVR: {default: true},
  50880. exitVR: {default: true}
  50881. },
  50882. init: function () {
  50883. this.onKeyup = this.onKeyup.bind(this);
  50884. },
  50885. update: function (oldData) {
  50886. var data = this.data;
  50887. this.enterVREnabled = data.enterVR;
  50888. },
  50889. play: function () {
  50890. window.addEventListener('keyup', this.onKeyup, false);
  50891. },
  50892. pause: function () {
  50893. window.removeEventListener('keyup', this.onKeyup);
  50894. },
  50895. onKeyup: function (evt) {
  50896. var scene = this.el;
  50897. if (!shouldCaptureKeyEvent(evt)) { return; }
  50898. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  50899. scene.enterVR();
  50900. }
  50901. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  50902. scene.exitVR();
  50903. }
  50904. }
  50905. });
  50906. },{"../../core/component":130,"../../utils/":204}],106:[function(_dereq_,module,exports){
  50907. var debug = _dereq_('../../utils/debug');
  50908. var registerComponent = _dereq_('../../core/component').registerComponent;
  50909. var warn = debug('components:pool:warn');
  50910. /**
  50911. * Pool component to reuse entities.
  50912. * Avoids creating and destroying the same kind of entities.
  50913. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  50914. *
  50915. * @member {array} availableEls - Available entities in the pool.
  50916. * @member {array} usedEls - Entities of the pool in use.
  50917. */
  50918. module.exports.Component = registerComponent('pool', {
  50919. schema: {
  50920. container: {default: ''},
  50921. mixin: {default: ''},
  50922. size: {default: 0},
  50923. dynamic: {default: false}
  50924. },
  50925. multiple: true,
  50926. initPool: function () {
  50927. var i;
  50928. this.availableEls = [];
  50929. this.usedEls = [];
  50930. if (!this.data.mixin) {
  50931. warn('No mixin provided for pool component.');
  50932. }
  50933. if (this.data.container) {
  50934. this.container = document.querySelector(this.data.container);
  50935. if (!this.container) {
  50936. warn('Container ' + this.data.container + ' not found.');
  50937. }
  50938. }
  50939. this.container = this.container || this.el;
  50940. for (i = 0; i < this.data.size; ++i) {
  50941. this.createEntity();
  50942. }
  50943. },
  50944. update: function (oldData) {
  50945. var data = this.data;
  50946. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  50947. this.initPool();
  50948. }
  50949. },
  50950. /**
  50951. * Add a new entity to the list of available entities.
  50952. */
  50953. createEntity: function () {
  50954. var el;
  50955. el = document.createElement('a-entity');
  50956. el.play = this.wrapPlay(el.play);
  50957. el.setAttribute('mixin', this.data.mixin);
  50958. el.object3D.visible = false;
  50959. el.pause();
  50960. this.container.appendChild(el);
  50961. this.availableEls.push(el);
  50962. },
  50963. /**
  50964. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  50965. * entities that are not in use.
  50966. */
  50967. wrapPlay: function (playMethod) {
  50968. var usedEls = this.usedEls;
  50969. return function () {
  50970. if (usedEls.indexOf(this) === -1) { return; }
  50971. playMethod.call(this);
  50972. };
  50973. },
  50974. /**
  50975. * Used to request one of the available entities of the pool.
  50976. */
  50977. requestEntity: function () {
  50978. var el;
  50979. if (this.availableEls.length === 0) {
  50980. if (this.data.dynamic === false) {
  50981. warn('Requested entity from empty pool: ' + this.attrName);
  50982. return;
  50983. } else {
  50984. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  50985. 'automatically. You might want to increase its initial size: ' + this.attrName);
  50986. }
  50987. this.createEntity();
  50988. }
  50989. el = this.availableEls.shift();
  50990. this.usedEls.push(el);
  50991. el.object3D.visible = true;
  50992. return el;
  50993. },
  50994. /**
  50995. * Used to return a used entity to the pool.
  50996. */
  50997. returnEntity: function (el) {
  50998. var index = this.usedEls.indexOf(el);
  50999. if (index === -1) {
  51000. warn('The returned entity was not previously pooled from ' + this.attrName);
  51001. return;
  51002. }
  51003. this.usedEls.splice(index, 1);
  51004. this.availableEls.push(el);
  51005. el.object3D.visible = false;
  51006. el.pause();
  51007. return el;
  51008. }
  51009. });
  51010. },{"../../core/component":130,"../../utils/debug":200}],107:[function(_dereq_,module,exports){
  51011. /* global ImageData, URL */
  51012. var registerComponent = _dereq_('../../core/component').registerComponent;
  51013. var THREE = _dereq_('../../lib/three');
  51014. var VERTEX_SHADER = [
  51015. 'attribute vec3 position;',
  51016. 'attribute vec2 uv;',
  51017. 'uniform mat4 projectionMatrix;',
  51018. 'uniform mat4 modelViewMatrix;',
  51019. 'varying vec2 vUv;',
  51020. 'void main() {',
  51021. ' vUv = vec2( 1.- uv.x, uv.y );',
  51022. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  51023. '}'
  51024. ].join('\n');
  51025. var FRAGMENT_SHADER = [
  51026. 'precision mediump float;',
  51027. 'uniform samplerCube map;',
  51028. 'varying vec2 vUv;',
  51029. '#define M_PI 3.141592653589793238462643383279',
  51030. 'void main() {',
  51031. ' vec2 uv = vUv;',
  51032. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  51033. ' float latitude = uv.y * M_PI;',
  51034. ' vec3 dir = vec3(',
  51035. ' - sin( longitude ) * sin( latitude ),',
  51036. ' cos( latitude ),',
  51037. ' - cos( longitude ) * sin( latitude )',
  51038. ' );',
  51039. ' normalize( dir );',
  51040. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  51041. '}'
  51042. ].join('\n');
  51043. /**
  51044. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  51045. * It can be configured to either take 360&deg; captures (`equirectangular`)
  51046. * or regular screenshots (`projection`)
  51047. *
  51048. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  51049. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  51050. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  51051. * WebGLRenderTarget with an ortographic camera.
  51052. */
  51053. module.exports.Component = registerComponent('screenshot', {
  51054. schema: {
  51055. width: {default: 4096},
  51056. height: {default: 2048},
  51057. camera: {type: 'selector'}
  51058. },
  51059. init: function () {
  51060. var el = this.el;
  51061. var self = this;
  51062. if (el.renderer) {
  51063. setup();
  51064. } else {
  51065. el.addEventListener('render-target-loaded', setup);
  51066. }
  51067. function setup () {
  51068. var gl = el.renderer.getContext();
  51069. if (!gl) { return; }
  51070. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  51071. self.material = new THREE.RawShaderMaterial({
  51072. uniforms: {map: {type: 't', value: null}},
  51073. vertexShader: VERTEX_SHADER,
  51074. fragmentShader: FRAGMENT_SHADER,
  51075. side: THREE.DoubleSide
  51076. });
  51077. self.quad = new THREE.Mesh(
  51078. new THREE.PlaneBufferGeometry(1, 1),
  51079. self.material
  51080. );
  51081. self.quad.visible = false;
  51082. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  51083. self.canvas = document.createElement('canvas');
  51084. self.ctx = self.canvas.getContext('2d');
  51085. el.object3D.add(self.quad);
  51086. self.onKeyDown = self.onKeyDown.bind(self);
  51087. }
  51088. },
  51089. getRenderTarget: function (width, height) {
  51090. return new THREE.WebGLRenderTarget(width, height, {
  51091. minFilter: THREE.LinearFilter,
  51092. magFilter: THREE.LinearFilter,
  51093. wrapS: THREE.ClampToEdgeWrapping,
  51094. wrapT: THREE.ClampToEdgeWrapping,
  51095. format: THREE.RGBAFormat,
  51096. type: THREE.UnsignedByteType
  51097. });
  51098. },
  51099. resize: function (width, height) {
  51100. // Resize quad.
  51101. this.quad.scale.set(width, height, 1);
  51102. // Resize camera.
  51103. this.camera.left = -1 * width / 2;
  51104. this.camera.right = width / 2;
  51105. this.camera.top = height / 2;
  51106. this.camera.bottom = -1 * height / 2;
  51107. this.camera.updateProjectionMatrix();
  51108. // Resize canvas.
  51109. this.canvas.width = width;
  51110. this.canvas.height = height;
  51111. },
  51112. play: function () {
  51113. window.addEventListener('keydown', this.onKeyDown);
  51114. },
  51115. /**
  51116. * <ctrl> + <alt> + s = Regular screenshot.
  51117. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  51118. */
  51119. onKeyDown: function (evt) {
  51120. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  51121. if (!this.data || !shortcutPressed) { return; }
  51122. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  51123. this.capture(projection);
  51124. },
  51125. /**
  51126. * Capture a screenshot of the scene.
  51127. *
  51128. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  51129. */
  51130. setCapture: function (projection) {
  51131. var el = this.el;
  51132. var size;
  51133. var camera;
  51134. var cubeCamera;
  51135. var cubeRenderTarget;
  51136. // Configure camera.
  51137. if (projection === 'perspective') {
  51138. // Quad is only used in equirectangular mode. Hide it in this case.
  51139. this.quad.visible = false;
  51140. // Use scene camera.
  51141. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  51142. size = {width: this.data.width, height: this.data.height};
  51143. } else {
  51144. // Use ortho camera.
  51145. camera = this.camera;
  51146. cubeRenderTarget = new THREE.WebGLCubeRenderTarget(
  51147. Math.min(this.cubeMapSize, 2048),
  51148. {
  51149. format: THREE.RGBFormat,
  51150. generateMipmaps: true,
  51151. minFilter: THREE.LinearMipmapLinearFilter,
  51152. encoding: THREE.sRGBEncoding
  51153. });
  51154. // Create cube camera and copy position from scene camera.
  51155. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far, cubeRenderTarget);
  51156. // Copy camera position into cube camera;
  51157. el.camera.getWorldPosition(cubeCamera.position);
  51158. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  51159. // Render scene with cube camera.
  51160. cubeCamera.update(el.renderer, el.object3D);
  51161. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  51162. size = {width: this.data.width, height: this.data.height};
  51163. // Use quad to project image taken by the cube camera.
  51164. this.quad.visible = true;
  51165. }
  51166. return {
  51167. camera: camera,
  51168. size: size,
  51169. projection: projection
  51170. };
  51171. },
  51172. /**
  51173. * Maintained for backwards compatibility.
  51174. */
  51175. capture: function (projection) {
  51176. var isVREnabled = this.el.renderer.xr.enabled;
  51177. var renderer = this.el.renderer;
  51178. var params;
  51179. // Disable VR.
  51180. renderer.xr.enabled = false;
  51181. params = this.setCapture(projection);
  51182. this.renderCapture(params.camera, params.size, params.projection);
  51183. // Trigger file download.
  51184. this.saveCapture();
  51185. // Restore VR.
  51186. renderer.xr.enabled = isVREnabled;
  51187. },
  51188. /**
  51189. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  51190. */
  51191. getCanvas: function (projection) {
  51192. var isVREnabled = this.el.renderer.xr.enabled;
  51193. var renderer = this.el.renderer;
  51194. // Disable VR.
  51195. var params = this.setCapture(projection);
  51196. renderer.xr.enabled = false;
  51197. this.renderCapture(params.camera, params.size, params.projection);
  51198. // Restore VR.
  51199. renderer.xr.enabled = isVREnabled;
  51200. return this.canvas;
  51201. },
  51202. renderCapture: function (camera, size, projection) {
  51203. var autoClear = this.el.renderer.autoClear;
  51204. var el = this.el;
  51205. var imageData;
  51206. var output;
  51207. var pixels;
  51208. var renderer = el.renderer;
  51209. // Create rendering target and buffer to store the read pixels.
  51210. output = this.getRenderTarget(size.width, size.height);
  51211. pixels = new Uint8Array(4 * size.width * size.height);
  51212. // Resize quad, camera, and canvas.
  51213. this.resize(size.width, size.height);
  51214. // Render scene to render target.
  51215. renderer.autoClear = true;
  51216. renderer.clear();
  51217. renderer.setRenderTarget(output);
  51218. renderer.render(el.object3D, camera);
  51219. renderer.autoClear = autoClear;
  51220. // Read image pizels back.
  51221. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  51222. renderer.setRenderTarget(null);
  51223. if (projection === 'perspective') {
  51224. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  51225. }
  51226. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  51227. // Hide quad after projecting the image.
  51228. this.quad.visible = false;
  51229. // Copy pixels into canvas.
  51230. this.ctx.putImageData(imageData, 0, 0);
  51231. },
  51232. flipPixelsVertically: function (pixels, width, height) {
  51233. var flippedPixels = pixels.slice(0);
  51234. for (var x = 0; x < width; ++x) {
  51235. for (var y = 0; y < height; ++y) {
  51236. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  51237. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  51238. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  51239. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  51240. }
  51241. }
  51242. return flippedPixels;
  51243. },
  51244. /**
  51245. * Download capture to file.
  51246. */
  51247. saveCapture: function () {
  51248. this.canvas.toBlob(function (blob) {
  51249. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  51250. var linkEl = document.createElement('a');
  51251. var url = URL.createObjectURL(blob);
  51252. linkEl.href = url;
  51253. linkEl.setAttribute('download', fileName);
  51254. linkEl.innerHTML = 'downloading...';
  51255. linkEl.style.display = 'none';
  51256. document.body.appendChild(linkEl);
  51257. setTimeout(function () {
  51258. linkEl.click();
  51259. document.body.removeChild(linkEl);
  51260. }, 1);
  51261. }, 'image/png');
  51262. }
  51263. });
  51264. },{"../../core/component":130,"../../lib/three":178}],108:[function(_dereq_,module,exports){
  51265. var registerComponent = _dereq_('../../core/component').registerComponent;
  51266. var RStats = _dereq_('../../../vendor/rStats');
  51267. var utils = _dereq_('../../utils');
  51268. _dereq_('../../../vendor/rStats.extras');
  51269. _dereq_('../../lib/rStatsAframe');
  51270. var AFrameStats = window.aframeStats;
  51271. var bind = utils.bind;
  51272. var HIDDEN_CLASS = 'a-hidden';
  51273. var ThreeStats = window.threeStats;
  51274. /**
  51275. * Stats appended to document.body by RStats.
  51276. */
  51277. module.exports.Component = registerComponent('stats', {
  51278. schema: {default: true},
  51279. init: function () {
  51280. var scene = this.el;
  51281. if (utils.getUrlParameter('stats') === 'false') { return; }
  51282. this.stats = createStats(scene);
  51283. this.statsEl = document.querySelector('.rs-base');
  51284. this.hideBound = bind(this.hide, this);
  51285. this.showBound = bind(this.show, this);
  51286. scene.addEventListener('enter-vr', this.hideBound);
  51287. scene.addEventListener('exit-vr', this.showBound);
  51288. },
  51289. update: function () {
  51290. if (!this.stats) { return; }
  51291. return (!this.data) ? this.hide() : this.show();
  51292. },
  51293. remove: function () {
  51294. this.el.removeEventListener('enter-vr', this.hideBound);
  51295. this.el.removeEventListener('exit-vr', this.showBound);
  51296. if (!this.statsEl) { return; } // Scene detached.
  51297. this.statsEl.parentNode.removeChild(this.statsEl);
  51298. },
  51299. tick: function () {
  51300. var stats = this.stats;
  51301. if (!stats) { return; }
  51302. stats('rAF').tick();
  51303. stats('FPS').frame();
  51304. stats().update();
  51305. },
  51306. hide: function () {
  51307. this.statsEl.classList.add(HIDDEN_CLASS);
  51308. },
  51309. show: function () {
  51310. this.statsEl.classList.remove(HIDDEN_CLASS);
  51311. }
  51312. });
  51313. function createStats (scene) {
  51314. var threeStats = new ThreeStats(scene.renderer);
  51315. var aframeStats = new AFrameStats(scene);
  51316. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  51317. return new RStats({
  51318. css: [], // Our stylesheet is injected from `src/index.js`.
  51319. values: {
  51320. fps: {caption: 'fps', below: 30}
  51321. },
  51322. groups: [
  51323. {caption: 'Framerate', values: ['fps', 'raf']}
  51324. ],
  51325. plugins: plugins
  51326. });
  51327. }
  51328. },{"../../../vendor/rStats":216,"../../../vendor/rStats.extras":215,"../../core/component":130,"../../lib/rStatsAframe":177,"../../utils":204}],109:[function(_dereq_,module,exports){
  51329. var registerComponent = _dereq_('../../core/component').registerComponent;
  51330. var constants = _dereq_('../../constants/');
  51331. var utils = _dereq_('../../utils/');
  51332. var bind = utils.bind;
  51333. var ENTER_VR_CLASS = 'a-enter-vr';
  51334. var ENTER_AR_CLASS = 'a-enter-ar';
  51335. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  51336. var ENTER_AR_BTN_CLASS = 'a-enter-ar-button';
  51337. var HIDDEN_CLASS = 'a-hidden';
  51338. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  51339. /**
  51340. * UI for entering VR mode.
  51341. */
  51342. module.exports.Component = registerComponent('vr-mode-ui', {
  51343. dependencies: ['canvas'],
  51344. schema: {
  51345. enabled: {default: true},
  51346. enterVRButton: {default: ''},
  51347. enterARButton: {default: ''}
  51348. },
  51349. init: function () {
  51350. var self = this;
  51351. var sceneEl = this.el;
  51352. if (utils.getUrlParameter('ui') === 'false') { return; }
  51353. this.insideLoader = false;
  51354. this.enterVREl = null;
  51355. this.enterAREl = null;
  51356. this.orientationModalEl = null;
  51357. this.bindMethods();
  51358. // Hide/show VR UI when entering/exiting VR mode.
  51359. sceneEl.addEventListener('enter-vr', this.updateEnterInterfaces);
  51360. sceneEl.addEventListener('exit-vr', this.updateEnterInterfaces);
  51361. sceneEl.addEventListener('update-vr-devices', this.updateEnterInterfaces);
  51362. window.addEventListener('message', function (event) {
  51363. if (event.data.type === 'loaderReady') {
  51364. self.insideLoader = true;
  51365. self.remove();
  51366. }
  51367. });
  51368. // Modal that tells the user to change orientation if in portrait.
  51369. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  51370. },
  51371. bindMethods: function () {
  51372. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  51373. this.onEnterARButtonClick = bind(this.onEnterARButtonClick, this);
  51374. this.onModalClick = bind(this.onModalClick, this);
  51375. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  51376. this.updateEnterInterfaces = bind(this.updateEnterInterfaces, this);
  51377. },
  51378. /**
  51379. * Exit VR when modal clicked.
  51380. */
  51381. onModalClick: function () {
  51382. this.el.exitVR();
  51383. },
  51384. /**
  51385. * Enter VR when clicked.
  51386. */
  51387. onEnterVRButtonClick: function () {
  51388. this.el.enterVR();
  51389. },
  51390. /**
  51391. * Enter AR when clicked.
  51392. */
  51393. onEnterARButtonClick: function () {
  51394. this.el.enterAR();
  51395. },
  51396. update: function () {
  51397. var data = this.data;
  51398. var sceneEl = this.el;
  51399. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  51400. return this.remove();
  51401. }
  51402. if (this.enterVREl || this.enterAREl || this.orientationModalEl) { return; }
  51403. // Add UI if enabled and not already present.
  51404. if (data.enterVRButton) {
  51405. // Custom button.
  51406. this.enterVREl = document.querySelector(data.enterVRButton);
  51407. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  51408. } else {
  51409. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  51410. sceneEl.appendChild(this.enterVREl);
  51411. }
  51412. if (data.enterARButton) {
  51413. // Custom button.
  51414. this.enterAREl = document.querySelector(data.enterARButton);
  51415. this.enterAREl.addEventListener('click', this.onEnterARButtonClick);
  51416. } else {
  51417. this.enterAREl = createEnterARButton(this.onEnterARButtonClick);
  51418. sceneEl.appendChild(this.enterAREl);
  51419. }
  51420. this.orientationModalEl = createOrientationModal(this.onModalClick);
  51421. sceneEl.appendChild(this.orientationModalEl);
  51422. this.updateEnterInterfaces();
  51423. },
  51424. remove: function () {
  51425. [this.enterVREl, this.enterAREl, this.orientationModalEl].forEach(function (uiElement) {
  51426. if (uiElement && uiElement.parentNode) {
  51427. uiElement.parentNode.removeChild(uiElement);
  51428. }
  51429. });
  51430. this.enterVREl = undefined;
  51431. this.enterAREl = undefined;
  51432. this.orientationModalEl = undefined;
  51433. },
  51434. updateEnterInterfaces: function () {
  51435. this.toggleEnterVRButtonIfNeeded();
  51436. this.toggleEnterARButtonIfNeeded();
  51437. this.toggleOrientationModalIfNeeded();
  51438. },
  51439. toggleEnterVRButtonIfNeeded: function () {
  51440. var sceneEl = this.el;
  51441. if (!this.enterVREl) { return; }
  51442. if (sceneEl.is('vr-mode')) {
  51443. this.enterVREl.classList.add(HIDDEN_CLASS);
  51444. } else {
  51445. this.enterVREl.classList.remove(HIDDEN_CLASS);
  51446. }
  51447. },
  51448. toggleEnterARButtonIfNeeded: function () {
  51449. var sceneEl = this.el;
  51450. if (!this.enterAREl) { return; }
  51451. // Hide the button while in a session, or if AR is not supported.
  51452. if (sceneEl.is('vr-mode') || !utils.device.checkARSupport()) {
  51453. this.enterAREl.classList.add(HIDDEN_CLASS);
  51454. } else {
  51455. this.enterAREl.classList.remove(HIDDEN_CLASS);
  51456. }
  51457. },
  51458. toggleOrientationModalIfNeeded: function () {
  51459. var sceneEl = this.el;
  51460. var orientationModalEl = this.orientationModalEl;
  51461. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  51462. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  51463. // Show if in VR mode on portrait.
  51464. orientationModalEl.classList.remove(HIDDEN_CLASS);
  51465. } else {
  51466. orientationModalEl.classList.add(HIDDEN_CLASS);
  51467. }
  51468. }
  51469. });
  51470. /**
  51471. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  51472. *
  51473. * Structure: <div><button></div>
  51474. *
  51475. * @param {function} onClick - click event handler
  51476. * @returns {Element} Wrapper <div>.
  51477. */
  51478. function createEnterVRButton (onClick) {
  51479. var vrButton;
  51480. var wrapper;
  51481. // Create elements.
  51482. wrapper = document.createElement('div');
  51483. wrapper.classList.add(ENTER_VR_CLASS);
  51484. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51485. vrButton = document.createElement('button');
  51486. vrButton.className = ENTER_VR_BTN_CLASS;
  51487. vrButton.setAttribute('title',
  51488. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  51489. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51490. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  51491. if (utils.device.isMobile()) { applyStickyHoverFix(vrButton); }
  51492. // Insert elements.
  51493. wrapper.appendChild(vrButton);
  51494. vrButton.addEventListener('click', function (evt) {
  51495. onClick();
  51496. evt.stopPropagation();
  51497. });
  51498. return wrapper;
  51499. }
  51500. /**
  51501. * Create a button that when clicked will enter into AR mode
  51502. *
  51503. * Structure: <div><button></div>
  51504. *
  51505. * @param {function} onClick - click event handler
  51506. * @returns {Element} Wrapper <div>.
  51507. */
  51508. function createEnterARButton (onClick) {
  51509. var arButton;
  51510. var wrapper;
  51511. // Create elements.
  51512. wrapper = document.createElement('div');
  51513. wrapper.classList.add(ENTER_AR_CLASS);
  51514. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51515. arButton = document.createElement('button');
  51516. arButton.className = ENTER_AR_BTN_CLASS;
  51517. arButton.setAttribute('title',
  51518. 'Enter AR mode with a headset or handheld device. ' +
  51519. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51520. arButton.setAttribute(constants.AFRAME_INJECTED, '');
  51521. if (utils.device.isMobile()) { applyStickyHoverFix(arButton); }
  51522. // Insert elements.
  51523. wrapper.appendChild(arButton);
  51524. arButton.addEventListener('click', function (evt) {
  51525. onClick();
  51526. evt.stopPropagation();
  51527. });
  51528. return wrapper;
  51529. }
  51530. /**
  51531. * Creates a modal dialog to request the user to switch to landscape orientation.
  51532. *
  51533. * @param {function} onClick - click event handler
  51534. * @returns {Element} Wrapper <div>.
  51535. */
  51536. function createOrientationModal (onClick) {
  51537. var modal = document.createElement('div');
  51538. modal.className = ORIENTATION_MODAL_CLASS;
  51539. modal.classList.add(HIDDEN_CLASS);
  51540. modal.setAttribute(constants.AFRAME_INJECTED, '');
  51541. var exit = document.createElement('button');
  51542. exit.setAttribute(constants.AFRAME_INJECTED, '');
  51543. exit.innerHTML = 'Exit VR';
  51544. // Exit VR on close.
  51545. exit.addEventListener('click', onClick);
  51546. modal.appendChild(exit);
  51547. return modal;
  51548. }
  51549. /**
  51550. * CSS hover state is sticky in iOS (as in 12/18/2019)
  51551. * They are not removed on mouseleave and this function applies a class
  51552. * to resets the style.
  51553. *
  51554. * @param {function} buttonEl - Button element
  51555. */
  51556. function applyStickyHoverFix (buttonEl) {
  51557. buttonEl.addEventListener('touchstart', function () {
  51558. buttonEl.classList.remove('resethover');
  51559. });
  51560. buttonEl.addEventListener('touchend', function () {
  51561. buttonEl.classList.add('resethover');
  51562. });
  51563. }
  51564. },{"../../constants/":122,"../../core/component":130,"../../utils/":204}],110:[function(_dereq_,module,exports){
  51565. var component = _dereq_('../core/component');
  51566. var THREE = _dereq_('../lib/three');
  51567. var bind = _dereq_('../utils/bind');
  51568. var registerComponent = component.registerComponent;
  51569. /**
  51570. * Shadow component.
  51571. *
  51572. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  51573. * shadows as specified by the `cast` and `receive` properties.
  51574. */
  51575. module.exports.Component = registerComponent('shadow', {
  51576. schema: {
  51577. cast: {default: true},
  51578. receive: {default: true}
  51579. },
  51580. init: function () {
  51581. this.onMeshChanged = bind(this.update, this);
  51582. this.el.addEventListener('object3dset', this.onMeshChanged);
  51583. this.system.setShadowMapEnabled(true);
  51584. },
  51585. update: function () {
  51586. var data = this.data;
  51587. this.updateDescendants(data.cast, data.receive);
  51588. },
  51589. remove: function () {
  51590. var el = this.el;
  51591. el.removeEventListener('object3dset', this.onMeshChanged);
  51592. this.updateDescendants(false, false);
  51593. },
  51594. updateDescendants: function (cast, receive) {
  51595. var sceneEl = this.el.sceneEl;
  51596. this.el.object3D.traverse(function (node) {
  51597. if (!(node instanceof THREE.Mesh)) { return; }
  51598. node.castShadow = cast;
  51599. node.receiveShadow = receive;
  51600. // If scene has already rendered, materials must be updated.
  51601. if (sceneEl.hasLoaded && node.material) {
  51602. var materials = Array.isArray(node.material) ? node.material : [node.material];
  51603. for (var i = 0; i < materials.length; i++) {
  51604. materials[i].needsUpdate = true;
  51605. }
  51606. }
  51607. });
  51608. }
  51609. });
  51610. },{"../core/component":130,"../lib/three":178,"../utils/bind":198}],111:[function(_dereq_,module,exports){
  51611. var registerComponent = _dereq_('../core/component').registerComponent;
  51612. var debug = _dereq_('../utils/debug');
  51613. var THREE = _dereq_('../lib/three');
  51614. var warn = debug('components:sound:warn');
  51615. /**
  51616. * Sound component.
  51617. */
  51618. module.exports.Component = registerComponent('sound', {
  51619. schema: {
  51620. autoplay: {default: false},
  51621. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  51622. loop: {default: false},
  51623. maxDistance: {default: 10000},
  51624. on: {default: ''},
  51625. poolSize: {default: 1},
  51626. positional: {default: true},
  51627. refDistance: {default: 1},
  51628. rolloffFactor: {default: 1},
  51629. src: {type: 'audio'},
  51630. volume: {default: 1}
  51631. },
  51632. multiple: true,
  51633. init: function () {
  51634. var self = this;
  51635. this.listener = null;
  51636. this.audioLoader = new THREE.AudioLoader();
  51637. this.pool = new THREE.Group();
  51638. this.loaded = false;
  51639. this.mustPlay = false;
  51640. // Don't pass evt because playSound takes a function as parameter.
  51641. this.playSoundBound = function () { self.playSound(); };
  51642. },
  51643. update: function (oldData) {
  51644. var data = this.data;
  51645. var i;
  51646. var sound;
  51647. var srcChanged = data.src !== oldData.src;
  51648. // Create new sound if not yet created or changing `src`.
  51649. if (srcChanged) {
  51650. if (!data.src) { return; }
  51651. this.setupSound();
  51652. }
  51653. for (i = 0; i < this.pool.children.length; i++) {
  51654. sound = this.pool.children[i];
  51655. if (data.positional) {
  51656. sound.setDistanceModel(data.distanceModel);
  51657. sound.setMaxDistance(data.maxDistance);
  51658. sound.setRefDistance(data.refDistance);
  51659. sound.setRolloffFactor(data.rolloffFactor);
  51660. }
  51661. sound.setLoop(data.loop);
  51662. sound.setVolume(data.volume);
  51663. sound.isPaused = false;
  51664. }
  51665. if (data.on !== oldData.on) {
  51666. this.updateEventListener(oldData.on);
  51667. }
  51668. // All sound values set. Load in `src`.
  51669. if (srcChanged) {
  51670. var self = this;
  51671. this.loaded = false;
  51672. this.audioLoader.load(data.src, function (buffer) {
  51673. for (i = 0; i < self.pool.children.length; i++) {
  51674. sound = self.pool.children[i];
  51675. sound.setBuffer(buffer);
  51676. }
  51677. self.loaded = true;
  51678. // Remove this key from cache, otherwise we can't play it again
  51679. THREE.Cache.remove(data.src);
  51680. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  51681. self.el.emit('sound-loaded', self.evtDetail, false);
  51682. });
  51683. }
  51684. },
  51685. pause: function () {
  51686. this.stopSound();
  51687. this.removeEventListener();
  51688. },
  51689. play: function () {
  51690. if (this.data.autoplay) { this.playSound(); }
  51691. this.updateEventListener();
  51692. },
  51693. remove: function () {
  51694. var i;
  51695. var sound;
  51696. this.removeEventListener();
  51697. if (this.el.getObject3D(this.attrName)) {
  51698. this.el.removeObject3D(this.attrName);
  51699. }
  51700. try {
  51701. for (i = 0; i < this.pool.children.length; i++) {
  51702. sound = this.pool.children[i];
  51703. sound.disconnect();
  51704. }
  51705. } catch (e) {
  51706. // disconnect() will throw if it was never connected initially.
  51707. warn('Audio source not properly disconnected');
  51708. }
  51709. },
  51710. /**
  51711. * Update listener attached to the user defined on event.
  51712. */
  51713. updateEventListener: function (oldEvt) {
  51714. var el = this.el;
  51715. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  51716. el.addEventListener(this.data.on, this.playSoundBound);
  51717. },
  51718. removeEventListener: function () {
  51719. this.el.removeEventListener(this.data.on, this.playSoundBound);
  51720. },
  51721. /**
  51722. * Removes current sound object, creates new sound object, adds to entity.
  51723. *
  51724. * @returns {object} sound
  51725. */
  51726. setupSound: function () {
  51727. var el = this.el;
  51728. var i;
  51729. var sceneEl = el.sceneEl;
  51730. var self = this;
  51731. var sound;
  51732. if (this.pool.children.length > 0) {
  51733. this.stopSound();
  51734. el.removeObject3D('sound');
  51735. }
  51736. // Only want one AudioListener. Cache it on the scene.
  51737. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  51738. sceneEl.audioListener = listener;
  51739. if (sceneEl.camera) {
  51740. sceneEl.camera.add(listener);
  51741. }
  51742. // Wait for camera if necessary.
  51743. sceneEl.addEventListener('camera-set-active', function (evt) {
  51744. evt.detail.cameraEl.getObject3D('camera').add(listener);
  51745. });
  51746. // Create [poolSize] audio instances and attach them to pool
  51747. this.pool = new THREE.Group();
  51748. for (i = 0; i < this.data.poolSize; i++) {
  51749. sound = this.data.positional
  51750. ? new THREE.PositionalAudio(listener)
  51751. : new THREE.Audio(listener);
  51752. this.pool.add(sound);
  51753. }
  51754. el.setObject3D(this.attrName, this.pool);
  51755. for (i = 0; i < this.pool.children.length; i++) {
  51756. sound = this.pool.children[i];
  51757. sound.onEnded = function () {
  51758. this.isPlaying = false;
  51759. self.el.emit('sound-ended', self.evtDetail, false);
  51760. };
  51761. }
  51762. },
  51763. /**
  51764. * Pause all the sounds in the pool.
  51765. */
  51766. pauseSound: function () {
  51767. var i;
  51768. var sound;
  51769. this.isPlaying = false;
  51770. for (i = 0; i < this.pool.children.length; i++) {
  51771. sound = this.pool.children[i];
  51772. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  51773. continue;
  51774. }
  51775. sound.isPaused = true;
  51776. sound.pause();
  51777. }
  51778. },
  51779. /**
  51780. * Look for an unused sound in the pool and play it if found.
  51781. */
  51782. playSound: function (processSound) {
  51783. var found;
  51784. var i;
  51785. var sound;
  51786. if (!this.loaded) {
  51787. warn('Sound not loaded yet. It will be played once it finished loading');
  51788. this.mustPlay = true;
  51789. return;
  51790. }
  51791. found = false;
  51792. this.isPlaying = true;
  51793. for (i = 0; i < this.pool.children.length; i++) {
  51794. sound = this.pool.children[i];
  51795. if (!sound.isPlaying && sound.buffer && !found) {
  51796. if (processSound) { processSound(sound); }
  51797. sound.play();
  51798. sound.isPaused = false;
  51799. found = true;
  51800. continue;
  51801. }
  51802. }
  51803. if (!found) {
  51804. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  51805. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  51806. return;
  51807. }
  51808. this.mustPlay = false;
  51809. },
  51810. /**
  51811. * Stop all the sounds in the pool.
  51812. */
  51813. stopSound: function () {
  51814. var i;
  51815. var sound;
  51816. this.isPlaying = false;
  51817. for (i = 0; i < this.pool.children.length; i++) {
  51818. sound = this.pool.children[i];
  51819. if (!sound.source || !sound.source.buffer) { return; }
  51820. sound.stop();
  51821. }
  51822. }
  51823. });
  51824. },{"../core/component":130,"../lib/three":178,"../utils/debug":200}],112:[function(_dereq_,module,exports){
  51825. var createTextGeometry = _dereq_('three-bmfont-text');
  51826. var loadBMFont = _dereq_('load-bmfont');
  51827. var registerComponent = _dereq_('../core/component').registerComponent;
  51828. var coreShader = _dereq_('../core/shader');
  51829. var THREE = _dereq_('../lib/three');
  51830. var utils = _dereq_('../utils/');
  51831. var error = utils.debug('components:text:error');
  51832. var shaders = coreShader.shaders;
  51833. var warn = utils.debug('components:text:warn');
  51834. // 1 to match other A-Frame default widths.
  51835. var DEFAULT_WIDTH = 1;
  51836. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  51837. var MAX_ANISOTROPY = 16;
  51838. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  51839. var FONTS = {
  51840. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  51841. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  51842. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  51843. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  51844. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  51845. monoid: FONT_BASE_URL + 'Monoid.fnt',
  51846. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  51847. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  51848. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  51849. };
  51850. var MSDF_FONTS = ['roboto'];
  51851. var DEFAULT_FONT = 'roboto';
  51852. module.exports.FONTS = FONTS;
  51853. var cache = new PromiseCache();
  51854. var fontWidthFactors = {};
  51855. var textures = {};
  51856. // Regular expression for detecting a URLs with a protocol prefix.
  51857. var protocolRe = /^\w+:/;
  51858. /**
  51859. * SDF-based text component.
  51860. * Based on https://github.com/Jam3/three-bmfont-text.
  51861. *
  51862. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  51863. * original `sdf` shader.
  51864. */
  51865. module.exports.Component = registerComponent('text', {
  51866. multiple: true,
  51867. schema: {
  51868. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  51869. alphaTest: {default: 0.5},
  51870. // `anchor` defaults to center to match geometries.
  51871. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  51872. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  51873. color: {type: 'color', default: '#FFF'},
  51874. font: {type: 'string', default: DEFAULT_FONT},
  51875. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  51876. fontImage: {type: 'string'},
  51877. // `height` has no default, will be populated at layout.
  51878. height: {type: 'number'},
  51879. letterSpacing: {type: 'number', default: 0},
  51880. // `lineHeight` defaults to font's `lineHeight` value.
  51881. lineHeight: {type: 'number'},
  51882. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  51883. negate: {type: 'boolean', default: true},
  51884. opacity: {type: 'number', default: 1.0},
  51885. shader: {default: 'sdf', oneOf: shaders},
  51886. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  51887. tabSize: {default: 4},
  51888. transparent: {default: true},
  51889. value: {type: 'string'},
  51890. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  51891. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  51892. width: {type: 'number'},
  51893. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  51894. wrapCount: {type: 'number', default: 40},
  51895. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  51896. wrapPixels: {type: 'number'},
  51897. // `xOffset` to add padding.
  51898. xOffset: {type: 'number', default: 0},
  51899. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  51900. yOffset: {type: 'number', default: 0},
  51901. // `zOffset` will provide a small z offset to avoid z-fighting.
  51902. zOffset: {type: 'number', default: 0.001}
  51903. },
  51904. init: function () {
  51905. this.shaderData = {};
  51906. this.geometry = createTextGeometry();
  51907. this.createOrUpdateMaterial();
  51908. },
  51909. update: function (oldData) {
  51910. var data = this.data;
  51911. var font = this.currentFont;
  51912. if (textures[data.font]) {
  51913. this.texture = textures[data.font];
  51914. } else {
  51915. // Create texture per font.
  51916. this.texture = textures[data.font] = new THREE.Texture();
  51917. this.texture.anisotropy = MAX_ANISOTROPY;
  51918. }
  51919. // Update material.
  51920. this.createOrUpdateMaterial();
  51921. // New font. `updateFont` will later change data and layout.
  51922. if (oldData.font !== data.font) {
  51923. this.updateFont();
  51924. return;
  51925. }
  51926. // Update geometry and layout.
  51927. if (font) {
  51928. this.updateGeometry(this.geometry, font);
  51929. this.updateLayout();
  51930. }
  51931. },
  51932. /**
  51933. * Clean up geometry, material, texture, mesh, objects.
  51934. */
  51935. remove: function () {
  51936. this.geometry.dispose();
  51937. this.geometry = null;
  51938. this.el.removeObject3D(this.attrName);
  51939. this.material.dispose();
  51940. this.material = null;
  51941. this.texture.dispose();
  51942. this.texture = null;
  51943. if (this.shaderObject) { delete this.shaderObject; }
  51944. },
  51945. /**
  51946. * Update the shader of the material.
  51947. */
  51948. createOrUpdateMaterial: function () {
  51949. var data = this.data;
  51950. var hasChangedShader;
  51951. var material = this.material;
  51952. var NewShader;
  51953. var shaderData = this.shaderData;
  51954. var shaderName;
  51955. // Infer shader if using a stock font (or from `-msdf` filename convention).
  51956. shaderName = data.shader;
  51957. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  51958. shaderName = 'msdf';
  51959. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  51960. shaderName = 'sdf';
  51961. }
  51962. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  51963. shaderData.alphaTest = data.alphaTest;
  51964. shaderData.color = data.color;
  51965. shaderData.map = this.texture;
  51966. shaderData.opacity = data.opacity;
  51967. shaderData.side = parseSide(data.side);
  51968. shaderData.transparent = data.transparent;
  51969. shaderData.negate = data.negate;
  51970. // Shader has not changed, do an update.
  51971. if (!hasChangedShader) {
  51972. // Update shader material.
  51973. this.shaderObject.update(shaderData);
  51974. // Apparently, was not set on `init` nor `update`.
  51975. material.transparent = shaderData.transparent;
  51976. material.side = shaderData.side;
  51977. return;
  51978. }
  51979. // Shader has changed. Create a shader material.
  51980. NewShader = createShader(this.el, shaderName, shaderData);
  51981. this.material = NewShader.material;
  51982. this.shaderObject = NewShader.shader;
  51983. // Set new shader material.
  51984. this.material.side = shaderData.side;
  51985. if (this.mesh) { this.mesh.material = this.material; }
  51986. },
  51987. /**
  51988. * Load font for geometry, load font image for material, and apply.
  51989. */
  51990. updateFont: function () {
  51991. var data = this.data;
  51992. var el = this.el;
  51993. var fontSrc;
  51994. var geometry = this.geometry;
  51995. var self = this;
  51996. if (!data.font) { warn('No font specified. Using the default font.'); }
  51997. // Make invisible during font swap.
  51998. if (this.mesh) { this.mesh.visible = false; }
  51999. // Look up font URL to use, and perform cached load.
  52000. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  52001. cache.get(fontSrc, function doLoadFont () {
  52002. return loadFont(fontSrc, data.yOffset);
  52003. }).then(function setFont (font) {
  52004. var fontImgSrc;
  52005. if (font.pages.length !== 1) {
  52006. throw new Error('Currently only single-page bitmap fonts are supported.');
  52007. }
  52008. if (!fontWidthFactors[fontSrc]) {
  52009. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  52010. }
  52011. self.currentFont = font;
  52012. // Look up font image URL to use, and perform cached load.
  52013. fontImgSrc = self.getFontImageSrc();
  52014. cache.get(fontImgSrc, function () {
  52015. return loadTexture(fontImgSrc);
  52016. }).then(function (image) {
  52017. // Make mesh visible and apply font image as texture.
  52018. var texture = self.texture;
  52019. texture.image = image;
  52020. texture.needsUpdate = true;
  52021. textures[data.font] = texture;
  52022. self.texture = texture;
  52023. self.initMesh();
  52024. self.currentFont = font;
  52025. // Update geometry given font metrics.
  52026. self.updateGeometry(geometry, font);
  52027. self.updateLayout();
  52028. self.mesh.visible = true;
  52029. el.emit('textfontset', {font: data.font, fontObj: font});
  52030. }).catch(function (err) {
  52031. error(err.message);
  52032. error(err.stack);
  52033. });
  52034. }).catch(function (err) {
  52035. error(err.message);
  52036. error(err.stack);
  52037. });
  52038. },
  52039. initMesh: function () {
  52040. if (this.mesh) { return; }
  52041. this.mesh = new THREE.Mesh(this.geometry, this.material);
  52042. this.el.setObject3D(this.attrName, this.mesh);
  52043. },
  52044. getFontImageSrc: function () {
  52045. if (this.data.fontImage) { return this.data.fontImage; }
  52046. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  52047. var imageSrc = this.currentFont.pages[0];
  52048. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  52049. // path on disk and try to infer the path from the font source instead.
  52050. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  52051. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  52052. }
  52053. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  52054. },
  52055. /**
  52056. * Update layout with anchor, alignment, baseline, and considering any meshes.
  52057. */
  52058. updateLayout: function () {
  52059. var anchor;
  52060. var baseline;
  52061. var el = this.el;
  52062. var data = this.data;
  52063. var geometry = this.geometry;
  52064. var geometryComponent;
  52065. var height;
  52066. var layout;
  52067. var mesh = this.mesh;
  52068. var textRenderWidth;
  52069. var textScale;
  52070. var width;
  52071. var x;
  52072. var y;
  52073. if (!mesh || !geometry.layout) { return; }
  52074. // Determine width to use (defined width, geometry's width, or default width).
  52075. geometryComponent = el.getAttribute('geometry');
  52076. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  52077. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  52078. // Note that experimental factor will never be correct for variable width fonts.
  52079. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  52080. this.currentFont.widthFactor);
  52081. textScale = width / textRenderWidth;
  52082. // Determine height to use.
  52083. layout = geometry.layout;
  52084. height = textScale * (layout.height + layout.descender);
  52085. // Update geometry dimensions to match text layout if width and height are set to 0.
  52086. // For example, scales a plane to fit text.
  52087. if (geometryComponent && geometryComponent.primitive === 'plane') {
  52088. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  52089. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  52090. }
  52091. // Calculate X position to anchor text left, center, or right.
  52092. anchor = data.anchor === 'align' ? data.align : data.anchor;
  52093. if (anchor === 'left') {
  52094. x = 0;
  52095. } else if (anchor === 'right') {
  52096. x = -1 * layout.width;
  52097. } else if (anchor === 'center') {
  52098. x = -1 * layout.width / 2;
  52099. } else {
  52100. throw new TypeError('Invalid text.anchor property value', anchor);
  52101. }
  52102. // Calculate Y position to anchor text top, center, or bottom.
  52103. baseline = data.baseline;
  52104. if (baseline === 'bottom') {
  52105. y = 0;
  52106. } else if (baseline === 'top') {
  52107. y = -1 * layout.height + layout.ascender;
  52108. } else if (baseline === 'center') {
  52109. y = -1 * layout.height / 2;
  52110. } else {
  52111. throw new TypeError('Invalid text.baseline property value', baseline);
  52112. }
  52113. // Position and scale mesh to apply layout.
  52114. mesh.position.x = x * textScale + data.xOffset;
  52115. mesh.position.y = y * textScale;
  52116. // Place text slightly in front to avoid Z-fighting.
  52117. mesh.position.z = data.zOffset;
  52118. mesh.scale.set(textScale, -1 * textScale, textScale);
  52119. },
  52120. /**
  52121. * Grab font from the constant.
  52122. * Set as a method for test stubbing purposes.
  52123. */
  52124. lookupFont: function (key) {
  52125. return FONTS[key];
  52126. },
  52127. /**
  52128. * Update the text geometry using `three-bmfont-text.update`.
  52129. */
  52130. updateGeometry: (function () {
  52131. var geometryUpdateBase = {};
  52132. var geometryUpdateData = {};
  52133. var newLineRegex = /\\n/g;
  52134. var tabRegex = /\\t/g;
  52135. return function (geometry, font) {
  52136. var data = this.data;
  52137. geometryUpdateData.font = font;
  52138. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  52139. ? data.lineHeight
  52140. : font.common.lineHeight;
  52141. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  52142. .replace(tabRegex, '\t');
  52143. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  52144. font.widthFactor);
  52145. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  52146. };
  52147. })()
  52148. });
  52149. /**
  52150. * Due to using negative scale, we return the opposite side specified.
  52151. * https://github.com/mrdoob/three.js/pull/12787/
  52152. */
  52153. function parseSide (side) {
  52154. switch (side) {
  52155. case 'back': {
  52156. return THREE.FrontSide;
  52157. }
  52158. case 'double': {
  52159. return THREE.DoubleSide;
  52160. }
  52161. default: {
  52162. return THREE.BackSide;
  52163. }
  52164. }
  52165. }
  52166. /**
  52167. * @returns {Promise}
  52168. */
  52169. function loadFont (src, yOffset) {
  52170. return new Promise(function (resolve, reject) {
  52171. loadBMFont(src, function (err, font) {
  52172. if (err) {
  52173. error('Error loading font', src);
  52174. reject(err);
  52175. return;
  52176. }
  52177. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  52178. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  52179. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  52180. resolve(font);
  52181. });
  52182. });
  52183. }
  52184. /**
  52185. * @returns {Promise}
  52186. */
  52187. function loadTexture (src) {
  52188. return new Promise(function (resolve, reject) {
  52189. new THREE.ImageLoader().load(src, function (image) {
  52190. resolve(image);
  52191. }, undefined, function () {
  52192. error('Error loading font image', src);
  52193. reject(null);
  52194. });
  52195. });
  52196. }
  52197. function createShader (el, shaderName, data) {
  52198. var shader;
  52199. var shaderObject;
  52200. // Set up Shader.
  52201. shaderObject = new shaders[shaderName].Shader();
  52202. shaderObject.el = el;
  52203. shaderObject.init(data);
  52204. shaderObject.update(data);
  52205. // Get material.
  52206. shader = shaderObject.material;
  52207. // Apparently, was not set on `init` nor `update`.
  52208. shader.transparent = data.transparent;
  52209. return {
  52210. material: shader,
  52211. shader: shaderObject
  52212. };
  52213. }
  52214. /**
  52215. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  52216. * Note that experimental factor will never be correct for variable width fonts.
  52217. */
  52218. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  52219. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  52220. }
  52221. /**
  52222. * Compute default font width factor to use.
  52223. */
  52224. function computeFontWidthFactor (font) {
  52225. var sum = 0;
  52226. var digitsum = 0;
  52227. var digits = 0;
  52228. font.chars.map(function (ch) {
  52229. sum += ch.xadvance;
  52230. if (ch.id >= 48 && ch.id <= 57) {
  52231. digits++;
  52232. digitsum += ch.xadvance;
  52233. }
  52234. });
  52235. return digits ? digitsum / digits : sum / font.chars.length;
  52236. }
  52237. /**
  52238. * Get or create a promise given a key and promise generator.
  52239. * @todo Move to a utility and use in other parts of A-Frame.
  52240. */
  52241. function PromiseCache () {
  52242. var cache = this.cache = {};
  52243. this.get = function (key, promiseGenerator) {
  52244. if (key in cache) {
  52245. return cache[key];
  52246. }
  52247. cache[key] = promiseGenerator();
  52248. return cache[key];
  52249. };
  52250. }
  52251. },{"../core/component":130,"../core/shader":140,"../lib/three":178,"../utils/":204,"load-bmfont":37,"three-bmfont-text":62}],113:[function(_dereq_,module,exports){
  52252. var registerComponent = _dereq_('../core/component').registerComponent;
  52253. var controllerUtils = _dereq_('../utils/tracked-controls');
  52254. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  52255. var THREE = _dereq_('../lib/three');
  52256. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  52257. // Vector from eyes to elbow (divided by user height).
  52258. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  52259. // Vector from eyes to elbow (divided by user height).
  52260. var FOREARM = {x: 0, y: 0, z: -0.175};
  52261. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  52262. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  52263. var EVENTS = {
  52264. AXISMOVE: 'axismove',
  52265. BUTTONCHANGED: 'buttonchanged',
  52266. BUTTONDOWN: 'buttondown',
  52267. BUTTONUP: 'buttonup',
  52268. TOUCHSTART: 'touchstart',
  52269. TOUCHEND: 'touchend'
  52270. };
  52271. /**
  52272. * Tracked controls component.
  52273. * Wrap the gamepad API for pose and button states.
  52274. * Select the appropriate controller and apply pose to the entity.
  52275. * Observe button states and emit appropriate events.
  52276. *
  52277. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52278. * Only used if hand property is not set.
  52279. * @property {string} id - Selected controller among those returned by Gamepad API.
  52280. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52281. * given value for hand. If set, we ignore 'controller' property
  52282. */
  52283. module.exports.Component = registerComponent('tracked-controls-webvr', {
  52284. schema: {
  52285. autoHide: {default: true},
  52286. controller: {default: 0},
  52287. id: {type: 'string', default: ''},
  52288. hand: {type: 'string', default: ''},
  52289. idPrefix: {type: 'string', default: ''},
  52290. orientationOffset: {type: 'vec3'},
  52291. // Arm model parameters when not 6DoF.
  52292. armModel: {default: false},
  52293. headElement: {type: 'selector'}
  52294. },
  52295. init: function () {
  52296. // Copy variables back to tracked-controls for backwards compatibility.
  52297. // Some 3rd components rely on them.
  52298. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52299. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52300. this.changedAxes = [];
  52301. this.targetControllerNumber = this.data.controller;
  52302. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52303. this.deltaControllerPosition = new THREE.Vector3();
  52304. this.controllerQuaternion = new THREE.Quaternion();
  52305. this.controllerEuler = new THREE.Euler();
  52306. this.updateGamepad();
  52307. this.buttonEventDetails = {};
  52308. },
  52309. tick: function (time, delta) {
  52310. var mesh = this.el.getObject3D('mesh');
  52311. // Update mesh animations.
  52312. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  52313. this.updateGamepad();
  52314. this.updatePose();
  52315. this.updateButtons();
  52316. },
  52317. /**
  52318. * Return default user height to use for non-6DOF arm model.
  52319. */
  52320. defaultUserHeight: function () {
  52321. return DEFAULT_CAMERA_HEIGHT;
  52322. },
  52323. /**
  52324. * Return head element to use for non-6DOF arm model.
  52325. */
  52326. getHeadElement: function () {
  52327. return this.data.headElement || this.el.sceneEl.camera.el;
  52328. },
  52329. /**
  52330. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52331. */
  52332. updateGamepad: function () {
  52333. var data = this.data;
  52334. var controller = controllerUtils.findMatchingControllerWebVR(
  52335. this.system.controllers,
  52336. data.id,
  52337. data.idPrefix,
  52338. data.hand,
  52339. data.controller
  52340. );
  52341. this.controller = controller;
  52342. // Legacy handle to the controller for old components.
  52343. this.el.components['tracked-controls'].controller = controller;
  52344. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52345. },
  52346. /**
  52347. * Applies an artificial arm model to simulate elbow to wrist positioning
  52348. * based on the orientation of the controller.
  52349. *
  52350. * @param {object} controllerPosition - Existing vector to update with controller position.
  52351. */
  52352. applyArmModel: function (controllerPosition) {
  52353. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  52354. var controller = this.controller;
  52355. var controllerEuler = this.controllerEuler;
  52356. var controllerQuaternion = this.controllerQuaternion;
  52357. var deltaControllerPosition = this.deltaControllerPosition;
  52358. var hand;
  52359. var headEl;
  52360. var headObject3D;
  52361. var pose;
  52362. var userHeight;
  52363. headEl = this.getHeadElement();
  52364. headObject3D = headEl.object3D;
  52365. userHeight = this.defaultUserHeight();
  52366. pose = controller.pose;
  52367. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  52368. // Use camera position as head position.
  52369. controllerPosition.copy(headObject3D.position);
  52370. // Set offset for degenerate "arm model" to elbow.
  52371. deltaControllerPosition.set(
  52372. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  52373. EYES_TO_ELBOW.y, // Lower than our eyes.
  52374. EYES_TO_ELBOW.z); // Slightly out in front.
  52375. // Scale offset by user height.
  52376. deltaControllerPosition.multiplyScalar(userHeight);
  52377. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  52378. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  52379. // Apply rotated offset to position.
  52380. controllerPosition.add(deltaControllerPosition);
  52381. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  52382. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  52383. // Scale offset by user height.
  52384. deltaControllerPosition.multiplyScalar(userHeight);
  52385. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  52386. if (pose.orientation) {
  52387. controllerQuaternion.fromArray(pose.orientation);
  52388. } else {
  52389. controllerQuaternion.copy(headObject3D.quaternion);
  52390. }
  52391. controllerEuler.setFromQuaternion(controllerQuaternion);
  52392. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  52393. deltaControllerPosition.applyEuler(controllerEuler);
  52394. // Apply rotated offset to position.
  52395. controllerPosition.add(deltaControllerPosition);
  52396. },
  52397. /**
  52398. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  52399. */
  52400. updatePose: function () {
  52401. var controller = this.controller;
  52402. var data = this.data;
  52403. var object3D = this.el.object3D;
  52404. var pose;
  52405. var vrDisplay = this.system.vrDisplay;
  52406. var standingMatrix;
  52407. if (!controller) { return; }
  52408. // Compose pose from Gamepad.
  52409. pose = controller.pose;
  52410. if (pose.position) {
  52411. object3D.position.fromArray(pose.position);
  52412. } else {
  52413. // Controller not 6DOF, apply arm model.
  52414. if (data.armModel) { this.applyArmModel(object3D.position); }
  52415. }
  52416. if (pose.orientation) {
  52417. object3D.quaternion.fromArray(pose.orientation);
  52418. }
  52419. // Apply transforms, if 6DOF and in VR.
  52420. if (vrDisplay && pose.position) {
  52421. standingMatrix = this.el.sceneEl.renderer.xr.getStandingMatrix();
  52422. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  52423. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  52424. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  52425. }
  52426. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  52427. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  52428. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  52429. },
  52430. /**
  52431. * Handle button changes including axes, presses, touches, values.
  52432. */
  52433. updateButtons: function () {
  52434. var buttonState;
  52435. var controller = this.controller;
  52436. var id;
  52437. if (!controller) { return; }
  52438. // Check every button.
  52439. for (id = 0; id < controller.buttons.length; ++id) {
  52440. // Initialize button state.
  52441. if (!this.buttonStates[id]) {
  52442. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52443. }
  52444. if (!this.buttonEventDetails[id]) {
  52445. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52446. }
  52447. buttonState = controller.buttons[id];
  52448. this.handleButton(id, buttonState);
  52449. }
  52450. // Check axes.
  52451. this.handleAxes();
  52452. },
  52453. /**
  52454. * Handle presses and touches for a single button.
  52455. *
  52456. * @param {number} id - Index of button in Gamepad button array.
  52457. * @param {number} buttonState - Value of button state from 0 to 1.
  52458. * @returns {boolean} Whether button has changed in any way.
  52459. */
  52460. handleButton: function (id, buttonState) {
  52461. var changed;
  52462. changed = this.handlePress(id, buttonState) |
  52463. this.handleTouch(id, buttonState) |
  52464. this.handleValue(id, buttonState);
  52465. if (!changed) { return false; }
  52466. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52467. return true;
  52468. },
  52469. /**
  52470. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52471. * Compare each component of the axis to the previous value to determine change.
  52472. *
  52473. * @returns {boolean} Whether axes changed.
  52474. */
  52475. handleAxes: function () {
  52476. var changed = false;
  52477. var controllerAxes = this.controller.axes;
  52478. var i;
  52479. var previousAxis = this.axis;
  52480. var changedAxes = this.changedAxes;
  52481. // Check if axis changed.
  52482. this.changedAxes.splice(0, this.changedAxes.length);
  52483. for (i = 0; i < controllerAxes.length; ++i) {
  52484. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52485. if (changedAxes[i]) { changed = true; }
  52486. }
  52487. if (!changed) { return false; }
  52488. this.axis.splice(0, this.axis.length);
  52489. for (i = 0; i < controllerAxes.length; i++) {
  52490. this.axis.push(controllerAxes[i]);
  52491. }
  52492. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52493. return true;
  52494. },
  52495. /**
  52496. * Determine whether a button press has occured and emit events as appropriate.
  52497. *
  52498. * @param {string} id - ID of the button to check.
  52499. * @param {object} buttonState - State of the button to check.
  52500. * @returns {boolean} Whether button press state changed.
  52501. */
  52502. handlePress: function (id, buttonState) {
  52503. var evtName;
  52504. var previousButtonState = this.buttonStates[id];
  52505. // Not changed.
  52506. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52507. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52508. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52509. previousButtonState.pressed = buttonState.pressed;
  52510. return true;
  52511. },
  52512. /**
  52513. * Determine whether a button touch has occured and emit events as appropriate.
  52514. *
  52515. * @param {string} id - ID of the button to check.
  52516. * @param {object} buttonState - State of the button to check.
  52517. * @returns {boolean} Whether button touch state changed.
  52518. */
  52519. handleTouch: function (id, buttonState) {
  52520. var evtName;
  52521. var previousButtonState = this.buttonStates[id];
  52522. // Not changed.
  52523. if (buttonState.touched === previousButtonState.touched) { return false; }
  52524. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52525. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  52526. previousButtonState.touched = buttonState.touched;
  52527. return true;
  52528. },
  52529. /**
  52530. * Determine whether a button value has changed.
  52531. *
  52532. * @param {string} id - Id of the button to check.
  52533. * @param {object} buttonState - State of the button to check.
  52534. * @returns {boolean} Whether button value changed.
  52535. */
  52536. handleValue: function (id, buttonState) {
  52537. var previousButtonState = this.buttonStates[id];
  52538. // Not changed.
  52539. if (buttonState.value === previousButtonState.value) { return false; }
  52540. previousButtonState.value = buttonState.value;
  52541. return true;
  52542. }
  52543. });
  52544. },{"../constants":122,"../core/component":130,"../lib/three":178,"../utils/tracked-controls":213}],114:[function(_dereq_,module,exports){
  52545. var controllerUtils = _dereq_('../utils/tracked-controls');
  52546. var registerComponent = _dereq_('../core/component').registerComponent;
  52547. var EVENTS = {
  52548. AXISMOVE: 'axismove',
  52549. BUTTONCHANGED: 'buttonchanged',
  52550. BUTTONDOWN: 'buttondown',
  52551. BUTTONUP: 'buttonup',
  52552. TOUCHSTART: 'touchstart',
  52553. TOUCHEND: 'touchend'
  52554. };
  52555. module.exports.Component = registerComponent('tracked-controls-webxr', {
  52556. schema: {
  52557. id: {type: 'string', default: ''},
  52558. hand: {type: 'string', default: ''},
  52559. handTrackingEnabled: {default: false},
  52560. index: {type: 'int', default: -1},
  52561. iterateControllerProfiles: {default: false}
  52562. },
  52563. init: function () {
  52564. this.updateController = this.updateController.bind(this);
  52565. this.buttonEventDetails = {};
  52566. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52567. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52568. this.changedAxes = [];
  52569. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52570. },
  52571. update: function () {
  52572. this.updateController();
  52573. },
  52574. play: function () {
  52575. var sceneEl = this.el.sceneEl;
  52576. this.updateController();
  52577. sceneEl.addEventListener('controllersupdated', this.updateController);
  52578. },
  52579. pause: function () {
  52580. var sceneEl = this.el.sceneEl;
  52581. sceneEl.removeEventListener('controllersupdated', this.updateController);
  52582. },
  52583. isControllerPresent: function (evt) {
  52584. if (!this.controller || this.controller.gamepad) { return false; }
  52585. if (evt.inputSource.handedness !== 'none' &&
  52586. evt.inputSource.handedness !== this.data.hand) {
  52587. return false;
  52588. }
  52589. return true;
  52590. },
  52591. /**
  52592. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52593. */
  52594. updateController: function () {
  52595. this.controller = controllerUtils.findMatchingControllerWebXR(
  52596. this.system.controllers,
  52597. this.data.id,
  52598. this.data.hand,
  52599. this.data.index,
  52600. this.data.iterateControllerProfiles,
  52601. this.data.handTrackingEnabled
  52602. );
  52603. // Legacy handle to the controller for old components.
  52604. this.el.components['tracked-controls'].controller = this.controller;
  52605. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52606. },
  52607. tick: function () {
  52608. var sceneEl = this.el.sceneEl;
  52609. var controller = this.controller;
  52610. var frame = sceneEl.frame;
  52611. if (!controller || !sceneEl.frame || !this.system.referenceSpace) { return; }
  52612. if (!controller.hand) {
  52613. this.pose = frame.getPose(controller.targetRaySpace, this.system.referenceSpace);
  52614. this.updatePose();
  52615. this.updateButtons();
  52616. }
  52617. },
  52618. updatePose: function () {
  52619. var object3D = this.el.object3D;
  52620. var pose = this.pose;
  52621. if (!pose) { return; }
  52622. object3D.matrix.elements = pose.transform.matrix;
  52623. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  52624. },
  52625. /**
  52626. * Handle button changes including axes, presses, touches, values.
  52627. */
  52628. updateButtons: function () {
  52629. var buttonState;
  52630. var id;
  52631. var controller = this.controller;
  52632. var gamepad;
  52633. if (!controller || !controller.gamepad) { return; }
  52634. gamepad = controller.gamepad;
  52635. // Check every button.
  52636. for (id = 0; id < gamepad.buttons.length; ++id) {
  52637. // Initialize button state.
  52638. if (!this.buttonStates[id]) {
  52639. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52640. }
  52641. if (!this.buttonEventDetails[id]) {
  52642. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52643. }
  52644. buttonState = gamepad.buttons[id];
  52645. this.handleButton(id, buttonState);
  52646. }
  52647. // Check axes.
  52648. this.handleAxes();
  52649. },
  52650. /**
  52651. * Handle presses and touches for a single button.
  52652. *
  52653. * @param {number} id - Index of button in Gamepad button array.
  52654. * @param {number} buttonState - Value of button state from 0 to 1.
  52655. * @returns {boolean} Whether button has changed in any way.
  52656. */
  52657. handleButton: function (id, buttonState) {
  52658. var changed;
  52659. changed = this.handlePress(id, buttonState) |
  52660. this.handleTouch(id, buttonState) |
  52661. this.handleValue(id, buttonState);
  52662. if (!changed) { return false; }
  52663. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52664. return true;
  52665. },
  52666. /**
  52667. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52668. * Compare each component of the axis to the previous value to determine change.
  52669. *
  52670. * @returns {boolean} Whether axes changed.
  52671. */
  52672. handleAxes: function () {
  52673. var changed = false;
  52674. var controllerAxes = this.controller.gamepad.axes;
  52675. var i;
  52676. var previousAxis = this.axis;
  52677. var changedAxes = this.changedAxes;
  52678. // Check if axis changed.
  52679. this.changedAxes.splice(0, this.changedAxes.length);
  52680. for (i = 0; i < controllerAxes.length; ++i) {
  52681. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52682. if (changedAxes[i]) { changed = true; }
  52683. }
  52684. if (!changed) { return false; }
  52685. this.axis.splice(0, this.axis.length);
  52686. for (i = 0; i < controllerAxes.length; i++) {
  52687. this.axis.push(controllerAxes[i]);
  52688. }
  52689. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52690. return true;
  52691. },
  52692. /**
  52693. * Determine whether a button press has occured and emit events as appropriate.
  52694. *
  52695. * @param {string} id - ID of the button to check.
  52696. * @param {object} buttonState - State of the button to check.
  52697. * @returns {boolean} Whether button press state changed.
  52698. */
  52699. handlePress: function (id, buttonState) {
  52700. var evtName;
  52701. var previousButtonState = this.buttonStates[id];
  52702. // Not changed.
  52703. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52704. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52705. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52706. previousButtonState.pressed = buttonState.pressed;
  52707. return true;
  52708. },
  52709. /**
  52710. * Determine whether a button touch has occured and emit events as appropriate.
  52711. *
  52712. * @param {string} id - ID of the button to check.
  52713. * @param {object} buttonState - State of the button to check.
  52714. * @returns {boolean} Whether button touch state changed.
  52715. */
  52716. handleTouch: function (id, buttonState) {
  52717. var evtName;
  52718. var previousButtonState = this.buttonStates[id];
  52719. // Not changed.
  52720. if (buttonState.touched === previousButtonState.touched) { return false; }
  52721. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52722. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52723. previousButtonState.touched = buttonState.touched;
  52724. return true;
  52725. },
  52726. /**
  52727. * Determine whether a button value has changed.
  52728. *
  52729. * @param {string} id - Id of the button to check.
  52730. * @param {object} buttonState - State of the button to check.
  52731. * @returns {boolean} Whether button value changed.
  52732. */
  52733. handleValue: function (id, buttonState) {
  52734. var previousButtonState = this.buttonStates[id];
  52735. // Not changed.
  52736. if (buttonState.value === previousButtonState.value) { return false; }
  52737. previousButtonState.value = buttonState.value;
  52738. return true;
  52739. }
  52740. });
  52741. },{"../core/component":130,"../utils/tracked-controls":213}],115:[function(_dereq_,module,exports){
  52742. var registerComponent = _dereq_('../core/component').registerComponent;
  52743. /**
  52744. * Tracked controls.
  52745. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  52746. *
  52747. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52748. * Only used if hand property is not set.
  52749. * @property {string} id - Selected controller among those returned by Gamepad API.
  52750. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52751. * given value for hand. If set, we ignore 'controller' property
  52752. */
  52753. module.exports.Component = registerComponent('tracked-controls', {
  52754. schema: {
  52755. autoHide: {default: true},
  52756. controller: {default: -1},
  52757. id: {type: 'string', default: ''},
  52758. hand: {type: 'string', default: ''},
  52759. idPrefix: {type: 'string', default: ''},
  52760. handTrackingEnabled: {default: false},
  52761. orientationOffset: {type: 'vec3'},
  52762. // Arm model parameters when not 6DoF.
  52763. armModel: {default: false},
  52764. headElement: {type: 'selector'},
  52765. iterateControllerProfiles: {default: false}
  52766. },
  52767. update: function () {
  52768. var data = this.data;
  52769. var el = this.el;
  52770. if (el.sceneEl.hasWebXR) {
  52771. el.setAttribute('tracked-controls-webxr', {
  52772. id: data.id,
  52773. hand: data.hand,
  52774. index: data.controller,
  52775. iterateControllerProfiles: data.iterateControllerProfiles,
  52776. handTrackingEnabled: data.handTrackingEnabled
  52777. });
  52778. } else {
  52779. el.setAttribute('tracked-controls-webvr', data);
  52780. }
  52781. }
  52782. });
  52783. },{"../core/component":130}],116:[function(_dereq_,module,exports){
  52784. var registerComponent = _dereq_('../core/component').registerComponent;
  52785. var bind = _dereq_('../utils/bind');
  52786. var THREE = _dereq_('../lib/three');
  52787. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  52788. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52789. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52790. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52791. var INDEX_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/valve/index/valve-index-';
  52792. var INDEX_CONTROLLER_MODEL_URL = {
  52793. left: INDEX_CONTROLLER_MODEL_BASE_URL + 'left.glb',
  52794. right: INDEX_CONTROLLER_MODEL_BASE_URL + 'right.glb'
  52795. };
  52796. var GAMEPAD_ID_PREFIX = 'valve';
  52797. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  52798. var INDEX_CONTROLLER_POSITION_OFFSET_WEBVR = {
  52799. left: {x: -0.00023692678902063457, y: 0.04724540367838371, z: -0.061959880395271096},
  52800. right: {x: 0.002471558599671131, y: 0.055765208987076195, z: -0.061068168708348844}
  52801. };
  52802. var INDEX_CONTROLLER_POSITION_OFFSET_WEBXR = {
  52803. left: {x: 0, y: -0.05, z: 0.06},
  52804. right: {x: 0, y: -0.05, z: 0.06}
  52805. };
  52806. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR = {
  52807. left: {_x: 0.692295102620542, _y: -0.0627618864318427, _z: -0.06265893149611756, _order: 'XYZ'},
  52808. right: {_x: 0.6484021229942998, _y: -0.032563619881892894, _z: -0.1327973171917482, _order: 'XYZ'}
  52809. };
  52810. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR = {
  52811. left: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'},
  52812. right: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'}
  52813. };
  52814. var INDEX_CONTROLLER_ROTATION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR : INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR;
  52815. var INDEX_CONTROLLER_POSITION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_POSITION_OFFSET_WEBXR : INDEX_CONTROLLER_POSITION_OFFSET_WEBVR;
  52816. /**
  52817. * Vive controls.
  52818. * Interface with Vive controllers and map Gamepad events to controller buttons:
  52819. * trackpad, trigger, grip, menu, system
  52820. * Load a controller model and highlight the pressed buttons.
  52821. */
  52822. module.exports.Component = registerComponent('valve-index-controls', {
  52823. schema: {
  52824. hand: {default: 'left'},
  52825. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  52826. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  52827. model: {default: true},
  52828. orientationOffset: {type: 'vec3'}
  52829. },
  52830. mapping: {
  52831. axes: {
  52832. trackpad: [0, 1],
  52833. thumbstick: [2, 3]
  52834. },
  52835. buttons: ['trigger', 'grip', 'trackpad', 'thumbstick', 'abutton']
  52836. },
  52837. init: function () {
  52838. var self = this;
  52839. this.controllerPresent = false;
  52840. this.lastControllerCheck = 0;
  52841. this.onButtonChanged = bind(this.onButtonChanged, this);
  52842. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  52843. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  52844. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  52845. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  52846. this.previousButtonValues = {};
  52847. this.rendererSystem = this.el.sceneEl.systems.renderer;
  52848. this.bindMethods();
  52849. },
  52850. play: function () {
  52851. this.checkIfControllerPresent();
  52852. this.addControllersUpdateListener();
  52853. },
  52854. pause: function () {
  52855. this.removeEventListeners();
  52856. this.removeControllersUpdateListener();
  52857. },
  52858. bindMethods: function () {
  52859. this.onModelLoaded = bind(this.onModelLoaded, this);
  52860. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  52861. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  52862. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  52863. this.onAxisMoved = bind(this.onAxisMoved, this);
  52864. },
  52865. addEventListeners: function () {
  52866. var el = this.el;
  52867. el.addEventListener('buttonchanged', this.onButtonChanged);
  52868. el.addEventListener('buttondown', this.onButtonDown);
  52869. el.addEventListener('buttonup', this.onButtonUp);
  52870. el.addEventListener('touchend', this.onButtonTouchEnd);
  52871. el.addEventListener('touchstart', this.onButtonTouchStart);
  52872. el.addEventListener('model-loaded', this.onModelLoaded);
  52873. el.addEventListener('axismove', this.onAxisMoved);
  52874. this.controllerEventsActive = true;
  52875. },
  52876. removeEventListeners: function () {
  52877. var el = this.el;
  52878. el.removeEventListener('buttonchanged', this.onButtonChanged);
  52879. el.removeEventListener('buttondown', this.onButtonDown);
  52880. el.removeEventListener('buttonup', this.onButtonUp);
  52881. el.removeEventListener('touchend', this.onButtonTouchEnd);
  52882. el.removeEventListener('touchstart', this.onButtonTouchStart);
  52883. el.removeEventListener('model-loaded', this.onModelLoaded);
  52884. el.removeEventListener('axismove', this.onAxisMoved);
  52885. this.controllerEventsActive = false;
  52886. },
  52887. /**
  52888. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  52889. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  52890. { hand: data.hand });
  52891. * Until then, use hardcoded index.
  52892. */
  52893. checkIfControllerPresent: function () {
  52894. var data = this.data;
  52895. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  52896. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex, iterateControllerProfiles: true, hand: data.hand});
  52897. },
  52898. injectTrackedControls: function () {
  52899. var el = this.el;
  52900. var data = this.data;
  52901. // If we have an OpenVR Gamepad, use the fixed mapping.
  52902. el.setAttribute('tracked-controls', {
  52903. idPrefix: GAMEPAD_ID_PREFIX,
  52904. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  52905. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  52906. hand: data.hand,
  52907. orientationOffset: data.orientationOffset
  52908. });
  52909. this.loadModel();
  52910. },
  52911. loadModel: function () {
  52912. var data = this.data;
  52913. if (!data.model) { return; }
  52914. this.el.setAttribute('gltf-model', '' + INDEX_CONTROLLER_MODEL_URL[data.hand] + '');
  52915. },
  52916. addControllersUpdateListener: function () {
  52917. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  52918. },
  52919. removeControllersUpdateListener: function () {
  52920. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  52921. },
  52922. onControllersUpdate: function () {
  52923. this.checkIfControllerPresent();
  52924. },
  52925. /**
  52926. * Rotate the trigger button based on how hard the trigger is pressed.
  52927. */
  52928. onButtonChanged: function (evt) {
  52929. var button = this.mapping.buttons[evt.detail.id];
  52930. var buttonMeshes = this.buttonMeshes;
  52931. var analogValue;
  52932. if (!button) { return; }
  52933. if (button === 'trigger') {
  52934. analogValue = evt.detail.state.value;
  52935. // Update trigger rotation depending on button value.
  52936. if (buttonMeshes && buttonMeshes.trigger) {
  52937. buttonMeshes.trigger.rotation.x = this.triggerOriginalRotationX - analogValue * (Math.PI / 40);
  52938. }
  52939. }
  52940. // Pass along changed event with button state, using button mapping for convenience.
  52941. this.el.emit(button + 'changed', evt.detail.state);
  52942. },
  52943. onModelLoaded: function (evt) {
  52944. var buttonMeshes;
  52945. var controllerObject3D = evt.detail.model;
  52946. var self = this;
  52947. if (!this.data.model) { return; }
  52948. // Store button meshes object to be able to change their colors.
  52949. buttonMeshes = this.buttonMeshes = {};
  52950. buttonMeshes.grip = {
  52951. left: controllerObject3D.getObjectByName('leftgrip'),
  52952. right: controllerObject3D.getObjectByName('rightgrip')
  52953. };
  52954. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  52955. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  52956. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  52957. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  52958. this.triggerOriginalRotationX = buttonMeshes.trigger.rotation.x;
  52959. // Set default colors.
  52960. Object.keys(buttonMeshes).forEach(function (buttonName) {
  52961. self.setButtonColor(buttonName, self.data.buttonColor);
  52962. });
  52963. // Offset pivot point.
  52964. controllerObject3D.position.copy(INDEX_CONTROLLER_POSITION_OFFSET[this.data.hand]);
  52965. controllerObject3D.rotation.copy(INDEX_CONTROLLER_ROTATION_OFFSET[this.data.hand]);
  52966. this.el.emit('controllermodelready', {
  52967. name: 'valve-index-controlls',
  52968. model: this.data.model,
  52969. rayOrigin: new THREE.Vector3(0, 0, 0)
  52970. });
  52971. },
  52972. onAxisMoved: function (evt) {
  52973. emitIfAxesChanged(this, this.mapping.axes, evt);
  52974. },
  52975. updateModel: function (buttonName, evtName) {
  52976. var color;
  52977. var isTouch;
  52978. if (!this.data.model) { return; }
  52979. isTouch = evtName.indexOf('touch') !== -1;
  52980. // Don't change color for trackpad touch.
  52981. if (isTouch) { return; }
  52982. // Update colors.
  52983. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  52984. this.setButtonColor(buttonName, color);
  52985. },
  52986. setButtonColor: function (buttonName, color) {
  52987. // TODO: The meshes aren't set up correctly now, skipping for the moment
  52988. return;
  52989. }
  52990. });
  52991. },{"../core/component":130,"../lib/three":178,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],117:[function(_dereq_,module,exports){
  52992. var registerComponent = _dereq_('../core/component').registerComponent;
  52993. /**
  52994. * Visibility component.
  52995. */
  52996. module.exports.Component = registerComponent('visible', {
  52997. schema: {default: true},
  52998. update: function () {
  52999. this.el.object3D.visible = this.data;
  53000. }
  53001. });
  53002. },{"../core/component":130}],118:[function(_dereq_,module,exports){
  53003. var registerComponent = _dereq_('../core/component').registerComponent;
  53004. var bind = _dereq_('../utils/bind');
  53005. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53006. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53007. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53008. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53009. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  53010. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  53011. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  53012. var GAMEPAD_ID_WEBXR = 'htc-vive-controller-mv';
  53013. var GAMEPAD_ID_WEBVR = 'OpenVR ';
  53014. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  53015. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53016. /**
  53017. * Button IDs:
  53018. * 0 - trackpad
  53019. * 1 - trigger (intensity value from 0.5 to 1)
  53020. * 2 - grip
  53021. * 3 - menu (dispatch but better for menu options)
  53022. * 4 - system (never dispatched on this layer)
  53023. */
  53024. var INPUT_MAPPING_WEBVR = {
  53025. axes: {trackpad: [0, 1]},
  53026. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  53027. };
  53028. /**
  53029. * Button IDs:
  53030. * 0 - trigger
  53031. * 1 - squeeze
  53032. * 2 - touchpad
  53033. * 3 - none (dispatch but better for menu options)
  53034. * 4 - menu (never dispatched on this layer)
  53035. *
  53036. * Axis:
  53037. * 0 - touchpad x axis
  53038. * 1 - touchpad y axis
  53039. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/htc/htc-vive.json
  53040. */
  53041. var INPUT_MAPPING_WEBXR = {
  53042. axes: {thumbstick: [0, 1]},
  53043. buttons: ['trigger', 'grip', 'trackpad', 'none', 'menu']
  53044. };
  53045. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53046. /**
  53047. * Vive controls.
  53048. * Interface with Vive controllers and map Gamepad events to controller buttons:
  53049. * trackpad, trigger, grip, menu, system
  53050. * Load a controller model and highlight the pressed buttons.
  53051. */
  53052. module.exports.Component = registerComponent('vive-controls', {
  53053. schema: {
  53054. hand: {default: 'left'},
  53055. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  53056. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  53057. model: {default: true},
  53058. orientationOffset: {type: 'vec3'}
  53059. },
  53060. mapping: INPUT_MAPPING,
  53061. init: function () {
  53062. var self = this;
  53063. this.controllerPresent = false;
  53064. this.lastControllerCheck = 0;
  53065. this.onButtonChanged = bind(this.onButtonChanged, this);
  53066. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53067. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53068. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53069. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53070. this.previousButtonValues = {};
  53071. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53072. this.bindMethods();
  53073. },
  53074. update: function () {
  53075. var data = this.data;
  53076. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  53077. },
  53078. play: function () {
  53079. this.checkIfControllerPresent();
  53080. this.addControllersUpdateListener();
  53081. },
  53082. pause: function () {
  53083. this.removeEventListeners();
  53084. this.removeControllersUpdateListener();
  53085. },
  53086. bindMethods: function () {
  53087. this.onModelLoaded = bind(this.onModelLoaded, this);
  53088. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53089. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53090. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53091. this.onAxisMoved = bind(this.onAxisMoved, this);
  53092. },
  53093. addEventListeners: function () {
  53094. var el = this.el;
  53095. el.addEventListener('buttonchanged', this.onButtonChanged);
  53096. el.addEventListener('buttondown', this.onButtonDown);
  53097. el.addEventListener('buttonup', this.onButtonUp);
  53098. el.addEventListener('touchend', this.onButtonTouchEnd);
  53099. el.addEventListener('touchstart', this.onButtonTouchStart);
  53100. el.addEventListener('model-loaded', this.onModelLoaded);
  53101. el.addEventListener('axismove', this.onAxisMoved);
  53102. this.controllerEventsActive = true;
  53103. },
  53104. removeEventListeners: function () {
  53105. var el = this.el;
  53106. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53107. el.removeEventListener('buttondown', this.onButtonDown);
  53108. el.removeEventListener('buttonup', this.onButtonUp);
  53109. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53110. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53111. el.removeEventListener('model-loaded', this.onModelLoaded);
  53112. el.removeEventListener('axismove', this.onAxisMoved);
  53113. this.controllerEventsActive = false;
  53114. },
  53115. /**
  53116. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  53117. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  53118. { hand: data.hand });
  53119. * Until then, use hardcoded index.
  53120. */
  53121. checkIfControllerPresent: function () {
  53122. var data = this.data;
  53123. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: this.controllerIndex, hand: data.hand});
  53124. },
  53125. injectTrackedControls: function () {
  53126. var el = this.el;
  53127. var data = this.data;
  53128. // If we have an OpenVR Gamepad, use the fixed mapping.
  53129. el.setAttribute('tracked-controls', {
  53130. idPrefix: GAMEPAD_ID_PREFIX,
  53131. hand: data.hand,
  53132. controller: this.controllerIndex,
  53133. orientationOffset: data.orientationOffset
  53134. });
  53135. // Load model.
  53136. if (!this.data.model) { return; }
  53137. this.el.setAttribute('obj-model', {
  53138. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  53139. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  53140. });
  53141. },
  53142. addControllersUpdateListener: function () {
  53143. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53144. },
  53145. removeControllersUpdateListener: function () {
  53146. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53147. },
  53148. onControllersUpdate: function () {
  53149. this.checkIfControllerPresent();
  53150. },
  53151. /**
  53152. * Rotate the trigger button based on how hard the trigger is pressed.
  53153. */
  53154. onButtonChanged: function (evt) {
  53155. var button = this.mapping.buttons[evt.detail.id];
  53156. var buttonMeshes = this.buttonMeshes;
  53157. var analogValue;
  53158. if (!button) { return; }
  53159. if (button === 'trigger') {
  53160. analogValue = evt.detail.state.value;
  53161. // Update trigger rotation depending on button value.
  53162. if (buttonMeshes && buttonMeshes.trigger) {
  53163. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  53164. }
  53165. }
  53166. // Pass along changed event with button state, using button mapping for convenience.
  53167. this.el.emit(button + 'changed', evt.detail.state);
  53168. },
  53169. onModelLoaded: function (evt) {
  53170. var buttonMeshes;
  53171. var controllerObject3D = evt.detail.model;
  53172. var self = this;
  53173. if (!this.data.model) { return; }
  53174. // Store button meshes object to be able to change their colors.
  53175. buttonMeshes = this.buttonMeshes = {};
  53176. buttonMeshes.grip = {
  53177. left: controllerObject3D.getObjectByName('leftgrip'),
  53178. right: controllerObject3D.getObjectByName('rightgrip')
  53179. };
  53180. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  53181. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  53182. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  53183. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  53184. // Set default colors.
  53185. Object.keys(buttonMeshes).forEach(function (buttonName) {
  53186. self.setButtonColor(buttonName, self.data.buttonColor);
  53187. });
  53188. // Offset pivot point.
  53189. controllerObject3D.position.set(0, -0.015, 0.04);
  53190. },
  53191. onAxisMoved: function (evt) {
  53192. emitIfAxesChanged(this, this.mapping.axes, evt);
  53193. },
  53194. updateModel: function (buttonName, evtName) {
  53195. var color;
  53196. var isTouch;
  53197. if (!this.data.model) { return; }
  53198. isTouch = evtName.indexOf('touch') !== -1;
  53199. // Don't change color for trackpad touch.
  53200. if (isTouch) { return; }
  53201. // Update colors.
  53202. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  53203. this.setButtonColor(buttonName, color);
  53204. },
  53205. setButtonColor: function (buttonName, color) {
  53206. var buttonMeshes = this.buttonMeshes;
  53207. var rendererSystem = this.rendererSystem;
  53208. if (!buttonMeshes) { return; }
  53209. // Need to do both left and right sides for grip.
  53210. if (buttonName === 'grip') {
  53211. buttonMeshes.grip.left.material.color.set(color);
  53212. buttonMeshes.grip.right.material.color.set(color);
  53213. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  53214. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  53215. return;
  53216. }
  53217. buttonMeshes[buttonName].material.color.set(color);
  53218. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  53219. }
  53220. });
  53221. },{"../core/component":130,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],119:[function(_dereq_,module,exports){
  53222. var registerComponent = _dereq_('../core/component').registerComponent;
  53223. var bind = _dereq_('../utils/bind');
  53224. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53225. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53226. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53227. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53228. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  53229. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  53230. /**
  53231. * Vive Focus controls.
  53232. * Interface with Vive Focus controller and map Gamepad events to
  53233. * controller buttons: trackpad, trigger
  53234. * Load a controller model and highlight the pressed buttons.
  53235. */
  53236. module.exports.Component = registerComponent('vive-focus-controls', {
  53237. schema: {
  53238. hand: {default: ''}, // This informs the degenerate arm model.
  53239. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  53240. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  53241. model: {default: true},
  53242. orientationOffset: {type: 'vec3'},
  53243. armModel: {default: true}
  53244. },
  53245. /**
  53246. * Button IDs:
  53247. * 0 - trackpad
  53248. * 1 - trigger
  53249. */
  53250. mapping: {
  53251. axes: {trackpad: [0, 1]},
  53252. buttons: ['trackpad', 'trigger']
  53253. },
  53254. bindMethods: function () {
  53255. this.onModelLoaded = bind(this.onModelLoaded, this);
  53256. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53257. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53258. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53259. this.onAxisMoved = bind(this.onAxisMoved, this);
  53260. },
  53261. init: function () {
  53262. var self = this;
  53263. this.onButtonChanged = bind(this.onButtonChanged, this);
  53264. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53265. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53266. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53267. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53268. this.controllerPresent = false;
  53269. this.lastControllerCheck = 0;
  53270. this.bindMethods();
  53271. },
  53272. addEventListeners: function () {
  53273. var el = this.el;
  53274. el.addEventListener('buttonchanged', this.onButtonChanged);
  53275. el.addEventListener('buttondown', this.onButtonDown);
  53276. el.addEventListener('buttonup', this.onButtonUp);
  53277. el.addEventListener('touchstart', this.onButtonTouchStart);
  53278. el.addEventListener('touchend', this.onButtonTouchEnd);
  53279. el.addEventListener('model-loaded', this.onModelLoaded);
  53280. el.addEventListener('axismove', this.onAxisMoved);
  53281. this.controllerEventsActive = true;
  53282. this.addControllersUpdateListener();
  53283. },
  53284. removeEventListeners: function () {
  53285. var el = this.el;
  53286. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53287. el.removeEventListener('buttondown', this.onButtonDown);
  53288. el.removeEventListener('buttonup', this.onButtonUp);
  53289. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53290. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53291. el.removeEventListener('model-loaded', this.onModelLoaded);
  53292. el.removeEventListener('axismove', this.onAxisMoved);
  53293. this.controllerEventsActive = false;
  53294. this.removeControllersUpdateListener();
  53295. },
  53296. checkIfControllerPresent: function () {
  53297. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  53298. this.data.hand ? {hand: this.data.hand} : {});
  53299. },
  53300. play: function () {
  53301. this.checkIfControllerPresent();
  53302. this.addControllersUpdateListener();
  53303. },
  53304. pause: function () {
  53305. this.removeEventListeners();
  53306. this.removeControllersUpdateListener();
  53307. },
  53308. injectTrackedControls: function () {
  53309. var el = this.el;
  53310. var data = this.data;
  53311. el.setAttribute('tracked-controls', {
  53312. armModel: data.armModel,
  53313. idPrefix: GAMEPAD_ID_PREFIX,
  53314. orientationOffset: data.orientationOffset
  53315. });
  53316. if (!this.data.model) { return; }
  53317. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  53318. },
  53319. addControllersUpdateListener: function () {
  53320. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53321. },
  53322. removeControllersUpdateListener: function () {
  53323. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53324. },
  53325. onControllersUpdate: function () {
  53326. this.checkIfControllerPresent();
  53327. },
  53328. onModelLoaded: function (evt) {
  53329. var controllerObject3D = evt.detail.model;
  53330. var buttonMeshes;
  53331. if (!this.data.model) { return; }
  53332. buttonMeshes = this.buttonMeshes = {};
  53333. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  53334. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  53335. if (buttonMeshes.triggerPressed) {
  53336. buttonMeshes.triggerPressed.visible = false;
  53337. }
  53338. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  53339. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  53340. if (buttonMeshes.trackpadPressed) {
  53341. buttonMeshes.trackpadPressed.visible = false;
  53342. }
  53343. },
  53344. // No analog buttons, only emits 0/1 values
  53345. onButtonChanged: function (evt) {
  53346. var button = this.mapping.buttons[evt.detail.id];
  53347. if (!button) return;
  53348. // Pass along changed event with button state, using button mapping for convenience.
  53349. this.el.emit(button + 'changed', evt.detail.state);
  53350. },
  53351. onAxisMoved: function (evt) {
  53352. emitIfAxesChanged(this, this.mapping.axes, evt);
  53353. },
  53354. updateModel: function (buttonName, evtName) {
  53355. if (!this.data.model) { return; }
  53356. this.updateButtonModel(buttonName, evtName);
  53357. },
  53358. updateButtonModel: function (buttonName, state) {
  53359. var buttonMeshes = this.buttonMeshes;
  53360. var pressedName = buttonName + 'Pressed';
  53361. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  53362. return;
  53363. }
  53364. var color;
  53365. switch (state) {
  53366. case 'down':
  53367. color = this.data.buttonHighlightColor;
  53368. break;
  53369. case 'touchstart':
  53370. color = this.data.buttonTouchedColor;
  53371. break;
  53372. }
  53373. if (color) {
  53374. buttonMeshes[pressedName].material.color.set(color);
  53375. }
  53376. buttonMeshes[pressedName].visible = !!color;
  53377. buttonMeshes[buttonName].visible = !color;
  53378. }
  53379. });
  53380. },{"../core/component":130,"../utils/bind":198,"../utils/tracked-controls":213}],120:[function(_dereq_,module,exports){
  53381. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  53382. var registerComponent = _dereq_('../core/component').registerComponent;
  53383. var THREE = _dereq_('../lib/three');
  53384. var utils = _dereq_('../utils/');
  53385. var bind = utils.bind;
  53386. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  53387. var CLAMP_VELOCITY = 0.00001;
  53388. var MAX_DELTA = 0.2;
  53389. var KEYS = [
  53390. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  53391. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  53392. ];
  53393. /**
  53394. * WASD component to control entities using WASD keys.
  53395. */
  53396. module.exports.Component = registerComponent('wasd-controls', {
  53397. schema: {
  53398. acceleration: {default: 65},
  53399. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  53400. adEnabled: {default: true},
  53401. adInverted: {default: false},
  53402. enabled: {default: true},
  53403. fly: {default: false},
  53404. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  53405. wsEnabled: {default: true},
  53406. wsInverted: {default: false}
  53407. },
  53408. init: function () {
  53409. // To keep track of the pressed keys.
  53410. this.keys = {};
  53411. this.easing = 1.1;
  53412. this.velocity = new THREE.Vector3();
  53413. // Bind methods and add event listeners.
  53414. this.onBlur = bind(this.onBlur, this);
  53415. this.onContextMenu = bind(this.onContextMenu, this);
  53416. this.onFocus = bind(this.onFocus, this);
  53417. this.onKeyDown = bind(this.onKeyDown, this);
  53418. this.onKeyUp = bind(this.onKeyUp, this);
  53419. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  53420. this.attachVisibilityEventListeners();
  53421. },
  53422. tick: function (time, delta) {
  53423. var data = this.data;
  53424. var el = this.el;
  53425. var velocity = this.velocity;
  53426. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  53427. isEmptyObject(this.keys)) { return; }
  53428. // Update velocity.
  53429. delta = delta / 1000;
  53430. this.updateVelocity(delta);
  53431. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  53432. // Get movement vector and translate position.
  53433. el.object3D.position.add(this.getMovementVector(delta));
  53434. },
  53435. remove: function () {
  53436. this.removeKeyEventListeners();
  53437. this.removeVisibilityEventListeners();
  53438. },
  53439. play: function () {
  53440. this.attachKeyEventListeners();
  53441. },
  53442. pause: function () {
  53443. this.keys = {};
  53444. this.removeKeyEventListeners();
  53445. },
  53446. updateVelocity: function (delta) {
  53447. var acceleration;
  53448. var adAxis;
  53449. var adSign;
  53450. var data = this.data;
  53451. var keys = this.keys;
  53452. var velocity = this.velocity;
  53453. var wsAxis;
  53454. var wsSign;
  53455. adAxis = data.adAxis;
  53456. wsAxis = data.wsAxis;
  53457. // If FPS too low, reset velocity.
  53458. if (delta > MAX_DELTA) {
  53459. velocity[adAxis] = 0;
  53460. velocity[wsAxis] = 0;
  53461. return;
  53462. }
  53463. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  53464. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  53465. // Velocity Easing.
  53466. if (velocity[adAxis] !== 0) {
  53467. velocity[adAxis] = velocity[adAxis] * scaledEasing;
  53468. }
  53469. if (velocity[wsAxis] !== 0) {
  53470. velocity[wsAxis] = velocity[wsAxis] * scaledEasing;
  53471. }
  53472. // Clamp velocity easing.
  53473. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  53474. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  53475. if (!data.enabled) { return; }
  53476. // Update velocity using keys pressed.
  53477. acceleration = data.acceleration;
  53478. if (data.adEnabled) {
  53479. adSign = data.adInverted ? -1 : 1;
  53480. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  53481. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  53482. }
  53483. if (data.wsEnabled) {
  53484. wsSign = data.wsInverted ? -1 : 1;
  53485. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  53486. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  53487. }
  53488. },
  53489. getMovementVector: (function () {
  53490. var directionVector = new THREE.Vector3(0, 0, 0);
  53491. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  53492. return function (delta) {
  53493. var rotation = this.el.getAttribute('rotation');
  53494. var velocity = this.velocity;
  53495. var xRotation;
  53496. directionVector.copy(velocity);
  53497. directionVector.multiplyScalar(delta);
  53498. // Absolute.
  53499. if (!rotation) { return directionVector; }
  53500. xRotation = this.data.fly ? rotation.x : 0;
  53501. // Transform direction relative to heading.
  53502. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  53503. directionVector.applyEuler(rotationEuler);
  53504. return directionVector;
  53505. };
  53506. })(),
  53507. attachVisibilityEventListeners: function () {
  53508. window.oncontextmenu = this.onContextMenu;
  53509. window.addEventListener('blur', this.onBlur);
  53510. window.addEventListener('focus', this.onFocus);
  53511. document.addEventListener('visibilitychange', this.onVisibilityChange);
  53512. },
  53513. removeVisibilityEventListeners: function () {
  53514. window.removeEventListener('blur', this.onBlur);
  53515. window.removeEventListener('focus', this.onFocus);
  53516. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  53517. },
  53518. attachKeyEventListeners: function () {
  53519. window.addEventListener('keydown', this.onKeyDown);
  53520. window.addEventListener('keyup', this.onKeyUp);
  53521. },
  53522. removeKeyEventListeners: function () {
  53523. window.removeEventListener('keydown', this.onKeyDown);
  53524. window.removeEventListener('keyup', this.onKeyUp);
  53525. },
  53526. onContextMenu: function () {
  53527. var keys = Object.keys(this.keys);
  53528. for (var i = 0; i < keys.length; i++) {
  53529. delete this.keys[keys[i]];
  53530. }
  53531. },
  53532. onBlur: function () {
  53533. this.pause();
  53534. },
  53535. onFocus: function () {
  53536. this.play();
  53537. },
  53538. onVisibilityChange: function () {
  53539. if (document.hidden) {
  53540. this.onBlur();
  53541. } else {
  53542. this.onFocus();
  53543. }
  53544. },
  53545. onKeyDown: function (event) {
  53546. var code;
  53547. if (!shouldCaptureKeyEvent(event)) { return; }
  53548. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53549. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  53550. },
  53551. onKeyUp: function (event) {
  53552. var code;
  53553. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53554. delete this.keys[code];
  53555. }
  53556. });
  53557. function isEmptyObject (keys) {
  53558. var key;
  53559. for (key in keys) { return false; }
  53560. return true;
  53561. }
  53562. },{"../constants":122,"../core/component":130,"../lib/three":178,"../utils/":204}],121:[function(_dereq_,module,exports){
  53563. /* global THREE */
  53564. var registerComponent = _dereq_('../core/component').registerComponent;
  53565. var bind = _dereq_('../utils/bind');
  53566. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53567. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53568. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53569. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53570. var utils = _dereq_('../utils/');
  53571. var debug = utils.debug('components:windows-motion-controls:debug');
  53572. var warn = utils.debug('components:windows-motion-controls:warn');
  53573. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  53574. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  53575. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  53576. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  53577. var GAMEPAD_ID_WEBXR = 'windows-mixed-reality';
  53578. var GAMEPAD_ID_WEBVR = 'Spatial Controller (Spatial Interaction Source) ';
  53579. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  53580. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53581. var INPUT_MAPPING_WEBVR = {
  53582. // A-Frame specific semantic axis names
  53583. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  53584. // A-Frame specific semantic button names
  53585. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  53586. // A mapping of the semantic name to node name in the glTF model file,
  53587. // that should be transformed by axis value.
  53588. // This array mirrors the browser Gamepad.axes array, such that
  53589. // the mesh corresponding to axis 0 is in this array index 0.
  53590. axisMeshNames: [
  53591. 'THUMBSTICK_X',
  53592. 'THUMBSTICK_Y',
  53593. 'TOUCHPAD_TOUCH_X',
  53594. 'TOUCHPAD_TOUCH_Y'
  53595. ],
  53596. // A mapping of the semantic name to button node name in the glTF model file,
  53597. // that should be transformed by button value.
  53598. buttonMeshNames: {
  53599. 'trigger': 'SELECT',
  53600. 'menu': 'MENU',
  53601. 'grip': 'GRASP',
  53602. 'thumbstick': 'THUMBSTICK_PRESS',
  53603. 'trackpad': 'TOUCHPAD_PRESS'
  53604. },
  53605. pointingPoseMeshName: 'POINTING_POSE'
  53606. };
  53607. var INPUT_MAPPING_WEBXR = {
  53608. // A-Frame specific semantic axis names
  53609. axes: {'touchpad': [0, 1], 'thumbstick': [2, 3]},
  53610. // A-Frame specific semantic button names
  53611. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick', 'menu'],
  53612. // A mapping of the semantic name to node name in the glTF model file,
  53613. // that should be transformed by axis value.
  53614. // This array mirrors the browser Gamepad.axes array, such that
  53615. // the mesh corresponding to axis 0 is in this array index 0.
  53616. axisMeshNames: [
  53617. 'TOUCHPAD_TOUCH_X',
  53618. 'TOUCHPAD_TOUCH_X',
  53619. 'THUMBSTICK_X',
  53620. 'THUMBSTICK_Y'
  53621. ],
  53622. // A mapping of the semantic name to button node name in the glTF model file,
  53623. // that should be transformed by button value.
  53624. buttonMeshNames: {
  53625. 'trigger': 'SELECT',
  53626. 'menu': 'MENU',
  53627. 'squeeze': 'GRASP',
  53628. 'thumbstick': 'THUMBSTICK_PRESS',
  53629. 'touchpad': 'TOUCHPAD_PRESS'
  53630. },
  53631. pointingPoseMeshName: 'POINTING_POSE'
  53632. };
  53633. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53634. /**
  53635. * Windows Motion Controller controls.
  53636. * Interface with Windows Motion Controller controllers and map Gamepad events to
  53637. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  53638. * Load a controller model and transform the pressed buttons.
  53639. */
  53640. module.exports.Component = registerComponent('windows-motion-controls', {
  53641. schema: {
  53642. hand: {default: DEFAULT_HANDEDNESS},
  53643. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  53644. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  53645. pair: {default: 0},
  53646. // If true, loads the controller glTF asset.
  53647. model: {default: true},
  53648. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  53649. hideDisconnected: {default: true}
  53650. },
  53651. mapping: INPUT_MAPPING,
  53652. bindMethods: function () {
  53653. this.onModelError = bind(this.onModelError, this);
  53654. this.onModelLoaded = bind(this.onModelLoaded, this);
  53655. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53656. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53657. this.onAxisMoved = bind(this.onAxisMoved, this);
  53658. },
  53659. init: function () {
  53660. var self = this;
  53661. var el = this.el;
  53662. this.onButtonChanged = bind(this.onButtonChanged, this);
  53663. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53664. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53665. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53666. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53667. this.onControllerConnected = function () { self.setModelVisibility(true); };
  53668. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  53669. this.controllerPresent = false;
  53670. this.lastControllerCheck = 0;
  53671. this.previousButtonValues = {};
  53672. this.bindMethods();
  53673. // Cache for submeshes that we have looked up by name.
  53674. this.loadedMeshInfo = {
  53675. buttonMeshes: null,
  53676. axisMeshes: null
  53677. };
  53678. // Pointing poses
  53679. this.rayOrigin = {
  53680. origin: new THREE.Vector3(),
  53681. direction: new THREE.Vector3(0, 0, -1),
  53682. createdFromMesh: false
  53683. };
  53684. el.addEventListener('controllerconnected', this.onControllerConnected);
  53685. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  53686. },
  53687. addEventListeners: function () {
  53688. var el = this.el;
  53689. el.addEventListener('buttonchanged', this.onButtonChanged);
  53690. el.addEventListener('buttondown', this.onButtonDown);
  53691. el.addEventListener('buttonup', this.onButtonUp);
  53692. el.addEventListener('touchstart', this.onButtonTouchStart);
  53693. el.addEventListener('touchend', this.onButtonTouchEnd);
  53694. el.addEventListener('axismove', this.onAxisMoved);
  53695. el.addEventListener('model-error', this.onModelError);
  53696. el.addEventListener('model-loaded', this.onModelLoaded);
  53697. this.controllerEventsActive = true;
  53698. },
  53699. removeEventListeners: function () {
  53700. var el = this.el;
  53701. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53702. el.removeEventListener('buttondown', this.onButtonDown);
  53703. el.removeEventListener('buttonup', this.onButtonUp);
  53704. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53705. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53706. el.removeEventListener('axismove', this.onAxisMoved);
  53707. el.removeEventListener('model-error', this.onModelError);
  53708. el.removeEventListener('model-loaded', this.onModelLoaded);
  53709. this.controllerEventsActive = false;
  53710. },
  53711. checkIfControllerPresent: function () {
  53712. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  53713. hand: this.data.hand,
  53714. index: this.data.pair,
  53715. iterateControllerProfiles: true
  53716. });
  53717. },
  53718. play: function () {
  53719. this.checkIfControllerPresent();
  53720. this.addControllersUpdateListener();
  53721. },
  53722. pause: function () {
  53723. this.removeEventListeners();
  53724. this.removeControllersUpdateListener();
  53725. },
  53726. updateControllerModel: function () {
  53727. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  53728. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  53729. this.modelReady();
  53730. return;
  53731. }
  53732. var sourceUrl = this.createControllerModelUrl();
  53733. this.loadModel(sourceUrl);
  53734. },
  53735. /**
  53736. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  53737. * art assets.
  53738. */
  53739. createControllerModelUrl: function (forceDefault) {
  53740. // Determine the device specific folder based on the ID suffix
  53741. var trackedControlsComponent = this.el.components['tracked-controls'];
  53742. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  53743. var device = 'default';
  53744. var hand = this.data.hand;
  53745. var filename;
  53746. if (controller && !window.hasNativeWebXRImplementation) {
  53747. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  53748. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  53749. // In this case, we want to load the universal model, so need to get the '' from the controller.
  53750. hand = controller.hand;
  53751. if (!forceDefault) {
  53752. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  53753. device = ((match && match[0]) || device);
  53754. }
  53755. }
  53756. // Hand
  53757. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  53758. // Final url
  53759. return MODEL_BASE_URL + device + '/' + filename;
  53760. },
  53761. injectTrackedControls: function () {
  53762. var data = this.data;
  53763. this.el.setAttribute('tracked-controls', {
  53764. idPrefix: GAMEPAD_ID_PREFIX,
  53765. controller: data.pair,
  53766. hand: data.hand,
  53767. armModel: false
  53768. });
  53769. this.updateControllerModel();
  53770. },
  53771. addControllersUpdateListener: function () {
  53772. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53773. },
  53774. removeControllersUpdateListener: function () {
  53775. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53776. },
  53777. onControllersUpdate: function () {
  53778. this.checkIfControllerPresent();
  53779. },
  53780. onModelError: function (evt) {
  53781. var defaultUrl = this.createControllerModelUrl(true);
  53782. if (evt.detail.src !== defaultUrl) {
  53783. warn('Failed to load controller model for device, attempting to load default.');
  53784. this.loadModel(defaultUrl);
  53785. } else {
  53786. warn('Failed to load default controller model.');
  53787. }
  53788. },
  53789. loadModel: function (url) {
  53790. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  53791. // removed and re-loaded if the given url changes.
  53792. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  53793. },
  53794. onModelLoaded: function (evt) {
  53795. var rootNode = this.controllerModel = evt.detail.model;
  53796. var loadedMeshInfo = this.loadedMeshInfo;
  53797. var i;
  53798. var meshName;
  53799. var mesh;
  53800. var meshInfo;
  53801. debug('Processing model');
  53802. // Reset the caches
  53803. loadedMeshInfo.buttonMeshes = {};
  53804. loadedMeshInfo.axisMeshes = {};
  53805. // Cache our meshes so we aren't traversing the hierarchy per frame
  53806. if (rootNode) {
  53807. // Button Meshes
  53808. for (i = 0; i < this.mapping.buttons.length; i++) {
  53809. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  53810. if (!meshName) {
  53811. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  53812. continue;
  53813. }
  53814. mesh = rootNode.getObjectByName(meshName);
  53815. if (!mesh) {
  53816. warn('Missing button mesh with name: ' + meshName);
  53817. continue;
  53818. }
  53819. meshInfo = {
  53820. index: i,
  53821. value: getImmediateChildByName(mesh, 'VALUE'),
  53822. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  53823. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  53824. };
  53825. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  53826. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  53827. } else {
  53828. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  53829. warn('Missing button submesh under mesh with name: ' + meshName +
  53830. '(VALUE: ' + !!meshInfo.value +
  53831. ', PRESSED: ' + !!meshInfo.pressed +
  53832. ', UNPRESSED:' + !!meshInfo.unpressed +
  53833. ')');
  53834. }
  53835. }
  53836. // Axis Meshes
  53837. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  53838. meshName = this.mapping.axisMeshNames[i];
  53839. if (!meshName) {
  53840. debug('Skipping unknown axis at index: ' + i);
  53841. continue;
  53842. }
  53843. mesh = rootNode.getObjectByName(meshName);
  53844. if (!mesh) {
  53845. warn('Missing axis mesh with name: ' + meshName);
  53846. continue;
  53847. }
  53848. meshInfo = {
  53849. index: i,
  53850. value: getImmediateChildByName(mesh, 'VALUE'),
  53851. min: getImmediateChildByName(mesh, 'MIN'),
  53852. max: getImmediateChildByName(mesh, 'MAX')
  53853. };
  53854. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  53855. loadedMeshInfo.axisMeshes[i] = meshInfo;
  53856. } else {
  53857. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  53858. warn('Missing axis submesh under mesh with name: ' + meshName +
  53859. '(VALUE: ' + !!meshInfo.value +
  53860. ', MIN: ' + !!meshInfo.min +
  53861. ', MAX:' + !!meshInfo.max +
  53862. ')');
  53863. }
  53864. }
  53865. this.calculateRayOriginFromMesh(rootNode);
  53866. // Determine if the model has to be visible or not.
  53867. this.setModelVisibility();
  53868. }
  53869. debug('Model load complete.');
  53870. // Look through only immediate children. This will return null if no mesh exists with the given name.
  53871. function getImmediateChildByName (object3d, value) {
  53872. for (var i = 0, l = object3d.children.length; i < l; i++) {
  53873. var obj = object3d.children[i];
  53874. if (obj && obj['name'] === value) {
  53875. return obj;
  53876. }
  53877. }
  53878. return undefined;
  53879. }
  53880. },
  53881. calculateRayOriginFromMesh: (function () {
  53882. var quaternion = new THREE.Quaternion();
  53883. return function (rootNode) {
  53884. var mesh;
  53885. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  53886. // in the glTF (assumes that root node is at world origin)
  53887. this.rayOrigin.origin.set(0, 0, 0);
  53888. this.rayOrigin.direction.set(0, 0, -1);
  53889. this.rayOrigin.createdFromMesh = true;
  53890. // Try to read Pointing pose from the source model
  53891. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  53892. if (mesh) {
  53893. var parent = rootNode.parent;
  53894. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  53895. if (parent) {
  53896. rootNode.parent = null;
  53897. rootNode.updateMatrixWorld(true);
  53898. rootNode.parent = parent;
  53899. }
  53900. mesh.getWorldPosition(this.rayOrigin.origin);
  53901. mesh.getWorldQuaternion(quaternion);
  53902. this.rayOrigin.direction.applyQuaternion(quaternion);
  53903. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  53904. if (parent) {
  53905. rootNode.updateMatrixWorld(true);
  53906. }
  53907. } else {
  53908. debug('Mesh does not contain pointing origin data, defaulting to none.');
  53909. }
  53910. // Emit event stating that our pointing ray is now accurate.
  53911. this.modelReady();
  53912. };
  53913. })(),
  53914. lerpAxisTransform: (function () {
  53915. var quaternion = new THREE.Quaternion();
  53916. return function (axis, axisValue) {
  53917. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  53918. if (!axisMeshInfo) return;
  53919. var min = axisMeshInfo.min;
  53920. var max = axisMeshInfo.max;
  53921. var target = axisMeshInfo.value;
  53922. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  53923. var lerpValue = axisValue * 0.5 + 0.5;
  53924. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  53925. target.position.lerpVectors(min.position, max.position, lerpValue);
  53926. };
  53927. })(),
  53928. lerpButtonTransform: (function () {
  53929. var quaternion = new THREE.Quaternion();
  53930. return function (buttonName, buttonValue) {
  53931. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  53932. if (!buttonMeshInfo) return;
  53933. var min = buttonMeshInfo.unpressed;
  53934. var max = buttonMeshInfo.pressed;
  53935. var target = buttonMeshInfo.value;
  53936. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  53937. target.position.lerpVectors(min.position, max.position, buttonValue);
  53938. };
  53939. })(),
  53940. modelReady: function () {
  53941. this.el.emit('controllermodelready', {
  53942. name: 'windows-motion-controls',
  53943. model: this.data.model,
  53944. rayOrigin: this.rayOrigin
  53945. });
  53946. },
  53947. onButtonChanged: function (evt) {
  53948. var buttonName = this.mapping.buttons[evt.detail.id];
  53949. if (buttonName) {
  53950. // Update the button mesh transform
  53951. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  53952. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  53953. }
  53954. // Only emit events for buttons that we know how to map from index to name
  53955. this.el.emit(buttonName + 'changed', evt.detail.state);
  53956. }
  53957. },
  53958. onAxisMoved: function (evt) {
  53959. var numAxes = this.mapping.axisMeshNames.length;
  53960. // Only attempt to update meshes if we have valid data.
  53961. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  53962. for (var axis = 0; axis < numAxes; axis++) {
  53963. // Update the button mesh transform
  53964. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  53965. }
  53966. }
  53967. emitIfAxesChanged(this, this.mapping.axes, evt);
  53968. },
  53969. setModelVisibility: function (visible) {
  53970. var model = this.el.getObject3D('mesh');
  53971. visible = visible !== undefined ? visible : this.modelVisible;
  53972. this.modelVisible = visible;
  53973. if (!model) { return; }
  53974. model.visible = visible;
  53975. }
  53976. });
  53977. },{"../constants":122,"../core/component":130,"../utils/":204,"../utils/bind":198,"../utils/tracked-controls":213}],122:[function(_dereq_,module,exports){
  53978. module.exports = {
  53979. AFRAME_INJECTED: 'aframe-injected',
  53980. DEFAULT_CAMERA_HEIGHT: 1.6,
  53981. DEFAULT_HANDEDNESS: 'right',
  53982. keyboardevent: _dereq_('./keyboardevent')
  53983. };
  53984. },{"./keyboardevent":123}],123:[function(_dereq_,module,exports){
  53985. module.exports = {
  53986. // Tiny KeyboardEvent.code polyfill.
  53987. KEYCODE_TO_CODE: {
  53988. '38': 'ArrowUp',
  53989. '37': 'ArrowLeft',
  53990. '40': 'ArrowDown',
  53991. '39': 'ArrowRight',
  53992. '87': 'KeyW',
  53993. '65': 'KeyA',
  53994. '83': 'KeyS',
  53995. '68': 'KeyD'
  53996. }
  53997. };
  53998. },{}],124:[function(_dereq_,module,exports){
  53999. var ANode = _dereq_('./a-node');
  54000. var bind = _dereq_('../utils/bind');
  54001. var debug = _dereq_('../utils/debug');
  54002. var registerElement = _dereq_('./a-register-element').registerElement;
  54003. var THREE = _dereq_('../lib/three');
  54004. var fileLoader = new THREE.FileLoader();
  54005. var warn = debug('core:a-assets:warn');
  54006. /**
  54007. * Asset management system. Handles blocking on asset loading.
  54008. */
  54009. module.exports = registerElement('a-assets', {
  54010. prototype: Object.create(ANode.prototype, {
  54011. createdCallback: {
  54012. value: function () {
  54013. this.isAssets = true;
  54014. this.fileLoader = fileLoader;
  54015. this.timeout = null;
  54016. }
  54017. },
  54018. attachedCallback: {
  54019. value: function () {
  54020. var self = this;
  54021. var i;
  54022. var loaded = [];
  54023. var mediaEl;
  54024. var mediaEls;
  54025. var imgEl;
  54026. var imgEls;
  54027. var timeout;
  54028. if (!this.parentNode.isScene) {
  54029. throw new Error('<a-assets> must be a child of a <a-scene>.');
  54030. }
  54031. // Wait for <img>s.
  54032. imgEls = this.querySelectorAll('img');
  54033. for (i = 0; i < imgEls.length; i++) {
  54034. imgEl = fixUpMediaElement(imgEls[i]);
  54035. loaded.push(new Promise(function (resolve, reject) {
  54036. // Set in cache because we won't be needing to call three.js loader if we have.
  54037. // a loaded media element.
  54038. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  54039. imgEl.onload = resolve;
  54040. imgEl.onerror = reject;
  54041. }));
  54042. }
  54043. // Wait for <audio>s and <video>s.
  54044. mediaEls = this.querySelectorAll('audio, video');
  54045. for (i = 0; i < mediaEls.length; i++) {
  54046. mediaEl = fixUpMediaElement(mediaEls[i]);
  54047. if (!mediaEl.src && !mediaEl.srcObject) {
  54048. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  54049. }
  54050. loaded.push(mediaElementLoaded(mediaEl));
  54051. }
  54052. // Trigger loaded for scene to start rendering.
  54053. Promise.all(loaded).then(bind(this.load, this));
  54054. // Timeout to start loading anyways.
  54055. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  54056. this.timeout = setTimeout(function () {
  54057. if (self.hasLoaded) { return; }
  54058. warn('Asset loading timed out in ', timeout, 'ms');
  54059. self.emit('timeout');
  54060. self.load();
  54061. }, timeout);
  54062. }
  54063. },
  54064. detachedCallback: {
  54065. value: function () {
  54066. if (this.timeout) { clearTimeout(this.timeout); }
  54067. }
  54068. },
  54069. load: {
  54070. value: function () {
  54071. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  54072. return el.isAssetItem && el.hasAttribute('src');
  54073. });
  54074. }
  54075. }
  54076. })
  54077. });
  54078. /**
  54079. * Preload using XHRLoader for any type of asset.
  54080. */
  54081. registerElement('a-asset-item', {
  54082. prototype: Object.create(ANode.prototype, {
  54083. createdCallback: {
  54084. value: function () {
  54085. this.data = null;
  54086. this.isAssetItem = true;
  54087. }
  54088. },
  54089. attachedCallback: {
  54090. value: function () {
  54091. var self = this;
  54092. var src = this.getAttribute('src');
  54093. fileLoader.setResponseType(
  54094. this.getAttribute('response-type') || inferResponseType(src));
  54095. fileLoader.load(src, function handleOnLoad (response) {
  54096. self.data = response;
  54097. /*
  54098. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  54099. previous one closes, the second request never finishes.
  54100. setTimeout finishes the first request and lets the logic triggered by load open
  54101. subsequent requests.
  54102. setTimeout can be removed once the fix for the bug below ships:
  54103. https://bugs.chromium.org/p/chromium/issues/detail?id=633696&q=component%3ABlink%3ENetwork%3EXHR%20&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified
  54104. */
  54105. setTimeout(function load () { ANode.prototype.load.call(self); });
  54106. }, function handleOnProgress (xhr) {
  54107. self.emit('progress', {
  54108. loadedBytes: xhr.loaded,
  54109. totalBytes: xhr.total,
  54110. xhr: xhr
  54111. });
  54112. }, function handleOnError (xhr) {
  54113. self.emit('error', {xhr: xhr});
  54114. });
  54115. }
  54116. }
  54117. })
  54118. });
  54119. /**
  54120. * Create a Promise that resolves once the media element has finished buffering.
  54121. *
  54122. * @param {Element} el - HTMLMediaElement.
  54123. * @returns {Promise}
  54124. */
  54125. function mediaElementLoaded (el) {
  54126. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  54127. return;
  54128. }
  54129. // If media specifies autoplay or preload, wait until media is completely buffered.
  54130. return new Promise(function (resolve, reject) {
  54131. if (el.readyState === 4) { return resolve(); } // Already loaded.
  54132. if (el.error) { return reject(); } // Error.
  54133. el.addEventListener('loadeddata', checkProgress, false);
  54134. el.addEventListener('progress', checkProgress, false);
  54135. el.addEventListener('error', reject, false);
  54136. function checkProgress () {
  54137. // Add up the seconds buffered.
  54138. var secondsBuffered = 0;
  54139. for (var i = 0; i < el.buffered.length; i++) {
  54140. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  54141. }
  54142. // Compare seconds buffered to media duration.
  54143. if (secondsBuffered >= el.duration) {
  54144. // Set in cache because we won't be needing to call three.js loader if we have.
  54145. // a loaded media element.
  54146. // Store video elements only. three.js loader is used for audio elements.
  54147. // See assetParse too.
  54148. if (el.tagName === 'VIDEO') {
  54149. THREE.Cache.files[el.getAttribute('src')] = el;
  54150. }
  54151. resolve();
  54152. }
  54153. }
  54154. });
  54155. }
  54156. /**
  54157. * Automatically add attributes to media elements where convenient.
  54158. * crossorigin, playsinline.
  54159. */
  54160. function fixUpMediaElement (mediaEl) {
  54161. // Cross-origin.
  54162. var newMediaEl = setCrossOrigin(mediaEl);
  54163. // Plays inline for mobile.
  54164. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  54165. newMediaEl.setAttribute('playsinline', '');
  54166. newMediaEl.setAttribute('webkit-playsinline', '');
  54167. }
  54168. if (newMediaEl !== mediaEl) {
  54169. mediaEl.parentNode.appendChild(newMediaEl);
  54170. mediaEl.parentNode.removeChild(mediaEl);
  54171. }
  54172. return newMediaEl;
  54173. }
  54174. /**
  54175. * Automatically set `crossorigin` if not defined on the media element.
  54176. * If it is not defined, we must create and re-append a new media element <img> and
  54177. * have the browser re-request it with `crossorigin` set.
  54178. *
  54179. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  54180. * @returns {Element} Media element to be used to listen to for loaded events.
  54181. */
  54182. function setCrossOrigin (mediaEl) {
  54183. var newMediaEl;
  54184. var src;
  54185. // Already has crossorigin set.
  54186. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  54187. src = mediaEl.getAttribute('src');
  54188. if (src !== null) {
  54189. // Does not have protocol.
  54190. if (src.indexOf('://') === -1) { return mediaEl; }
  54191. // Determine if cross origin is actually needed.
  54192. if (extractDomain(src) === window.location.host) { return mediaEl; }
  54193. }
  54194. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  54195. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  54196. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  54197. mediaEl.crossOrigin = 'anonymous';
  54198. newMediaEl = mediaEl.cloneNode(true);
  54199. return newMediaEl;
  54200. }
  54201. /**
  54202. * Extract domain out of URL.
  54203. *
  54204. * @param {string} url
  54205. * @returns {string}
  54206. */
  54207. function extractDomain (url) {
  54208. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  54209. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  54210. // Find and remove port number.
  54211. return domain.substring(0, domain.indexOf(':'));
  54212. }
  54213. /**
  54214. * Infer response-type attribute from src.
  54215. * Default is text (default XMLHttpRequest.responseType)
  54216. * and arraybuffer for .glb files.
  54217. *
  54218. * @param {string} src
  54219. * @returns {string}
  54220. */
  54221. function inferResponseType (src) {
  54222. var fileName = getFileNameFromURL(src);
  54223. var dotLastIndex = fileName.lastIndexOf('.');
  54224. if (dotLastIndex >= 0) {
  54225. var extension = fileName.slice(dotLastIndex, src.search(/\?|#|$/));
  54226. if (extension === '.glb') {
  54227. return 'arraybuffer';
  54228. }
  54229. }
  54230. return 'text';
  54231. }
  54232. module.exports.inferResponseType = inferResponseType;
  54233. /**
  54234. * Extract filename from URL
  54235. *
  54236. * @param {string} url
  54237. * @returns {string}
  54238. */
  54239. function getFileNameFromURL (url) {
  54240. var parser = document.createElement('a');
  54241. parser.href = url;
  54242. var query = parser.search.replace(/^\?/, '');
  54243. var filePath = url.replace(query, '').replace('?', '');
  54244. return filePath.substring(filePath.lastIndexOf('/') + 1);
  54245. }
  54246. module.exports.getFileNameFromURL = getFileNameFromURL;
  54247. },{"../lib/three":178,"../utils/bind":198,"../utils/debug":200,"./a-node":128,"./a-register-element":129}],125:[function(_dereq_,module,exports){
  54248. var debug = _dereq_('../utils/debug');
  54249. var registerElement = _dereq_('./a-register-element').registerElement;
  54250. var warn = debug('core:cubemap:warn');
  54251. /**
  54252. * Cubemap element that handles validation and exposes list of URLs.
  54253. * Does not listen to updates.
  54254. */
  54255. module.exports = registerElement('a-cubemap', {
  54256. prototype: Object.create(window.HTMLElement.prototype, {
  54257. /**
  54258. * Calculates this.srcs.
  54259. */
  54260. attachedCallback: {
  54261. value: function () {
  54262. this.srcs = this.validate();
  54263. },
  54264. writable: window.debug
  54265. },
  54266. /**
  54267. * Checks for exactly six elements with [src].
  54268. * Does not check explicitly for <img>s in case user does not want
  54269. * prefetching.
  54270. *
  54271. * @returns {Array|null} - six URLs if valid, else null.
  54272. */
  54273. validate: {
  54274. value: function () {
  54275. var elements = this.querySelectorAll('[src]');
  54276. var i;
  54277. var srcs = [];
  54278. if (elements.length === 6) {
  54279. for (i = 0; i < elements.length; i++) {
  54280. srcs.push(elements[i].getAttribute('src'));
  54281. }
  54282. return srcs;
  54283. }
  54284. // Else if there are not six elements, throw a warning.
  54285. warn(
  54286. '<a-cubemap> did not contain exactly six elements each with a ' +
  54287. '`src` attribute.');
  54288. },
  54289. writable: window.debug
  54290. }
  54291. })
  54292. });
  54293. },{"../utils/debug":200,"./a-register-element":129}],126:[function(_dereq_,module,exports){
  54294. var ANode = _dereq_('./a-node');
  54295. var COMPONENTS = _dereq_('./component').components;
  54296. var registerElement = _dereq_('./a-register-element').registerElement;
  54297. var THREE = _dereq_('../lib/three');
  54298. var utils = _dereq_('../utils/');
  54299. var AEntity;
  54300. var debug = utils.debug('core:a-entity:debug');
  54301. var warn = utils.debug('core:a-entity:warn');
  54302. var MULTIPLE_COMPONENT_DELIMITER = '__';
  54303. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  54304. var ONCE = {once: true};
  54305. /**
  54306. * Entity is a container object that components are plugged into to comprise everything in
  54307. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  54308. *
  54309. * To be able to take components, the scene element inherits from the entity definition.
  54310. *
  54311. * @member {object} components - entity's currently initialized components.
  54312. * @member {object} object3D - three.js object.
  54313. * @member {array} states
  54314. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  54315. */
  54316. var proto = Object.create(ANode.prototype, {
  54317. createdCallback: {
  54318. value: function () {
  54319. this.components = {};
  54320. // To avoid double initializations and infinite loops.
  54321. this.initializingComponents = {};
  54322. this.componentsToUpdate = {};
  54323. this.isEntity = true;
  54324. this.isPlaying = false;
  54325. this.object3D = new THREE.Group();
  54326. this.object3D.el = this;
  54327. this.object3DMap = {};
  54328. this.parentEl = null;
  54329. this.rotationObj = {};
  54330. this.states = [];
  54331. }
  54332. },
  54333. /**
  54334. * Handle changes coming from the browser DOM inspector.
  54335. */
  54336. attributeChangedCallback: {
  54337. value: function (attr, oldVal, newVal) {
  54338. var component = this.components[attr];
  54339. // If the empty string is passed by the component initialization
  54340. // logic we ignore the component update.
  54341. if (component && component.justInitialized && newVal === '') {
  54342. delete component.justInitialized;
  54343. return;
  54344. }
  54345. // When a component is removed after calling el.removeAttribute('material')
  54346. if (!component && newVal === null) { return; }
  54347. this.setEntityAttribute(attr, oldVal, newVal);
  54348. }
  54349. },
  54350. /**
  54351. * Add to parent, load, play.
  54352. */
  54353. attachedCallback: {
  54354. value: function () {
  54355. var assetsEl; // Asset management system element.
  54356. var sceneEl = this.sceneEl;
  54357. var self = this; // Component.
  54358. this.addToParent();
  54359. // Don't .load() scene on attachedCallback.
  54360. if (this.isScene) { return; }
  54361. // Gracefully not error when outside of <a-scene> (e.g., tests).
  54362. if (!sceneEl) {
  54363. this.load();
  54364. return;
  54365. }
  54366. // Wait for asset management system to finish before loading.
  54367. assetsEl = sceneEl.querySelector('a-assets');
  54368. if (assetsEl && !assetsEl.hasLoaded) {
  54369. assetsEl.addEventListener('loaded', function () { self.load(); });
  54370. return;
  54371. }
  54372. this.load();
  54373. }
  54374. },
  54375. /**
  54376. * Tell parent to remove this element's object3D from its object3D.
  54377. * Do not call on scene element because that will cause a call to document.body.remove().
  54378. */
  54379. detachedCallback: {
  54380. value: function () {
  54381. var componentName;
  54382. if (!this.parentEl) { return; }
  54383. // Remove components.
  54384. for (componentName in this.components) {
  54385. this.removeComponent(componentName, false);
  54386. }
  54387. if (this.isScene) { return; }
  54388. this.removeFromParent();
  54389. ANode.prototype.detachedCallback.call(this);
  54390. // Remove cyclic reference.
  54391. this.object3D.el = null;
  54392. }
  54393. },
  54394. getObject3D: {
  54395. value: function (type) {
  54396. return this.object3DMap[type];
  54397. }
  54398. },
  54399. /**
  54400. * Set a THREE.Object3D into the map.
  54401. *
  54402. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  54403. * @param {object} obj - A THREE.Object3D.
  54404. */
  54405. setObject3D: {
  54406. value: function (type, obj) {
  54407. var oldObj;
  54408. var self = this;
  54409. if (!(obj instanceof THREE.Object3D)) {
  54410. throw new Error(
  54411. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  54412. 'THREE.Object3D.'
  54413. );
  54414. }
  54415. // Remove existing object of the type.
  54416. oldObj = this.getObject3D(type);
  54417. if (oldObj) { this.object3D.remove(oldObj); }
  54418. // Set references to A-Frame entity.
  54419. obj.el = this;
  54420. if (obj.children.length) {
  54421. obj.traverse(function bindEl (child) {
  54422. child.el = self;
  54423. });
  54424. }
  54425. // Add.
  54426. this.object3D.add(obj);
  54427. this.object3DMap[type] = obj;
  54428. this.emit('object3dset', {object: obj, type: type});
  54429. }
  54430. },
  54431. /**
  54432. * Remove object from scene and entity object3D map.
  54433. */
  54434. removeObject3D: {
  54435. value: function (type) {
  54436. var obj = this.getObject3D(type);
  54437. if (!obj) {
  54438. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  54439. return;
  54440. }
  54441. this.object3D.remove(obj);
  54442. delete this.object3DMap[type];
  54443. this.emit('object3dremove', {type: type});
  54444. }
  54445. },
  54446. /**
  54447. * Gets or creates an object3D of a given type.
  54448. *
  54449. * @param {string} type - Type of the object3D.
  54450. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  54451. * @returns {object}
  54452. */
  54453. getOrCreateObject3D: {
  54454. value: function (type, Constructor) {
  54455. var object3D = this.getObject3D(type);
  54456. if (!object3D && Constructor) {
  54457. object3D = new Constructor();
  54458. this.setObject3D(type, object3D);
  54459. }
  54460. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  54461. 'and `object3dset` event instead.');
  54462. return object3D;
  54463. }
  54464. },
  54465. /**
  54466. * Add child entity.
  54467. *
  54468. * @param {Element} el - Child entity.
  54469. */
  54470. add: {
  54471. value: function (el) {
  54472. if (!el.object3D) {
  54473. throw new Error("Trying to add an element that doesn't have an `object3D`");
  54474. }
  54475. this.object3D.add(el.object3D);
  54476. this.emit('child-attached', {el: el});
  54477. }
  54478. },
  54479. /**
  54480. * Tell parentNode to add this entity to itself.
  54481. */
  54482. addToParent: {
  54483. value: function () {
  54484. var parentNode = this.parentEl = this.parentNode;
  54485. // `!parentNode` check primarily for unit tests.
  54486. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  54487. parentNode.add(this);
  54488. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  54489. }
  54490. },
  54491. /**
  54492. * Tell parentNode to remove this entity from itself.
  54493. */
  54494. removeFromParent: {
  54495. value: function () {
  54496. var parentEl = this.parentEl;
  54497. this.parentEl.remove(this);
  54498. this.attachedToParent = false;
  54499. this.parentEl = null;
  54500. parentEl.emit('child-detached', {el: this});
  54501. }
  54502. },
  54503. load: {
  54504. value: function () {
  54505. var self = this;
  54506. if (this.hasLoaded || !this.parentEl) { return; }
  54507. ANode.prototype.load.call(this, function entityLoadCallback () {
  54508. // Check if entity was detached while it was waiting to load.
  54509. if (!self.parentEl) { return; }
  54510. self.updateComponents();
  54511. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  54512. });
  54513. },
  54514. writable: window.debug
  54515. },
  54516. /**
  54517. * Remove child entity.
  54518. *
  54519. * @param {Element} el - Child entity.
  54520. */
  54521. remove: {
  54522. value: function (el) {
  54523. if (el) {
  54524. this.object3D.remove(el.object3D);
  54525. } else {
  54526. this.parentNode.removeChild(this);
  54527. }
  54528. }
  54529. },
  54530. /**
  54531. * @returns {array} Direct children that are entities.
  54532. */
  54533. getChildEntities: {
  54534. value: function () {
  54535. var children = this.children;
  54536. var childEntities = [];
  54537. for (var i = 0; i < children.length; i++) {
  54538. var child = children[i];
  54539. if (child instanceof AEntity) {
  54540. childEntities.push(child);
  54541. }
  54542. }
  54543. return childEntities;
  54544. }
  54545. },
  54546. /**
  54547. * Initialize component.
  54548. *
  54549. * @param {string} attrName - Attribute name asociated to the component.
  54550. * @param {object} data - Component data
  54551. * @param {boolean} isDependency - True if the component is a dependency.
  54552. */
  54553. initComponent: {
  54554. value: function (attrName, data, isDependency) {
  54555. var component;
  54556. var componentId;
  54557. var componentInfo;
  54558. var componentName;
  54559. var isComponentDefined;
  54560. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  54561. componentName = componentInfo[0];
  54562. componentId = componentInfo.length > 2
  54563. ? componentInfo.slice(1).join('__')
  54564. : componentInfo[1];
  54565. // Not a registered component.
  54566. if (!COMPONENTS[componentName]) { return; }
  54567. // Component is not a dependency and is undefined.
  54568. // If a component is a dependency, then it is okay to have no data.
  54569. isComponentDefined = checkComponentDefined(this, attrName) ||
  54570. data !== undefined;
  54571. if (!isComponentDefined && !isDependency) { return; }
  54572. // Component already initialized.
  54573. if (attrName in this.components) { return; }
  54574. // Initialize dependencies first
  54575. this.initComponentDependencies(componentName);
  54576. // If component name has an id we check component type multiplic
  54577. if (componentId && !COMPONENTS[componentName].multiple) {
  54578. throw new Error('Trying to initialize multiple ' +
  54579. 'components of type `' + componentName +
  54580. '`. There can only be one component of this type per entity.');
  54581. }
  54582. component = new COMPONENTS[componentName].Component(this, data, componentId);
  54583. if (this.isPlaying) { component.play(); }
  54584. // Components are reflected in the DOM as attributes but the state is not shown
  54585. // hence we set the attribute to empty string.
  54586. // The flag justInitialized is for attributeChangedCallback to not overwrite
  54587. // the component with the empty string.
  54588. if (!this.hasAttribute(attrName)) {
  54589. component.justInitialized = true;
  54590. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  54591. }
  54592. debug('Component initialized: %s', attrName);
  54593. },
  54594. writable: window.debug
  54595. },
  54596. /**
  54597. * Initialize dependencies of a component.
  54598. *
  54599. * @param {string} name - Root component name.
  54600. */
  54601. initComponentDependencies: {
  54602. value: function (name) {
  54603. var self = this;
  54604. var component = COMPONENTS[name];
  54605. var dependencies;
  54606. var i;
  54607. // Not a component.
  54608. if (!component) { return; }
  54609. // No dependencies.
  54610. dependencies = COMPONENTS[name].dependencies;
  54611. if (!dependencies) { return; }
  54612. // Initialize dependencies.
  54613. for (i = 0; i < dependencies.length; i++) {
  54614. // Call getAttribute to initialize the data from the DOM.
  54615. self.initComponent(
  54616. dependencies[i],
  54617. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  54618. true
  54619. );
  54620. }
  54621. }
  54622. },
  54623. removeComponent: {
  54624. value: function (name, destroy) {
  54625. var component;
  54626. component = this.components[name];
  54627. if (!component) { return; }
  54628. // Wait for component to initialize.
  54629. if (!component.initialized) {
  54630. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  54631. if (evt.detail.name !== name) { return; }
  54632. this.removeComponent(name, destroy);
  54633. this.removeEventListener('componentinitialized', tryRemoveLater);
  54634. });
  54635. return;
  54636. }
  54637. component.pause();
  54638. component.remove();
  54639. // Keep component attached to entity in case of just full entity detach.
  54640. if (destroy) {
  54641. component.destroy();
  54642. delete this.components[name];
  54643. }
  54644. this.emit('componentremoved', component.evtDetail, false);
  54645. },
  54646. writable: window.debug
  54647. },
  54648. /**
  54649. * Initialize or update all components.
  54650. * Build data using initial components, defined attributes, mixins, and defaults.
  54651. * Update default components before the rest.
  54652. *
  54653. * @member {function} getExtraComponents - Can be implemented to include component data
  54654. * from other sources (e.g., implemented by primitives).
  54655. */
  54656. updateComponents: {
  54657. value: function () {
  54658. var data;
  54659. var extraComponents;
  54660. var i;
  54661. var name;
  54662. var componentsToUpdate = this.componentsToUpdate;
  54663. if (!this.hasLoaded) { return; }
  54664. // Gather mixin-defined components.
  54665. for (i = 0; i < this.mixinEls.length; i++) {
  54666. for (name in this.mixinEls[i].componentCache) {
  54667. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54668. }
  54669. }
  54670. // Gather from extra initial component data if defined (e.g., primitives).
  54671. if (this.getExtraComponents) {
  54672. extraComponents = this.getExtraComponents();
  54673. for (name in extraComponents) {
  54674. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54675. }
  54676. }
  54677. // Gather entity-defined components.
  54678. for (i = 0; i < this.attributes.length; ++i) {
  54679. name = this.attributes[i].name;
  54680. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  54681. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54682. }
  54683. // object3D components first (position, rotation, scale, visible).
  54684. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  54685. name = OBJECT3D_COMPONENTS[i];
  54686. if (!this.hasAttribute(name)) { continue; }
  54687. this.updateComponent(name, this.getDOMAttribute(name));
  54688. }
  54689. // Initialize or update rest of components.
  54690. for (name in componentsToUpdate) {
  54691. data = mergeComponentData(this.getDOMAttribute(name),
  54692. extraComponents && extraComponents[name]);
  54693. this.updateComponent(name, data);
  54694. delete componentsToUpdate[name];
  54695. }
  54696. },
  54697. writable: window.debug
  54698. },
  54699. /**
  54700. * Initialize, update, or remove a single component.
  54701. *
  54702. * When initializing, we set the component on `this.components`.
  54703. *
  54704. * @param {string} attr - Component name.
  54705. * @param {object} attrValue - Value of the DOM attribute.
  54706. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  54707. */
  54708. updateComponent: {
  54709. value: function (attr, attrValue, clobber) {
  54710. var component = this.components[attr];
  54711. if (component) {
  54712. // Remove component.
  54713. if (attrValue === null && !checkComponentDefined(this, attr)) {
  54714. this.removeComponent(attr, true);
  54715. return;
  54716. }
  54717. // Component already initialized. Update component.
  54718. component.updateProperties(attrValue, clobber);
  54719. return;
  54720. }
  54721. // Component not yet initialized. Initialize component.
  54722. this.initComponent(attr, attrValue, false);
  54723. }
  54724. },
  54725. /**
  54726. * If `attr` is a component name, detach the component from the entity.
  54727. *
  54728. * If `propertyName` is given, reset the component property value to its default.
  54729. *
  54730. * @param {string} attr - Attribute name, which could also be a component name.
  54731. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  54732. */
  54733. removeAttribute: {
  54734. value: function (attr, propertyName) {
  54735. var component = this.components[attr];
  54736. // Remove component.
  54737. if (component && propertyName === undefined) {
  54738. this.removeComponent(attr, true);
  54739. }
  54740. // Reset component property value.
  54741. if (component && propertyName !== undefined) {
  54742. component.resetProperty(propertyName);
  54743. return;
  54744. }
  54745. // Remove mixins.
  54746. if (attr === 'mixin') {
  54747. this.mixinUpdate('');
  54748. }
  54749. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  54750. }
  54751. },
  54752. /**
  54753. * Start dynamic behavior associated with entity such as dynamic components and animations.
  54754. * Tell all children entities to also play.
  54755. */
  54756. play: {
  54757. value: function () {
  54758. var entities;
  54759. var i;
  54760. var key;
  54761. // Already playing.
  54762. if (this.isPlaying || !this.hasLoaded) { return; }
  54763. this.isPlaying = true;
  54764. // Wake up all components.
  54765. for (key in this.components) { this.components[key].play(); }
  54766. // Tell all child entities to play.
  54767. entities = this.getChildEntities();
  54768. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  54769. this.emit('play');
  54770. },
  54771. writable: true
  54772. },
  54773. /**
  54774. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  54775. * Tell all children entities to also pause.
  54776. */
  54777. pause: {
  54778. value: function () {
  54779. var entities;
  54780. var i;
  54781. var key;
  54782. if (!this.isPlaying) { return; }
  54783. this.isPlaying = false;
  54784. // Sleep all components.
  54785. for (key in this.components) { this.components[key].pause(); }
  54786. // Tell all child entities to pause.
  54787. entities = this.getChildEntities();
  54788. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  54789. this.emit('pause');
  54790. },
  54791. writable: true
  54792. },
  54793. /**
  54794. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  54795. *
  54796. * @param {string} attr
  54797. * @param {string} oldVal
  54798. * @param {string|object} newVal
  54799. */
  54800. setEntityAttribute: {
  54801. value: function (attr, oldVal, newVal) {
  54802. if (COMPONENTS[attr] || this.components[attr]) {
  54803. this.updateComponent(attr, newVal);
  54804. return;
  54805. }
  54806. if (attr === 'mixin') {
  54807. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  54808. if (newVal === this.computedMixinStr) { return; }
  54809. this.mixinUpdate(newVal, oldVal);
  54810. }
  54811. }
  54812. },
  54813. /**
  54814. * When mixins updated, trigger init or optimized-update of relevant components.
  54815. */
  54816. mixinUpdate: {
  54817. value: (function () {
  54818. var componentsUpdated = [];
  54819. return function (newMixins, oldMixins) {
  54820. var component;
  54821. var mixinEl;
  54822. var mixinIds;
  54823. var i;
  54824. var self = this;
  54825. if (!this.hasLoaded) {
  54826. this.addEventListener('loaded', function () {
  54827. self.mixinUpdate(newMixins, oldMixins);
  54828. }, ONCE);
  54829. return;
  54830. }
  54831. oldMixins = oldMixins || this.getAttribute('mixin');
  54832. mixinIds = this.updateMixins(newMixins, oldMixins);
  54833. // Loop over current mixins.
  54834. componentsUpdated.length = 0;
  54835. for (i = 0; i < this.mixinEls.length; i++) {
  54836. for (component in this.mixinEls[i].componentCache) {
  54837. if (componentsUpdated.indexOf(component) === -1) {
  54838. if (this.components[component]) {
  54839. // Update. Just rebuild data.
  54840. this.components[component].handleMixinUpdate();
  54841. } else {
  54842. // Init. buildData will gather mixin values.
  54843. this.initComponent(component, null);
  54844. }
  54845. componentsUpdated.push(component);
  54846. }
  54847. }
  54848. }
  54849. // Loop over old mixins to call for data rebuild.
  54850. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  54851. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  54852. if (!mixinEl) { continue; }
  54853. for (component in mixinEl.componentCache) {
  54854. if (componentsUpdated.indexOf(component) === -1) {
  54855. if (this.components[component]) {
  54856. if (this.getDOMAttribute(component)) {
  54857. // Update component if explicitly defined.
  54858. this.components[component].handleMixinUpdate();
  54859. } else {
  54860. // Remove component if not explicitly defined.
  54861. this.removeComponent(component, true);
  54862. }
  54863. }
  54864. }
  54865. }
  54866. }
  54867. };
  54868. })()
  54869. },
  54870. /**
  54871. * setAttribute can:
  54872. *
  54873. * 1. Set a single property of a multi-property component.
  54874. * 2. Set multiple properties of a multi-property component.
  54875. * 3. Replace properties of a multi-property component.
  54876. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  54877. *
  54878. * @param {string} attrName - Component or attribute name.
  54879. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  54880. * object of properties.
  54881. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  54882. * it is a boolean indicating whether to clobber previous values (defaults to false).
  54883. */
  54884. setAttribute: {
  54885. value: (function () {
  54886. var singlePropUpdate = {};
  54887. return function (attrName, arg1, arg2) {
  54888. var newAttrValue;
  54889. var clobber;
  54890. var componentName;
  54891. var delimiterIndex;
  54892. var isDebugMode;
  54893. var key;
  54894. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  54895. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  54896. // Not a component. Normal set attribute.
  54897. if (!COMPONENTS[componentName]) {
  54898. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  54899. ANode.prototype.setAttribute.call(this, attrName, arg1);
  54900. return;
  54901. }
  54902. // Initialize component first if not yet initialized.
  54903. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  54904. this.updateComponent(
  54905. attrName,
  54906. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  54907. }
  54908. // Determine new attributes from the arguments
  54909. if (typeof arg2 !== 'undefined' &&
  54910. typeof arg1 === 'string' &&
  54911. arg1.length > 0 &&
  54912. typeof utils.styleParser.parse(arg1) === 'string') {
  54913. // Update a single property of a multi-property component
  54914. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  54915. newAttrValue = singlePropUpdate;
  54916. newAttrValue[arg1] = arg2;
  54917. clobber = false;
  54918. } else {
  54919. // Update with a value, object, or CSS-style property string, with the possiblity
  54920. // of clobbering previous values.
  54921. newAttrValue = arg1;
  54922. clobber = (arg2 === true);
  54923. }
  54924. // Update component
  54925. this.updateComponent(attrName, newAttrValue, clobber);
  54926. // In debug mode, write component data up to the DOM.
  54927. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  54928. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  54929. };
  54930. })(),
  54931. writable: window.debug
  54932. },
  54933. /**
  54934. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  54935. *
  54936. * @param {bool} recursive - Also flushToDOM on the children.
  54937. **/
  54938. flushToDOM: {
  54939. value: function (recursive) {
  54940. var components = this.components;
  54941. var child;
  54942. var children = this.children;
  54943. var i;
  54944. var key;
  54945. // Flush entity's components to DOM.
  54946. for (key in components) {
  54947. components[key].flushToDOM();
  54948. }
  54949. // Recurse.
  54950. if (!recursive) { return; }
  54951. for (i = 0; i < children.length; ++i) {
  54952. child = children[i];
  54953. if (!child.flushToDOM) { continue; }
  54954. child.flushToDOM(recursive);
  54955. }
  54956. }
  54957. },
  54958. /**
  54959. * If `attr` is a component, returns ALL component data including applied mixins and
  54960. * defaults.
  54961. *
  54962. * If `attr` is not a component, fall back to HTML getAttribute.
  54963. *
  54964. * @param {string} attr
  54965. * @returns {object|string} Object if component, else string.
  54966. */
  54967. getAttribute: {
  54968. value: function (attr) {
  54969. // If component, return component data.
  54970. var component;
  54971. if (attr === 'position') { return this.object3D.position; }
  54972. if (attr === 'rotation') { return getRotation(this); }
  54973. if (attr === 'scale') { return this.object3D.scale; }
  54974. if (attr === 'visible') { return this.object3D.visible; }
  54975. component = this.components[attr];
  54976. if (component) { return component.data; }
  54977. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  54978. },
  54979. writable: window.debug
  54980. },
  54981. /**
  54982. * If `attr` is a component, returns JUST the component data defined on the entity.
  54983. * Like a partial version of `getComputedAttribute` as returned component data
  54984. * does not include applied mixins or defaults.
  54985. *
  54986. * If `attr` is not a component, fall back to HTML getAttribute.
  54987. *
  54988. * @param {string} attr
  54989. * @returns {object|string} Object if component, else string.
  54990. */
  54991. getDOMAttribute: {
  54992. value: function (attr) {
  54993. // If cached value exists, return partial component data.
  54994. var component = this.components[attr];
  54995. if (component) { return component.attrValue; }
  54996. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  54997. },
  54998. writable: window.debug
  54999. },
  55000. addState: {
  55001. value: function (state) {
  55002. if (this.is(state)) { return; }
  55003. this.states.push(state);
  55004. this.emit('stateadded', state);
  55005. }
  55006. },
  55007. removeState: {
  55008. value: function (state) {
  55009. var stateIndex = this.states.indexOf(state);
  55010. if (stateIndex === -1) { return; }
  55011. this.states.splice(stateIndex, 1);
  55012. this.emit('stateremoved', state);
  55013. }
  55014. },
  55015. /**
  55016. * Checks if the element is in a given state. e.g. el.is('alive');
  55017. * @type {string} state - Name of the state we want to check
  55018. */
  55019. is: {
  55020. value: function (state) {
  55021. return this.states.indexOf(state) !== -1;
  55022. }
  55023. },
  55024. /**
  55025. * Open Inspector to this entity.
  55026. */
  55027. inspect: {
  55028. value: function () {
  55029. this.sceneEl.components.inspector.openInspector(this);
  55030. }
  55031. },
  55032. /**
  55033. * Clean up memory and return memory to object pools.
  55034. */
  55035. destroy: {
  55036. value: function () {
  55037. var key;
  55038. if (this.parentNode) {
  55039. warn('Entity can only be destroyed if detached from scenegraph.');
  55040. return;
  55041. }
  55042. for (key in this.components) {
  55043. this.components[key].destroy();
  55044. }
  55045. }
  55046. }
  55047. });
  55048. /**
  55049. * Check if a component is *defined* for an entity, including defaults and mixins.
  55050. * Does not check whether the component has been *initialized* for an entity.
  55051. *
  55052. * @param {string} el - Entity.
  55053. * @param {string} name - Component name.
  55054. * @returns {boolean}
  55055. */
  55056. function checkComponentDefined (el, name) {
  55057. // Check if element contains the component.
  55058. if (el.components[name] && el.components[name].attrValue) { return true; }
  55059. return isComponentMixedIn(name, el.mixinEls);
  55060. }
  55061. /**
  55062. * Check if any mixins contains a component.
  55063. *
  55064. * @param {string} name - Component name.
  55065. * @param {array} mixinEls - Array of <a-mixin>s.
  55066. */
  55067. function isComponentMixedIn (name, mixinEls) {
  55068. var i;
  55069. var inMixin = false;
  55070. for (i = 0; i < mixinEls.length; ++i) {
  55071. inMixin = mixinEls[i].hasAttribute(name);
  55072. if (inMixin) { break; }
  55073. }
  55074. return inMixin;
  55075. }
  55076. /**
  55077. * Given entity defined value, merge in extra data if necessary.
  55078. * Handle both single and multi-property components.
  55079. *
  55080. * @param {string} attrValue - Entity data.
  55081. * @param extraData - Entity data from another source to merge in.
  55082. */
  55083. function mergeComponentData (attrValue, extraData) {
  55084. // Extra data not defined, just return attrValue.
  55085. if (!extraData) { return attrValue; }
  55086. // Merge multi-property data.
  55087. if (extraData.constructor === Object) {
  55088. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  55089. }
  55090. // Return data, precendence to the defined value.
  55091. return attrValue || extraData;
  55092. }
  55093. function isComponent (componentName) {
  55094. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  55095. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  55096. }
  55097. if (!COMPONENTS[componentName]) { return false; }
  55098. return true;
  55099. }
  55100. function getRotation (entityEl) {
  55101. var radToDeg = THREE.Math.radToDeg;
  55102. var rotation = entityEl.object3D.rotation;
  55103. var rotationObj = entityEl.rotationObj;
  55104. rotationObj.x = radToDeg(rotation.x);
  55105. rotationObj.y = radToDeg(rotation.y);
  55106. rotationObj.z = radToDeg(rotation.z);
  55107. return rotationObj;
  55108. }
  55109. AEntity = registerElement('a-entity', {prototype: proto});
  55110. module.exports = AEntity;
  55111. },{"../lib/three":178,"../utils/":204,"./a-node":128,"./a-register-element":129,"./component":130}],127:[function(_dereq_,module,exports){
  55112. var ANode = _dereq_('./a-node');
  55113. var registerElement = _dereq_('./a-register-element').registerElement;
  55114. var components = _dereq_('./component').components;
  55115. var utils = _dereq_('../utils');
  55116. var MULTIPLE_COMPONENT_DELIMITER = '__';
  55117. /**
  55118. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  55119. * are component names and the values are already parsed by the component.
  55120. */
  55121. module.exports = registerElement('a-mixin', {
  55122. prototype: Object.create(ANode.prototype, {
  55123. createdCallback: {
  55124. value: function () {
  55125. this.componentCache = {};
  55126. this.id = this.getAttribute('id');
  55127. this.isMixin = true;
  55128. }
  55129. },
  55130. attributeChangedCallback: {
  55131. value: function (attr, oldVal, newVal) {
  55132. this.cacheAttribute(attr, newVal);
  55133. this.updateEntities();
  55134. }
  55135. },
  55136. attachedCallback: {
  55137. value: function () {
  55138. this.sceneEl = this.closestScene();
  55139. this.cacheAttributes();
  55140. this.updateEntities();
  55141. this.load();
  55142. }
  55143. },
  55144. /**
  55145. * setAttribute that parses and caches component values.
  55146. */
  55147. setAttribute: {
  55148. value: function (attr, value) {
  55149. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  55150. this.cacheAttribute(attr, value);
  55151. }
  55152. },
  55153. /**
  55154. * If `attr` is a component, then parse the value using the schema and store it.
  55155. */
  55156. cacheAttribute: {
  55157. value: function (attr, value) {
  55158. var component;
  55159. var componentName;
  55160. // Get component data.
  55161. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  55162. component = components[componentName];
  55163. if (!component) { return; }
  55164. if (value === undefined) {
  55165. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  55166. }
  55167. this.componentCache[attr] = component.parseAttrValueForCache(value);
  55168. }
  55169. },
  55170. /**
  55171. * If `attr` is a component, then grab pre-parsed value from the cache.
  55172. * Else do a normal getAttribute.
  55173. */
  55174. getAttribute: {
  55175. value: function (attr) {
  55176. return this.componentCache[attr] ||
  55177. window.HTMLElement.prototype.getAttribute.call(this, attr);
  55178. }
  55179. },
  55180. /**
  55181. * Parse and cache every component defined on the mixin.
  55182. */
  55183. cacheAttributes: {
  55184. value: function () {
  55185. var attributes = this.attributes;
  55186. var attrName;
  55187. var i;
  55188. for (i = 0; i < attributes.length; i++) {
  55189. attrName = attributes[i].name;
  55190. this.cacheAttribute(attrName);
  55191. }
  55192. }
  55193. },
  55194. /**
  55195. * For entities that already have been loaded by the time the mixin was attached, tell
  55196. * those entities to register the mixin and refresh their component data.
  55197. */
  55198. updateEntities: {
  55199. value: function () {
  55200. var entity;
  55201. var entities;
  55202. var i;
  55203. if (!this.sceneEl) { return; }
  55204. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  55205. for (i = 0; i < entities.length; i++) {
  55206. entity = entities[i];
  55207. if (!entity.hasLoaded || entity.isMixin) { continue; }
  55208. entity.mixinUpdate(this.id);
  55209. }
  55210. }
  55211. }
  55212. })
  55213. });
  55214. },{"../utils":204,"./a-node":128,"./a-register-element":129,"./component":130}],128:[function(_dereq_,module,exports){
  55215. /* global CustomEvent */
  55216. var registerElement = _dereq_('./a-register-element').registerElement;
  55217. var isNode = _dereq_('./a-register-element').isNode;
  55218. var utils = _dereq_('../utils/');
  55219. var warn = utils.debug('core:a-node:warn');
  55220. var error = utils.debug('core:a-node:error');
  55221. /**
  55222. * Base class for A-Frame that manages loading of objects.
  55223. *
  55224. * Nodes can be modified using mixins.
  55225. * Nodes emit a `loaded` event when they and their children have initialized.
  55226. */
  55227. module.exports = registerElement('a-node', {
  55228. prototype: Object.create(window.HTMLElement.prototype, {
  55229. createdCallback: {
  55230. value: function () {
  55231. this.computedMixinStr = '';
  55232. this.hasLoaded = false;
  55233. this.isNode = true;
  55234. this.mixinEls = [];
  55235. },
  55236. writable: window.debug
  55237. },
  55238. attachedCallback: {
  55239. value: function () {
  55240. var mixins;
  55241. this.sceneEl = this.closestScene();
  55242. if (!this.sceneEl) {
  55243. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  55244. 'scene. Append this element to `<a-scene>` instead.');
  55245. }
  55246. this.hasLoaded = false;
  55247. this.emit('nodeready', undefined, false);
  55248. if (!this.isMixin) {
  55249. mixins = this.getAttribute('mixin');
  55250. if (mixins) { this.updateMixins(mixins); }
  55251. }
  55252. },
  55253. writable: window.debug
  55254. },
  55255. /**
  55256. * Handle mixin.
  55257. */
  55258. attributeChangedCallback: {
  55259. value: function (attr, oldVal, newVal) {
  55260. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  55261. if (newVal === this.computedMixinStr) { return; }
  55262. if (attr === 'mixin' && !this.isMixin) {
  55263. this.updateMixins(newVal, oldVal);
  55264. }
  55265. }
  55266. },
  55267. /**
  55268. * Returns the first scene by traversing up the tree starting from and
  55269. * including receiver element.
  55270. */
  55271. closestScene: {
  55272. value: function closest () {
  55273. var element = this;
  55274. while (element) {
  55275. if (element.isScene) { break; }
  55276. element = element.parentElement;
  55277. }
  55278. return element;
  55279. }
  55280. },
  55281. /**
  55282. * Returns first element matching a selector by traversing up the tree starting
  55283. * from and including receiver element.
  55284. *
  55285. * @param {string} selector - Selector of element to find.
  55286. */
  55287. closest: {
  55288. value: function closest (selector) {
  55289. var matches = this.matches || this.mozMatchesSelector ||
  55290. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  55291. var element = this;
  55292. while (element) {
  55293. if (matches.call(element, selector)) { break; }
  55294. element = element.parentElement;
  55295. }
  55296. return element;
  55297. }
  55298. },
  55299. detachedCallback: {
  55300. value: function () {
  55301. this.hasLoaded = false;
  55302. }
  55303. },
  55304. /**
  55305. * Wait for children to load, if any.
  55306. * Then emit `loaded` event and set `hasLoaded`.
  55307. */
  55308. load: {
  55309. value: function (cb, childFilter) {
  55310. var children;
  55311. var childrenLoaded;
  55312. var self = this;
  55313. if (this.hasLoaded) { return; }
  55314. // Default to waiting for all nodes.
  55315. childFilter = childFilter || isNode;
  55316. // Wait for children to load (if any), then load.
  55317. children = this.getChildren();
  55318. childrenLoaded = children.filter(childFilter).map(function (child) {
  55319. return new Promise(function waitForLoaded (resolve) {
  55320. if (child.hasLoaded) { return resolve(); }
  55321. child.addEventListener('loaded', resolve);
  55322. });
  55323. });
  55324. Promise.all(childrenLoaded).then(function emitLoaded () {
  55325. self.hasLoaded = true;
  55326. if (cb) { cb(); }
  55327. self.emit('loaded', undefined, false);
  55328. }).catch(function (err) {
  55329. error('Failure loading node: ', err);
  55330. });
  55331. },
  55332. writable: true
  55333. },
  55334. getChildren: {
  55335. value: function () {
  55336. return Array.prototype.slice.call(this.children, 0);
  55337. }
  55338. },
  55339. /**
  55340. * Unregister old mixins and listeners.
  55341. * Register new mixins and listeners.
  55342. * Registering means to update `this.mixinEls` with listeners.
  55343. */
  55344. updateMixins: {
  55345. value: (function () {
  55346. var newMixinIdArray = [];
  55347. var oldMixinIdArray = [];
  55348. var mixinIds = {};
  55349. return function (newMixins, oldMixins) {
  55350. var i;
  55351. var newMixinIds;
  55352. var oldMixinIds;
  55353. newMixinIdArray.length = 0;
  55354. oldMixinIdArray.length = 0;
  55355. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  55356. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  55357. mixinIds.newMixinIds = newMixinIds;
  55358. mixinIds.oldMixinIds = oldMixinIds;
  55359. // Unregister old mixins.
  55360. for (i = 0; i < oldMixinIds.length; i++) {
  55361. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  55362. this.unregisterMixin(oldMixinIds[i]);
  55363. }
  55364. }
  55365. // Register new mixins.
  55366. this.computedMixinStr = '';
  55367. this.mixinEls.length = 0;
  55368. for (i = 0; i < newMixinIds.length; i++) {
  55369. this.registerMixin(document.getElementById(newMixinIds[i]));
  55370. }
  55371. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  55372. // update.
  55373. if (this.computedMixinStr) {
  55374. this.computedMixinStr = this.computedMixinStr.trim();
  55375. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  55376. this.computedMixinStr);
  55377. }
  55378. return mixinIds;
  55379. };
  55380. })()
  55381. },
  55382. /**
  55383. * From mixin ID, add mixin element to `mixinEls`.
  55384. *
  55385. * @param {Element} mixinEl
  55386. */
  55387. registerMixin: {
  55388. value: function (mixinEl) {
  55389. var compositedMixinIds;
  55390. var i;
  55391. var mixin;
  55392. if (!mixinEl) { return; }
  55393. // Register composited mixins (if mixin has mixins).
  55394. mixin = mixinEl.getAttribute('mixin');
  55395. if (mixin) {
  55396. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  55397. for (i = 0; i < compositedMixinIds.length; i++) {
  55398. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  55399. }
  55400. }
  55401. // Register mixin.
  55402. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  55403. this.mixinEls.push(mixinEl);
  55404. }
  55405. },
  55406. setAttribute: {
  55407. value: function (attr, newValue) {
  55408. if (attr === 'mixin') { this.updateMixins(newValue); }
  55409. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  55410. }
  55411. },
  55412. unregisterMixin: {
  55413. value: function (mixinId) {
  55414. var i;
  55415. var mixinEls = this.mixinEls;
  55416. var mixinEl;
  55417. for (i = 0; i < mixinEls.length; ++i) {
  55418. mixinEl = mixinEls[i];
  55419. if (mixinId === mixinEl.id) {
  55420. mixinEls.splice(i, 1);
  55421. break;
  55422. }
  55423. }
  55424. }
  55425. },
  55426. /**
  55427. * Emit a DOM event.
  55428. *
  55429. * @param {string} name - Name of event.
  55430. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  55431. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  55432. * @param {object} [extraData] - Extra data to pass to the event, if any.
  55433. */
  55434. emit: {
  55435. value: (function () {
  55436. var data = {};
  55437. return function (name, detail, bubbles, extraData) {
  55438. if (bubbles === undefined) { bubbles = true; }
  55439. data.bubbles = !!bubbles;
  55440. data.detail = detail;
  55441. // If extra data is present, we need to create a new object.
  55442. if (extraData) { data = utils.extend({}, extraData, data); }
  55443. this.dispatchEvent(new CustomEvent(name, data));
  55444. };
  55445. })(),
  55446. writable: window.debug
  55447. }
  55448. })
  55449. });
  55450. },{"../utils/":204,"./a-register-element":129}],129:[function(_dereq_,module,exports){
  55451. /*
  55452. ------------------------------------------------------------
  55453. ------------- WARNING WARNING WARNING WARNING --------------
  55454. ------------------------------------------------------------
  55455. This module wraps registerElement to deal with components that inherit from
  55456. `ANode` and `AEntity`. It's a pass through in any other case.
  55457. It wraps some of the prototype methods of the created element to make sure
  55458. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  55459. are also invoked. The method in the base prototype is always called before the one
  55460. in the derived prototype.
  55461. */
  55462. // Polyfill `document.registerElement`.
  55463. _dereq_('document-register-element');
  55464. var ANode; // Must declare before AEntity. Initialized at the bottom.
  55465. var AEntity;
  55466. var knownTags = module.exports.knownTags = {};
  55467. function addTagName (tagName) {
  55468. knownTags[tagName.toLowerCase()] = true;
  55469. }
  55470. /**
  55471. * Return whether the element type is one of our known registered ones.
  55472. *
  55473. * @param {string} node - The name of the tag to register.
  55474. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  55475. */
  55476. module.exports.isNode = function (node) {
  55477. return node.tagName.toLowerCase() in knownTags || node.isNode;
  55478. };
  55479. /**
  55480. * @param {string} tagName - The name of the tag to register.
  55481. * @param {object} obj - The prototype of the new element.
  55482. * @returns {object} The prototype of the new element.
  55483. */
  55484. module.exports.registerElement = function (tagName, obj) {
  55485. var proto = Object.getPrototypeOf(obj.prototype);
  55486. var newObj = obj;
  55487. var isANode = ANode && proto === ANode.prototype;
  55488. var isAEntity = AEntity && proto === AEntity.prototype;
  55489. if (isANode || isAEntity) { addTagName(tagName); }
  55490. // Wrap if element inherits from `ANode`.
  55491. if (isANode) {
  55492. newObj = wrapANodeMethods(obj.prototype);
  55493. newObj = {prototype: Object.create(proto, newObj)};
  55494. }
  55495. // Wrap if element inherits from `AEntity`.
  55496. if (isAEntity) {
  55497. newObj = wrapAEntityMethods(obj.prototype);
  55498. newObj = {prototype: Object.create(proto, newObj)};
  55499. }
  55500. // Give all functions their proper name.
  55501. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  55502. var propVal = newObj.prototype[propName];
  55503. if (typeof propVal === 'function') {
  55504. propVal.displayName = propName;
  55505. }
  55506. });
  55507. return document.registerElement(tagName, newObj);
  55508. };
  55509. /**
  55510. * Wrap some obj methods to call those on `ANode` base prototype.
  55511. *
  55512. * @param {object} obj - Object that contains the methods that will be wrapped.
  55513. * @return {object} An object with the same properties as the input parameter but
  55514. * with some of methods wrapped.
  55515. */
  55516. function wrapANodeMethods (obj) {
  55517. var newObj = {};
  55518. var ANodeMethods = [
  55519. 'attachedCallback',
  55520. 'attributeChangedCallback',
  55521. 'createdCallback',
  55522. 'detachedCallback'
  55523. ];
  55524. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55525. copyProperties(obj, newObj);
  55526. return newObj;
  55527. }
  55528. /**
  55529. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  55530. *
  55531. * @param {object} obj - The objects that contains the methods that will be wrapped.
  55532. * @return {object} - An object with the same properties as the input parameter but
  55533. * with some of methods wrapped.
  55534. */
  55535. function wrapAEntityMethods (obj) {
  55536. var newObj = {};
  55537. var ANodeMethods = [
  55538. 'attachedCallback',
  55539. 'attributeChangedCallback',
  55540. 'createdCallback',
  55541. 'detachedCallback'
  55542. ];
  55543. var AEntityMethods = [
  55544. 'attachedCallback',
  55545. 'attributeChangedCallback',
  55546. 'createdCallback',
  55547. 'detachedCallback'
  55548. ];
  55549. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55550. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  55551. // Copies the remaining properties into the new object.
  55552. copyProperties(obj, newObj);
  55553. return newObj;
  55554. }
  55555. /**
  55556. * Wrap a list a methods to ensure that those in the base prototype are called
  55557. * before the derived one.
  55558. *
  55559. * @param {object} targetObj - Object that will contain the wrapped methods.
  55560. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  55561. * @param {object} derivedObject - Object that inherits from the baseObj.
  55562. * @param {object} baseObj - Object that derivedObj inherits from.
  55563. */
  55564. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  55565. methodList.forEach(function (methodName) {
  55566. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  55567. });
  55568. }
  55569. module.exports.wrapMethods = wrapMethods;
  55570. /**
  55571. * Wrap one method to ensure that the one in the base prototype is called before
  55572. * the one in the derived one.
  55573. *
  55574. * @param {object} obj - Object that will contain the wrapped method.
  55575. * @param {string} methodName - The name of the method that will be wrapped.
  55576. * @param {object} derivedObject - Object that inherits from the baseObj.
  55577. * @param {object} baseObj - Object that derivedObj inherits from.
  55578. */
  55579. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  55580. var derivedMethod = derivedObj[methodName];
  55581. var baseMethod = baseObj[methodName];
  55582. // Derived prototype does not define method, no need to wrap.
  55583. if (!derivedMethod || !baseMethod) { return; }
  55584. // Derived prototype doesn't override the one in the base one, no need to wrap.
  55585. if (derivedMethod === baseMethod) { return; }
  55586. // Wrap to ensure the base method is called before the one in the derived prototype.
  55587. obj[methodName] = {
  55588. value: function wrappedMethod () {
  55589. baseMethod.apply(this, arguments);
  55590. return derivedMethod.apply(this, arguments);
  55591. },
  55592. writable: window.debug
  55593. };
  55594. }
  55595. /**
  55596. * It copies the properties from source to destination object if they don't
  55597. * exist already.
  55598. *
  55599. * @param {object} source - The object where properties are copied from.
  55600. * @param {type} destination - The object where properties are copied to.
  55601. */
  55602. function copyProperties (source, destination) {
  55603. var props = Object.getOwnPropertyNames(source);
  55604. props.forEach(function (prop) {
  55605. var desc;
  55606. if (!destination[prop]) {
  55607. desc = Object.getOwnPropertyDescriptor(source, prop);
  55608. destination[prop] = {value: source[prop], writable: desc.writable};
  55609. }
  55610. });
  55611. }
  55612. ANode = _dereq_('./a-node');
  55613. AEntity = _dereq_('./a-entity');
  55614. },{"./a-entity":126,"./a-node":128,"document-register-element":12}],130:[function(_dereq_,module,exports){
  55615. /* global Node */
  55616. var schema = _dereq_('./schema');
  55617. var scenes = _dereq_('./scene/scenes');
  55618. var systems = _dereq_('./system');
  55619. var utils = _dereq_('../utils/');
  55620. var components = module.exports.components = {}; // Keep track of registered components.
  55621. var parseProperties = schema.parseProperties;
  55622. var parseProperty = schema.parseProperty;
  55623. var processSchema = schema.process;
  55624. var isSingleProp = schema.isSingleProperty;
  55625. var stringifyProperties = schema.stringifyProperties;
  55626. var stringifyProperty = schema.stringifyProperty;
  55627. var styleParser = utils.styleParser;
  55628. var warn = utils.debug('core:component:warn');
  55629. var aframeScript = document.currentScript;
  55630. var upperCaseRegExp = new RegExp('[A-Z]+');
  55631. // Object pools by component, created upon registration.
  55632. var objectPools = {};
  55633. /**
  55634. * Component class definition.
  55635. *
  55636. * Components configure appearance, modify behavior, or add functionality to
  55637. * entities. The behavior and appearance of an entity can be changed at runtime
  55638. * by adding, removing, or updating components. Entities do not share instances
  55639. * of components.
  55640. *
  55641. * @member {object} el - Reference to the entity element.
  55642. * @member {string} attrValue - Value of the corresponding HTML attribute.
  55643. * @member {object} data - Component data populated by parsing the
  55644. * mapped attribute of the component plus applying defaults and mixins.
  55645. */
  55646. var Component = module.exports.Component = function (el, attrValue, id) {
  55647. var self = this;
  55648. this.el = el;
  55649. this.id = id;
  55650. this.attrName = this.name + (id ? '__' + id : '');
  55651. this.evtDetail = {id: this.id, name: this.name};
  55652. this.initialized = false;
  55653. this.isSingleProperty = isSingleProp(this.schema);
  55654. this.isSinglePropertyObject = this.isSingleProperty &&
  55655. isObject(parseProperty(undefined, this.schema)) &&
  55656. !(this.schema.default instanceof window.HTMLElement);
  55657. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  55658. this.el.components[this.attrName] = this;
  55659. this.objectPool = objectPools[this.name];
  55660. const events = this.events;
  55661. this.events = {};
  55662. eventsBind(this, events);
  55663. // Store component data from previous update call.
  55664. this.attrValue = undefined;
  55665. if (this.isObjectBased) {
  55666. this.nextData = this.objectPool.use();
  55667. // Drop any properties added by dynamic schemas in previous use
  55668. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  55669. this.oldData = this.objectPool.use();
  55670. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  55671. this.previousOldData = this.objectPool.use();
  55672. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  55673. this.parsingAttrValue = this.objectPool.use();
  55674. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  55675. } else {
  55676. this.nextData = undefined;
  55677. this.oldData = undefined;
  55678. this.previousOldData = undefined;
  55679. this.parsingAttrValue = undefined;
  55680. }
  55681. // Last value passed to updateProperties.
  55682. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  55683. el.emit('componentchanged', self.evtDetail, false);
  55684. }, 200);
  55685. this.updateProperties(attrValue);
  55686. };
  55687. Component.prototype = {
  55688. /**
  55689. * Contains the type schema and defaults for the data values.
  55690. * Data is coerced into the types of the values of the defaults.
  55691. */
  55692. schema: {},
  55693. /**
  55694. * Init handler. Similar to attachedCallback.
  55695. * Called during component initialization and is only run once.
  55696. * Components can use this to set initial state.
  55697. */
  55698. init: function () { /* no-op */ },
  55699. /**
  55700. * Map of event names to binded event handlers that will be lifecycle-handled.
  55701. * Will be detached on pause / remove.
  55702. * Will be attached on play.
  55703. */
  55704. events: {},
  55705. /**
  55706. * Update handler. Similar to attributeChangedCallback.
  55707. * Called whenever component's data changes.
  55708. * Also called on component initialization when the component receives initial data.
  55709. *
  55710. * @param {object} prevData - Previous attributes of the component.
  55711. */
  55712. update: function (prevData) { /* no-op */ },
  55713. updateSchema: undefined,
  55714. /**
  55715. * Tick handler.
  55716. * Called on each tick of the scene render loop.
  55717. * Affected by play and pause.
  55718. *
  55719. * @param {number} time - Scene tick time.
  55720. * @param {number} timeDelta - Difference in current render time and previous render time.
  55721. */
  55722. tick: undefined,
  55723. /**
  55724. * Tock handler.
  55725. * Called on each tock of the scene render loop.
  55726. * Affected by play and pause.
  55727. *
  55728. * @param {number} time - Scene tick time.
  55729. * @param {number} timeDelta - Difference in current render time and previous render time.
  55730. * @param {object} camera - Camera used to render the last frame.
  55731. */
  55732. tock: undefined,
  55733. /**
  55734. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  55735. */
  55736. play: function () { /* no-op */ },
  55737. /**
  55738. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  55739. */
  55740. pause: function () { /* no-op */ },
  55741. /**
  55742. * Remove handler. Similar to detachedCallback.
  55743. * Called whenever component is removed from the entity (i.e., removeAttribute).
  55744. * Components can use this to reset behavior on the entity.
  55745. */
  55746. remove: function () { /* no-op */ },
  55747. /**
  55748. * Parses each property based on property type.
  55749. * If component is single-property, then parses the single property value.
  55750. *
  55751. * @param {string} value - HTML attribute value.
  55752. * @param {boolean} silent - Suppress warning messages.
  55753. * @returns {object} Component data.
  55754. */
  55755. parse: function (value, silent) {
  55756. var schema = this.schema;
  55757. if (this.isSingleProperty) { return parseProperty(value, schema); }
  55758. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  55759. },
  55760. /**
  55761. * Stringify properties if necessary.
  55762. *
  55763. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  55764. * value (e.g., selector, vec3 property types).
  55765. *
  55766. * @param {object} data - Complete component data.
  55767. * @returns {string}
  55768. */
  55769. stringify: function (data) {
  55770. var schema = this.schema;
  55771. if (typeof data === 'string') { return data; }
  55772. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  55773. data = stringifyProperties(data, schema);
  55774. return styleParser.stringify(data);
  55775. },
  55776. /**
  55777. * Update the cache of the pre-parsed attribute value.
  55778. *
  55779. * @param {string} value - New data.
  55780. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  55781. */
  55782. updateCachedAttrValue: function (value, clobber) {
  55783. var newAttrValue;
  55784. var tempObject;
  55785. var property;
  55786. if (value === undefined) { return; }
  55787. // If null value is the new attribute value, make the attribute value falsy.
  55788. if (value === null) {
  55789. if (this.isObjectBased && this.attrValue) {
  55790. this.objectPool.recycle(this.attrValue);
  55791. }
  55792. this.attrValue = undefined;
  55793. return;
  55794. }
  55795. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  55796. // If value is an object, copy it to our pooled newAttrValue object to use to update
  55797. // the attrValue.
  55798. tempObject = this.objectPool.use();
  55799. newAttrValue = utils.extend(tempObject, value);
  55800. } else {
  55801. newAttrValue = this.parseAttrValueForCache(value);
  55802. }
  55803. // Merge new data with previous `attrValue` if updating and not clobbering.
  55804. if (this.isObjectBased && !clobber && this.attrValue) {
  55805. for (property in this.attrValue) {
  55806. if (newAttrValue[property] === undefined) {
  55807. newAttrValue[property] = this.attrValue[property];
  55808. }
  55809. }
  55810. }
  55811. // Update attrValue.
  55812. if (this.isObjectBased && !this.attrValue) {
  55813. this.attrValue = this.objectPool.use();
  55814. }
  55815. utils.objectPool.clearObject(this.attrValue);
  55816. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  55817. utils.objectPool.clearObject(tempObject);
  55818. },
  55819. /**
  55820. * Given an HTML attribute value parses the string based on the component schema.
  55821. * To avoid double parsings of strings into strings we store the original instead
  55822. * of the parsed one
  55823. *
  55824. * @param {string} value - HTML attribute value
  55825. */
  55826. parseAttrValueForCache: function (value) {
  55827. var parsedValue;
  55828. if (typeof value !== 'string') { return value; }
  55829. if (this.isSingleProperty) {
  55830. parsedValue = this.schema.parse(value);
  55831. /**
  55832. * To avoid bogus double parsings. Cached values will be parsed when building
  55833. * component data. For instance when parsing a src id to its url, we want to cache
  55834. * original string and not the parsed one (#monster -> models/monster.dae)
  55835. * so when building data we parse the expected value.
  55836. */
  55837. if (typeof parsedValue === 'string') { parsedValue = value; }
  55838. } else {
  55839. // Parse using the style parser to avoid double parsing of individual properties.
  55840. utils.objectPool.clearObject(this.parsingAttrValue);
  55841. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  55842. }
  55843. return parsedValue;
  55844. },
  55845. /**
  55846. * Write cached attribute data to the entity DOM element.
  55847. *
  55848. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  55849. * default components.
  55850. */
  55851. flushToDOM: function (isDefault) {
  55852. var attrValue = isDefault ? this.data : this.attrValue;
  55853. if (attrValue === null || attrValue === undefined) { return; }
  55854. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  55855. this.stringify(attrValue));
  55856. },
  55857. /**
  55858. * Apply new component data if data has changed (from setAttribute).
  55859. *
  55860. * @param {string} attrValue - HTML attribute value.
  55861. * If undefined, use the cached attribute value and continue updating properties.
  55862. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  55863. */
  55864. updateProperties: function (attrValue, clobber) {
  55865. var el = this.el;
  55866. // Just cache the attribute if the entity has not loaded
  55867. // Components are not initialized until the entity has loaded
  55868. if (!el.hasLoaded) {
  55869. this.updateCachedAttrValue(attrValue);
  55870. return;
  55871. }
  55872. // Parse the attribute value.
  55873. // Cache current attrValue for future updates. Updates `this.attrValue`.
  55874. // `null` means no value on purpose, do not set a default value, let mixins take over.
  55875. if (attrValue !== null) {
  55876. attrValue = this.parseAttrValueForCache(attrValue);
  55877. }
  55878. // Cache current attrValue for future updates.
  55879. this.updateCachedAttrValue(attrValue, clobber);
  55880. if (this.initialized) {
  55881. this.updateComponent(attrValue, clobber);
  55882. this.callUpdateHandler();
  55883. } else {
  55884. this.initComponent();
  55885. }
  55886. },
  55887. initComponent: function () {
  55888. var el = this.el;
  55889. var initialOldData;
  55890. // Build data.
  55891. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  55892. this.data = this.buildData(this.attrValue);
  55893. // Component is being already initialized.
  55894. if (el.initializingComponents[this.name]) { return; }
  55895. // Prevent infinite loop in case of init method setting same component on the entity.
  55896. el.initializingComponents[this.name] = true;
  55897. // Initialize component.
  55898. this.init();
  55899. this.initialized = true;
  55900. delete el.initializingComponents[this.name];
  55901. // Store current data as previous data for future updates.
  55902. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  55903. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  55904. // Pass undefined to rest of types.
  55905. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  55906. this.update(initialOldData);
  55907. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  55908. // Play the component if the entity is playing.
  55909. if (el.isPlaying) { this.play(); }
  55910. el.emit('componentinitialized', this.evtDetail, false);
  55911. },
  55912. /**
  55913. * @param attrValue - Passed argument from setAttribute.
  55914. */
  55915. updateComponent: function (attrValue, clobber) {
  55916. var key;
  55917. var mayNeedSchemaUpdate;
  55918. if (clobber) {
  55919. // Clobber. Rebuild.
  55920. if (this.updateSchema) {
  55921. this.updateSchema(this.buildData(this.attrValue, true, true));
  55922. }
  55923. this.data = this.buildData(this.attrValue, true, false);
  55924. return;
  55925. }
  55926. // Apply new value to this.data in place since direct update.
  55927. if (this.isSingleProperty) {
  55928. if (this.isObjectBased) {
  55929. parseProperty(attrValue, this.schema);
  55930. }
  55931. // Single-property (already parsed).
  55932. this.data = attrValue;
  55933. return;
  55934. }
  55935. parseProperties(attrValue, this.schema, true, this.name);
  55936. // Check if we need to update schema.
  55937. if (this.schemaChangeKeys.length) {
  55938. for (key in attrValue) {
  55939. if (this.schema[key].schemaChange) {
  55940. mayNeedSchemaUpdate = true;
  55941. break;
  55942. }
  55943. }
  55944. }
  55945. if (mayNeedSchemaUpdate) {
  55946. // Rebuild data if need schema update.
  55947. if (this.updateSchema) {
  55948. this.updateSchema(this.buildData(this.attrValue, true, true));
  55949. }
  55950. this.data = this.buildData(this.attrValue, true, false);
  55951. return;
  55952. }
  55953. // Normal update.
  55954. for (key in attrValue) {
  55955. if (attrValue[key] === undefined) { continue; }
  55956. this.data[key] = attrValue[key];
  55957. }
  55958. },
  55959. /**
  55960. * Check if component should fire update and fire update lifecycle handler.
  55961. */
  55962. callUpdateHandler: function () {
  55963. var hasComponentChanged;
  55964. // Store the previous old data before we calculate the new oldData.
  55965. if (this.previousOldData instanceof Object) {
  55966. utils.objectPool.clearObject(this.previousOldData);
  55967. }
  55968. if (this.isObjectBased) {
  55969. copyData(this.previousOldData, this.oldData);
  55970. } else {
  55971. this.previousOldData = this.oldData;
  55972. }
  55973. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  55974. // Don't update if properties haven't changed.
  55975. // Always update rotation, position, scale.
  55976. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  55977. // Store current data as previous data for future updates.
  55978. // Reuse `this.oldData` object to try not to allocate another one.
  55979. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  55980. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  55981. // Update component with the previous old data.
  55982. this.update(this.previousOldData);
  55983. this.throttledEmitComponentChanged();
  55984. },
  55985. handleMixinUpdate: function () {
  55986. this.data = this.buildData(this.attrValue);
  55987. this.callUpdateHandler();
  55988. },
  55989. /**
  55990. * Reset value of a property to the property's default value.
  55991. * If single-prop component, reset value to component's default value.
  55992. *
  55993. * @param {string} propertyName - Name of property to reset.
  55994. */
  55995. resetProperty: function (propertyName) {
  55996. if (this.isObjectBased) {
  55997. if (!(propertyName in this.attrValue)) { return; }
  55998. delete this.attrValue[propertyName];
  55999. this.data[propertyName] = this.schema[propertyName].default;
  56000. } else {
  56001. this.attrValue = this.schema.default;
  56002. this.data = this.schema.default;
  56003. }
  56004. this.updateProperties(this.attrValue);
  56005. },
  56006. /**
  56007. * Extend schema of component given a partial schema.
  56008. *
  56009. * Some components might want to mutate their schema based on certain properties.
  56010. * e.g., Material component changes its schema based on `shader` to account for different
  56011. * uniforms
  56012. *
  56013. * @param {object} schemaAddon - Schema chunk that extend base schema.
  56014. */
  56015. extendSchema: function (schemaAddon) {
  56016. var extendedSchema;
  56017. // Clone base schema.
  56018. extendedSchema = utils.extend({}, components[this.name].schema);
  56019. // Extend base schema with new schema chunk.
  56020. utils.extend(extendedSchema, schemaAddon);
  56021. this.schema = processSchema(extendedSchema);
  56022. this.el.emit('schemachanged', this.evtDetail);
  56023. },
  56024. /**
  56025. * Build component data from the current state of the entity.data.
  56026. *
  56027. * Precedence:
  56028. * 1. Defaults data
  56029. * 2. Mixin data.
  56030. * 3. Attribute data.
  56031. *
  56032. * Finally coerce the data to the types of the defaults.
  56033. *
  56034. * @param {object} newData - Element new data.
  56035. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  56036. * @param {boolean} silent - Suppress warning messages.
  56037. * @return {object} The component data
  56038. */
  56039. buildData: function (newData, clobber, silent) {
  56040. var componentDefined;
  56041. var data;
  56042. var defaultValue;
  56043. var key;
  56044. var mixinData;
  56045. var nextData = this.nextData;
  56046. var schema = this.schema;
  56047. var i;
  56048. var mixinEls = this.el.mixinEls;
  56049. var previousData;
  56050. // Whether component has a defined value. For arrays, treat empty as not defined.
  56051. componentDefined = newData && newData.constructor === Array
  56052. ? newData.length
  56053. : newData !== undefined && newData !== null;
  56054. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  56055. // 1. Gather default values (lowest precendence).
  56056. if (this.isSingleProperty) {
  56057. if (this.isObjectBased) {
  56058. // If object-based single-prop, then copy over the data to our pooled object.
  56059. data = copyData(nextData, schema.default);
  56060. } else {
  56061. // If is plain single-prop, copy by value the default.
  56062. data = isObjectOrArray(schema.default)
  56063. ? utils.clone(schema.default)
  56064. : schema.default;
  56065. }
  56066. } else {
  56067. // Preserve previously set properties if clobber not enabled.
  56068. previousData = !clobber && this.attrValue;
  56069. // Clone default value if object so components don't share object
  56070. data = previousData instanceof Object
  56071. ? copyData(nextData, previousData)
  56072. : nextData;
  56073. // Apply defaults.
  56074. for (key in schema) {
  56075. defaultValue = schema[key].default;
  56076. if (data[key] !== undefined) { continue; }
  56077. // Clone default value if object so components don't share object
  56078. data[key] = isObjectOrArray(defaultValue)
  56079. ? utils.clone(defaultValue)
  56080. : defaultValue;
  56081. }
  56082. }
  56083. // 2. Gather mixin values.
  56084. for (i = 0; i < mixinEls.length; i++) {
  56085. mixinData = mixinEls[i].getAttribute(this.attrName);
  56086. if (!mixinData) { continue; }
  56087. data = extendProperties(data, mixinData, this.isObjectBased);
  56088. }
  56089. // 3. Gather attribute values (highest precendence).
  56090. if (componentDefined) {
  56091. if (this.isSingleProperty) {
  56092. // If object-based, copy the value to not modify the original.
  56093. if (isObject(newData)) {
  56094. copyData(this.parsingAttrValue, newData);
  56095. return parseProperty(this.parsingAttrValue, schema);
  56096. }
  56097. return parseProperty(newData, schema);
  56098. }
  56099. data = extendProperties(data, newData, this.isObjectBased);
  56100. } else {
  56101. // Parse and coerce using the schema.
  56102. if (this.isSingleProperty) { return parseProperty(data, schema); }
  56103. }
  56104. return parseProperties(data, schema, undefined, this.name, silent);
  56105. },
  56106. /**
  56107. * Attach events from component-defined events map.
  56108. */
  56109. eventsAttach: function () {
  56110. var eventName;
  56111. // Safety detach to prevent double-registration.
  56112. this.eventsDetach();
  56113. for (eventName in this.events) {
  56114. this.el.addEventListener(eventName, this.events[eventName]);
  56115. }
  56116. },
  56117. /**
  56118. * Detach events from component-defined events map.
  56119. */
  56120. eventsDetach: function () {
  56121. var eventName;
  56122. for (eventName in this.events) {
  56123. this.el.removeEventListener(eventName, this.events[eventName]);
  56124. }
  56125. },
  56126. /**
  56127. * Release and free memory.
  56128. */
  56129. destroy: function () {
  56130. this.objectPool.recycle(this.attrValue);
  56131. this.objectPool.recycle(this.oldData);
  56132. this.objectPool.recycle(this.parsingAttrValue);
  56133. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  56134. }
  56135. };
  56136. function eventsBind (component, events) {
  56137. var eventName;
  56138. for (eventName in events) {
  56139. component.events[eventName] = events[eventName].bind(component);
  56140. }
  56141. }
  56142. // For testing.
  56143. if (window.debug) {
  56144. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  56145. }
  56146. /**
  56147. * Register a component to A-Frame.
  56148. *
  56149. * @param {string} name - Component name.
  56150. * @param {object} definition - Component schema and lifecycle method handlers.
  56151. * @returns {object} Component.
  56152. */
  56153. module.exports.registerComponent = function (name, definition) {
  56154. var NewComponent;
  56155. var propertyName;
  56156. var proto = {};
  56157. var schema;
  56158. var schemaIsSingleProp;
  56159. // Warning if component is statically registered after the scene.
  56160. if (document.currentScript && document.currentScript !== aframeScript) {
  56161. scenes.forEach(function checkPosition (sceneEl) {
  56162. // Okay to register component after the scene at runtime.
  56163. if (sceneEl.hasLoaded) { return; }
  56164. // Check that component is declared before the scene.
  56165. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  56166. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  56167. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  56168. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  56169. 'such that the component is available to entities during scene initialization.');
  56170. // For testing.
  56171. if (window.debug) { registrationOrderWarnings[name] = true; }
  56172. });
  56173. }
  56174. if (upperCaseRegExp.test(name) === true) {
  56175. warn('The component name `' + name + '` contains uppercase characters, but ' +
  56176. 'HTML will ignore the capitalization of attribute names. ' +
  56177. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  56178. }
  56179. if (name.indexOf('__') !== -1) {
  56180. throw new Error('The component name `' + name + '` is not allowed. ' +
  56181. 'The sequence __ (double underscore) is reserved to specify an id' +
  56182. ' for multiple components of the same type');
  56183. }
  56184. // Format definition object to prototype object.
  56185. Object.keys(definition).forEach(function (key) {
  56186. proto[key] = {
  56187. value: definition[key],
  56188. writable: true
  56189. };
  56190. });
  56191. if (components[name]) {
  56192. throw new Error('The component `' + name + '` has been already registered. ' +
  56193. 'Check that you are not loading two versions of the same component ' +
  56194. 'or two different components of the same name.');
  56195. }
  56196. NewComponent = function (el, attr, id) {
  56197. Component.call(this, el, attr, id);
  56198. };
  56199. NewComponent.prototype = Object.create(Component.prototype, proto);
  56200. NewComponent.prototype.name = name;
  56201. NewComponent.prototype.isPositionRotationScale =
  56202. name === 'position' || name === 'rotation' || name === 'scale';
  56203. NewComponent.prototype.constructor = NewComponent;
  56204. NewComponent.prototype.system = systems && systems.systems[name];
  56205. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  56206. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  56207. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  56208. NewComponent.prototype.name));
  56209. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  56210. // Keep track of keys that may potentially change the schema.
  56211. if (!schemaIsSingleProp) {
  56212. NewComponent.prototype.schemaChangeKeys = [];
  56213. for (propertyName in schema) {
  56214. if (schema[propertyName].schemaChange) {
  56215. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  56216. }
  56217. }
  56218. }
  56219. // Create object pool for class of components.
  56220. objectPools[name] = utils.objectPool.createPool();
  56221. components[name] = {
  56222. Component: NewComponent,
  56223. dependencies: NewComponent.prototype.dependencies,
  56224. isSingleProp: schemaIsSingleProp,
  56225. multiple: NewComponent.prototype.multiple,
  56226. name: name,
  56227. parse: NewComponent.prototype.parse,
  56228. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  56229. schema: schema,
  56230. stringify: NewComponent.prototype.stringify,
  56231. type: NewComponent.prototype.type
  56232. };
  56233. return NewComponent;
  56234. };
  56235. /**
  56236. * Clone component data.
  56237. * Clone only the properties that are plain objects while keeping a reference for the rest.
  56238. *
  56239. * @param data - Component data to clone.
  56240. * @returns Cloned data.
  56241. */
  56242. function copyData (dest, sourceData) {
  56243. var parsedProperty;
  56244. var key;
  56245. for (key in sourceData) {
  56246. if (sourceData[key] === undefined) { continue; }
  56247. parsedProperty = sourceData[key];
  56248. dest[key] = isObjectOrArray(parsedProperty)
  56249. ? utils.clone(parsedProperty)
  56250. : parsedProperty;
  56251. }
  56252. return dest;
  56253. }
  56254. /**
  56255. * Object extending with checking for single-property schema.
  56256. *
  56257. * @param dest - Destination object or value.
  56258. * @param source - Source object or value
  56259. * @param {boolean} isObjectBased - Whether values are objects.
  56260. * @returns Overridden object or value.
  56261. */
  56262. function extendProperties (dest, source, isObjectBased) {
  56263. var key;
  56264. if (isObjectBased && source.constructor === Object) {
  56265. for (key in source) {
  56266. if (source[key] === undefined) { continue; }
  56267. if (source[key] && source[key].constructor === Object) {
  56268. dest[key] = utils.clone(source[key]);
  56269. } else {
  56270. dest[key] = source[key];
  56271. }
  56272. }
  56273. return dest;
  56274. }
  56275. return source;
  56276. }
  56277. /**
  56278. * Checks if a component has defined a method that needs to run every frame.
  56279. */
  56280. function hasBehavior (component) {
  56281. return component.tick || component.tock;
  56282. }
  56283. /**
  56284. * Wrapper for defined pause method.
  56285. * Pause component by removing tick behavior and calling user's pause method.
  56286. *
  56287. * @param pauseMethod {function}
  56288. */
  56289. function wrapPause (pauseMethod) {
  56290. return function pause () {
  56291. var sceneEl = this.el.sceneEl;
  56292. if (!this.isPlaying) { return; }
  56293. pauseMethod.call(this);
  56294. this.isPlaying = false;
  56295. this.eventsDetach();
  56296. // Remove tick behavior.
  56297. if (!hasBehavior(this)) { return; }
  56298. sceneEl.removeBehavior(this);
  56299. };
  56300. }
  56301. /**
  56302. * Wrapper for defined play method.
  56303. * Play component by adding tick behavior and calling user's play method.
  56304. *
  56305. * @param playMethod {function}
  56306. */
  56307. function wrapPlay (playMethod) {
  56308. return function play () {
  56309. var sceneEl = this.el.sceneEl;
  56310. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  56311. if (!this.initialized || !shouldPlay) { return; }
  56312. playMethod.call(this);
  56313. this.isPlaying = true;
  56314. this.eventsAttach();
  56315. // Add tick behavior.
  56316. if (!hasBehavior(this)) { return; }
  56317. sceneEl.addBehavior(this);
  56318. };
  56319. }
  56320. function isObject (value) {
  56321. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  56322. }
  56323. function isObjectOrArray (value) {
  56324. return value && (value.constructor === Object || value.constructor === Array) &&
  56325. !(value instanceof window.HTMLElement);
  56326. }
  56327. },{"../utils/":204,"./scene/scenes":137,"./schema":139,"./system":141}],131:[function(_dereq_,module,exports){
  56328. var schema = _dereq_('./schema');
  56329. var processSchema = schema.process;
  56330. var geometries = module.exports.geometries = {}; // Registered geometries.
  56331. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  56332. var THREE = _dereq_('../lib/three');
  56333. /**
  56334. * Geometry class definition.
  56335. *
  56336. * Geometries extend the geometry component API to create and register geometry types.
  56337. */
  56338. var Geometry = module.exports.Geometry = function () {};
  56339. Geometry.prototype = {
  56340. /**
  56341. * Contains the type schema and defaults for the data values.
  56342. * Data is coerced into the types of the values of the defaults.
  56343. */
  56344. schema: {},
  56345. /**
  56346. * Init handler. Similar to attachedCallback.
  56347. * Called during shader initialization and is only run once.
  56348. */
  56349. init: function (data) {
  56350. this.geometry = new THREE.Geometry();
  56351. return this.geometry;
  56352. },
  56353. /**
  56354. * Update handler. Similar to attributeChangedCallback.
  56355. * Called whenever the associated geometry data changes.
  56356. *
  56357. * @param {object} data - New geometry data.
  56358. */
  56359. update: function (data) { /* no-op */ }
  56360. };
  56361. /**
  56362. * Registers a geometry to A-Frame.
  56363. *
  56364. * @param {string} name - Geometry name.
  56365. * @param {object} definition - Geometry property and methods.
  56366. * @returns {object} Geometry.
  56367. */
  56368. module.exports.registerGeometry = function (name, definition) {
  56369. var NewGeometry;
  56370. var proto = {};
  56371. // Format definition object to prototype object.
  56372. Object.keys(definition).forEach(function expandDefinition (key) {
  56373. proto[key] = {
  56374. value: definition[key],
  56375. writable: true
  56376. };
  56377. });
  56378. if (geometries[name]) {
  56379. throw new Error('The geometry `' + name + '` has been already registered');
  56380. }
  56381. NewGeometry = function () { Geometry.call(this); };
  56382. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  56383. NewGeometry.prototype.name = name;
  56384. NewGeometry.prototype.constructor = NewGeometry;
  56385. geometries[name] = {
  56386. Geometry: NewGeometry,
  56387. schema: processSchema(NewGeometry.prototype.schema)
  56388. };
  56389. geometryNames.push(name);
  56390. return NewGeometry;
  56391. };
  56392. },{"../lib/three":178,"./schema":139}],132:[function(_dereq_,module,exports){
  56393. var coordinates = _dereq_('../utils/coordinates');
  56394. var debug = _dereq_('debug');
  56395. var error = debug('core:propertyTypes:warn');
  56396. var warn = debug('core:propertyTypes:warn');
  56397. var propertyTypes = module.exports.propertyTypes = {};
  56398. var nonCharRegex = /[,> .[\]:]/;
  56399. var urlRegex = /\url\((.+)\)/;
  56400. // Built-in property types.
  56401. registerPropertyType('audio', '', assetParse);
  56402. registerPropertyType('array', [], arrayParse, arrayStringify);
  56403. registerPropertyType('asset', '', assetParse);
  56404. registerPropertyType('boolean', false, boolParse);
  56405. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  56406. registerPropertyType('int', 0, intParse);
  56407. registerPropertyType('number', 0, numberParse);
  56408. registerPropertyType('map', '', assetParse);
  56409. registerPropertyType('model', '', assetParse);
  56410. registerPropertyType('selector', null, selectorParse, selectorStringify);
  56411. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  56412. registerPropertyType('src', '', srcParse);
  56413. registerPropertyType('string', '', defaultParse, defaultStringify);
  56414. registerPropertyType('time', 0, intParse);
  56415. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  56416. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  56417. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  56418. /**
  56419. * Register a parser for re-use such that when someone uses `type` in the schema,
  56420. * `schema.process` will set the property `parse` and `stringify`.
  56421. *
  56422. * @param {string} type - Type name.
  56423. * @param [defaultValue=null] -
  56424. * Default value to use if component does not define default value.
  56425. * @param {function} [parse=defaultParse] - Parse string function.
  56426. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  56427. */
  56428. function registerPropertyType (type, defaultValue, parse, stringify) {
  56429. if ('type' in propertyTypes) {
  56430. error('Property type ' + type + ' is already registered.');
  56431. return;
  56432. }
  56433. propertyTypes[type] = {
  56434. default: defaultValue,
  56435. parse: parse || defaultParse,
  56436. stringify: stringify || defaultStringify
  56437. };
  56438. }
  56439. module.exports.registerPropertyType = registerPropertyType;
  56440. function arrayParse (value) {
  56441. if (Array.isArray(value)) { return value; }
  56442. if (!value || typeof value !== 'string') { return []; }
  56443. return value.split(',').map(trim);
  56444. function trim (str) { return str.trim(); }
  56445. }
  56446. function arrayStringify (value) {
  56447. return value.join(', ');
  56448. }
  56449. /**
  56450. * For general assets.
  56451. *
  56452. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  56453. * just string.
  56454. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  56455. * just string.
  56456. */
  56457. function assetParse (value) {
  56458. var el;
  56459. var parsedUrl;
  56460. // If an element was provided (e.g. canvas or video), just return it.
  56461. if (typeof value !== 'string') { return value; }
  56462. // Wrapped `url()` in case of data URI.
  56463. parsedUrl = value.match(urlRegex);
  56464. if (parsedUrl) { return parsedUrl[1]; }
  56465. // ID.
  56466. if (value.charAt(0) === '#') {
  56467. el = document.getElementById(value.substring(1));
  56468. if (el) {
  56469. // Pass through media elements. If we have the elements, we don't have to call
  56470. // three.js loaders which would re-request the assets.
  56471. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  56472. return el;
  56473. }
  56474. return el.getAttribute('src');
  56475. }
  56476. warn('"' + value + '" asset not found.');
  56477. return;
  56478. }
  56479. // Non-wrapped url().
  56480. return value;
  56481. }
  56482. function defaultParse (value) {
  56483. return value;
  56484. }
  56485. function defaultStringify (value) {
  56486. if (value === null) { return 'null'; }
  56487. return value.toString();
  56488. }
  56489. function boolParse (value) {
  56490. return value !== 'false' && value !== false;
  56491. }
  56492. function intParse (value) {
  56493. return parseInt(value, 10);
  56494. }
  56495. function numberParse (value) {
  56496. return parseFloat(value, 10);
  56497. }
  56498. function selectorParse (value) {
  56499. if (!value) { return null; }
  56500. if (typeof value !== 'string') { return value; }
  56501. if (value[0] === '#' && !nonCharRegex.test(value)) {
  56502. // When selecting element by ID only, use getElementById for better performance.
  56503. // Don't match like #myId .child.
  56504. return document.getElementById(value.substring(1));
  56505. }
  56506. return document.querySelector(value);
  56507. }
  56508. function selectorAllParse (value) {
  56509. if (!value) { return null; }
  56510. if (typeof value !== 'string') { return value; }
  56511. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  56512. }
  56513. function selectorStringify (value) {
  56514. if (value.getAttribute) {
  56515. return '#' + value.getAttribute('id');
  56516. }
  56517. return defaultStringify(value);
  56518. }
  56519. function selectorAllStringify (value) {
  56520. if (value instanceof Array) {
  56521. return value.map(function (element) {
  56522. return '#' + element.getAttribute('id');
  56523. }).join(', ');
  56524. }
  56525. return defaultStringify(value);
  56526. }
  56527. function srcParse (value) {
  56528. warn('`src` property type is deprecated. Use `asset` instead.');
  56529. return assetParse(value);
  56530. }
  56531. function vecParse (value) {
  56532. return coordinates.parse(value, this.default);
  56533. }
  56534. /**
  56535. * Validate the default values in a schema to match their type.
  56536. *
  56537. * @param {string} type - Property type name.
  56538. * @param defaultVal - Property type default value.
  56539. * @returns {boolean} Whether default value is accurate given the type.
  56540. */
  56541. function isValidDefaultValue (type, defaultVal) {
  56542. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  56543. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  56544. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  56545. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  56546. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  56547. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  56548. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  56549. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  56550. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  56551. if (type === 'selector' && typeof defaultVal !== 'string' &&
  56552. defaultVal !== null) { return false; }
  56553. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  56554. defaultVal !== null) { return false; }
  56555. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  56556. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  56557. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  56558. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  56559. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  56560. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  56561. return true;
  56562. }
  56563. module.exports.isValidDefaultValue = isValidDefaultValue;
  56564. /**
  56565. * Checks if default coordinates are valid.
  56566. *
  56567. * @param possibleCoordinates
  56568. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  56569. * @returns {boolean} Whether coordinates are parsed correctly.
  56570. */
  56571. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  56572. if (possibleCoordinates === null) { return true; }
  56573. if (typeof possibleCoordinates !== 'object') { return false; }
  56574. if (Object.keys(possibleCoordinates).length !== dimensions) {
  56575. return false;
  56576. } else {
  56577. var x = possibleCoordinates.x;
  56578. var y = possibleCoordinates.y;
  56579. var z = possibleCoordinates.z;
  56580. var w = possibleCoordinates.w;
  56581. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  56582. if (dimensions > 2 && typeof z !== 'number') { return false; }
  56583. if (dimensions > 3 && typeof w !== 'number') { return false; }
  56584. }
  56585. return true;
  56586. }
  56587. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  56588. },{"../utils/coordinates":199,"debug":8}],133:[function(_dereq_,module,exports){
  56589. /* global Promise, screen, CustomEvent */
  56590. var initMetaTags = _dereq_('./metaTags').inject;
  56591. var initWakelock = _dereq_('./wakelock');
  56592. var loadingScreen = _dereq_('./loadingScreen');
  56593. var re = _dereq_('../a-register-element');
  56594. var scenes = _dereq_('./scenes');
  56595. var systems = _dereq_('../system').systems;
  56596. var THREE = _dereq_('../../lib/three');
  56597. var utils = _dereq_('../../utils/');
  56598. // Require after.
  56599. var AEntity = _dereq_('../a-entity');
  56600. var ANode = _dereq_('../a-node');
  56601. var initPostMessageAPI = _dereq_('./postMessage');
  56602. var bind = utils.bind;
  56603. var isIOS = utils.device.isIOS();
  56604. var isMobile = utils.device.isMobile();
  56605. var isWebXRAvailable = utils.device.isWebXRAvailable;
  56606. var registerElement = re.registerElement;
  56607. var warn = utils.debug('core:a-scene:warn');
  56608. if (isIOS) { _dereq_('../../utils/ios-orientationchange-blank-bug'); }
  56609. /**
  56610. * Scene element, holds all entities.
  56611. *
  56612. * @member {array} behaviors - Component instances that have registered themselves to be
  56613. updated on every tick.
  56614. * @member {object} camera - three.js Camera object.
  56615. * @member {object} canvas
  56616. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  56617. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  56618. * @member {object} object3D - Root three.js Scene object.
  56619. * @member {object} renderer
  56620. * @member {bool} renderStarted
  56621. * @member {object} systems - Registered instantiated systems.
  56622. * @member {number} time
  56623. */
  56624. module.exports.AScene = registerElement('a-scene', {
  56625. prototype: Object.create(AEntity.prototype, {
  56626. createdCallback: {
  56627. value: function () {
  56628. this.clock = new THREE.Clock();
  56629. this.isIOS = isIOS;
  56630. this.isMobile = isMobile;
  56631. this.hasWebXR = isWebXRAvailable;
  56632. this.isAR = false;
  56633. this.isScene = true;
  56634. this.object3D = new THREE.Scene();
  56635. var self = this;
  56636. this.object3D.onAfterRender = function (renderer, scene, camera) {
  56637. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  56638. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  56639. };
  56640. this.resize = bind(this.resize, this);
  56641. this.render = bind(this.render, this);
  56642. this.systems = {};
  56643. this.systemNames = [];
  56644. this.time = this.delta = 0;
  56645. this.behaviors = {tick: [], tock: []};
  56646. this.hasLoaded = false;
  56647. this.isPlaying = false;
  56648. this.originalHTML = this.innerHTML;
  56649. // Default components.
  56650. this.setAttribute('inspector', '');
  56651. this.setAttribute('keyboard-shortcuts', '');
  56652. this.setAttribute('screenshot', '');
  56653. this.setAttribute('vr-mode-ui', '');
  56654. this.setAttribute('device-orientation-permission-ui', '');
  56655. }
  56656. },
  56657. addFullScreenStyles: {
  56658. value: function () {
  56659. document.documentElement.classList.add('a-fullscreen');
  56660. }
  56661. },
  56662. removeFullScreenStyles: {
  56663. value: function () {
  56664. document.documentElement.classList.remove('a-fullscreen');
  56665. }
  56666. },
  56667. attachedCallback: {
  56668. value: function () {
  56669. var self = this;
  56670. var embedded = this.hasAttribute('embedded');
  56671. // Renderer initialization
  56672. setupCanvas(this);
  56673. this.setupRenderer();
  56674. loadingScreen.setup(this, getCanvasSize);
  56675. this.resize();
  56676. if (!embedded) { this.addFullScreenStyles(); }
  56677. initPostMessageAPI(this);
  56678. initMetaTags(this);
  56679. initWakelock(this);
  56680. // Handler to exit VR (e.g., Oculus Browser back button).
  56681. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  56682. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56683. // Bind functions.
  56684. this.enterVRBound = function () { self.enterVR(); };
  56685. this.exitVRBound = function () { self.exitVR(); };
  56686. this.exitVRTrueBound = function () { self.exitVR(true); };
  56687. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  56688. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  56689. if (!isWebXRAvailable) {
  56690. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  56691. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  56692. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  56693. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56694. // Register for mouse restricted events while in VR
  56695. // (e.g. mouse no longer available on desktop 2D view)
  56696. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56697. // Register for mouse unrestricted events while in VR
  56698. // (e.g. mouse once again available on desktop 2D view)
  56699. window.addEventListener('vrdisplaypointerunrestricted',
  56700. this.pointerUnrestrictedBound);
  56701. }
  56702. window.addEventListener('sessionend', this.resize);
  56703. // Camera set up by camera system.
  56704. this.addEventListener('cameraready', function () {
  56705. self.attachedCallbackPostCamera();
  56706. });
  56707. this.initSystems();
  56708. // WebXR Immersive navigation handler.
  56709. if (this.hasWebXR && navigator.xr && navigator.xr.addEventListener) {
  56710. navigator.xr.addEventListener('sessiongranted', function () { self.enterVR(); });
  56711. }
  56712. }
  56713. },
  56714. attachedCallbackPostCamera: {
  56715. value: function () {
  56716. var resize;
  56717. var self = this;
  56718. window.addEventListener('load', resize);
  56719. window.addEventListener('resize', function () {
  56720. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  56721. // where the window does not contain the correct viewport size
  56722. // after an orientation change. The window size is correct if the operation
  56723. // is postponed a few milliseconds.
  56724. // self.resize can be called directly once the bug above is fixed.
  56725. if (self.isIOS) {
  56726. setTimeout(self.resize, 100);
  56727. } else {
  56728. self.resize();
  56729. }
  56730. });
  56731. this.play();
  56732. // Add to scene index.
  56733. scenes.push(this);
  56734. },
  56735. writable: window.debug
  56736. },
  56737. /**
  56738. * Initialize all systems.
  56739. */
  56740. initSystems: {
  56741. value: function () {
  56742. var name;
  56743. // Initialize camera system first.
  56744. this.initSystem('camera');
  56745. for (name in systems) {
  56746. if (name === 'camera') { continue; }
  56747. this.initSystem(name);
  56748. }
  56749. }
  56750. },
  56751. /**
  56752. * Initialize a system.
  56753. */
  56754. initSystem: {
  56755. value: function (name) {
  56756. if (this.systems[name]) { return; }
  56757. this.systems[name] = new systems[name](this);
  56758. this.systemNames.push(name);
  56759. }
  56760. },
  56761. /**
  56762. * Shut down scene on detach.
  56763. */
  56764. detachedCallback: {
  56765. value: function () {
  56766. // Remove from scene index.
  56767. var sceneIndex = scenes.indexOf(this);
  56768. scenes.splice(sceneIndex, 1);
  56769. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56770. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  56771. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  56772. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  56773. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56774. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56775. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  56776. window.removeEventListener('sessionend', this.resize);
  56777. }
  56778. },
  56779. /**
  56780. * Add ticks and tocks.
  56781. *
  56782. * @param {object} behavior - A component.
  56783. */
  56784. addBehavior: {
  56785. value: function (behavior) {
  56786. var behaviorArr;
  56787. var behaviors = this.behaviors;
  56788. var behaviorType;
  56789. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  56790. for (behaviorType in behaviors) {
  56791. if (!behavior[behaviorType]) { continue; }
  56792. behaviorArr = this.behaviors[behaviorType];
  56793. if (behaviorArr.indexOf(behavior) === -1) {
  56794. behaviorArr.push(behavior);
  56795. }
  56796. }
  56797. }
  56798. },
  56799. /**
  56800. * For tests.
  56801. */
  56802. getPointerLockElement: {
  56803. value: function () {
  56804. return document.pointerLockElement;
  56805. },
  56806. writable: window.debug
  56807. },
  56808. /**
  56809. * For tests.
  56810. */
  56811. checkHeadsetConnected: {
  56812. value: utils.device.checkHeadsetConnected,
  56813. writable: window.debug
  56814. },
  56815. enterAR: {
  56816. value: function () {
  56817. var errorMessage;
  56818. if (!this.hasWebXR) {
  56819. errorMessage = 'Failed to enter AR mode, WebXR not supported.';
  56820. throw new Error(errorMessage);
  56821. }
  56822. if (!utils.device.checkARSupport()) {
  56823. errorMessage = 'Failed to enter AR, WebXR immersive-ar mode not supported in your browser or device.';
  56824. throw new Error(errorMessage);
  56825. }
  56826. return this.enterVR(true);
  56827. }
  56828. },
  56829. /**
  56830. * Call `requestPresent` if WebVR or WebVR polyfill.
  56831. * Call `requestFullscreen` on desktop.
  56832. * Handle events, states, fullscreen styles.
  56833. *
  56834. * @param {bool?} useAR - if true, try immersive-ar mode
  56835. * @returns {Promise}
  56836. */
  56837. enterVR: {
  56838. value: function (useAR) {
  56839. var self = this;
  56840. var vrDisplay;
  56841. var vrManager = self.renderer.xr;
  56842. var xrInit;
  56843. // Don't enter VR if already in VR.
  56844. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  56845. // Has VR.
  56846. if (this.checkHeadsetConnected() || this.isMobile) {
  56847. vrManager.enabled = true;
  56848. if (this.hasWebXR) {
  56849. // XR API.
  56850. if (this.xrSession) {
  56851. this.xrSession.removeEventListener('end', this.exitVRBound);
  56852. }
  56853. var refspace = this.sceneEl.systems.webxr.sessionReferenceSpaceType;
  56854. vrManager.setReferenceSpaceType(refspace);
  56855. var xrMode = useAR ? 'immersive-ar' : 'immersive-vr';
  56856. xrInit = this.sceneEl.systems.webxr.sessionConfiguration;
  56857. return new Promise(function (resolve, reject) {
  56858. navigator.xr.requestSession(xrMode, xrInit).then(
  56859. function requestSuccess (xrSession) {
  56860. self.xrSession = xrSession;
  56861. vrManager.layersEnabled = xrInit.requiredFeatures.indexOf('layers') !== -1;
  56862. vrManager.setSession(xrSession);
  56863. xrSession.addEventListener('end', self.exitVRBound);
  56864. enterVRSuccess(resolve);
  56865. },
  56866. function requestFail (error) {
  56867. var useAR = xrMode === 'immersive-ar';
  56868. var mode = useAR ? 'AR' : 'VR';
  56869. throw new Error('Failed to enter ' + mode + ' mode (`requestSession`) ' + error);
  56870. }
  56871. );
  56872. });
  56873. } else {
  56874. vrDisplay = utils.device.getVRDisplay();
  56875. vrManager.setDevice(vrDisplay);
  56876. if (vrDisplay.isPresenting &&
  56877. !window.hasNativeWebVRImplementation) {
  56878. enterVRSuccess();
  56879. return Promise.resolve();
  56880. }
  56881. var rendererSystem = this.getAttribute('renderer');
  56882. var presentationAttributes = {
  56883. highRefreshRate: rendererSystem.highRefreshRate,
  56884. foveationLevel: rendererSystem.foveationLevel
  56885. };
  56886. return vrDisplay.requestPresent([{
  56887. source: this.canvas,
  56888. attributes: presentationAttributes
  56889. }]).then(enterVRSuccess, enterVRFailure);
  56890. }
  56891. }
  56892. // No VR.
  56893. enterVRSuccess();
  56894. return Promise.resolve();
  56895. // Callback that happens on enter VR success or enter fullscreen (any API).
  56896. function enterVRSuccess (resolve) {
  56897. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  56898. // the first requestPresent could be called from ondisplayactivate and there is no way
  56899. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  56900. // for the actual requestPresent. Need to make sure there are no issues with firing the
  56901. // vrdisplaypresentchange multiple times.
  56902. var event;
  56903. if (window.hasNativeWebVRImplementation && !window.hasNativeWebXRImplementation) {
  56904. event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  56905. window.dispatchEvent(event);
  56906. }
  56907. if (useAR) {
  56908. self.addState('ar-mode');
  56909. } else {
  56910. self.addState('vr-mode');
  56911. }
  56912. self.emit('enter-vr', {target: self});
  56913. // Lock to landscape orientation on mobile.
  56914. if (!isWebXRAvailable && self.isMobile && screen.orientation && screen.orientation.lock) {
  56915. screen.orientation.lock('landscape');
  56916. }
  56917. self.addFullScreenStyles();
  56918. // On mobile, the polyfill handles fullscreen.
  56919. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  56920. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  56921. // connected.
  56922. if (!self.isMobile && !self.checkHeadsetConnected()) {
  56923. requestFullscreen(self.canvas);
  56924. }
  56925. self.renderer.setAnimationLoop(self.render);
  56926. self.resize();
  56927. if (resolve) { resolve(); }
  56928. }
  56929. function enterVRFailure (err) {
  56930. self.removeState('vr-mode');
  56931. if (err && err.message) {
  56932. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  56933. } else {
  56934. throw new Error('Failed to enter VR mode (`requestPresent`).');
  56935. }
  56936. }
  56937. },
  56938. writable: true
  56939. },
  56940. /**
  56941. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  56942. * Handle events, states, fullscreen styles.
  56943. *
  56944. * @returns {Promise}
  56945. */
  56946. exitVR: {
  56947. value: function () {
  56948. var self = this;
  56949. var vrDisplay;
  56950. var vrManager = this.renderer.xr;
  56951. // Don't exit VR if not in VR.
  56952. if (!this.is('vr-mode') && !this.is('ar-mode')) { return Promise.resolve('Not in immersive mode.'); }
  56953. // Handle exiting VR if not yet already and in a headset or polyfill.
  56954. if (this.checkHeadsetConnected() || this.isMobile) {
  56955. vrManager.enabled = false;
  56956. vrDisplay = utils.device.getVRDisplay();
  56957. if (this.hasWebXR) {
  56958. this.xrSession.removeEventListener('end', this.exitVRBound);
  56959. // Capture promise to avoid errors.
  56960. this.xrSession.end().then(function () {}, function () {});
  56961. this.xrSession = undefined;
  56962. vrManager.setSession(null);
  56963. } else {
  56964. if (vrDisplay.isPresenting) {
  56965. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  56966. }
  56967. }
  56968. } else {
  56969. exitFullscreen();
  56970. }
  56971. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  56972. exitVRSuccess();
  56973. return Promise.resolve();
  56974. function exitVRSuccess () {
  56975. self.removeState('vr-mode');
  56976. self.removeState('ar-mode');
  56977. // Lock to landscape orientation on mobile.
  56978. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  56979. screen.orientation.unlock();
  56980. }
  56981. // Exiting VR in embedded mode, no longer need fullscreen styles.
  56982. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  56983. self.resize();
  56984. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  56985. self.renderer.setPixelRatio(window.devicePixelRatio);
  56986. self.emit('exit-vr', {target: self});
  56987. }
  56988. function exitVRFailure (err) {
  56989. if (err && err.message) {
  56990. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  56991. } else {
  56992. throw new Error('Failed to exit VR mode (`exitPresent`).');
  56993. }
  56994. }
  56995. },
  56996. writable: true
  56997. },
  56998. pointerRestricted: {
  56999. value: function () {
  57000. if (this.canvas) {
  57001. var pointerLockElement = this.getPointerLockElement();
  57002. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  57003. // Recreate pointer lock on the canvas, if taken on another element.
  57004. document.exitPointerLock();
  57005. }
  57006. if (this.canvas.requestPointerLock) {
  57007. this.canvas.requestPointerLock();
  57008. }
  57009. }
  57010. }
  57011. },
  57012. pointerUnrestricted: {
  57013. value: function () {
  57014. var pointerLockElement = this.getPointerLockElement();
  57015. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  57016. document.exitPointerLock();
  57017. }
  57018. }
  57019. },
  57020. /**
  57021. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  57022. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  57023. */
  57024. onVRPresentChange: {
  57025. value: function (evt) {
  57026. // Polyfill places display inside the detail property
  57027. var display = evt.display || evt.detail.display;
  57028. // Entering VR.
  57029. if (display && display.isPresenting) {
  57030. this.enterVR();
  57031. return;
  57032. }
  57033. // Exiting VR.
  57034. this.exitVR();
  57035. }
  57036. },
  57037. /**
  57038. * Wraps Entity.getAttribute to take into account for systems.
  57039. * If system exists, then return system data rather than possible component data.
  57040. */
  57041. getAttribute: {
  57042. value: function (attr) {
  57043. var system = this.systems[attr];
  57044. if (system) { return system.data; }
  57045. return AEntity.prototype.getAttribute.call(this, attr);
  57046. }
  57047. },
  57048. /**
  57049. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  57050. * what `getAttribute` is now. Now legacy code.
  57051. */
  57052. getComputedAttribute: {
  57053. value: function (attr) {
  57054. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  57055. this.getAttribute(attr);
  57056. }
  57057. },
  57058. /**
  57059. * Wraps Entity.getDOMAttribute to take into account for systems.
  57060. * If system exists, then return system data rather than possible component data.
  57061. */
  57062. getDOMAttribute: {
  57063. value: function (attr) {
  57064. var system = this.systems[attr];
  57065. if (system) { return system.data; }
  57066. return AEntity.prototype.getDOMAttribute.call(this, attr);
  57067. }
  57068. },
  57069. /**
  57070. * Wrap Entity.setAttribute to take into account for systems.
  57071. * If system exists, then skip component initialization checks and do a normal
  57072. * setAttribute.
  57073. */
  57074. setAttribute: {
  57075. value: function (attr, value, componentPropValue) {
  57076. var system = this.systems[attr];
  57077. if (system) {
  57078. ANode.prototype.setAttribute.call(this, attr, value);
  57079. system.updateProperties(value);
  57080. return;
  57081. }
  57082. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  57083. }
  57084. },
  57085. /**
  57086. * @param {object} behavior - A component.
  57087. */
  57088. removeBehavior: {
  57089. value: function (behavior) {
  57090. var behaviorArr;
  57091. var behaviorType;
  57092. var behaviors = this.behaviors;
  57093. var index;
  57094. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  57095. // array.
  57096. for (behaviorType in behaviors) {
  57097. if (!behavior[behaviorType]) { continue; }
  57098. behaviorArr = this.behaviors[behaviorType];
  57099. index = behaviorArr.indexOf(behavior);
  57100. if (index !== -1) { behaviorArr.splice(index, 1); }
  57101. }
  57102. }
  57103. },
  57104. resize: {
  57105. value: function () {
  57106. var camera = this.camera;
  57107. var canvas = this.canvas;
  57108. var embedded;
  57109. var isVRPresenting;
  57110. var size;
  57111. var isPresenting = this.renderer.xr.isPresenting;
  57112. isVRPresenting = this.renderer.xr.enabled && isPresenting;
  57113. // Do not update renderer, if a camera or a canvas have not been injected.
  57114. // In VR mode, three handles canvas resize based on the dimensions returned by
  57115. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  57116. // the window size, therefore should not be overwritten with the window's width and
  57117. // height, // except when in fullscreen mode.
  57118. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  57119. return;
  57120. }
  57121. // Update camera.
  57122. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  57123. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  57124. camera.aspect = size.width / size.height;
  57125. camera.updateProjectionMatrix();
  57126. // Notify renderer of size change.
  57127. this.renderer.setSize(size.width, size.height, false);
  57128. this.emit('rendererresize', null, false);
  57129. },
  57130. writable: true
  57131. },
  57132. setupRenderer: {
  57133. value: function () {
  57134. var self = this;
  57135. var renderer;
  57136. var rendererAttr;
  57137. var rendererAttrString;
  57138. var rendererConfig;
  57139. rendererConfig = {
  57140. alpha: true,
  57141. antialias: !isMobile,
  57142. canvas: this.canvas,
  57143. logarithmicDepthBuffer: false,
  57144. powerPreference: 'high-performance'
  57145. };
  57146. this.maxCanvasSize = {height: 1920, width: 1920};
  57147. if (this.hasAttribute('renderer')) {
  57148. rendererAttrString = this.getAttribute('renderer');
  57149. rendererAttr = utils.styleParser.parse(rendererAttrString);
  57150. if (rendererAttr.precision) {
  57151. rendererConfig.precision = rendererAttr.precision + 'p';
  57152. }
  57153. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  57154. rendererConfig.antialias = rendererAttr.antialias === 'true';
  57155. }
  57156. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  57157. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  57158. }
  57159. if (rendererAttr.alpha) {
  57160. rendererConfig.alpha = rendererAttr.alpha === 'true';
  57161. }
  57162. this.maxCanvasSize = {
  57163. width: rendererAttr.maxCanvasWidth
  57164. ? parseInt(rendererAttr.maxCanvasWidth)
  57165. : this.maxCanvasSize.width,
  57166. height: rendererAttr.maxCanvasHeight
  57167. ? parseInt(rendererAttr.maxCanvasHeight)
  57168. : this.maxCanvasSize.height
  57169. };
  57170. }
  57171. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  57172. renderer.setPixelRatio(window.devicePixelRatio);
  57173. renderer.sortObjects = false;
  57174. if (this.camera) { renderer.xr.setPoseTarget(this.camera.el.object3D); }
  57175. this.addEventListener('camera-set-active', function () {
  57176. renderer.xr.setPoseTarget(self.camera.el.object3D);
  57177. });
  57178. },
  57179. writable: window.debug
  57180. },
  57181. /**
  57182. * Handler attached to elements to help scene know when to kick off.
  57183. * Scene waits for all entities to load.
  57184. */
  57185. play: {
  57186. value: function () {
  57187. var self = this;
  57188. var sceneEl = this;
  57189. if (this.renderStarted) {
  57190. AEntity.prototype.play.call(this);
  57191. return;
  57192. }
  57193. this.addEventListener('loaded', function () {
  57194. var renderer = this.renderer;
  57195. var vrDisplay;
  57196. var vrManager = this.renderer.xr;
  57197. AEntity.prototype.play.call(this); // .play() *before* render.
  57198. if (sceneEl.renderStarted) { return; }
  57199. sceneEl.resize();
  57200. // Kick off render loop.
  57201. if (sceneEl.renderer) {
  57202. if (window.performance) { window.performance.mark('render-started'); }
  57203. loadingScreen.remove();
  57204. vrDisplay = utils.device.getVRDisplay();
  57205. if (vrDisplay && vrDisplay.isPresenting) {
  57206. vrManager.setDevice(vrDisplay);
  57207. vrManager.enabled = true;
  57208. sceneEl.enterVR();
  57209. }
  57210. renderer.setAnimationLoop(this.render);
  57211. sceneEl.renderStarted = true;
  57212. sceneEl.emit('renderstart');
  57213. }
  57214. });
  57215. // setTimeout to wait for all nodes to attach and run their callbacks.
  57216. setTimeout(function () {
  57217. AEntity.prototype.load.call(self);
  57218. });
  57219. }
  57220. },
  57221. /**
  57222. * Wrap `updateComponent` to not initialize the component if the component has a system
  57223. * (aframevr/aframe#2365).
  57224. */
  57225. updateComponent: {
  57226. value: function (componentName) {
  57227. if (componentName in systems) { return; }
  57228. AEntity.prototype.updateComponent.apply(this, arguments);
  57229. }
  57230. },
  57231. /**
  57232. * Behavior-updater meant to be called from scene render.
  57233. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  57234. * needing to render.
  57235. */
  57236. tick: {
  57237. value: function (time, timeDelta) {
  57238. var i;
  57239. var systems = this.systems;
  57240. // Components.
  57241. for (i = 0; i < this.behaviors.tick.length; i++) {
  57242. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  57243. this.behaviors.tick[i].tick(time, timeDelta);
  57244. }
  57245. // Systems.
  57246. for (i = 0; i < this.systemNames.length; i++) {
  57247. if (!systems[this.systemNames[i]].tick) { continue; }
  57248. systems[this.systemNames[i]].tick(time, timeDelta);
  57249. }
  57250. }
  57251. },
  57252. /**
  57253. * Behavior-updater meant to be called after scene render for post processing purposes.
  57254. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  57255. * needing to render.
  57256. */
  57257. tock: {
  57258. value: function (time, timeDelta, camera) {
  57259. var i;
  57260. var systems = this.systems;
  57261. // Components.
  57262. for (i = 0; i < this.behaviors.tock.length; i++) {
  57263. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  57264. this.behaviors.tock[i].tock(time, timeDelta, camera);
  57265. }
  57266. // Systems.
  57267. for (i = 0; i < this.systemNames.length; i++) {
  57268. if (!systems[this.systemNames[i]].tock) { continue; }
  57269. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  57270. }
  57271. }
  57272. },
  57273. /**
  57274. * The render loop.
  57275. *
  57276. * Updates animations.
  57277. * Updates behaviors.
  57278. * Renders with request animation frame.
  57279. */
  57280. render: {
  57281. value: function (time, frame) {
  57282. var renderer = this.renderer;
  57283. this.frame = frame;
  57284. this.delta = this.clock.getDelta() * 1000;
  57285. this.time = this.clock.elapsedTime * 1000;
  57286. if (this.isPlaying) { this.tick(this.time, this.delta); }
  57287. var savedBackground = null;
  57288. if (this.is('ar-mode')) {
  57289. // In AR mode, don't render the default background. Hide it, then
  57290. // restore it again after rendering.
  57291. savedBackground = this.object3D.background;
  57292. this.object3D.background = null;
  57293. }
  57294. renderer.render(this.object3D, this.camera);
  57295. if (savedBackground) {
  57296. this.object3D.background = savedBackground;
  57297. }
  57298. },
  57299. writable: true
  57300. }
  57301. })
  57302. });
  57303. /**
  57304. * Return the canvas size where the scene will be rendered.
  57305. * Will be always the window size except when the scene is embedded.
  57306. * The parent size (less than max size) will be returned in that case.
  57307. *
  57308. * @param {object} canvasEl - the canvas element
  57309. * @param {boolean} embedded - Is the scene embedded?
  57310. * @param {object} max - Max size parameters
  57311. * @param {boolean} isVR - If in VR
  57312. */
  57313. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  57314. if (!canvasEl.parentElement) { return {height: 0, width: 0}; }
  57315. if (embedded) {
  57316. return {
  57317. height: canvasEl.parentElement.offsetHeight,
  57318. width: canvasEl.parentElement.offsetWidth
  57319. };
  57320. }
  57321. return getMaxSize(maxSize, isVR);
  57322. }
  57323. /**
  57324. * Return the canvas size. Will be the window size unless that size is greater than the
  57325. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  57326. * maintaining aspect ratio
  57327. *
  57328. * @param {object} maxSize - Max size parameters (width and height).
  57329. * @param {boolean} isVR - If in VR.
  57330. * @returns {object} Width and height.
  57331. */
  57332. function getMaxSize (maxSize, isVR) {
  57333. var aspectRatio;
  57334. var size;
  57335. var pixelRatio = window.devicePixelRatio;
  57336. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  57337. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  57338. return size;
  57339. }
  57340. if (size.width * pixelRatio < maxSize.width &&
  57341. size.height * pixelRatio < maxSize.height) {
  57342. return size;
  57343. }
  57344. aspectRatio = size.width / size.height;
  57345. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  57346. size.width = Math.round(maxSize.width / pixelRatio);
  57347. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  57348. }
  57349. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  57350. size.height = Math.round(maxSize.height / pixelRatio);
  57351. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  57352. }
  57353. return size;
  57354. }
  57355. function requestFullscreen (canvas) {
  57356. var requestFullscreen =
  57357. canvas.requestFullscreen ||
  57358. canvas.webkitRequestFullscreen ||
  57359. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  57360. canvas.msRequestFullscreen;
  57361. // Hide navigation buttons on Android.
  57362. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  57363. }
  57364. function exitFullscreen () {
  57365. var fullscreenEl =
  57366. document.fullscreenElement ||
  57367. document.webkitFullscreenElement ||
  57368. document.mozFullScreenElement;
  57369. if (!fullscreenEl) { return; }
  57370. if (document.exitFullscreen) {
  57371. document.exitFullscreen();
  57372. } else if (document.mozCancelFullScreen) {
  57373. document.mozCancelFullScreen();
  57374. } else if (document.webkitExitFullscreen) {
  57375. document.webkitExitFullscreen();
  57376. }
  57377. }
  57378. function setupCanvas (sceneEl) {
  57379. var canvasEl;
  57380. canvasEl = document.createElement('canvas');
  57381. canvasEl.classList.add('a-canvas');
  57382. // Mark canvas as provided/injected by A-Frame.
  57383. canvasEl.dataset.aframeCanvas = true;
  57384. sceneEl.appendChild(canvasEl);
  57385. document.addEventListener('fullscreenchange', onFullScreenChange);
  57386. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  57387. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  57388. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  57389. // Prevent overscroll on mobile.
  57390. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  57391. // Set canvas on scene.
  57392. sceneEl.canvas = canvasEl;
  57393. sceneEl.emit('render-target-loaded', {target: canvasEl});
  57394. // For unknown reasons a synchronous resize does not work on desktop when
  57395. // entering/exiting fullscreen.
  57396. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  57397. function onFullScreenChange () {
  57398. var fullscreenEl =
  57399. document.fullscreenElement ||
  57400. document.mozFullScreenElement ||
  57401. document.webkitFullscreenElement;
  57402. // No fullscren element === exit fullscreen
  57403. if (!fullscreenEl) { sceneEl.exitVR(); }
  57404. document.activeElement.blur();
  57405. document.body.focus();
  57406. }
  57407. }
  57408. module.exports.setupCanvas = setupCanvas; // For testing.
  57409. },{"../../lib/three":178,"../../utils/":204,"../../utils/ios-orientationchange-blank-bug":205,"../a-entity":126,"../a-node":128,"../a-register-element":129,"../system":141,"./loadingScreen":134,"./metaTags":135,"./postMessage":136,"./scenes":137,"./wakelock":138}],134:[function(_dereq_,module,exports){
  57410. /* global THREE */
  57411. var utils = _dereq_('../../utils/');
  57412. var styleParser = utils.styleParser;
  57413. var sceneEl;
  57414. var titleEl;
  57415. var getSceneCanvasSize;
  57416. var ATTR_NAME = 'loading-screen';
  57417. var LOADER_TITLE_CLASS = 'a-loader-title';
  57418. module.exports.setup = function setup (el, getCanvasSize) {
  57419. sceneEl = el;
  57420. getSceneCanvasSize = getCanvasSize;
  57421. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  57422. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  57423. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  57424. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  57425. var loaderScene;
  57426. var sphereGeometry;
  57427. var sphereMaterial;
  57428. var sphereMesh1;
  57429. var sphereMesh2;
  57430. var sphereMesh3;
  57431. var camera;
  57432. var clock;
  57433. var time;
  57434. var render;
  57435. if (!loaderEnabled) { return; }
  57436. // Setup Scene.
  57437. loaderScene = new THREE.Scene();
  57438. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  57439. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  57440. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  57441. sphereMesh2 = sphereMesh1.clone();
  57442. sphereMesh3 = sphereMesh1.clone();
  57443. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  57444. clock = new THREE.Clock();
  57445. time = 0;
  57446. render = function () {
  57447. sceneEl.renderer.render(loaderScene, camera);
  57448. time = clock.getElapsedTime() % 4;
  57449. sphereMesh1.visible = time >= 1;
  57450. sphereMesh2.visible = time >= 2;
  57451. sphereMesh3.visible = time >= 3;
  57452. };
  57453. loaderScene.background = new THREE.Color(backgroundColor);
  57454. loaderScene.add(camera);
  57455. sphereMesh1.position.set(-1, 0, -15);
  57456. sphereMesh2.position.set(0, 0, -15);
  57457. sphereMesh3.position.set(1, 0, -15);
  57458. camera.add(sphereMesh1);
  57459. camera.add(sphereMesh2);
  57460. camera.add(sphereMesh3);
  57461. setupTitle();
  57462. // Delay 200ms to avoid loader flashes.
  57463. setTimeout(function () {
  57464. if (sceneEl.hasLoaded) { return; }
  57465. resize(camera);
  57466. titleEl.style.display = 'block';
  57467. window.addEventListener('resize', function () { resize(camera); });
  57468. sceneEl.renderer.setAnimationLoop(render);
  57469. }, 200);
  57470. };
  57471. module.exports.remove = function remove () {
  57472. window.removeEventListener('resize', resize);
  57473. if (!titleEl) { return; }
  57474. // Hide title.
  57475. titleEl.style.display = 'none';
  57476. };
  57477. function resize (camera) {
  57478. var embedded = sceneEl.hasAttribute('embedded');
  57479. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  57480. camera.aspect = size.width / size.height;
  57481. camera.updateProjectionMatrix();
  57482. // Notify renderer of size change.
  57483. sceneEl.renderer.setSize(size.width, size.height, false);
  57484. }
  57485. function setupTitle () {
  57486. titleEl = document.createElement('div');
  57487. titleEl.className = LOADER_TITLE_CLASS;
  57488. titleEl.innerHTML = document.title;
  57489. titleEl.style.display = 'none';
  57490. sceneEl.appendChild(titleEl);
  57491. }
  57492. },{"../../utils/":204}],135:[function(_dereq_,module,exports){
  57493. var constants = _dereq_('../../constants/');
  57494. var extend = _dereq_('../../utils').extend;
  57495. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  57496. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui,viewport-fit=cover'}),
  57497. // W3C-standardised meta tags.
  57498. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  57499. Meta({name: 'theme-color', content: 'black'})
  57500. ];
  57501. var MOBILE_IOS_HEAD_TAGS = [
  57502. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  57503. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  57504. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  57505. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  57506. ];
  57507. function Meta (attrs) {
  57508. return {
  57509. tagName: 'meta',
  57510. attributes: attrs,
  57511. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  57512. };
  57513. }
  57514. function Link (attrs) {
  57515. return {
  57516. tagName: 'link',
  57517. attributes: attrs,
  57518. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  57519. };
  57520. }
  57521. /**
  57522. * Injects the necessary metatags in the document for mobile support:
  57523. * 1. Prevent the user to zoom in the document.
  57524. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  57525. * values and the canvas is properly scaled.
  57526. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  57527. * iOS.
  57528. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  57529. *
  57530. * @param {object} scene - Scene element
  57531. * @returns {Array}
  57532. */
  57533. module.exports.inject = function injectHeadTags (scene) {
  57534. var headEl = document.head;
  57535. var headScriptEl = headEl.querySelector('script');
  57536. var tag;
  57537. var headTags = [];
  57538. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  57539. if (scene.isIOS) {
  57540. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  57541. }
  57542. return headTags;
  57543. function createAndInjectTag (tagObj) {
  57544. if (!tagObj || tagObj.exists()) { return; }
  57545. tag = createTag(tagObj);
  57546. if (!tag) { return; }
  57547. if (headScriptEl) {
  57548. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  57549. } else {
  57550. headEl.appendChild(tag);
  57551. }
  57552. headTags.push(tag);
  57553. }
  57554. };
  57555. function createTag (tagObj) {
  57556. if (!tagObj || !tagObj.tagName) { return; }
  57557. var meta = document.createElement(tagObj.tagName);
  57558. meta.setAttribute(constants.AFRAME_INJECTED, '');
  57559. return extend(meta, tagObj.attributes);
  57560. }
  57561. },{"../../constants/":122,"../../utils":204}],136:[function(_dereq_,module,exports){
  57562. var bind = _dereq_('../../utils/bind');
  57563. var isIframed = _dereq_('../../utils/').isIframed;
  57564. /**
  57565. * Provides a post message API for scenes contained
  57566. * in an iframe.
  57567. */
  57568. module.exports = function initPostMessageAPI (scene) {
  57569. // Handles fullscreen behavior when inside an iframe.
  57570. if (!isIframed()) { return; }
  57571. // postMessage API handler
  57572. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  57573. };
  57574. function postMessageAPIHandler (event) {
  57575. var scene = this;
  57576. if (!event.data) { return; }
  57577. switch (event.data.type) {
  57578. case 'vr': {
  57579. switch (event.data.data) {
  57580. case 'enter':
  57581. scene.enterVR();
  57582. break;
  57583. case 'exit':
  57584. scene.exitVR();
  57585. break;
  57586. }
  57587. }
  57588. }
  57589. }
  57590. },{"../../utils/":204,"../../utils/bind":198}],137:[function(_dereq_,module,exports){
  57591. /*
  57592. Scene index for keeping track of created scenes.
  57593. */
  57594. module.exports = [];
  57595. },{}],138:[function(_dereq_,module,exports){
  57596. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  57597. module.exports = function initWakelock (scene) {
  57598. if (!scene.isMobile) { return; }
  57599. var wakelock = scene.wakelock = new Wakelock();
  57600. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  57601. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  57602. };
  57603. },{"../../../vendor/wakelock/wakelock":219}],139:[function(_dereq_,module,exports){
  57604. var utils = _dereq_('../utils/');
  57605. var PropertyTypes = _dereq_('./propertyTypes');
  57606. var debug = utils.debug;
  57607. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  57608. var propertyTypes = PropertyTypes.propertyTypes;
  57609. var warn = debug('core:schema:warn');
  57610. /**
  57611. * A schema is classified as a schema for a single property if:
  57612. * - `type` is defined on the schema as a string.
  57613. * - OR `default` is defined on the schema, as a reserved keyword.
  57614. * - OR schema is empty.
  57615. */
  57616. function isSingleProperty (schema) {
  57617. if ('type' in schema) {
  57618. return typeof schema.type === 'string';
  57619. }
  57620. return 'default' in schema;
  57621. }
  57622. module.exports.isSingleProperty = isSingleProperty;
  57623. /**
  57624. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  57625. *
  57626. * @param {object} schema
  57627. * @param {string} componentName
  57628. * @returns {object} Schema.
  57629. */
  57630. module.exports.process = function (schema, componentName) {
  57631. var propName;
  57632. // For single property schema, run processPropDefinition over the whole schema.
  57633. if (isSingleProperty(schema)) {
  57634. return processPropertyDefinition(schema, componentName);
  57635. }
  57636. // For multi-property schema, run processPropDefinition over each property definition.
  57637. for (propName in schema) {
  57638. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  57639. }
  57640. return schema;
  57641. };
  57642. /**
  57643. * Inject default value, parser, stringifier for single property.
  57644. *
  57645. * @param {object} propDefinition
  57646. * @param {string} componentName
  57647. */
  57648. function processPropertyDefinition (propDefinition, componentName) {
  57649. var defaultVal = propDefinition.default;
  57650. var isCustomType;
  57651. var propType;
  57652. var typeName = propDefinition.type;
  57653. // Type inference.
  57654. if (!propDefinition.type) {
  57655. if (defaultVal !== undefined &&
  57656. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  57657. // Type inference.
  57658. typeName = typeof defaultVal;
  57659. } else if (Array.isArray(defaultVal)) {
  57660. typeName = 'array';
  57661. } else {
  57662. // Fall back to string.
  57663. typeName = 'string';
  57664. }
  57665. } else if (propDefinition.type === 'bool') {
  57666. typeName = 'boolean';
  57667. } else if (propDefinition.type === 'float') {
  57668. typeName = 'number';
  57669. }
  57670. propType = propertyTypes[typeName];
  57671. if (!propType) {
  57672. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  57673. }
  57674. // Fill in parse and stringify using property types.
  57675. isCustomType = !!propDefinition.parse;
  57676. propDefinition.parse = propDefinition.parse || propType.parse;
  57677. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  57678. // Fill in type name.
  57679. propDefinition.type = typeName;
  57680. // Check that default value exists.
  57681. if ('default' in propDefinition) {
  57682. // Check that default values are valid.
  57683. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  57684. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  57685. '` in component `' + componentName + '`');
  57686. }
  57687. } else {
  57688. // Fill in default value.
  57689. propDefinition.default = propType.default;
  57690. }
  57691. return propDefinition;
  57692. }
  57693. module.exports.processPropertyDefinition = processPropertyDefinition;
  57694. /**
  57695. * Parse propData using schema. Use default values if not existing in propData.
  57696. *
  57697. * @param {object} propData - Unparsed properties.
  57698. * @param {object} schema - Property types definition.
  57699. * @param {boolean} getPartialData - Whether to return full component data or just the data
  57700. * with keys in `propData`.
  57701. * @param {string } componentName - Name of the component, used for the property warning.
  57702. * @param {boolean} silent - Suppress warning messages.
  57703. */
  57704. module.exports.parseProperties = (function () {
  57705. var propNames = [];
  57706. return function (propData, schema, getPartialData, componentName, silent) {
  57707. var i;
  57708. var propName;
  57709. var propDefinition;
  57710. var propValue;
  57711. propNames.length = 0;
  57712. for (propName in (getPartialData ? propData : schema)) {
  57713. if (getPartialData && propData[propName] === undefined) { continue; }
  57714. propNames.push(propName);
  57715. }
  57716. if (propData === null || typeof propData !== 'object') { return propData; }
  57717. // Validation errors.
  57718. for (propName in propData) {
  57719. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  57720. warn('Unknown property `' + propName +
  57721. '` for component/system `' + componentName + '`.');
  57722. }
  57723. }
  57724. for (i = 0; i < propNames.length; i++) {
  57725. propName = propNames[i];
  57726. propDefinition = schema[propName];
  57727. propValue = propData[propName];
  57728. if (!(schema[propName])) { return; }
  57729. propData[propName] = parseProperty(propValue, propDefinition);
  57730. }
  57731. return propData;
  57732. };
  57733. })();
  57734. /**
  57735. * Deserialize a single property.
  57736. */
  57737. function parseProperty (value, propDefinition) {
  57738. // Use default value if value is falsy.
  57739. if (value === undefined || value === null || value === '') {
  57740. value = propDefinition.default;
  57741. if (Array.isArray(value)) { value = value.slice(); }
  57742. }
  57743. // Invoke property type parser.
  57744. return propDefinition.parse(value, propDefinition.default);
  57745. }
  57746. module.exports.parseProperty = parseProperty;
  57747. /**
  57748. * Serialize a group of properties.
  57749. */
  57750. module.exports.stringifyProperties = function (propData, schema) {
  57751. var propName;
  57752. var propDefinition;
  57753. var propValue;
  57754. var stringifiedData = {};
  57755. var value;
  57756. for (propName in propData) {
  57757. propDefinition = schema[propName];
  57758. propValue = propData[propName];
  57759. value = propValue;
  57760. if (typeof value === 'object') {
  57761. value = stringifyProperty(propValue, propDefinition);
  57762. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  57763. }
  57764. stringifiedData[propName] = value;
  57765. }
  57766. return stringifiedData;
  57767. };
  57768. /**
  57769. * Serialize a single property.
  57770. */
  57771. function stringifyProperty (value, propDefinition) {
  57772. // This function stringifies but it's used in a context where
  57773. // there's always second stringification pass. By returning the original
  57774. // value when it's not an object we save one unnecessary call
  57775. // to JSON.stringify.
  57776. if (typeof value !== 'object') { return value; }
  57777. // if there's no schema for the property we use standar JSON stringify
  57778. if (!propDefinition || value === null) { return JSON.stringify(value); }
  57779. return propDefinition.stringify(value);
  57780. }
  57781. module.exports.stringifyProperty = stringifyProperty;
  57782. },{"../utils/":204,"./propertyTypes":132}],140:[function(_dereq_,module,exports){
  57783. var schema = _dereq_('./schema');
  57784. var processSchema = schema.process;
  57785. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  57786. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  57787. var THREE = _dereq_('../lib/three');
  57788. var utils = _dereq_('../utils');
  57789. // A-Frame properties to three.js uniform types.
  57790. var propertyToThreeMapping = {
  57791. array: 'v3',
  57792. color: 'v3',
  57793. int: 'i',
  57794. number: 'f',
  57795. map: 't',
  57796. time: 'f',
  57797. vec2: 'v2',
  57798. vec3: 'v3',
  57799. vec4: 'v4'
  57800. };
  57801. /**
  57802. * Shader class definition.
  57803. *
  57804. * Shaders extend the material component API so you can create your own library
  57805. * of customized materials
  57806. *
  57807. */
  57808. var Shader = module.exports.Shader = function () {};
  57809. Shader.prototype = {
  57810. /**
  57811. * Contains the type schema and defaults for the data values.
  57812. * Data is coerced into the types of the values of the defaults.
  57813. */
  57814. schema: {},
  57815. vertexShader:
  57816. 'void main() {' +
  57817. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  57818. '}',
  57819. fragmentShader:
  57820. 'void main() {' +
  57821. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  57822. '}',
  57823. /**
  57824. * Init handler. Similar to attachedCallback.
  57825. * Called during shader initialization and is only run once.
  57826. */
  57827. init: function (data) {
  57828. this.attributes = this.initVariables(data, 'attribute');
  57829. this.uniforms = this.initVariables(data, 'uniform');
  57830. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  57831. // attributes: this.attributes,
  57832. uniforms: this.uniforms,
  57833. vertexShader: this.vertexShader,
  57834. fragmentShader: this.fragmentShader
  57835. });
  57836. return this.material;
  57837. },
  57838. initVariables: function (data, type) {
  57839. var key;
  57840. var schema = this.schema;
  57841. var variables = {};
  57842. var varType;
  57843. for (key in schema) {
  57844. if (schema[key].is !== type) { continue; }
  57845. varType = propertyToThreeMapping[schema[key].type];
  57846. variables[key] = {
  57847. type: varType,
  57848. value: undefined // Let updateVariables handle setting these.
  57849. };
  57850. }
  57851. return variables;
  57852. },
  57853. /**
  57854. * Update handler. Similar to attributeChangedCallback.
  57855. * Called whenever the associated material data changes.
  57856. *
  57857. * @param {object} data - New material data.
  57858. */
  57859. update: function (data) {
  57860. this.updateVariables(data, 'attribute');
  57861. this.updateVariables(data, 'uniform');
  57862. },
  57863. updateVariables: function (data, type) {
  57864. var key;
  57865. var materialKey;
  57866. var schema = this.schema;
  57867. var variables;
  57868. variables = type === 'uniform' ? this.uniforms : this.attributes;
  57869. for (key in data) {
  57870. if (!schema[key] || schema[key].is !== type) { continue; }
  57871. if (schema[key].type === 'map') {
  57872. // If data unchanged, get out early.
  57873. if (!variables[key] || variables[key].value === data[key]) { continue; }
  57874. // Special handling is needed for textures.
  57875. materialKey = '_texture_' + key;
  57876. // We can't actually set the variable correctly until we've loaded the texture.
  57877. this.setMapOnTextureLoad(variables, key, materialKey);
  57878. // Kick off the texture update now that handler is added.
  57879. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  57880. continue;
  57881. }
  57882. variables[key].value = this.parseValue(schema[key].type, data[key]);
  57883. variables[key].needsUpdate = true;
  57884. }
  57885. },
  57886. parseValue: function (type, value) {
  57887. var color;
  57888. switch (type) {
  57889. case 'vec2': {
  57890. return new THREE.Vector2(value.x, value.y);
  57891. }
  57892. case 'vec3': {
  57893. return new THREE.Vector3(value.x, value.y, value.z);
  57894. }
  57895. case 'vec4': {
  57896. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  57897. }
  57898. case 'color': {
  57899. color = new THREE.Color(value);
  57900. return new THREE.Vector3(color.r, color.g, color.b);
  57901. }
  57902. case 'map': {
  57903. return THREE.ImageUtils.loadTexture(value);
  57904. }
  57905. default: {
  57906. return value;
  57907. }
  57908. }
  57909. },
  57910. setMapOnTextureLoad: function (variables, key, materialKey) {
  57911. var self = this;
  57912. this.el.addEventListener('materialtextureloaded', function () {
  57913. variables[key].value = self.material[materialKey];
  57914. variables[key].needsUpdate = true;
  57915. });
  57916. }
  57917. };
  57918. /**
  57919. * Registers a shader to A-Frame.
  57920. *
  57921. * @param {string} name - shader name.
  57922. * @param {object} definition - shader property and methods.
  57923. * @returns {object} Shader.
  57924. */
  57925. module.exports.registerShader = function (name, definition) {
  57926. var NewShader;
  57927. var proto = {};
  57928. // Format definition object to prototype object.
  57929. Object.keys(definition).forEach(function (key) {
  57930. proto[key] = {
  57931. value: definition[key],
  57932. writable: true
  57933. };
  57934. });
  57935. if (shaders[name]) {
  57936. throw new Error('The shader ' + name + ' has been already registered');
  57937. }
  57938. NewShader = function () { Shader.call(this); };
  57939. NewShader.prototype = Object.create(Shader.prototype, proto);
  57940. NewShader.prototype.name = name;
  57941. NewShader.prototype.constructor = NewShader;
  57942. shaders[name] = {
  57943. Shader: NewShader,
  57944. schema: processSchema(NewShader.prototype.schema)
  57945. };
  57946. shaderNames.push(name);
  57947. return NewShader;
  57948. };
  57949. },{"../lib/three":178,"../utils":204,"./schema":139}],141:[function(_dereq_,module,exports){
  57950. var components = _dereq_('./component');
  57951. var schema = _dereq_('./schema');
  57952. var utils = _dereq_('../utils/');
  57953. var parseProperties = schema.parseProperties;
  57954. var parseProperty = schema.parseProperty;
  57955. var processSchema = schema.process;
  57956. var isSingleProp = schema.isSingleProperty;
  57957. var styleParser = utils.styleParser;
  57958. var systems = module.exports.systems = {}; // Keep track of registered systems.
  57959. /**
  57960. * System class definition.
  57961. *
  57962. * Systems provide global scope and services to a group of instantiated components of the
  57963. * same class. They can also help abstract logic away from components such that components
  57964. * only have to worry about data.
  57965. *
  57966. * For example, a physics component that creates a physics world that oversees
  57967. * all entities with a physics or rigid body component.
  57968. *
  57969. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  57970. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  57971. * setAttribute behavior).
  57972. *
  57973. * @member {string} name - Name that system is registered under.
  57974. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  57975. */
  57976. var System = module.exports.System = function (sceneEl) {
  57977. var component = components && components.components[this.name];
  57978. // Set reference to scene.
  57979. this.el = sceneEl;
  57980. this.sceneEl = sceneEl;
  57981. // Set reference to matching component (if exists).
  57982. if (component) { component.Component.prototype.system = this; }
  57983. // Process system configuration.
  57984. this.buildData();
  57985. this.init();
  57986. this.update({});
  57987. };
  57988. System.prototype = {
  57989. /**
  57990. * Schema to configure system.
  57991. */
  57992. schema: {},
  57993. /**
  57994. * Init handler. Called during scene initialization and is only run once.
  57995. * Systems can use this to set initial state.
  57996. */
  57997. init: function () { /* no-op */ },
  57998. /**
  57999. * Update handler. Called during scene attribute updates.
  58000. * Systems can use this to dynamically update their state.
  58001. */
  58002. update: function (oldData) { /* no-op */ },
  58003. /**
  58004. * Build data and call update handler.
  58005. *
  58006. * @private
  58007. */
  58008. updateProperties: function (rawData) {
  58009. var oldData = this.data;
  58010. if (!Object.keys(schema).length) { return; }
  58011. this.buildData(rawData);
  58012. this.update(oldData);
  58013. },
  58014. /**
  58015. * Parse data.
  58016. */
  58017. buildData: function (rawData) {
  58018. var schema = this.schema;
  58019. if (!Object.keys(schema).length) { return; }
  58020. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  58021. if (isSingleProp(schema)) {
  58022. this.data = parseProperty(rawData, schema);
  58023. } else {
  58024. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  58025. }
  58026. },
  58027. /**
  58028. * Tick handler.
  58029. * Called on each tick of the scene render loop.
  58030. * Affected by play and pause.
  58031. *
  58032. * @param {number} time - Scene tick time.
  58033. * @param {number} timeDelta - Difference in current render time and previous render time.
  58034. */
  58035. tick: undefined,
  58036. /**
  58037. * Tock handler.
  58038. * Called on each tock of the scene render loop.
  58039. * Affected by play and pause.
  58040. *
  58041. * @param {number} time - Scene tick time.
  58042. * @param {number} timeDelta - Difference in current render time and previous render time.
  58043. */
  58044. tock: undefined,
  58045. /**
  58046. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  58047. */
  58048. play: function () { /* no-op */ },
  58049. /**
  58050. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  58051. */
  58052. pause: function () { /* no-op */ }
  58053. };
  58054. /**
  58055. * Registers a system to A-Frame.
  58056. *
  58057. * @param {string} name - Component name.
  58058. * @param {object} definition - Component property and methods.
  58059. * @returns {object} Component.
  58060. */
  58061. module.exports.registerSystem = function (name, definition) {
  58062. var i;
  58063. var NewSystem;
  58064. var proto = {};
  58065. var scenes = utils.findAllScenes(document);
  58066. // Format definition object to prototype object.
  58067. Object.keys(definition).forEach(function (key) {
  58068. proto[key] = {
  58069. value: definition[key],
  58070. writable: true
  58071. };
  58072. });
  58073. if (systems[name]) {
  58074. throw new Error('The system `' + name + '` has been already registered. ' +
  58075. 'Check that you are not loading two versions of the same system ' +
  58076. 'or two different systems of the same name.');
  58077. }
  58078. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  58079. NewSystem.prototype = Object.create(System.prototype, proto);
  58080. NewSystem.prototype.name = name;
  58081. NewSystem.prototype.constructor = NewSystem;
  58082. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  58083. systems[name] = NewSystem;
  58084. // Initialize systems for existing scenes
  58085. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  58086. };
  58087. },{"../utils/":204,"./component":130,"./schema":139}],142:[function(_dereq_,module,exports){
  58088. _dereq_('./pivot');
  58089. },{"./pivot":143}],143:[function(_dereq_,module,exports){
  58090. var registerComponent = _dereq_('../../core/component').registerComponent;
  58091. var THREE = _dereq_('../../lib/three');
  58092. var originalPosition = new THREE.Vector3();
  58093. var originalRotation = new THREE.Vector3();
  58094. /**
  58095. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  58096. */
  58097. registerComponent('pivot', {
  58098. dependencies: ['position'],
  58099. schema: {type: 'vec3'},
  58100. init: function () {
  58101. var data = this.data;
  58102. var el = this.el;
  58103. var originalParent = el.object3D.parent;
  58104. var originalGroup = el.object3D;
  58105. var outerGroup = new THREE.Group();
  58106. originalPosition.copy(originalGroup.position);
  58107. originalRotation.copy(originalGroup.rotation);
  58108. // Detach current group from parent.
  58109. originalParent.remove(originalGroup);
  58110. outerGroup.add(originalGroup);
  58111. // Set new group as the outer group.
  58112. originalParent.add(outerGroup);
  58113. // Set outer group as new object3D.
  58114. el.object3D = outerGroup;
  58115. // Apply pivot to original group.
  58116. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  58117. // Offset the pivot so that world position not affected.
  58118. // And restore position onto outer group.
  58119. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  58120. data.z + originalPosition.z);
  58121. // Transfer rotation to outer group.
  58122. outerGroup.rotation.copy(originalGroup.rotation);
  58123. originalGroup.rotation.set(0, 0, 0);
  58124. }
  58125. });
  58126. },{"../../core/component":130,"../../lib/three":178}],144:[function(_dereq_,module,exports){
  58127. /**
  58128. * Common mesh defaults, mappings, and transforms.
  58129. */
  58130. var components = _dereq_('../../core/component').components;
  58131. var shaders = _dereq_('../../core/shader').shaders;
  58132. var utils = _dereq_('../../utils/');
  58133. var materialMappings = {};
  58134. Object.keys(components.material.schema).forEach(addMapping);
  58135. Object.keys(shaders.standard.schema).forEach(addMapping);
  58136. function addMapping (prop) {
  58137. // To hyphenated.
  58138. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58139. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  58140. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  58141. materialMappings[htmlAttrName] = 'material.' + prop;
  58142. }
  58143. module.exports = function getMeshMixin () {
  58144. return {
  58145. defaultComponents: {material: {}},
  58146. mappings: utils.extend({}, materialMappings)
  58147. };
  58148. };
  58149. },{"../../core/component":130,"../../core/shader":140,"../../utils/":204}],145:[function(_dereq_,module,exports){
  58150. _dereq_('./primitives/a-camera');
  58151. _dereq_('./primitives/a-cursor');
  58152. _dereq_('./primitives/a-curvedimage');
  58153. _dereq_('./primitives/a-gltf-model');
  58154. _dereq_('./primitives/a-image');
  58155. _dereq_('./primitives/a-light');
  58156. _dereq_('./primitives/a-link');
  58157. _dereq_('./primitives/a-obj-model');
  58158. _dereq_('./primitives/a-sky');
  58159. _dereq_('./primitives/a-sound');
  58160. _dereq_('./primitives/a-text');
  58161. _dereq_('./primitives/a-video');
  58162. _dereq_('./primitives/a-videosphere');
  58163. _dereq_('./primitives/meshPrimitives');
  58164. },{"./primitives/a-camera":147,"./primitives/a-cursor":148,"./primitives/a-curvedimage":149,"./primitives/a-gltf-model":150,"./primitives/a-image":151,"./primitives/a-light":152,"./primitives/a-link":153,"./primitives/a-obj-model":154,"./primitives/a-sky":155,"./primitives/a-sound":156,"./primitives/a-text":157,"./primitives/a-video":158,"./primitives/a-videosphere":159,"./primitives/meshPrimitives":160}],146:[function(_dereq_,module,exports){
  58165. var AEntity = _dereq_('../../core/a-entity');
  58166. var components = _dereq_('../../core/component').components;
  58167. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  58168. var utils = _dereq_('../../utils/');
  58169. var debug = utils.debug;
  58170. var setComponentProperty = utils.entity.setComponentProperty;
  58171. var log = debug('extras:primitives:debug');
  58172. var warn = debug('extras:primitives:warn');
  58173. var primitives = module.exports.primitives = {};
  58174. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  58175. name = name.toLowerCase();
  58176. log('Registering <%s>', name);
  58177. // Deprecation warning for defaultAttributes usage.
  58178. if (definition.defaultAttributes) {
  58179. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  58180. }
  58181. var primitive = registerElement(name, {
  58182. prototype: Object.create(AEntity.prototype, {
  58183. defaultComponentsFromPrimitive: {
  58184. value: definition.defaultComponents || definition.defaultAttributes || {}
  58185. },
  58186. deprecated: {value: definition.deprecated || null},
  58187. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  58188. mappings: {value: definition.mappings || {}},
  58189. createdCallback: {
  58190. value: function () {
  58191. if (definition.deprecated) { console.warn(definition.deprecated); }
  58192. this.resolveMappingCollisions();
  58193. }
  58194. },
  58195. /**
  58196. * If a mapping collides with a registered component name
  58197. * it renames the mapping to componentname-property
  58198. */
  58199. resolveMappingCollisions: {
  58200. value: function () {
  58201. var mappings = this.mappings;
  58202. var self = this;
  58203. Object.keys(mappings).forEach(function resolveCollision (key) {
  58204. var newAttribute;
  58205. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  58206. if (components[key]) {
  58207. newAttribute = mappings[key].replace('.', '-');
  58208. mappings[newAttribute] = mappings[key];
  58209. delete mappings[key];
  58210. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  58211. 'The attribute ' + key + ' has the same name as a registered component and' +
  58212. ' has been renamed to ' + newAttribute);
  58213. }
  58214. });
  58215. }
  58216. },
  58217. getExtraComponents: {
  58218. value: function () {
  58219. var attr;
  58220. var data;
  58221. var i;
  58222. var mapping;
  58223. var mixins;
  58224. var path;
  58225. var self = this;
  58226. // Gather component data from default components.
  58227. data = utils.clone(this.defaultComponentsFromPrimitive);
  58228. // Factor in mixins to overwrite default components.
  58229. mixins = this.getAttribute('mixin');
  58230. if (mixins) {
  58231. mixins = mixins.trim().split(' ');
  58232. mixins.forEach(function applyMixin (mixinId) {
  58233. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  58234. Object.keys(mixinComponents).forEach(function setComponent (name) {
  58235. data[name] = extend(data[name], mixinComponents[name]);
  58236. });
  58237. });
  58238. }
  58239. // Gather component data from mappings.
  58240. for (i = 0; i < this.attributes.length; i++) {
  58241. attr = this.attributes[i];
  58242. mapping = this.mappings[attr.name];
  58243. if (mapping) {
  58244. path = utils.entity.getComponentPropertyPath(mapping);
  58245. if (path.constructor === Array) {
  58246. data[path[0]] = data[path[0]] || {};
  58247. data[path[0]][path[1]] = attr.value.trim();
  58248. } else {
  58249. data[path] = attr.value.trim();
  58250. }
  58251. continue;
  58252. }
  58253. }
  58254. return data;
  58255. /**
  58256. * For the base to be extensible, both objects must be pure JavaScript objects.
  58257. * The function assumes that base is undefined, or null or a pure object.
  58258. */
  58259. function extend (base, extension) {
  58260. if (isUndefined(base)) {
  58261. return copy(extension);
  58262. }
  58263. if (isUndefined(extension)) {
  58264. return copy(base);
  58265. }
  58266. if (isPureObject(base) && isPureObject(extension)) {
  58267. return utils.extendDeep(base, extension);
  58268. }
  58269. return copy(extension);
  58270. }
  58271. function isUndefined (value) {
  58272. return typeof value === 'undefined';
  58273. }
  58274. function copy (value) {
  58275. if (isPureObject(value)) {
  58276. return utils.extendDeep({}, value);
  58277. }
  58278. return value;
  58279. }
  58280. function isPureObject (value) {
  58281. return value !== null && value.constructor === Object;
  58282. }
  58283. }
  58284. },
  58285. /**
  58286. * Sync to attribute to component property whenever mapped attribute changes.
  58287. * If attribute is mapped to a component property, set the component property using
  58288. * the attribute value.
  58289. */
  58290. attributeChangedCallback: {
  58291. value: function (attr, oldVal, value) {
  58292. var componentName = this.mappings[attr];
  58293. if (attr in this.deprecatedMappings) {
  58294. console.warn(this.deprecatedMappings[attr]);
  58295. }
  58296. if (!attr || !componentName) { return; }
  58297. // Set value.
  58298. setComponentProperty(this, componentName, value);
  58299. }
  58300. }
  58301. })
  58302. });
  58303. // Store.
  58304. primitives[name] = primitive;
  58305. return primitive;
  58306. };
  58307. /**
  58308. * Add component mappings using schema.
  58309. */
  58310. function addComponentMapping (componentName, mappings) {
  58311. var schema = components[componentName].schema;
  58312. Object.keys(schema).map(function (prop) {
  58313. // Hyphenate where there is camelCase.
  58314. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58315. // If there is a mapping collision, prefix with component name and hyphen.
  58316. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  58317. mappings[attrName] = componentName + '.' + prop;
  58318. });
  58319. }
  58320. /**
  58321. * Helper to define a primitive, building mappings using a component schema.
  58322. */
  58323. function definePrimitive (tagName, defaultComponents, mappings) {
  58324. // If no initial mappings provided, start from empty map.
  58325. mappings = mappings || {};
  58326. // From the default components, add mapping automagically.
  58327. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  58328. addComponentMapping(componentName, mappings);
  58329. });
  58330. // Register the primitive.
  58331. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  58332. defaultComponents: defaultComponents,
  58333. mappings: mappings
  58334. }));
  58335. }
  58336. module.exports.definePrimitive = definePrimitive;
  58337. },{"../../core/a-entity":126,"../../core/a-register-element":129,"../../core/component":130,"../../utils/":204}],147:[function(_dereq_,module,exports){
  58338. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58339. registerPrimitive('a-camera', {
  58340. defaultComponents: {
  58341. 'camera': {},
  58342. 'look-controls': {},
  58343. 'wasd-controls': {},
  58344. 'position': {x: 0, y: 1.6, z: 0}
  58345. },
  58346. mappings: {
  58347. active: 'camera.active',
  58348. far: 'camera.far',
  58349. fov: 'camera.fov',
  58350. 'look-controls-enabled': 'look-controls.enabled',
  58351. near: 'camera.near',
  58352. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  58353. 'wasd-controls-enabled': 'wasd-controls.enabled',
  58354. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  58355. zoom: 'camera.zoom'
  58356. }
  58357. });
  58358. },{"../primitives":146}],148:[function(_dereq_,module,exports){
  58359. var getMeshMixin = _dereq_('../getMeshMixin');
  58360. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58361. var utils = _dereq_('../../../utils/');
  58362. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  58363. defaultComponents: {
  58364. cursor: {},
  58365. geometry: {
  58366. primitive: 'ring',
  58367. radiusOuter: 0.016,
  58368. radiusInner: 0.01,
  58369. segmentsTheta: 32
  58370. },
  58371. material: {
  58372. color: '#000',
  58373. shader: 'flat',
  58374. opacity: 0.8
  58375. },
  58376. position: {
  58377. x: 0,
  58378. y: 0,
  58379. z: -1
  58380. }
  58381. },
  58382. mappings: {
  58383. far: 'raycaster.far',
  58384. fuse: 'cursor.fuse',
  58385. 'fuse-timeout': 'cursor.fuseTimeout',
  58386. interval: 'raycaster.interval',
  58387. objects: 'raycaster.objects'
  58388. }
  58389. }));
  58390. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],149:[function(_dereq_,module,exports){
  58391. var getMeshMixin = _dereq_('../getMeshMixin');
  58392. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58393. var utils = _dereq_('../../../utils/');
  58394. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  58395. defaultComponents: {
  58396. geometry: {
  58397. height: 1,
  58398. primitive: 'cylinder',
  58399. radius: 2,
  58400. segmentsRadial: 48,
  58401. thetaLength: 270,
  58402. openEnded: true,
  58403. thetaStart: 0
  58404. },
  58405. material: {
  58406. color: '#FFF',
  58407. shader: 'flat',
  58408. side: 'double',
  58409. transparent: true,
  58410. repeat: '-1 1'
  58411. }
  58412. },
  58413. mappings: {
  58414. height: 'geometry.height',
  58415. 'open-ended': 'geometry.openEnded',
  58416. radius: 'geometry.radius',
  58417. segments: 'geometry.segmentsRadial',
  58418. start: 'geometry.thetaStart',
  58419. 'theta-length': 'geometry.thetaLength',
  58420. 'theta-start': 'geometry.thetaStart',
  58421. 'width': 'geometry.thetaLength'
  58422. }
  58423. }));
  58424. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],150:[function(_dereq_,module,exports){
  58425. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58426. registerPrimitive('a-gltf-model', {
  58427. mappings: {
  58428. src: 'gltf-model'
  58429. }
  58430. });
  58431. },{"../primitives":146}],151:[function(_dereq_,module,exports){
  58432. var getMeshMixin = _dereq_('../getMeshMixin');
  58433. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58434. var utils = _dereq_('../../../utils/');
  58435. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  58436. defaultComponents: {
  58437. geometry: {
  58438. primitive: 'plane'
  58439. },
  58440. material: {
  58441. color: '#FFF',
  58442. shader: 'flat',
  58443. side: 'double',
  58444. transparent: true
  58445. }
  58446. },
  58447. mappings: {
  58448. height: 'geometry.height',
  58449. width: 'geometry.width'
  58450. }
  58451. }));
  58452. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],152:[function(_dereq_,module,exports){
  58453. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58454. registerPrimitive('a-light', {
  58455. defaultComponents: {
  58456. light: {}
  58457. },
  58458. mappings: {
  58459. angle: 'light.angle',
  58460. color: 'light.color',
  58461. 'ground-color': 'light.groundColor',
  58462. decay: 'light.decay',
  58463. distance: 'light.distance',
  58464. intensity: 'light.intensity',
  58465. penumbra: 'light.penumbra',
  58466. type: 'light.type',
  58467. target: 'light.target'
  58468. }
  58469. });
  58470. },{"../primitives":146}],153:[function(_dereq_,module,exports){
  58471. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58472. registerPrimitive('a-link', {
  58473. defaultComponents: {
  58474. link: {
  58475. visualAspectEnabled: true
  58476. }
  58477. },
  58478. mappings: {
  58479. href: 'link.href',
  58480. image: 'link.image',
  58481. title: 'link.title'
  58482. }
  58483. });
  58484. },{"../primitives":146}],154:[function(_dereq_,module,exports){
  58485. var meshMixin = _dereq_('../getMeshMixin')();
  58486. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58487. var utils = _dereq_('../../../utils/');
  58488. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  58489. defaultComponents: {
  58490. 'obj-model': {}
  58491. },
  58492. mappings: {
  58493. src: 'obj-model.obj',
  58494. mtl: 'obj-model.mtl'
  58495. }
  58496. }));
  58497. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],155:[function(_dereq_,module,exports){
  58498. var getMeshMixin = _dereq_('../getMeshMixin');
  58499. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58500. var utils = _dereq_('../../../utils/');
  58501. var meshPrimitives = _dereq_('./meshPrimitives');
  58502. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  58503. defaultComponents: {
  58504. geometry: {
  58505. primitive: 'sphere',
  58506. radius: 500,
  58507. segmentsWidth: 64,
  58508. segmentsHeight: 32
  58509. },
  58510. material: {
  58511. color: '#FFF',
  58512. side: 'back',
  58513. shader: 'flat',
  58514. npot: true
  58515. },
  58516. scale: '-1 1 1'
  58517. },
  58518. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  58519. }));
  58520. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146,"./meshPrimitives":160}],156:[function(_dereq_,module,exports){
  58521. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58522. registerPrimitive('a-sound', {
  58523. defaultComponents: {
  58524. sound: {}
  58525. },
  58526. mappings: {
  58527. src: 'sound.src',
  58528. on: 'sound.on',
  58529. autoplay: 'sound.autoplay',
  58530. loop: 'sound.loop',
  58531. volume: 'sound.volume'
  58532. }
  58533. });
  58534. },{"../primitives":146}],157:[function(_dereq_,module,exports){
  58535. // <a-text> using `definePrimitive` helper.
  58536. var definePrimitive = _dereq_('../primitives').definePrimitive;
  58537. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  58538. },{"../primitives":146}],158:[function(_dereq_,module,exports){
  58539. var getMeshMixin = _dereq_('../getMeshMixin');
  58540. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58541. var utils = _dereq_('../../../utils/');
  58542. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  58543. defaultComponents: {
  58544. geometry: {
  58545. primitive: 'plane'
  58546. },
  58547. material: {
  58548. color: '#FFF',
  58549. shader: 'flat',
  58550. side: 'double',
  58551. transparent: true
  58552. }
  58553. },
  58554. mappings: {
  58555. height: 'geometry.height',
  58556. width: 'geometry.width'
  58557. }
  58558. }));
  58559. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],159:[function(_dereq_,module,exports){
  58560. var getMeshMixin = _dereq_('../getMeshMixin');
  58561. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58562. var utils = _dereq_('../../../utils/');
  58563. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  58564. defaultComponents: {
  58565. geometry: {
  58566. primitive: 'sphere',
  58567. radius: 500,
  58568. segmentsWidth: 64,
  58569. segmentsHeight: 32
  58570. },
  58571. material: {
  58572. color: '#FFF',
  58573. shader: 'flat',
  58574. side: 'back',
  58575. npot: true
  58576. },
  58577. scale: '-1 1 1'
  58578. },
  58579. mappings: {
  58580. radius: 'geometry.radius',
  58581. 'segments-height': 'geometry.segmentsHeight',
  58582. 'segments-width': 'geometry.segmentsWidth'
  58583. }
  58584. }));
  58585. },{"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],160:[function(_dereq_,module,exports){
  58586. /**
  58587. * Automated mesh primitive registration.
  58588. */
  58589. var getMeshMixin = _dereq_('../getMeshMixin');
  58590. var geometries = _dereq_('../../../core/geometry').geometries;
  58591. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  58592. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58593. var utils = _dereq_('../../../utils/');
  58594. // For testing.
  58595. var meshPrimitives = module.exports = {};
  58596. // Generate primitive for each geometry type.
  58597. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  58598. var geometry = geometries[geometryName];
  58599. var geometryHyphened = unCamelCase(geometryName);
  58600. // Generate mappings.
  58601. var mappings = {};
  58602. Object.keys(geometry.schema).forEach(function createMapping (property) {
  58603. mappings[unCamelCase(property)] = 'geometry.' + property;
  58604. });
  58605. // Register.
  58606. var tagName = 'a-' + geometryHyphened;
  58607. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  58608. defaultComponents: {geometry: {primitive: geometryName}},
  58609. mappings: mappings
  58610. }));
  58611. meshPrimitives[tagName] = primitive;
  58612. });
  58613. /**
  58614. * camelCase to hyphened-string.
  58615. */
  58616. function unCamelCase (str) {
  58617. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58618. }
  58619. },{"../../../core/geometry":131,"../../../utils/":204,"../getMeshMixin":144,"../primitives":146}],161:[function(_dereq_,module,exports){
  58620. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58621. var THREE = _dereq_('../lib/three');
  58622. registerGeometry('box', {
  58623. schema: {
  58624. depth: {default: 1, min: 0},
  58625. height: {default: 1, min: 0},
  58626. width: {default: 1, min: 0},
  58627. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58628. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  58629. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  58630. },
  58631. init: function (data) {
  58632. this.geometry = new THREE.BoxGeometry(
  58633. data.width, data.height, data.depth,
  58634. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  58635. }
  58636. });
  58637. },{"../core/geometry":131,"../lib/three":178}],162:[function(_dereq_,module,exports){
  58638. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58639. var THREE = _dereq_('../lib/three');
  58640. var degToRad = THREE.Math.degToRad;
  58641. registerGeometry('circle', {
  58642. schema: {
  58643. radius: {default: 1, min: 0},
  58644. segments: {default: 32, min: 3, type: 'int'},
  58645. thetaLength: {default: 360, min: 0},
  58646. thetaStart: {default: 0}
  58647. },
  58648. init: function (data) {
  58649. this.geometry = new THREE.CircleGeometry(
  58650. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58651. }
  58652. });
  58653. },{"../core/geometry":131,"../lib/three":178}],163:[function(_dereq_,module,exports){
  58654. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58655. var THREE = _dereq_('../lib/three');
  58656. var degToRad = THREE.Math.degToRad;
  58657. registerGeometry('cone', {
  58658. schema: {
  58659. height: {default: 1, min: 0},
  58660. openEnded: {default: false},
  58661. radiusBottom: {default: 1, min: 0},
  58662. radiusTop: {default: 0.01, min: 0},
  58663. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58664. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58665. thetaLength: {default: 360, min: 0},
  58666. thetaStart: {default: 0}
  58667. },
  58668. init: function (data) {
  58669. this.geometry = new THREE.CylinderGeometry(
  58670. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  58671. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  58672. degToRad(data.thetaLength));
  58673. }
  58674. });
  58675. },{"../core/geometry":131,"../lib/three":178}],164:[function(_dereq_,module,exports){
  58676. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58677. var THREE = _dereq_('../lib/three');
  58678. var degToRad = THREE.Math.degToRad;
  58679. registerGeometry('cylinder', {
  58680. schema: {
  58681. height: {default: 1, min: 0},
  58682. openEnded: {default: false},
  58683. radius: {default: 1, min: 0},
  58684. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58685. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58686. thetaLength: {default: 360, min: 0},
  58687. thetaStart: {default: 0}
  58688. },
  58689. init: function (data) {
  58690. this.geometry = new THREE.CylinderGeometry(
  58691. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  58692. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58693. }
  58694. });
  58695. },{"../core/geometry":131,"../lib/three":178}],165:[function(_dereq_,module,exports){
  58696. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58697. var THREE = _dereq_('../lib/three');
  58698. registerGeometry('dodecahedron', {
  58699. schema: {
  58700. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58701. radius: {default: 1, min: 0}
  58702. },
  58703. init: function (data) {
  58704. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  58705. }
  58706. });
  58707. },{"../core/geometry":131,"../lib/three":178}],166:[function(_dereq_,module,exports){
  58708. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58709. var THREE = _dereq_('../lib/three');
  58710. registerGeometry('icosahedron', {
  58711. schema: {
  58712. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58713. radius: {default: 1, min: 0}
  58714. },
  58715. init: function (data) {
  58716. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  58717. }
  58718. });
  58719. },{"../core/geometry":131,"../lib/three":178}],167:[function(_dereq_,module,exports){
  58720. _dereq_('./box.js');
  58721. _dereq_('./circle.js');
  58722. _dereq_('./cone.js');
  58723. _dereq_('./cylinder.js');
  58724. _dereq_('./dodecahedron.js');
  58725. _dereq_('./icosahedron.js');
  58726. _dereq_('./octahedron.js');
  58727. _dereq_('./plane.js');
  58728. _dereq_('./ring.js');
  58729. _dereq_('./sphere.js');
  58730. _dereq_('./tetrahedron.js');
  58731. _dereq_('./torus.js');
  58732. _dereq_('./torusKnot.js');
  58733. _dereq_('./triangle.js');
  58734. },{"./box.js":161,"./circle.js":162,"./cone.js":163,"./cylinder.js":164,"./dodecahedron.js":165,"./icosahedron.js":166,"./octahedron.js":168,"./plane.js":169,"./ring.js":170,"./sphere.js":171,"./tetrahedron.js":172,"./torus.js":173,"./torusKnot.js":174,"./triangle.js":175}],168:[function(_dereq_,module,exports){
  58735. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58736. var THREE = _dereq_('../lib/three');
  58737. registerGeometry('octahedron', {
  58738. schema: {
  58739. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58740. radius: {default: 1, min: 0}
  58741. },
  58742. init: function (data) {
  58743. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  58744. }
  58745. });
  58746. },{"../core/geometry":131,"../lib/three":178}],169:[function(_dereq_,module,exports){
  58747. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58748. var THREE = _dereq_('../lib/three');
  58749. registerGeometry('plane', {
  58750. schema: {
  58751. height: {default: 1, min: 0},
  58752. width: {default: 1, min: 0},
  58753. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58754. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  58755. },
  58756. init: function (data) {
  58757. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  58758. }
  58759. });
  58760. },{"../core/geometry":131,"../lib/three":178}],170:[function(_dereq_,module,exports){
  58761. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58762. var THREE = _dereq_('../lib/three');
  58763. var degToRad = THREE.Math.degToRad;
  58764. registerGeometry('ring', {
  58765. schema: {
  58766. radiusInner: {default: 0.8, min: 0},
  58767. radiusOuter: {default: 1.2, min: 0},
  58768. segmentsPhi: {default: 10, min: 1, type: 'int'},
  58769. segmentsTheta: {default: 32, min: 3, type: 'int'},
  58770. thetaLength: {default: 360, min: 0},
  58771. thetaStart: {default: 0}
  58772. },
  58773. init: function (data) {
  58774. this.geometry = new THREE.RingGeometry(
  58775. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  58776. degToRad(data.thetaStart), degToRad(data.thetaLength));
  58777. }
  58778. });
  58779. },{"../core/geometry":131,"../lib/three":178}],171:[function(_dereq_,module,exports){
  58780. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58781. var THREE = _dereq_('../lib/three');
  58782. var degToRad = THREE.Math.degToRad;
  58783. registerGeometry('sphere', {
  58784. schema: {
  58785. radius: {default: 1, min: 0},
  58786. phiLength: {default: 360},
  58787. phiStart: {default: 0, min: 0},
  58788. thetaLength: {default: 180, min: 0},
  58789. thetaStart: {default: 0},
  58790. segmentsHeight: {default: 18, min: 2, type: 'int'},
  58791. segmentsWidth: {default: 36, min: 3, type: 'int'}
  58792. },
  58793. init: function (data) {
  58794. this.geometry = new THREE.SphereGeometry(
  58795. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  58796. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  58797. }
  58798. });
  58799. },{"../core/geometry":131,"../lib/three":178}],172:[function(_dereq_,module,exports){
  58800. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58801. var THREE = _dereq_('../lib/three');
  58802. registerGeometry('tetrahedron', {
  58803. schema: {
  58804. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58805. radius: {default: 1, min: 0}
  58806. },
  58807. init: function (data) {
  58808. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  58809. }
  58810. });
  58811. },{"../core/geometry":131,"../lib/three":178}],173:[function(_dereq_,module,exports){
  58812. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58813. var THREE = _dereq_('../lib/three');
  58814. var degToRad = THREE.Math.degToRad;
  58815. registerGeometry('torus', {
  58816. schema: {
  58817. arc: {default: 360},
  58818. radius: {default: 1, min: 0},
  58819. radiusTubular: {default: 0.2, min: 0},
  58820. segmentsRadial: {default: 36, min: 2, type: 'int'},
  58821. segmentsTubular: {default: 32, min: 3, type: 'int'}
  58822. },
  58823. init: function (data) {
  58824. this.geometry = new THREE.TorusGeometry(
  58825. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  58826. degToRad(data.arc));
  58827. }
  58828. });
  58829. },{"../core/geometry":131,"../lib/three":178}],174:[function(_dereq_,module,exports){
  58830. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58831. var THREE = _dereq_('../lib/three');
  58832. registerGeometry('torusKnot', {
  58833. schema: {
  58834. p: {default: 2, min: 1},
  58835. q: {default: 3, min: 1},
  58836. radius: {default: 1, min: 0},
  58837. radiusTubular: {default: 0.2, min: 0},
  58838. segmentsRadial: {default: 8, min: 3, type: 'int'},
  58839. segmentsTubular: {default: 100, min: 3, type: 'int'}
  58840. },
  58841. init: function (data) {
  58842. this.geometry = new THREE.TorusKnotGeometry(
  58843. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  58844. data.p, data.q);
  58845. }
  58846. });
  58847. },{"../core/geometry":131,"../lib/three":178}],175:[function(_dereq_,module,exports){
  58848. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58849. var THREE = _dereq_('../lib/three');
  58850. var quaternion = new THREE.Quaternion();
  58851. var rotateVector = new THREE.Vector3(0, 0, 1);
  58852. var uvMinVector = new THREE.Vector2();
  58853. var uvMaxVector = new THREE.Vector2();
  58854. var uvScaleVector = new THREE.Vector2();
  58855. registerGeometry('triangle', {
  58856. schema: {
  58857. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  58858. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  58859. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  58860. },
  58861. init: function (data) {
  58862. var geometry;
  58863. var normal;
  58864. var triangle;
  58865. var uvA;
  58866. var uvB;
  58867. var uvC;
  58868. triangle = new THREE.Triangle();
  58869. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  58870. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  58871. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  58872. normal = triangle.getNormal(new THREE.Vector3());
  58873. // Rotate the 3D triangle to be parallel to XY plane.
  58874. quaternion.setFromUnitVectors(normal, rotateVector);
  58875. uvA = triangle.a.clone().applyQuaternion(quaternion);
  58876. uvB = triangle.b.clone().applyQuaternion(quaternion);
  58877. uvC = triangle.c.clone().applyQuaternion(quaternion);
  58878. // Compute UVs.
  58879. // Normalize x/y values of UV so they are within 0 to 1.
  58880. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  58881. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  58882. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  58883. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  58884. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  58885. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  58886. geometry = this.geometry = new THREE.Geometry();
  58887. geometry.vertices.push(triangle.a);
  58888. geometry.vertices.push(triangle.b);
  58889. geometry.vertices.push(triangle.c);
  58890. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  58891. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  58892. }
  58893. });
  58894. },{"../core/geometry":131,"../lib/three":178}],176:[function(_dereq_,module,exports){
  58895. // Polyfill `Promise`.
  58896. window.Promise = window.Promise || _dereq_('promise-polyfill');
  58897. // WebVR polyfill
  58898. // Check before the polyfill runs.
  58899. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  58900. !!window.navigator.getVRDevices;
  58901. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  58902. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  58903. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  58904. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  58905. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  58906. // Only for iOS on versions older than 10.
  58907. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  58908. var WebVRPolyfill = _dereq_('webvr-polyfill');
  58909. var polyfillConfig = {
  58910. BUFFER_SCALE: bufferScale,
  58911. CARDBOARD_UI_DISABLED: true,
  58912. ROTATE_INSTRUCTIONS_DISABLED: true,
  58913. MOBILE_WAKE_LOCK: !!window.cordova
  58914. };
  58915. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  58916. }
  58917. var utils = _dereq_('./utils/');
  58918. var debug = utils.debug;
  58919. if (utils.isIE11) {
  58920. // Polyfill `CustomEvent`.
  58921. _dereq_('custom-event-polyfill');
  58922. // Polyfill String.startsWith.
  58923. _dereq_('../vendor/starts-with-polyfill');
  58924. }
  58925. var error = debug('A-Frame:error');
  58926. var warn = debug('A-Frame:warn');
  58927. if (window.document.currentScript && window.document.currentScript.parentNode !==
  58928. window.document.head && !window.debug) {
  58929. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  58930. 'ensure everything for A-Frame is properly registered before they are used from ' +
  58931. 'HTML.');
  58932. }
  58933. // Error if not using a server.
  58934. if (!window.cordova && window.location.protocol === 'file:') {
  58935. error(
  58936. 'This HTML file is currently being served via the file:// protocol. ' +
  58937. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  58938. 'Please use a local or hosted server: ' +
  58939. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  58940. }
  58941. _dereq_('present'); // Polyfill `performance.now()`.
  58942. // CSS.
  58943. if (utils.device.isBrowserEnvironment) {
  58944. _dereq_('./style/aframe.css');
  58945. _dereq_('./style/rStats.css');
  58946. }
  58947. // Required before `AEntity` so that all components are registered.
  58948. var AScene = _dereq_('./core/scene/a-scene').AScene;
  58949. var components = _dereq_('./core/component').components;
  58950. var registerComponent = _dereq_('./core/component').registerComponent;
  58951. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  58952. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  58953. var registerShader = _dereq_('./core/shader').registerShader;
  58954. var registerSystem = _dereq_('./core/system').registerSystem;
  58955. var shaders = _dereq_('./core/shader').shaders;
  58956. var systems = _dereq_('./core/system').systems;
  58957. // Exports THREE to window so three.js can be used without alteration.
  58958. var THREE = window.THREE = _dereq_('./lib/three');
  58959. var pkg = _dereq_('../package');
  58960. _dereq_('./components/index'); // Register standard components.
  58961. _dereq_('./geometries/index'); // Register standard geometries.
  58962. _dereq_('./shaders/index'); // Register standard shaders.
  58963. _dereq_('./systems/index'); // Register standard systems.
  58964. var ANode = _dereq_('./core/a-node');
  58965. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  58966. _dereq_('./core/a-assets');
  58967. _dereq_('./core/a-cubemap');
  58968. _dereq_('./core/a-mixin');
  58969. // Extras.
  58970. _dereq_('./extras/components/');
  58971. _dereq_('./extras/primitives/');
  58972. console.log('A-Frame Version: 1.1.0 (Date 2021-01-11, Commit #60a23326)');
  58973. console.log('THREE Version (https://github.com/supermedium/three.js):',
  58974. pkg.dependencies['super-three']);
  58975. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  58976. module.exports = window.AFRAME = {
  58977. AComponent: _dereq_('./core/component').Component,
  58978. AEntity: AEntity,
  58979. ANode: ANode,
  58980. ANIME: _dereq_('super-animejs'),
  58981. AScene: AScene,
  58982. components: components,
  58983. coreComponents: Object.keys(components),
  58984. geometries: _dereq_('./core/geometry').geometries,
  58985. registerComponent: registerComponent,
  58986. registerElement: _dereq_('./core/a-register-element').registerElement,
  58987. registerGeometry: registerGeometry,
  58988. registerPrimitive: registerPrimitive,
  58989. registerShader: registerShader,
  58990. registerSystem: registerSystem,
  58991. primitives: {
  58992. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  58993. primitives: _dereq_('./extras/primitives/primitives').primitives
  58994. },
  58995. scenes: _dereq_('./core/scene/scenes'),
  58996. schema: _dereq_('./core/schema'),
  58997. shaders: shaders,
  58998. systems: systems,
  58999. THREE: THREE,
  59000. utils: utils,
  59001. version: pkg.version
  59002. };
  59003. },{"../package":72,"../vendor/starts-with-polyfill":217,"./components/index":83,"./core/a-assets":124,"./core/a-cubemap":125,"./core/a-entity":126,"./core/a-mixin":127,"./core/a-node":128,"./core/a-register-element":129,"./core/component":130,"./core/geometry":131,"./core/scene/a-scene":133,"./core/scene/scenes":137,"./core/schema":139,"./core/shader":140,"./core/system":141,"./extras/components/":142,"./extras/primitives/":145,"./extras/primitives/getMeshMixin":144,"./extras/primitives/primitives":146,"./geometries/index":167,"./lib/three":178,"./shaders/index":180,"./style/aframe.css":185,"./style/rStats.css":186,"./systems/index":190,"./utils/":204,"./utils/isIOSOlderThan10":207,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":67}],177:[function(_dereq_,module,exports){
  59004. window.aframeStats = function (scene) {
  59005. var _rS = null;
  59006. var _scene = scene;
  59007. var _values = {
  59008. te: {
  59009. caption: 'Entities'
  59010. },
  59011. lt: {
  59012. caption: 'Load Time'
  59013. }
  59014. };
  59015. var _groups = [ {
  59016. caption: 'A-Frame',
  59017. values: [ 'te', 'lt' ]
  59018. } ];
  59019. function _update () {
  59020. _rS('te').set(getEntityCount());
  59021. if (window.performance.getEntriesByName) {
  59022. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  59023. }
  59024. }
  59025. function getEntityCount () {
  59026. var elements = _scene.querySelectorAll('*');
  59027. Array.prototype.slice.call(elements).filter(function (el) {
  59028. return el.isEntity;
  59029. });
  59030. return elements.length;
  59031. }
  59032. function _start () {}
  59033. function _end () {}
  59034. function _attach (r) {
  59035. _rS = r;
  59036. }
  59037. return {
  59038. update: _update,
  59039. start: _start,
  59040. end: _end,
  59041. attach: _attach,
  59042. values: _values,
  59043. groups: _groups,
  59044. fractions: []
  59045. };
  59046. };
  59047. if (typeof module === 'object') {
  59048. module.exports = {
  59049. aframeStats: window.aframeStats
  59050. };
  59051. }
  59052. },{}],178:[function(_dereq_,module,exports){
  59053. (function (global){
  59054. var THREE = global.THREE = _dereq_('super-three');
  59055. // Allow cross-origin images to be loaded.
  59056. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  59057. // Must be on `THREE.TextureLoader`.
  59058. if (THREE.TextureLoader) {
  59059. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  59060. }
  59061. // This is for images loaded from the model loaders.
  59062. if (THREE.ImageLoader) {
  59063. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  59064. }
  59065. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  59066. if (THREE.Cache) {
  59067. THREE.Cache.enabled = true;
  59068. }
  59069. // TODO: Eventually include these only if they are needed by a component.
  59070. _dereq_('../../vendor/DeviceOrientationControls'); // THREE.DeviceOrientationControls
  59071. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  59072. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  59073. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  59074. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  59075. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  59076. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  59077. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  59078. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  59079. module.exports = THREE;
  59080. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  59081. },{"../../vendor/DeviceOrientationControls":214,"super-three":57,"super-three/examples/js/loaders/DRACOLoader":58,"super-three/examples/js/loaders/GLTFLoader":59,"super-three/examples/js/loaders/MTLLoader":60,"super-three/examples/js/loaders/OBJLoader":61}],179:[function(_dereq_,module,exports){
  59082. var registerShader = _dereq_('../core/shader').registerShader;
  59083. var THREE = _dereq_('../lib/three');
  59084. var utils = _dereq_('../utils/');
  59085. /**
  59086. * Flat shader using THREE.MeshBasicMaterial.
  59087. */
  59088. module.exports.Shader = registerShader('flat', {
  59089. schema: {
  59090. color: {type: 'color'},
  59091. fog: {default: true},
  59092. height: {default: 256},
  59093. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59094. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59095. src: {type: 'map'},
  59096. width: {default: 512},
  59097. wireframe: {default: false},
  59098. wireframeLinewidth: {default: 2}
  59099. },
  59100. /**
  59101. * Initializes the shader.
  59102. * Adds a reference from the scene to this entity as the camera.
  59103. */
  59104. init: function (data) {
  59105. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59106. this.materialData = {color: new THREE.Color()};
  59107. this.textureSrc = null;
  59108. getMaterialData(data, this.materialData);
  59109. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59110. this.material = new THREE.MeshBasicMaterial(this.materialData);
  59111. utils.material.updateMap(this, data);
  59112. },
  59113. update: function (data) {
  59114. this.updateMaterial(data);
  59115. utils.material.updateMap(this, data);
  59116. },
  59117. /**
  59118. * Updating existing material.
  59119. *
  59120. * @param {object} data - Material component data.
  59121. */
  59122. updateMaterial: function (data) {
  59123. var key;
  59124. getMaterialData(data, this.materialData);
  59125. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59126. for (key in this.materialData) {
  59127. this.material[key] = this.materialData[key];
  59128. }
  59129. }
  59130. });
  59131. /**
  59132. * Builds and normalize material data, normalizing stuff along the way.
  59133. *
  59134. * @param {object} data - Material data.
  59135. * @param {object} materialData - Object to reuse.
  59136. * @returns {object} Updated material data.
  59137. */
  59138. function getMaterialData (data, materialData) {
  59139. materialData.color.set(data.color);
  59140. materialData.fog = data.fog;
  59141. materialData.wireframe = data.wireframe;
  59142. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59143. return materialData;
  59144. }
  59145. },{"../core/shader":140,"../lib/three":178,"../utils/":204}],180:[function(_dereq_,module,exports){
  59146. _dereq_('./flat');
  59147. _dereq_('./standard');
  59148. _dereq_('./sdf');
  59149. _dereq_('./msdf');
  59150. _dereq_('./ios10hls');
  59151. },{"./flat":179,"./ios10hls":181,"./msdf":182,"./sdf":183,"./standard":184}],181:[function(_dereq_,module,exports){
  59152. var registerShader = _dereq_('../core/shader').registerShader;
  59153. /**
  59154. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  59155. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  59156. */
  59157. module.exports.Shader = registerShader('ios10hls', {
  59158. schema: {
  59159. src: {type: 'map', is: 'uniform'},
  59160. opacity: {type: 'number', is: 'uniform', default: 1}
  59161. },
  59162. vertexShader: [
  59163. 'varying vec2 vUV;',
  59164. 'void main(void) {',
  59165. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59166. ' vUV = uv;',
  59167. '}'
  59168. ].join('\n'),
  59169. fragmentShader: [
  59170. 'uniform sampler2D src;',
  59171. 'uniform float opacity;',
  59172. 'varying vec2 vUV;',
  59173. 'void main() {',
  59174. ' vec2 offset = vec2(0, 0);',
  59175. ' vec2 repeat = vec2(1, 1);',
  59176. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  59177. ' gl_FragColor = vec4(color.rgb, opacity);',
  59178. '}'
  59179. ].join('\n')
  59180. });
  59181. },{"../core/shader":140}],182:[function(_dereq_,module,exports){
  59182. var registerShader = _dereq_('../core/shader').registerShader;
  59183. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  59184. var VERTEX_SHADER_WEBGL1 = [
  59185. 'attribute vec2 uv;',
  59186. 'attribute vec3 position;',
  59187. 'uniform mat4 projectionMatrix;',
  59188. 'uniform mat4 modelViewMatrix;',
  59189. 'varying vec2 vUV;',
  59190. 'void main(void) {',
  59191. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59192. ' vUV = uv;',
  59193. '}'
  59194. ].join('\n');
  59195. var VERTEX_SHADER_WEBGL2 = [
  59196. '#version 300 es',
  59197. 'in vec2 uv;',
  59198. 'in vec3 position;',
  59199. 'uniform mat4 projectionMatrix;',
  59200. 'uniform mat4 modelViewMatrix;',
  59201. 'out vec2 vUV;',
  59202. 'void main(void) {',
  59203. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59204. ' vUV = uv;',
  59205. '}'
  59206. ].join('\n');
  59207. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  59208. var FRAGMENT_SHADER_WEBGL1 = [
  59209. '#ifdef GL_OES_standard_derivatives',
  59210. '#extension GL_OES_standard_derivatives: enable',
  59211. '#endif',
  59212. 'precision highp float;',
  59213. 'uniform bool negate;',
  59214. 'uniform float alphaTest;',
  59215. 'uniform float opacity;',
  59216. 'uniform sampler2D map;',
  59217. 'uniform vec3 color;',
  59218. 'varying vec2 vUV;',
  59219. 'float median(float r, float g, float b) {',
  59220. ' return max(min(r, g), min(max(r, g), b));',
  59221. '}',
  59222. // FIXME: Experimentally determined constants.
  59223. '#define BIG_ENOUGH 0.001',
  59224. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59225. 'void main() {',
  59226. ' vec3 sampleColor = texture2D(map, vUV).rgb;',
  59227. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  59228. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  59229. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  59230. ' float dscale = 0.353505;',
  59231. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  59232. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59233. // When texel is too small, blend raw alpha value rather than supersampling.
  59234. // FIXME: Experimentally determined constant.
  59235. ' // Do modified alpha test.',
  59236. ' if (isBigEnough > BIG_ENOUGH) {',
  59237. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59238. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  59239. ' }',
  59240. ' // Do modified alpha test.',
  59241. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59242. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  59243. '}'
  59244. ].join('\n');
  59245. var FRAGMENT_SHADER_WEBGL2 = [
  59246. '#version 300 es',
  59247. 'precision highp float;',
  59248. 'uniform bool negate;',
  59249. 'uniform float alphaTest;',
  59250. 'uniform float opacity;',
  59251. 'uniform sampler2D map;',
  59252. 'uniform vec3 color;',
  59253. 'in vec2 vUV;',
  59254. 'out vec4 fragColor;',
  59255. 'float median(float r, float g, float b) {',
  59256. ' return max(min(r, g), min(max(r, g), b));',
  59257. '}',
  59258. // FIXME: Experimentally determined constants.
  59259. '#define BIG_ENOUGH 0.001',
  59260. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59261. 'void main() {',
  59262. ' vec3 sampleColor = texture(map, vUV).rgb;',
  59263. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  59264. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  59265. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  59266. ' float dscale = 0.353505;',
  59267. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  59268. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59269. // When texel is too small, blend raw alpha value rather than supersampling.
  59270. // FIXME: Experimentally determined constant.
  59271. ' // Do modified alpha test.',
  59272. ' if (isBigEnough > BIG_ENOUGH) {',
  59273. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59274. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  59275. ' }',
  59276. ' // Do modified alpha test.',
  59277. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59278. ' fragColor = vec4(color.xyz, alpha * opacity);',
  59279. '}'
  59280. ].join('\n');
  59281. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  59282. /**
  59283. * Multi-channel signed distance field.
  59284. * Used by text component.
  59285. */
  59286. module.exports.Shader = registerShader('msdf', {
  59287. schema: {
  59288. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59289. color: {type: 'color', is: 'uniform', default: 'white'},
  59290. map: {type: 'map', is: 'uniform'},
  59291. negate: {type: 'boolean', is: 'uniform', default: true},
  59292. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59293. },
  59294. raw: true,
  59295. vertexShader: VERTEX_SHADER,
  59296. fragmentShader: FRAGMENT_SHADER
  59297. });
  59298. },{"../core/shader":140}],183:[function(_dereq_,module,exports){
  59299. var registerShader = _dereq_('../core/shader').registerShader;
  59300. /**
  59301. * Signed distance field.
  59302. * Used by text component.
  59303. */
  59304. module.exports.Shader = registerShader('sdf', {
  59305. schema: {
  59306. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59307. color: {type: 'color', is: 'uniform', default: 'white'},
  59308. map: {type: 'map', is: 'uniform'},
  59309. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59310. },
  59311. raw: true,
  59312. vertexShader: [
  59313. '#version 300 es',
  59314. 'in vec2 uv;',
  59315. 'in vec3 position;',
  59316. 'uniform mat4 projectionMatrix;',
  59317. 'uniform mat4 modelViewMatrix;',
  59318. 'out vec2 vUV;',
  59319. 'void main(void) {',
  59320. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59321. ' vUV = uv;',
  59322. '}'
  59323. ].join('\n'),
  59324. fragmentShader: [
  59325. '#version 300 es',
  59326. 'precision highp float;',
  59327. 'uniform float alphaTest;',
  59328. 'uniform float opacity;',
  59329. 'uniform sampler2D map;',
  59330. 'uniform vec3 color;',
  59331. 'in vec2 vUV;',
  59332. 'out vec4 fragColor;',
  59333. '#ifdef GL_OES_standard_derivatives',
  59334. ' float contour(float width, float value) {',
  59335. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  59336. ' }',
  59337. '#else',
  59338. ' float aastep(float value, float afwidth) {',
  59339. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  59340. ' }',
  59341. '#endif',
  59342. // FIXME: Experimentally determined constants.
  59343. '#define BIG_ENOUGH 0.001',
  59344. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59345. '#define ALL_SMOOTH 0.4',
  59346. '#define ALL_ROUGH 0.02',
  59347. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  59348. 'void main() {',
  59349. // When we have derivatives and can get texel size for supersampling.
  59350. ' #ifdef GL_OES_standard_derivatives',
  59351. ' vec2 uv = vUV;',
  59352. ' vec4 texColor = texture(map, uv);',
  59353. ' float dist = texColor.a;',
  59354. ' float width = fwidth(dist);',
  59355. ' float alpha = contour(dist, width);',
  59356. ' float dscale = 0.353505;',
  59357. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  59358. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59359. // When texel is too small, blend raw alpha value rather than supersampling.
  59360. // FIXME: experimentally determined constant
  59361. ' if (isBigEnough > BIG_ENOUGH) {',
  59362. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59363. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  59364. ' }',
  59365. // Otherwise do weighted supersampling.
  59366. // FIXME: why this weighting?
  59367. ' if (isBigEnough <= BIG_ENOUGH) {',
  59368. ' vec4 box = vec4 (uv - duv, uv + duv);',
  59369. ' alpha = (alpha + 0.5 * (',
  59370. ' contour(texture(map, box.xy).a, width)',
  59371. ' + contour(texture(map, box.zw).a, width)',
  59372. ' + contour(texture(map, box.xw).a, width)',
  59373. ' + contour(texture(map, box.zy).a, width)',
  59374. ' )) / 3.0;',
  59375. ' }',
  59376. // Do modified alpha test.
  59377. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59378. ' #else',
  59379. // When we don't have derivatives, use approximations.
  59380. ' vec4 texColor = texture(map, vUV);',
  59381. ' float value = texColor.a;',
  59382. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59383. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59384. ' float alpha = aastep(value, afwidth);',
  59385. // Use gl_FragCoord.w to guess when we should blend.
  59386. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59387. ' float ratio = (gl_FragCoord.w >= ALL_SMOOTH) ? 1.0 : (gl_FragCoord.w < ALL_ROUGH) ? 0.0 : (gl_FragCoord.w - ALL_ROUGH) / (ALL_SMOOTH - ALL_ROUGH);',
  59388. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59389. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59390. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59391. ' #endif',
  59392. ' fragColor = vec4(color, opacity * alpha);',
  59393. '}'
  59394. ].join('\n')
  59395. });
  59396. },{"../core/shader":140}],184:[function(_dereq_,module,exports){
  59397. var registerShader = _dereq_('../core/shader').registerShader;
  59398. var THREE = _dereq_('../lib/three');
  59399. var utils = _dereq_('../utils/');
  59400. var CubeLoader = new THREE.CubeTextureLoader();
  59401. var texturePromises = {};
  59402. /**
  59403. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  59404. */
  59405. module.exports.Shader = registerShader('standard', {
  59406. schema: {
  59407. ambientOcclusionMap: {type: 'map'},
  59408. ambientOcclusionMapIntensity: {default: 1},
  59409. ambientOcclusionTextureOffset: {type: 'vec2'},
  59410. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59411. color: {type: 'color'},
  59412. displacementMap: {type: 'map'},
  59413. displacementScale: {default: 1},
  59414. displacementBias: {default: 0.5},
  59415. displacementTextureOffset: {type: 'vec2'},
  59416. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59417. emissive: {type: 'color', default: '#000'},
  59418. emissiveIntensity: {default: 1},
  59419. envMap: {default: ''},
  59420. fog: {default: true},
  59421. height: {default: 256},
  59422. metalness: {default: 0.0, min: 0.0, max: 1.0},
  59423. metalnessMap: {type: 'map'},
  59424. metalnessTextureOffset: {type: 'vec2'},
  59425. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59426. normalMap: {type: 'map'},
  59427. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  59428. normalTextureOffset: {type: 'vec2'},
  59429. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59430. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59431. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59432. roughness: {default: 0.5, min: 0.0, max: 1.0},
  59433. roughnessMap: {type: 'map'},
  59434. roughnessTextureOffset: {type: 'vec2'},
  59435. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59436. sphericalEnvMap: {type: 'map'},
  59437. src: {type: 'map'},
  59438. width: {default: 512},
  59439. wireframe: {default: false},
  59440. wireframeLinewidth: {default: 2}
  59441. },
  59442. /**
  59443. * Initializes the shader.
  59444. * Adds a reference from the scene to this entity as the camera.
  59445. */
  59446. init: function (data) {
  59447. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59448. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  59449. getMaterialData(data, this.materialData);
  59450. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59451. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59452. this.material = new THREE.MeshStandardMaterial(this.materialData);
  59453. utils.material.updateMap(this, data);
  59454. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59455. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59456. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59457. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59458. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59459. this.updateEnvMap(data);
  59460. },
  59461. update: function (data) {
  59462. this.updateMaterial(data);
  59463. utils.material.updateMap(this, data);
  59464. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59465. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59466. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59467. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59468. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59469. this.updateEnvMap(data);
  59470. },
  59471. /**
  59472. * Updating existing material.
  59473. *
  59474. * @param {object} data - Material component data.
  59475. * @returns {object} Material.
  59476. */
  59477. updateMaterial: function (data) {
  59478. var key;
  59479. var material = this.material;
  59480. getMaterialData(data, this.materialData);
  59481. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59482. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59483. for (key in this.materialData) {
  59484. material[key] = this.materialData[key];
  59485. }
  59486. },
  59487. /**
  59488. * Handle environment cubemap. Textures are cached in texturePromises.
  59489. */
  59490. updateEnvMap: function (data) {
  59491. var self = this;
  59492. var material = this.material;
  59493. var envMap = data.envMap;
  59494. var sphericalEnvMap = data.sphericalEnvMap;
  59495. // No envMap defined or already loading.
  59496. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  59497. material.envMap = null;
  59498. material.needsUpdate = true;
  59499. return;
  59500. }
  59501. this.isLoadingEnvMap = true;
  59502. // if a spherical env map is defined then use it.
  59503. if (sphericalEnvMap) {
  59504. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  59505. self.isLoadingEnvMap = false;
  59506. texture.mapping = THREE.SphericalReflectionMapping;
  59507. material.envMap = texture;
  59508. utils.material.handleTextureEvents(self.el, texture);
  59509. material.needsUpdate = true;
  59510. });
  59511. return;
  59512. }
  59513. // Another material is already loading this texture. Wait on promise.
  59514. if (texturePromises[envMap]) {
  59515. texturePromises[envMap].then(function (cube) {
  59516. self.isLoadingEnvMap = false;
  59517. material.envMap = cube;
  59518. utils.material.handleTextureEvents(self.el, cube);
  59519. material.needsUpdate = true;
  59520. });
  59521. return;
  59522. }
  59523. // Material is first to load this texture. Load and resolve texture.
  59524. texturePromises[envMap] = new Promise(function (resolve) {
  59525. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  59526. CubeLoader.load(urls, function (cube) {
  59527. // Texture loaded.
  59528. self.isLoadingEnvMap = false;
  59529. material.envMap = cube;
  59530. utils.material.handleTextureEvents(self.el, cube);
  59531. resolve(cube);
  59532. });
  59533. });
  59534. });
  59535. }
  59536. });
  59537. /**
  59538. * Builds and normalize material data, normalizing stuff along the way.
  59539. *
  59540. * @param {object} data - Material data.
  59541. * @param {object} materialData - Object to use.
  59542. * @returns {object} Updated materialData.
  59543. */
  59544. function getMaterialData (data, materialData) {
  59545. materialData.color.set(data.color);
  59546. materialData.emissive.set(data.emissive);
  59547. materialData.emissiveIntensity = data.emissiveIntensity;
  59548. materialData.fog = data.fog;
  59549. materialData.metalness = data.metalness;
  59550. materialData.roughness = data.roughness;
  59551. materialData.wireframe = data.wireframe;
  59552. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59553. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  59554. if (data.ambientOcclusionMap) {
  59555. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  59556. }
  59557. if (data.displacementMap) {
  59558. materialData.displacementScale = data.displacementScale;
  59559. materialData.displacementBias = data.displacementBias;
  59560. }
  59561. return materialData;
  59562. }
  59563. },{"../core/shader":140,"../lib/three":178,"../utils/":204}],185:[function(_dereq_,module,exports){
  59564. var css = "html.a-fullscreen{bottom:0;left:0;position:fixed;right:0;top:0}html.a-fullscreen body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}html.a-fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;position:fixed!important}html:not(.a-fullscreen) .a-enter-ar,html:not(.a-fullscreen) .a-enter-vr{right:5px;bottom:5px}:-webkit-full-screen{background-color:transparent}.a-hidden{display:none!important}.a-canvas{height:100%;left:0;position:absolute;top:0;width:100%}.a-canvas.a-grab-cursor:hover{cursor:grab;cursor:-moz-grab;cursor:-webkit-grab}canvas.a-canvas.a-mouse-cursor-hover:hover{cursor:pointer}.a-inspector-loader{background-color:#ed3160;position:fixed;left:3px;top:3px;padding:6px 10px;color:#fff;text-decoration:none;font-size:12px;font-family:Roboto,sans-serif;text-align:center;z-index:99999;width:204px}@keyframes dots-1{from{opacity:0}25%{opacity:1}}@keyframes dots-2{from{opacity:0}50%{opacity:1}}@keyframes dots-3{from{opacity:0}75%{opacity:1}}@-webkit-keyframes dots-1{from{opacity:0}25%{opacity:1}}@-webkit-keyframes dots-2{from{opacity:0}50%{opacity:1}}@-webkit-keyframes dots-3{from{opacity:0}75%{opacity:1}}.a-inspector-loader .dots span{animation:dots-1 2s infinite steps(1);-webkit-animation:dots-1 2s infinite steps(1)}.a-inspector-loader .dots span:first-child+span{animation-name:dots-2;-webkit-animation-name:dots-2}.a-inspector-loader .dots span:first-child+span+span{animation-name:dots-3;-webkit-animation-name:dots-3}a-scene{display:block;position:relative;height:100%;width:100%}a-assets,a-scene audio,a-scene img,a-scene video{display:none}.a-enter-vr-modal,.a-orientation-modal{font-family:Consolas,Andale Mono,Courier New,monospace}.a-enter-vr-modal a{border-bottom:1px solid #fff;padding:2px 0;text-decoration:none;transition:.1s color ease-in}.a-enter-vr-modal a:hover{background-color:#fff;color:#111;padding:2px 4px;position:relative;left:-4px}.a-enter-ar,.a-enter-vr{font-family:sans-serif,monospace;font-size:13px;width:100%;font-weight:200;line-height:16px;position:absolute;right:20px;bottom:20px}.a-enter-ar{right:80px}.a-enter-vr-button,.a-enter-vr-modal,.a-enter-vr-modal a{color:#fff;user-select:none;outline:0}.a-enter-vr-button{background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='108' height='62' viewBox='0 0 108 62'%3E%3Ctitle%3Eaframe-vrmode-noborder-reduced-tracking%3C/title%3E%3Cpath d='M68.81,21.56H64.23v8.27h4.58a4.13,4.13,0,0,0,3.1-1.09,4.2,4.2,0,0,0,1-3,4.24,4.24,0,0,0-1-3A4.05,4.05,0,0,0,68.81,21.56Z' fill='%23fff'/%3E%3Cpath d='M96,0H12A12,12,0,0,0,0,12V50A12,12,0,0,0,12,62H96a12,12,0,0,0,12-12V12A12,12,0,0,0,96,0ZM41.9,46H34L24,16h8l6,21.84,6-21.84H52Zm39.29,0H73.44L68.15,35.39H64.23V46H57V16H68.81q5.32,0,8.34,2.37a8,8,0,0,1,3,6.69,9.68,9.68,0,0,1-1.27,5.18,8.9,8.9,0,0,1-4,3.34l6.26,12.11Z' fill='%23fff'/%3E%3C/svg%3E\") 50% 50% no-repeat rgba(0,0,0,.35)}.a-enter-ar-button{background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='108' height='62' viewBox='0 0 108 62'%3E%3Ctitle%3Eaframe-armode-noborder-reduced-tracking%3C/title%3E%3Cpath d='M96,0H12A12,12,0,0,0,0,12V50A12,12,0,0,0,12,62H96a12,12,0,0,0,12-12V12A12,12,0,0,0,96,0Zm8,50a8,8,0,0,1-8,8H12a8,8,0,0,1-8-8V12a8,8,0,0,1,8-8H96a8,8,0,0,1,8,8Z' fill='%23fff'/%3E%3Cpath d='M43.35,39.82H32.51L30.45,46H23.88L35,16h5.73L52,46H45.43Zm-9.17-5h7.5L37.91,23.58Z' fill='%23fff'/%3E%3Cpath d='M68.11,35H63.18V46H57V16H68.15q5.31,0,8.2,2.37a8.18,8.18,0,0,1,2.88,6.7,9.22,9.22,0,0,1-1.33,5.12,9.09,9.09,0,0,1-4,3.26l6.49,12.26V46H73.73Zm-4.93-5h5a5.09,5.09,0,0,0,3.6-1.18,4.21,4.21,0,0,0,1.28-3.27,4.56,4.56,0,0,0-1.2-3.34A5,5,0,0,0,68.15,21h-5Z' fill='%23fff'/%3E%3C/svg%3E\") 50% 50% no-repeat rgba(0,0,0,.2)}.a-enter-ar-button,.a-enter-vr-button{background-size:90% 90%;border:0;bottom:0;cursor:pointer;min-width:58px;min-height:34px;padding-right:0;padding-top:0;position:absolute;right:0;transition:background-color .05s ease;-webkit-transition:background-color .05s ease;z-index:9999;border-radius:8px;touch-action:manipulation}.a-enter-ar-button{background-size:100% 90%;margin-right:10px;border-radius:7px}.a-enter-ar-button:active,.a-enter-ar-button:hover,.a-enter-vr-button:active,.a-enter-vr-button:hover{background-color:#ef2d5e}.a-enter-vr-button.resethover{background-color:rgba(0,0,0,.35)}[data-a-enter-vr-no-webvr] .a-enter-vr-button{border-color:#666;opacity:.65}[data-a-enter-vr-no-webvr] .a-enter-vr-button:active,[data-a-enter-vr-no-webvr] .a-enter-vr-button:hover{background-color:rgba(0,0,0,.35);cursor:not-allowed}.a-enter-vr-modal{background-color:#666;border-radius:0;display:none;min-height:32px;margin-right:70px;padding:9px;width:280px;right:2%;position:absolute}.a-enter-vr-modal:after{border-bottom:10px solid transparent;border-left:10px solid #666;border-top:10px solid transparent;display:inline-block;content:'';position:absolute;right:-5px;top:5px;width:0;height:0}.a-enter-vr-modal a,.a-enter-vr-modal p{display:inline}.a-enter-vr-modal p{margin:0}.a-enter-vr-modal p:after{content:' '}[data-a-enter-vr-no-headset].a-enter-vr:hover .a-enter-vr-modal,[data-a-enter-vr-no-webvr].a-enter-vr:hover .a-enter-vr-modal{display:block}.a-orientation-modal{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%2090%2090%22%20enable-background%3D%22new%200%200%2090%2090%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20points%3D%220%2C0%200%2C0%200%2C0%20%22%3E%3C/polygon%3E%3Cg%3E%3Cpath%20d%3D%22M71.545%2C48.145h-31.98V20.743c0-2.627-2.138-4.765-4.765-4.765H18.456c-2.628%2C0-4.767%2C2.138-4.767%2C4.765v42.789%20%20%20c0%2C2.628%2C2.138%2C4.766%2C4.767%2C4.766h5.535v0.959c0%2C2.628%2C2.138%2C4.765%2C4.766%2C4.765h42.788c2.628%2C0%2C4.766-2.137%2C4.766-4.765V52.914%20%20%20C76.311%2C50.284%2C74.173%2C48.145%2C71.545%2C48.145z%20M18.455%2C16.935h16.344c2.1%2C0%2C3.808%2C1.708%2C3.808%2C3.808v27.401H37.25V22.636%20%20%20c0-0.264-0.215-0.478-0.479-0.478H16.482c-0.264%2C0-0.479%2C0.214-0.479%2C0.478v36.585c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h7.507v7.644%20%20%20h-5.534c-2.101%2C0-3.81-1.709-3.81-3.81V20.743C14.645%2C18.643%2C16.354%2C16.935%2C18.455%2C16.935z%20M16.96%2C23.116h19.331v25.031h-7.535%20%20%20c-2.628%2C0-4.766%2C2.139-4.766%2C4.768v5.828h-7.03V23.116z%20M71.545%2C73.064H28.757c-2.101%2C0-3.81-1.708-3.81-3.808V52.914%20%20%20c0-2.102%2C1.709-3.812%2C3.81-3.812h42.788c2.1%2C0%2C3.809%2C1.71%2C3.809%2C3.812v16.343C75.354%2C71.356%2C73.645%2C73.064%2C71.545%2C73.064z%22%3E%3C/path%3E%3Cpath%20d%3D%22M28.919%2C58.424c-1.466%2C0-2.659%2C1.193-2.659%2C2.66c0%2C1.466%2C1.193%2C2.658%2C2.659%2C2.658c1.468%2C0%2C2.662-1.192%2C2.662-2.658%20%20%20C31.581%2C59.617%2C30.387%2C58.424%2C28.919%2C58.424z%20M28.919%2C62.786c-0.939%2C0-1.703-0.764-1.703-1.702c0-0.939%2C0.764-1.704%2C1.703-1.704%20%20%20c0.94%2C0%2C1.705%2C0.765%2C1.705%2C1.704C30.623%2C62.022%2C29.858%2C62.786%2C28.919%2C62.786z%22%3E%3C/path%3E%3Cpath%20d%3D%22M69.654%2C50.461H33.069c-0.264%2C0-0.479%2C0.215-0.479%2C0.479v20.288c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h36.585%20%20%20c0.263%2C0%2C0.477-0.214%2C0.477-0.478V50.939C70.131%2C50.676%2C69.917%2C50.461%2C69.654%2C50.461z%20M69.174%2C51.417V70.75H33.548V51.417H69.174z%22%3E%3C/path%3E%3Cpath%20d%3D%22M45.201%2C30.296c6.651%2C0%2C12.233%2C5.351%2C12.551%2C11.977l-3.033-2.638c-0.193-0.165-0.507-0.142-0.675%2C0.048%20%20%20c-0.174%2C0.198-0.153%2C0.501%2C0.045%2C0.676l3.883%2C3.375c0.09%2C0.075%2C0.198%2C0.115%2C0.312%2C0.115c0.141%2C0%2C0.273-0.061%2C0.362-0.166%20%20%20l3.371-3.877c0.173-0.2%2C0.151-0.502-0.047-0.675c-0.194-0.166-0.508-0.144-0.676%2C0.048l-2.592%2C2.979%20%20%20c-0.18-3.417-1.629-6.605-4.099-9.001c-2.538-2.461-5.877-3.817-9.404-3.817c-0.264%2C0-0.479%2C0.215-0.479%2C0.479%20%20%20C44.72%2C30.083%2C44.936%2C30.296%2C45.201%2C30.296z%22%3E%3C/path%3E%3C/g%3E%3C/svg%3E) center/50% 50% no-repeat rgba(244,244,244,1);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-orientation-modal:after{color:#666;content:\"Insert phone into Cardboard holder.\";display:block;position:absolute;text-align:center;top:70%;transform:translateY(-70%);width:100%}.a-orientation-modal button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%20100%20100%22%20enable-background%3D%22new%200%200%20100%20100%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M55.209%2C50l17.803-17.803c1.416-1.416%2C1.416-3.713%2C0-5.129c-1.416-1.417-3.713-1.417-5.129%2C0L50.08%2C44.872%20%20L32.278%2C27.069c-1.416-1.417-3.714-1.417-5.129%2C0c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129L44.951%2C50L27.149%2C67.803%20%20c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129c0.708%2C0.708%2C1.636%2C1.062%2C2.564%2C1.062c0.928%2C0%2C1.856-0.354%2C2.564-1.062L50.08%2C55.13l17.803%2C17.802%20%20c0.708%2C0.708%2C1.637%2C1.062%2C2.564%2C1.062s1.856-0.354%2C2.564-1.062c1.416-1.416%2C1.416-3.713%2C0-5.129L55.209%2C50z%22%3E%3C/path%3E%3C/svg%3E) no-repeat;border:none;height:50px;text-indent:-9999px;width:50px}.a-loader-title{background-color:rgba(0,0,0,.6);font-family:sans-serif,monospace;text-align:center;font-size:20px;height:50px;font-weight:300;line-height:50px;position:absolute;right:0;left:0;top:0;color:#fff}.a-modal{background:0 0/50% 50% rgba(0,0,0,.6);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-dialog{position:relative;left:50%;top:50%;transform:translate(-50%,-50%);z-index:199995;width:300px;height:200px;background-size:contain;background-color:#fff;font-family:sans-serif,monospace;font-size:20px;border-radius:3px;padding:6px}.a-dialog-text-container{width:100%;height:70%;align-self:flex-start;display:flex;justify-content:center;align-content:center;flex-direction:column}.a-dialog-text{display:inline-block;font-weight:400;font-size:14pt;margin:8px}.a-dialog-buttons-container{display:inline-flex;align-self:flex-end;width:100%;height:30%}.a-dialog-button{cursor:pointer;align-self:center;opacity:.9;height:80%;width:50%;font-size:12pt;margin:4px;border-radius:2px;text-align:center;border:none;display:inline-block;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;box-shadow:0 1px 3px rgba(0,0,0,.1),0 1px 2px rgba(0,0,0,.2);user-select:none}.a-dialog-permission-button:hover{box-shadow:0 7px 14px rgba(0,0,0,.2),0 2px 2px rgba(0,0,0,.2)}.a-dialog-allow-button{background-color:#00ceff}.a-dialog-deny-button{background-color:#ff005b}.a-dialog-ok-button{background-color:#00ceff;width:100%}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  59565. },{"browserify-css":4}],186:[function(_dereq_,module,exports){
  59566. var css = ".rs-base{background-color:#333;color:#fafafa;border-radius:0;font:10px monospace;left:5px;line-height:1em;opacity:.85;overflow:hidden;padding:10px;position:fixed;top:5px;width:300px;z-index:10000}.rs-base div.hidden{display:none}.rs-base h1{color:#fff;cursor:pointer;font-size:1.4em;font-weight:300;margin:0 0 5px;padding:0}.rs-group{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-direction:column-reverse;flex-direction:column-reverse;margin-bottom:5px}.rs-group:last-child{margin-bottom:0}.rs-counter-base{align-items:center;display:-webkit-box;display:-webkit-flex;display:flex;height:10px;-webkit-justify-content:space-between;justify-content:space-between;margin:2px 0}.rs-counter-base.alarm{color:#b70000;text-shadow:0 0 0 #b70000,0 0 1px #fff,0 0 1px #fff,0 0 2px #fff,0 0 2px #fff,0 0 3px #fff,0 0 3px #fff,0 0 4px #fff,0 0 4px #fff}.rs-counter-id{font-weight:300;-webkit-box-ordinal-group:0;-webkit-order:0;order:0;width:54px}.rs-counter-value{font-weight:300;-webkit-box-ordinal-group:1;-webkit-order:1;order:1;text-align:right;width:35px}.rs-canvas{-webkit-box-ordinal-group:2;-webkit-order:2;order:2}@media (min-width:480px){.rs-base{left:20px;top:20px}}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/rStats.css"})); module.exports = css;
  59567. },{"browserify-css":4}],187:[function(_dereq_,module,exports){
  59568. var constants = _dereq_('../constants/');
  59569. var registerSystem = _dereq_('../core/system').registerSystem;
  59570. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  59571. /**
  59572. * Camera system. Manages which camera is active among multiple cameras in scene.
  59573. *
  59574. * @member {object} activeCameraEl - Active camera entity.
  59575. */
  59576. module.exports.System = registerSystem('camera', {
  59577. init: function () {
  59578. this.activeCameraEl = null;
  59579. this.render = this.render.bind(this);
  59580. this.unwrapRender = this.unwrapRender.bind(this);
  59581. this.wrapRender = this.wrapRender.bind(this);
  59582. this.initialCameraFound = false;
  59583. this.numUserCameras = 0;
  59584. this.numUserCamerasChecked = 0;
  59585. this.setupInitialCamera();
  59586. },
  59587. /**
  59588. * Setup initial camera, either searching for camera or
  59589. * creating a default camera if user has not added one during the initial scene traversal.
  59590. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  59591. * loads.
  59592. *
  59593. * Default camera offset height is at average eye level (~1.6m).
  59594. */
  59595. setupInitialCamera: function () {
  59596. var cameraEls;
  59597. var i;
  59598. var sceneEl = this.sceneEl;
  59599. var self = this;
  59600. // Camera already defined or the one defined it is an spectator one.
  59601. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  59602. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  59603. return;
  59604. }
  59605. // Search for initial user-defined camera.
  59606. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  59607. // No user cameras, create default one.
  59608. if (!cameraEls.length) {
  59609. this.createDefaultCamera();
  59610. return;
  59611. }
  59612. this.numUserCameras = cameraEls.length;
  59613. for (i = 0; i < cameraEls.length; i++) {
  59614. cameraEls[i].addEventListener('object3dset', function (evt) {
  59615. if (evt.detail.type !== 'camera') { return; }
  59616. self.checkUserCamera(this);
  59617. });
  59618. // Load camera and wait for camera to initialize.
  59619. if (cameraEls[i].isNode) {
  59620. cameraEls[i].load();
  59621. } else {
  59622. cameraEls[i].addEventListener('nodeready', function () {
  59623. this.load();
  59624. });
  59625. }
  59626. }
  59627. },
  59628. /**
  59629. * Check if a user-defined camera entity is appropriate to be initial camera.
  59630. * (active + non-spectator).
  59631. *
  59632. * Keep track of the number of cameras we checked and whether we found one.
  59633. */
  59634. checkUserCamera: function (cameraEl) {
  59635. var cameraData;
  59636. var sceneEl = this.el.sceneEl;
  59637. this.numUserCamerasChecked++;
  59638. // Already found one.
  59639. if (this.initialCameraFound) { return; }
  59640. // Check if camera is appropriate for being the initial camera.
  59641. cameraData = cameraEl.getAttribute('camera');
  59642. if (!cameraData.active || cameraData.spectator) {
  59643. // No user cameras eligible, create default camera.
  59644. if (this.numUserCamerasChecked === this.numUserCameras) {
  59645. this.createDefaultCamera();
  59646. }
  59647. return;
  59648. }
  59649. this.initialCameraFound = true;
  59650. sceneEl.camera = cameraEl.getObject3D('camera');
  59651. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  59652. },
  59653. createDefaultCamera: function () {
  59654. var defaultCameraEl;
  59655. var sceneEl = this.sceneEl;
  59656. // Set up default camera.
  59657. defaultCameraEl = document.createElement('a-entity');
  59658. defaultCameraEl.setAttribute('camera', {active: true});
  59659. defaultCameraEl.setAttribute('position', {
  59660. x: 0,
  59661. y: constants.DEFAULT_CAMERA_HEIGHT,
  59662. z: 0
  59663. });
  59664. defaultCameraEl.setAttribute('wasd-controls', '');
  59665. defaultCameraEl.setAttribute('look-controls', '');
  59666. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  59667. defaultCameraEl.addEventListener('object3dset', function (evt) {
  59668. if (evt.detail.type !== 'camera') { return; }
  59669. sceneEl.camera = evt.detail.object;
  59670. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  59671. });
  59672. sceneEl.appendChild(defaultCameraEl);
  59673. },
  59674. /**
  59675. * Set a different active camera.
  59676. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  59677. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  59678. * the new camera.
  59679. */
  59680. disableActiveCamera: function () {
  59681. var cameraEls;
  59682. var newActiveCameraEl;
  59683. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  59684. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  59685. newActiveCameraEl.setAttribute('camera', 'active', true);
  59686. },
  59687. /**
  59688. * Set active camera to be used by renderer.
  59689. * Removes the default camera (if present).
  59690. * Disables all other cameras in the scene.
  59691. *
  59692. * @param {Element} newCameraEl - Entity with camera component.
  59693. */
  59694. setActiveCamera: function (newCameraEl) {
  59695. var cameraEl;
  59696. var cameraEls;
  59697. var i;
  59698. var newCamera;
  59699. var previousCamera = this.activeCameraEl;
  59700. var sceneEl = this.sceneEl;
  59701. // Same camera.
  59702. newCamera = newCameraEl.getObject3D('camera');
  59703. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  59704. // Grab the default camera.
  59705. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59706. var defaultCameraEl = defaultCameraWrapper &&
  59707. defaultCameraWrapper.querySelector('[camera]');
  59708. // Remove default camera if new camera is not the default camera.
  59709. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  59710. // Make new camera active.
  59711. this.activeCameraEl = newCameraEl;
  59712. this.activeCameraEl.play();
  59713. sceneEl.camera = newCamera;
  59714. // Disable current camera
  59715. if (previousCamera) {
  59716. previousCamera.setAttribute('camera', 'active', false);
  59717. }
  59718. // Disable other cameras in the scene
  59719. cameraEls = sceneEl.querySelectorAll('[camera]');
  59720. for (i = 0; i < cameraEls.length; i++) {
  59721. cameraEl = cameraEls[i];
  59722. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  59723. cameraEl.setAttribute('camera', 'active', false);
  59724. cameraEl.pause();
  59725. }
  59726. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  59727. },
  59728. /**
  59729. * Set spectator camera to render the scene on a 2D display.
  59730. *
  59731. * @param {Element} newCameraEl - Entity with camera component.
  59732. */
  59733. setSpectatorCamera: function (newCameraEl) {
  59734. var newCamera;
  59735. var previousCamera = this.spectatorCameraEl;
  59736. var sceneEl = this.sceneEl;
  59737. var spectatorCameraEl;
  59738. // Same camera.
  59739. newCamera = newCameraEl.getObject3D('camera');
  59740. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  59741. // Disable current camera
  59742. if (previousCamera) {
  59743. previousCamera.setAttribute('camera', 'spectator', false);
  59744. }
  59745. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  59746. sceneEl.addEventListener('enter-vr', this.wrapRender);
  59747. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  59748. spectatorCameraEl.setAttribute('camera', 'active', false);
  59749. spectatorCameraEl.play();
  59750. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  59751. },
  59752. /**
  59753. * Disables current spectator camera.
  59754. */
  59755. disableSpectatorCamera: function () {
  59756. this.spectatorCameraEl = undefined;
  59757. },
  59758. /**
  59759. * Wrap the render method of the renderer to render
  59760. * the spectator camera after vrDisplay.submitFrame.
  59761. */
  59762. wrapRender: function () {
  59763. if (!this.spectatorCameraEl || this.originalRender) { return; }
  59764. this.originalRender = this.sceneEl.renderer.render;
  59765. this.sceneEl.renderer.render = this.render;
  59766. },
  59767. unwrapRender: function () {
  59768. if (!this.originalRender) { return; }
  59769. this.sceneEl.renderer.render = this.originalRender;
  59770. this.originalRender = undefined;
  59771. },
  59772. render: function (scene, camera) {
  59773. var isVREnabled;
  59774. var sceneEl = this.sceneEl;
  59775. var spectatorCamera;
  59776. isVREnabled = sceneEl.renderer.xr.enabled;
  59777. this.originalRender.call(sceneEl.renderer, scene, camera);
  59778. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  59779. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  59780. sceneEl.renderer.xr.enabled = false;
  59781. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  59782. sceneEl.renderer.xr.enabled = isVREnabled;
  59783. }
  59784. });
  59785. /**
  59786. * Remove injected default camera from scene, if present.
  59787. *
  59788. * @param {Element} sceneEl
  59789. */
  59790. function removeDefaultCamera (sceneEl) {
  59791. var defaultCamera;
  59792. var camera = sceneEl.camera;
  59793. if (!camera) { return; }
  59794. // Remove default camera if present.
  59795. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59796. if (!defaultCamera) { return; }
  59797. sceneEl.removeChild(defaultCamera);
  59798. }
  59799. },{"../constants/":122,"../core/system":141}],188:[function(_dereq_,module,exports){
  59800. var geometries = _dereq_('../core/geometry').geometries;
  59801. var registerSystem = _dereq_('../core/system').registerSystem;
  59802. var THREE = _dereq_('../lib/three');
  59803. /**
  59804. * System for geometry component.
  59805. * Handle geometry caching.
  59806. *
  59807. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  59808. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  59809. * know whether to dispose on removal.
  59810. */
  59811. module.exports.System = registerSystem('geometry', {
  59812. init: function () {
  59813. this.cache = {};
  59814. this.cacheCount = {};
  59815. },
  59816. /**
  59817. * Reset cache. Mainly for testing.
  59818. */
  59819. clearCache: function () {
  59820. this.cache = {};
  59821. this.cacheCount = {};
  59822. },
  59823. /**
  59824. * Attempt to retrieve from cache.
  59825. *
  59826. * @returns {Object|null} A geometry if it exists, else null.
  59827. */
  59828. getOrCreateGeometry: function (data) {
  59829. var cache = this.cache;
  59830. var cachedGeometry;
  59831. var hash;
  59832. // Skip all caching logic.
  59833. if (data.skipCache) { return createGeometry(data); }
  59834. // Try to retrieve from cache first.
  59835. hash = this.hash(data);
  59836. cachedGeometry = cache[hash];
  59837. incrementCacheCount(this.cacheCount, hash);
  59838. if (cachedGeometry) { return cachedGeometry; }
  59839. // Create geometry.
  59840. cachedGeometry = createGeometry(data);
  59841. // Cache and return geometry.
  59842. cache[hash] = cachedGeometry;
  59843. return cachedGeometry;
  59844. },
  59845. /**
  59846. * Let system know that an entity is no longer using a geometry.
  59847. */
  59848. unuseGeometry: function (data) {
  59849. var cache = this.cache;
  59850. var cacheCount = this.cacheCount;
  59851. var geometry;
  59852. var hash;
  59853. if (data.skipCache) { return; }
  59854. hash = this.hash(data);
  59855. if (!cache[hash]) { return; }
  59856. decrementCacheCount(cacheCount, hash);
  59857. // Another entity is still using this geometry. No need to do anything.
  59858. if (cacheCount[hash] > 0) { return; }
  59859. // No more entities are using this geometry. Dispose.
  59860. geometry = cache[hash];
  59861. geometry.dispose();
  59862. delete cache[hash];
  59863. delete cacheCount[hash];
  59864. },
  59865. /**
  59866. * Use JSON.stringify to turn component data into hash.
  59867. * Should be deterministic within a single browser engine.
  59868. * If not, then look into json-stable-stringify.
  59869. */
  59870. hash: function (data) {
  59871. return JSON.stringify(data);
  59872. }
  59873. });
  59874. /**
  59875. * Create geometry using component data.
  59876. *
  59877. * @param {object} data - Component data.
  59878. * @returns {object} Geometry.
  59879. */
  59880. function createGeometry (data) {
  59881. var geometryType = data.primitive;
  59882. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  59883. var geometryInstance = new GeometryClass();
  59884. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  59885. geometryInstance.init(data);
  59886. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  59887. }
  59888. /**
  59889. * Decreate count of entity using a geometry.
  59890. */
  59891. function decrementCacheCount (cacheCount, hash) {
  59892. cacheCount[hash]--;
  59893. }
  59894. /**
  59895. * Increase count of entity using a geometry.
  59896. */
  59897. function incrementCacheCount (cacheCount, hash) {
  59898. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  59899. }
  59900. /**
  59901. * Transform geometry to BufferGeometry if `doBuffer`.
  59902. *
  59903. * @param {object} geometry
  59904. * @param {boolean} doBuffer
  59905. * @returns {object} Geometry.
  59906. */
  59907. function toBufferGeometry (geometry, doBuffer) {
  59908. var bufferGeometry;
  59909. if (!doBuffer) { return geometry; }
  59910. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  59911. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  59912. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  59913. return bufferGeometry;
  59914. }
  59915. },{"../core/geometry":131,"../core/system":141,"../lib/three":178}],189:[function(_dereq_,module,exports){
  59916. var registerSystem = _dereq_('../core/system').registerSystem;
  59917. var THREE = _dereq_('../lib/three');
  59918. /**
  59919. * glTF model system.
  59920. *
  59921. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  59922. * provided externally.
  59923. *
  59924. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  59925. */
  59926. module.exports.System = registerSystem('gltf-model', {
  59927. schema: {
  59928. dracoDecoderPath: {default: ''}
  59929. },
  59930. init: function () {
  59931. var path = this.data.dracoDecoderPath;
  59932. this.dracoLoader = new THREE.DRACOLoader();
  59933. this.dracoLoader.setDecoderPath(path);
  59934. },
  59935. update: function () {
  59936. var path;
  59937. if (this.dracoLoader) { return; }
  59938. path = this.data.dracoDecoderPath;
  59939. this.dracoLoader = new THREE.DRACOLoader();
  59940. this.dracoLoader.setDecoderPath(path);
  59941. },
  59942. getDRACOLoader: function () {
  59943. return this.dracoLoader;
  59944. }
  59945. });
  59946. },{"../core/system":141,"../lib/three":178}],190:[function(_dereq_,module,exports){
  59947. _dereq_('./camera');
  59948. _dereq_('./geometry');
  59949. _dereq_('./gltf-model');
  59950. _dereq_('./light');
  59951. _dereq_('./material');
  59952. _dereq_('./renderer');
  59953. _dereq_('./shadow');
  59954. _dereq_('./tracked-controls-webvr');
  59955. _dereq_('./tracked-controls-webxr');
  59956. _dereq_('./webxr');
  59957. },{"./camera":187,"./geometry":188,"./gltf-model":189,"./light":191,"./material":192,"./renderer":193,"./shadow":194,"./tracked-controls-webvr":195,"./tracked-controls-webxr":196,"./webxr":197}],191:[function(_dereq_,module,exports){
  59958. var registerSystem = _dereq_('../core/system').registerSystem;
  59959. var bind = _dereq_('../utils/bind');
  59960. var constants = _dereq_('../constants/');
  59961. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  59962. /**
  59963. * Light system.
  59964. *
  59965. * Prescribes default lighting if not specified (one ambient, one directional).
  59966. * Removes default lighting from the scene when a new light is added.
  59967. *
  59968. * @param {bool} defaultLights - Whether default lighting are defined.
  59969. * @param {bool} userDefinedLights - Whether user lighting is defined.
  59970. */
  59971. module.exports.System = registerSystem('light', {
  59972. schema: {
  59973. defaultLightsEnabled: {default: true}
  59974. },
  59975. init: function () {
  59976. this.defaultLights = false;
  59977. this.userDefinedLights = false;
  59978. // Wait for all entities to fully load before checking for existence of lights.
  59979. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  59980. // will do so asynchronously.
  59981. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  59982. },
  59983. /**
  59984. * Notify scene that light has been added and to remove the default.
  59985. *
  59986. * @param {object} el - element holding the light component.
  59987. */
  59988. registerLight: function (el) {
  59989. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  59990. // User added a light, remove default lights through DOM.
  59991. this.removeDefaultLights();
  59992. this.userDefinedLights = true;
  59993. }
  59994. },
  59995. removeDefaultLights: function () {
  59996. var defaultLights;
  59997. var sceneEl = this.sceneEl;
  59998. if (!this.defaultLights) { return; }
  59999. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  60000. for (var i = 0; i < defaultLights.length; i++) {
  60001. sceneEl.removeChild(defaultLights[i]);
  60002. }
  60003. this.defaultLights = false;
  60004. },
  60005. /**
  60006. * Prescibe default lights to the scene.
  60007. * Does so by injecting markup such that this state is not invisible.
  60008. * These lights are removed if the user adds any lights.
  60009. */
  60010. setupDefaultLights: function () {
  60011. var sceneEl = this.sceneEl;
  60012. var ambientLight;
  60013. var directionalLight;
  60014. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  60015. return;
  60016. }
  60017. ambientLight = document.createElement('a-entity');
  60018. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  60019. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  60020. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  60021. sceneEl.appendChild(ambientLight);
  60022. directionalLight = document.createElement('a-entity');
  60023. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  60024. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  60025. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  60026. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  60027. sceneEl.appendChild(directionalLight);
  60028. this.defaultLights = true;
  60029. }
  60030. });
  60031. },{"../constants/":122,"../core/system":141,"../utils/bind":198}],192:[function(_dereq_,module,exports){
  60032. var registerSystem = _dereq_('../core/system').registerSystem;
  60033. var THREE = _dereq_('../lib/three');
  60034. var utils = _dereq_('../utils/');
  60035. var isHLS = _dereq_('../utils/material').isHLS;
  60036. var bind = utils.bind;
  60037. var debug = utils.debug;
  60038. var error = debug('components:texture:error');
  60039. var TextureLoader = new THREE.TextureLoader();
  60040. var warn = debug('components:texture:warn');
  60041. TextureLoader.setCrossOrigin('anonymous');
  60042. /**
  60043. * System for material component.
  60044. * Handle material registration, updates (for fog), and texture caching.
  60045. *
  60046. * @member {object} materials - Registered materials.
  60047. * @member {object} textureCounts - Number of times each texture is used. Tracked
  60048. * separately from textureCache, because the cache (1) is populated in
  60049. * multiple places, and (2) may be cleared at any time.
  60050. * @member {object} textureCache - Texture cache for:
  60051. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  60052. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  60053. */
  60054. module.exports.System = registerSystem('material', {
  60055. init: function () {
  60056. this.materials = {};
  60057. this.textureCounts = {};
  60058. this.textureCache = {};
  60059. this.sceneEl.addEventListener(
  60060. 'materialtextureloaded',
  60061. bind(this.onMaterialTextureLoaded, this)
  60062. );
  60063. },
  60064. clearTextureCache: function () {
  60065. this.textureCache = {};
  60066. },
  60067. /**
  60068. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  60069. *
  60070. * @param {string, or element} src - Texture URL or element.
  60071. * @param {string} data - Relevant texture data used for caching.
  60072. * @param {function} cb - Callback to pass texture to.
  60073. */
  60074. loadTexture: function (src, data, cb) {
  60075. var self = this;
  60076. // Canvas.
  60077. if (src.tagName === 'CANVAS') {
  60078. this.loadCanvas(src, data, cb);
  60079. return;
  60080. }
  60081. // Video element.
  60082. if (src.tagName === 'VIDEO') {
  60083. if (!src.src && !src.srcObject && !src.childElementCount) {
  60084. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  60085. }
  60086. this.loadVideo(src, data, cb);
  60087. return;
  60088. }
  60089. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  60090. function loadImageCb (src) { self.loadImage(src, data, cb); }
  60091. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  60092. },
  60093. /**
  60094. * High-level function for loading image textures (THREE.Texture).
  60095. *
  60096. * @param {Element|string} src - Texture source.
  60097. * @param {object} data - Texture data.
  60098. * @param {function} cb - Callback to pass texture to.
  60099. */
  60100. loadImage: function (src, data, handleImageTextureLoaded) {
  60101. var hash = this.hash(data);
  60102. var textureCache = this.textureCache;
  60103. // Texture already being loaded or already loaded. Wait on promise.
  60104. if (textureCache[hash]) {
  60105. textureCache[hash].then(handleImageTextureLoaded);
  60106. return;
  60107. }
  60108. // Texture not yet being loaded. Start loading it.
  60109. textureCache[hash] = loadImageTexture(src, data);
  60110. textureCache[hash].then(handleImageTextureLoaded);
  60111. },
  60112. /**
  60113. * High-level function for loading canvas textures (THREE.Texture).
  60114. *
  60115. * @param {Element|string} src - Texture source.
  60116. * @param {object} data - Texture data.
  60117. * @param {function} cb - Callback to pass texture to.
  60118. */
  60119. loadCanvas: function (src, data, cb) {
  60120. var texture;
  60121. texture = new THREE.CanvasTexture(src);
  60122. setTextureProperties(texture, data);
  60123. cb(texture);
  60124. },
  60125. /**
  60126. * Load video texture (THREE.VideoTexture).
  60127. * Which is just an image texture that RAFs + needsUpdate.
  60128. * Note that creating a video texture is synchronous unlike loading an image texture.
  60129. * Made asynchronous to be consistent with image textures.
  60130. *
  60131. * @param {Element|string} src - Texture source.
  60132. * @param {object} data - Texture data.
  60133. * @param {function} cb - Callback to pass texture to.
  60134. */
  60135. loadVideo: function (src, data, cb) {
  60136. var hash;
  60137. var texture;
  60138. var textureCache = this.textureCache;
  60139. var videoEl;
  60140. var videoTextureResult;
  60141. function handleVideoTextureLoaded (result) {
  60142. result.texture.needsUpdate = true;
  60143. cb(result.texture, result.videoEl);
  60144. }
  60145. // Video element provided.
  60146. if (typeof src !== 'string') {
  60147. // Check cache before creating texture.
  60148. videoEl = src;
  60149. hash = this.hashVideo(data, videoEl);
  60150. if (textureCache[hash]) {
  60151. textureCache[hash].then(handleVideoTextureLoaded);
  60152. return;
  60153. }
  60154. // If not in cache, fix up the attributes then start to create the texture.
  60155. fixVideoAttributes(videoEl);
  60156. }
  60157. // Only URL provided. Use video element to create texture.
  60158. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  60159. // Generated video element already cached. Use that.
  60160. hash = this.hashVideo(data, videoEl);
  60161. if (textureCache[hash]) {
  60162. textureCache[hash].then(handleVideoTextureLoaded);
  60163. return;
  60164. }
  60165. // Create new video texture.
  60166. texture = new THREE.VideoTexture(videoEl);
  60167. texture.minFilter = THREE.LinearFilter;
  60168. setTextureProperties(texture, data);
  60169. // If iOS and video is HLS, do some hacks.
  60170. if (this.sceneEl.isIOS &&
  60171. isHLS(videoEl.src || videoEl.getAttribute('src'),
  60172. videoEl.type || videoEl.getAttribute('type'))) {
  60173. // Actually BGRA. Tell shader to correct later.
  60174. texture.format = THREE.RGBAFormat;
  60175. texture.needsCorrectionBGRA = true;
  60176. // Apparently needed for HLS. Tell shader to correct later.
  60177. texture.flipY = false;
  60178. texture.needsCorrectionFlipY = true;
  60179. }
  60180. // Cache as promise to be consistent with image texture caching.
  60181. videoTextureResult = {texture: texture, videoEl: videoEl};
  60182. textureCache[hash] = Promise.resolve(videoTextureResult);
  60183. handleVideoTextureLoaded(videoTextureResult);
  60184. },
  60185. /**
  60186. * Create a hash of the material properties for texture cache key.
  60187. */
  60188. hash: function (data) {
  60189. if (data.src.tagName) {
  60190. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  60191. data = utils.extendDeep({}, data);
  60192. data.src = data.src.src;
  60193. }
  60194. return JSON.stringify(data);
  60195. },
  60196. hashVideo: function (data, videoEl) {
  60197. return calculateVideoCacheHash(data, videoEl);
  60198. },
  60199. /**
  60200. * Keep track of material in case an update trigger is needed (e.g., fog).
  60201. *
  60202. * @param {object} material
  60203. */
  60204. registerMaterial: function (material) {
  60205. this.materials[material.uuid] = material;
  60206. },
  60207. /**
  60208. * Stop tracking material, and dispose of any textures not being used by
  60209. * another material component.
  60210. *
  60211. * @param {object} material
  60212. */
  60213. unregisterMaterial: function (material) {
  60214. delete this.materials[material.uuid];
  60215. // If any textures on this material are no longer in use, dispose of them.
  60216. var textureCounts = this.textureCounts;
  60217. Object.keys(material)
  60218. .filter(function (propName) {
  60219. return material[propName] && material[propName].isTexture;
  60220. })
  60221. .forEach(function (mapName) {
  60222. textureCounts[material[mapName].uuid]--;
  60223. if (textureCounts[material[mapName].uuid] <= 0) {
  60224. material[mapName].dispose();
  60225. }
  60226. });
  60227. },
  60228. /**
  60229. * Trigger update to all registered materials.
  60230. */
  60231. updateMaterials: function (material) {
  60232. var materials = this.materials;
  60233. Object.keys(materials).forEach(function (uuid) {
  60234. materials[uuid].needsUpdate = true;
  60235. });
  60236. },
  60237. /**
  60238. * Track textures used by material components, so that they can be safely
  60239. * disposed when no longer in use. Textures must be registered here, and not
  60240. * through registerMaterial(), because textures may not be attached at the
  60241. * time the material is registered.
  60242. *
  60243. * @param {Event} e
  60244. */
  60245. onMaterialTextureLoaded: function (e) {
  60246. if (!this.textureCounts[e.detail.texture.uuid]) {
  60247. this.textureCounts[e.detail.texture.uuid] = 0;
  60248. }
  60249. this.textureCounts[e.detail.texture.uuid]++;
  60250. }
  60251. });
  60252. /**
  60253. * Calculates consistent hash from a video element using its attributes.
  60254. * If the video element has an ID, use that.
  60255. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  60256. *
  60257. * @param data {object} - Texture data such as repeat.
  60258. * @param videoEl {Element} - Video element.
  60259. * @returns {string}
  60260. */
  60261. function calculateVideoCacheHash (data, videoEl) {
  60262. var i;
  60263. var id = videoEl.getAttribute('id');
  60264. var hash;
  60265. var videoAttributes;
  60266. if (id) { return id; }
  60267. // Calculate hash using sorted video attributes.
  60268. hash = '';
  60269. videoAttributes = data || {};
  60270. for (i = 0; i < videoEl.attributes.length; i++) {
  60271. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  60272. }
  60273. Object.keys(videoAttributes).sort().forEach(function (name) {
  60274. hash += name + ':' + videoAttributes[name] + ';';
  60275. });
  60276. return hash;
  60277. }
  60278. /**
  60279. * Load image texture.
  60280. *
  60281. * @private
  60282. * @param {string|object} src - An <img> element or url to an image file.
  60283. * @param {object} data - Data to set texture properties like `repeat`.
  60284. * @returns {Promise} Resolves once texture is loaded.
  60285. */
  60286. function loadImageTexture (src, data) {
  60287. return new Promise(doLoadImageTexture);
  60288. function doLoadImageTexture (resolve, reject) {
  60289. var isEl = typeof src !== 'string';
  60290. function resolveTexture (texture) {
  60291. setTextureProperties(texture, data);
  60292. texture.needsUpdate = true;
  60293. resolve(texture);
  60294. }
  60295. // Create texture from an element.
  60296. if (isEl) {
  60297. resolveTexture(new THREE.Texture(src));
  60298. return;
  60299. }
  60300. // Request and load texture from src string. THREE will create underlying element.
  60301. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  60302. TextureLoader.load(
  60303. src,
  60304. resolveTexture,
  60305. function () { /* no-op */ },
  60306. function (xhr) {
  60307. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  60308. xhr.statusText);
  60309. }
  60310. );
  60311. }
  60312. }
  60313. /**
  60314. * Set texture properties such as repeat and offset.
  60315. *
  60316. * @param {object} data - With keys like `repeat`.
  60317. */
  60318. function setTextureProperties (texture, data) {
  60319. var offset = data.offset || {x: 0, y: 0};
  60320. var repeat = data.repeat || {x: 1, y: 1};
  60321. var npot = data.npot || false;
  60322. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  60323. // and filters must not use mipmaps (i.e. Nearest or Linear).
  60324. if (npot) {
  60325. texture.wrapS = THREE.ClampToEdgeWrapping;
  60326. texture.wrapT = THREE.ClampToEdgeWrapping;
  60327. texture.magFilter = THREE.LinearFilter;
  60328. texture.minFilter = THREE.LinearFilter;
  60329. }
  60330. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  60331. if (repeat.x !== 1 || repeat.y !== 1) {
  60332. texture.wrapS = THREE.RepeatWrapping;
  60333. texture.wrapT = THREE.RepeatWrapping;
  60334. texture.repeat.set(repeat.x, repeat.y);
  60335. }
  60336. // Don't bother setting offset if it is 0/0.
  60337. if (offset.x !== 0 || offset.y !== 0) {
  60338. texture.offset.set(offset.x, offset.y);
  60339. }
  60340. }
  60341. /**
  60342. * Create video element to be used as a texture.
  60343. *
  60344. * @param {string} src - Url to a video file.
  60345. * @param {number} width - Width of the video.
  60346. * @param {number} height - Height of the video.
  60347. * @returns {Element} Video element.
  60348. */
  60349. function createVideoEl (src, width, height) {
  60350. var videoEl = document.createElement('video');
  60351. videoEl.width = width;
  60352. videoEl.height = height;
  60353. // Support inline videos for iOS webviews.
  60354. videoEl.setAttribute('playsinline', '');
  60355. videoEl.setAttribute('webkit-playsinline', '');
  60356. videoEl.autoplay = true;
  60357. videoEl.loop = true;
  60358. videoEl.crossOrigin = 'anonymous';
  60359. videoEl.addEventListener('error', function () {
  60360. warn('`$s` is not a valid video', src);
  60361. }, true);
  60362. videoEl.src = src;
  60363. return videoEl;
  60364. }
  60365. /**
  60366. * Fixes a video element's attributes to prevent developers from accidentally passing the
  60367. * wrong attribute values to commonly misused video attributes.
  60368. *
  60369. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  60370. * as booleans. Existence of those attributes will mean truthy.
  60371. *
  60372. * For example, translates <video loop="false"> to <video>.
  60373. *
  60374. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  60375. * @param {Element} videoEl - Video element.
  60376. * @returns {Element} Video element with the correct properties updated.
  60377. */
  60378. function fixVideoAttributes (videoEl) {
  60379. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  60380. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  60381. if (videoEl.getAttribute('loop') === 'false') {
  60382. videoEl.removeAttribute('loop');
  60383. }
  60384. if (videoEl.getAttribute('preload') === 'false') {
  60385. videoEl.preload = 'none';
  60386. }
  60387. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  60388. // To support inline videos in iOS webviews.
  60389. videoEl.setAttribute('playsinline', '');
  60390. videoEl.setAttribute('webkit-playsinline', '');
  60391. return videoEl;
  60392. }
  60393. },{"../core/system":141,"../lib/three":178,"../utils/":204,"../utils/material":208}],193:[function(_dereq_,module,exports){
  60394. var registerSystem = _dereq_('../core/system').registerSystem;
  60395. var utils = _dereq_('../utils/');
  60396. var THREE = _dereq_('../lib/three');
  60397. var debug = utils.debug;
  60398. var warn = debug('components:renderer:warn');
  60399. /**
  60400. * Determines state of various renderer properties.
  60401. */
  60402. module.exports.System = registerSystem('renderer', {
  60403. schema: {
  60404. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60405. highRefreshRate: {default: utils.device.isOculusBrowser()},
  60406. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60407. maxCanvasWidth: {default: 1920},
  60408. maxCanvasHeight: {default: 1920},
  60409. physicallyCorrectLights: {default: false},
  60410. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  60411. sortObjects: {default: false},
  60412. colorManagement: {default: false},
  60413. gammaOutput: {default: false},
  60414. alpha: {default: true},
  60415. foveationLevel: {default: 0}
  60416. },
  60417. init: function () {
  60418. var data = this.data;
  60419. var sceneEl = this.el;
  60420. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  60421. var renderer = sceneEl.renderer;
  60422. renderer.sortObjects = data.sortObjects;
  60423. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  60424. if (data.colorManagement || data.gammaOutput) {
  60425. renderer.outputEncoding = THREE.sRGBEncoding;
  60426. if (data.gammaOutput) {
  60427. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  60428. }
  60429. }
  60430. if (sceneEl.hasAttribute('antialias')) {
  60431. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  60432. }
  60433. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  60434. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  60435. }
  60436. },
  60437. applyColorCorrection: function (colorOrTexture) {
  60438. if (!this.data.colorManagement || !colorOrTexture) {
  60439. return;
  60440. } else if (colorOrTexture.isColor) {
  60441. colorOrTexture.convertSRGBToLinear();
  60442. } else if (colorOrTexture.isTexture) {
  60443. colorOrTexture.encoding = THREE.sRGBEncoding;
  60444. }
  60445. }
  60446. });
  60447. },{"../core/system":141,"../lib/three":178,"../utils/":204}],194:[function(_dereq_,module,exports){
  60448. var registerSystem = _dereq_('../core/system').registerSystem;
  60449. var THREE = _dereq_('../lib/three');
  60450. var SHADOW_MAP_TYPE_MAP = {
  60451. basic: THREE.BasicShadowMap,
  60452. pcf: THREE.PCFShadowMap,
  60453. pcfsoft: THREE.PCFSoftShadowMap
  60454. };
  60455. /**
  60456. * Shadow system.
  60457. *
  60458. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  60459. * options on the WebGLRenderer for configuring shadow appearance.
  60460. */
  60461. module.exports.System = registerSystem('shadow', {
  60462. schema: {
  60463. enabled: {default: true},
  60464. autoUpdate: {default: true},
  60465. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  60466. },
  60467. init: function () {
  60468. var sceneEl = this.sceneEl;
  60469. var data = this.data;
  60470. this.shadowMapEnabled = false;
  60471. if (!sceneEl.renderer) { return; } // For tests.
  60472. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  60473. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  60474. this.setShadowMapEnabled(this.shadowMapEnabled);
  60475. },
  60476. update: function (prevData) {
  60477. if (prevData.enabled !== this.data.enabled) {
  60478. this.setShadowMapEnabled(this.data.enabled);
  60479. }
  60480. },
  60481. /**
  60482. * Enables/disables the renderer shadow map.
  60483. * @param {boolean} enabled
  60484. */
  60485. setShadowMapEnabled: function (enabled) {
  60486. var renderer = this.sceneEl.renderer;
  60487. this.shadowMapEnabled = this.data.enabled && enabled;
  60488. if (renderer) {
  60489. renderer.shadowMap.enabled = this.shadowMapEnabled;
  60490. }
  60491. }
  60492. });
  60493. },{"../core/system":141,"../lib/three":178}],195:[function(_dereq_,module,exports){
  60494. var registerSystem = _dereq_('../core/system').registerSystem;
  60495. var utils = _dereq_('../utils');
  60496. var isWebXRAvailable = utils.device.isWebXRAvailable;
  60497. /**
  60498. * Tracked controls system.
  60499. * Maintain list with available tracked controllers.
  60500. */
  60501. module.exports.System = registerSystem('tracked-controls-webvr', {
  60502. init: function () {
  60503. var self = this;
  60504. this.controllers = [];
  60505. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  60506. this.updateControllerList();
  60507. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60508. // Don't use WebVR if WebXR is available?
  60509. if (isWebXRAvailable) { return; }
  60510. if (!navigator.getVRDisplays) { return; }
  60511. this.sceneEl.addEventListener('enter-vr', function () {
  60512. navigator.getVRDisplays().then(function (displays) {
  60513. if (displays.length) { self.vrDisplay = displays[0]; }
  60514. });
  60515. });
  60516. },
  60517. tick: function () {
  60518. if (this.isChrome) {
  60519. // Retrieve new controller handlers with updated state (pose, buttons...)
  60520. this.updateControllerList();
  60521. } else {
  60522. this.throttledUpdateControllerList();
  60523. }
  60524. },
  60525. /**
  60526. * Update controller list.
  60527. */
  60528. updateControllerList: function () {
  60529. var controllers = this.controllers;
  60530. var gamepad;
  60531. var gamepads;
  60532. var i;
  60533. var prevCount;
  60534. gamepads = navigator.getGamepads && navigator.getGamepads();
  60535. if (!gamepads) { return; }
  60536. prevCount = controllers.length;
  60537. controllers.length = 0;
  60538. for (i = 0; i < gamepads.length; ++i) {
  60539. gamepad = gamepads[i];
  60540. if (gamepad && gamepad.pose) {
  60541. controllers.push(gamepad);
  60542. }
  60543. }
  60544. if (controllers.length !== prevCount) {
  60545. this.el.emit('controllersupdated', undefined, false);
  60546. }
  60547. }
  60548. });
  60549. },{"../core/system":141,"../utils":204}],196:[function(_dereq_,module,exports){
  60550. var registerSystem = _dereq_('../core/system').registerSystem;
  60551. var utils = _dereq_('../utils');
  60552. /**
  60553. * Tracked controls system.
  60554. * Maintain list with available tracked controllers.
  60555. */
  60556. module.exports.System = registerSystem('tracked-controls-webxr', {
  60557. init: function () {
  60558. this.controllers = [];
  60559. this.oldControllers = [];
  60560. this.oldControllersLength = 0;
  60561. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60562. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  60563. this.el.addEventListener('enter-vr', this.updateReferenceSpace);
  60564. this.el.addEventListener('exit-vr', this.updateReferenceSpace);
  60565. },
  60566. tick: function () {
  60567. this.throttledUpdateControllerList();
  60568. },
  60569. updateReferenceSpace: function () {
  60570. var self = this;
  60571. var xrSession = this.el.xrSession;
  60572. if (!xrSession) {
  60573. this.referenceSpace = undefined;
  60574. this.controllers = [];
  60575. if (this.oldControllersLength > 0) {
  60576. this.oldControllersLength = 0;
  60577. this.el.emit('controllersupdated', undefined, false);
  60578. }
  60579. return;
  60580. }
  60581. var refspace = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  60582. xrSession.requestReferenceSpace(refspace).then(function (referenceSpace) {
  60583. self.referenceSpace = referenceSpace;
  60584. }).catch(function (err) {
  60585. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(
  60586. refspace,
  60587. 'tracked-controls-webxr uses reference space "' + refspace + '".');
  60588. throw err;
  60589. });
  60590. },
  60591. updateControllerList: function () {
  60592. var xrSession = this.el.xrSession;
  60593. var oldControllers = this.oldControllers;
  60594. var i;
  60595. if (!xrSession) {
  60596. if (this.oldControllersLength === 0) { return; }
  60597. // Broadcast that we now have zero controllers connected if there is
  60598. // no session
  60599. this.oldControllersLength = 0;
  60600. this.controllers = [];
  60601. this.el.emit('controllersupdated', undefined, false);
  60602. return;
  60603. }
  60604. if (!xrSession.inputSources) { return; }
  60605. this.controllers = xrSession.inputSources;
  60606. if (this.oldControllersLength === this.controllers.length) {
  60607. var equal = true;
  60608. for (i = 0; i < this.controllers.length; ++i) {
  60609. if (this.controllers[i] === oldControllers[i] &&
  60610. this.controllers[i].gamepad === oldControllers[i].gamepad) { continue; }
  60611. equal = false;
  60612. break;
  60613. }
  60614. if (equal) { return; }
  60615. }
  60616. // Store reference to current controllers
  60617. oldControllers.length = 0;
  60618. for (i = 0; i < this.controllers.length; i++) {
  60619. oldControllers.push(this.controllers[i]);
  60620. }
  60621. this.oldControllersLength = this.controllers.length;
  60622. this.el.emit('controllersupdated', undefined, false);
  60623. }
  60624. });
  60625. },{"../core/system":141,"../utils":204}],197:[function(_dereq_,module,exports){
  60626. var registerSystem = _dereq_('../core/system').registerSystem;
  60627. var utils = _dereq_('../utils/');
  60628. var warn = utils.debug('systems:webxr:warn');
  60629. /**
  60630. * WebXR session initialization and XR module support.
  60631. */
  60632. module.exports.System = registerSystem('webxr', {
  60633. schema: {
  60634. referenceSpaceType: {type: 'string', default: 'local-floor'},
  60635. requiredFeatures: {type: 'array', default: ['local-floor']},
  60636. optionalFeatures: {type: 'array', default: ['bounded-floor']},
  60637. overlayElement: {type: 'selector'}
  60638. },
  60639. update: function () {
  60640. var data = this.data;
  60641. this.sessionConfiguration = {
  60642. requiredFeatures: data.requiredFeatures,
  60643. optionalFeatures: data.optionalFeatures
  60644. };
  60645. this.sessionReferenceSpaceType = data.referenceSpaceType;
  60646. if (data.overlayElement) {
  60647. this.warnIfFeatureNotRequested('dom-overlay');
  60648. this.sessionConfiguration.domOverlay = {root: data.overlayElement};
  60649. }
  60650. },
  60651. wasFeatureRequested: function (feature) {
  60652. // Features available by default for immersive sessions don't need to
  60653. // be requested explicitly.
  60654. if (feature === 'viewer' || feature === 'local') return true;
  60655. if (this.sessionConfiguration.requiredFeatures.includes(feature) ||
  60656. this.sessionConfiguration.optionalFeatures.includes(feature)) {
  60657. return true;
  60658. }
  60659. return false;
  60660. },
  60661. warnIfFeatureNotRequested: function (feature, optIntro) {
  60662. if (!this.wasFeatureRequested(feature)) {
  60663. var msg = 'Please add the feature "' + feature + '" to a-scene\'s ' +
  60664. 'webxr system options in requiredFeatures/optionalFeatures.';
  60665. warn((optIntro ? optIntro + ' ' : '') + msg);
  60666. }
  60667. }
  60668. });
  60669. },{"../core/system":141,"../utils/":204}],198:[function(_dereq_,module,exports){
  60670. /**
  60671. * Faster version of Function.prototype.bind
  60672. * @param {Function} fn - Function to wrap.
  60673. * @param {Object} ctx - What to bind as context.
  60674. * @param {...*} arguments - Arguments to pass through.
  60675. */
  60676. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  60677. return (function (prependedArgs) {
  60678. return function bound () {
  60679. // Concat the bound function arguments with those passed to original bind
  60680. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  60681. return fn.apply(ctx, args);
  60682. };
  60683. })(Array.prototype.slice.call(arguments, 2));
  60684. };
  60685. },{}],199:[function(_dereq_,module,exports){
  60686. /* global THREE */
  60687. var debug = _dereq_('./debug');
  60688. var extend = _dereq_('object-assign');
  60689. var warn = debug('utils:coordinates:warn');
  60690. // Order of coordinates parsed by coordinates.parse.
  60691. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  60692. // Coordinate string regex. Handles negative, positive, and decimals.
  60693. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  60694. module.exports.regex = regex;
  60695. var OBJECT = 'object';
  60696. var whitespaceRegex = /\s+/g;
  60697. /**
  60698. * Parses coordinates from an "x y z" string.
  60699. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  60700. *
  60701. * @param {string} val - An "x y z" string.
  60702. * @param {string} defaults - fallback value.
  60703. * @returns {object} An object with keys [x, y, z].
  60704. */
  60705. function parse (value, defaultVec) {
  60706. var coordinate;
  60707. var defaultVal;
  60708. var key;
  60709. var i;
  60710. var vec;
  60711. var x;
  60712. var y;
  60713. var z;
  60714. var w;
  60715. if (value && value instanceof Object) {
  60716. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  60717. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  60718. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  60719. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  60720. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  60721. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  60722. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  60723. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  60724. return value;
  60725. }
  60726. if (value === null || value === undefined) {
  60727. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  60728. }
  60729. coordinate = value.trim().split(whitespaceRegex);
  60730. vec = {};
  60731. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  60732. key = COORDINATE_KEYS[i];
  60733. if (coordinate[i]) {
  60734. vec[key] = parseFloat(coordinate[i], 10);
  60735. } else {
  60736. defaultVal = defaultVec && defaultVec[key];
  60737. if (defaultVal === undefined) { continue; }
  60738. vec[key] = parseIfString(defaultVal);
  60739. }
  60740. }
  60741. return vec;
  60742. }
  60743. module.exports.parse = parse;
  60744. /**
  60745. * Stringify coordinates from an object with keys [x y z].
  60746. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  60747. *
  60748. * @param {object|string} data - An object with keys [x y z].
  60749. * @returns {string} An "x y z" string.
  60750. */
  60751. function stringify (data) {
  60752. var str;
  60753. if (typeof data !== OBJECT) { return data; }
  60754. str = data.x + ' ' + data.y;
  60755. if (data.z != null) { str += ' ' + data.z; }
  60756. if (data.w != null) { str += ' ' + data.w; }
  60757. return str;
  60758. }
  60759. module.exports.stringify = stringify;
  60760. /**
  60761. * @returns {bool}
  60762. */
  60763. function isCoordinates (value) {
  60764. return regex.test(value);
  60765. }
  60766. module.exports.isCoordinates = isCoordinates;
  60767. module.exports.isCoordinate = function (value) {
  60768. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  60769. return isCoordinates(value);
  60770. };
  60771. function parseIfString (val) {
  60772. if (val !== null && val !== undefined && val.constructor === String) {
  60773. return parseFloat(val, 10);
  60774. }
  60775. return val;
  60776. }
  60777. /**
  60778. * Convert {x, y, z} object to three.js Vector3.
  60779. */
  60780. module.exports.toVector3 = function (vec3) {
  60781. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  60782. };
  60783. },{"./debug":200,"object-assign":39}],200:[function(_dereq_,module,exports){
  60784. (function (process){
  60785. var debugLib = _dereq_('debug');
  60786. var extend = _dereq_('object-assign');
  60787. var settings = {
  60788. colors: {
  60789. debug: 'gray',
  60790. error: 'red',
  60791. info: 'gray',
  60792. warn: 'orange'
  60793. }
  60794. };
  60795. /**
  60796. * Monkeypatches `debug` so we can colorize error/warning messages.
  60797. *
  60798. * (See issue: https://github.com/visionmedia/debug/issues/137)
  60799. */
  60800. var debug = function (namespace) {
  60801. var d = debugLib(namespace);
  60802. d.color = getDebugNamespaceColor(namespace);
  60803. return d;
  60804. };
  60805. extend(debug, debugLib);
  60806. /**
  60807. * Returns the type of the namespace (e.g., `error`, `warn`).
  60808. *
  60809. * @param {String} namespace
  60810. * The debug logger's namespace (e.g., `components:geometry:warn`).
  60811. * @returns {String} The type of the namespace (e.g., `warn`).
  60812. * @api private
  60813. */
  60814. function getDebugNamespaceType (namespace) {
  60815. var chunks = namespace.split(':');
  60816. return chunks[chunks.length - 1]; // Return the last one
  60817. }
  60818. /**
  60819. * Returns the color of the namespace (e.g., `orange`).
  60820. *
  60821. * @param {String} namespace
  60822. * The debug logger's namespace (e.g., `components:geometry:warn`).
  60823. * @returns {String} The color of the namespace (e.g., `orange`).
  60824. * @api private
  60825. */
  60826. function getDebugNamespaceColor (namespace) {
  60827. var type = getDebugNamespaceType(namespace);
  60828. var color = settings.colors && settings.colors[type];
  60829. return color || null;
  60830. }
  60831. /**
  60832. * Returns `localStorage` if possible.
  60833. *
  60834. * This is necessary because Safari throws when a user disables
  60835. * cookies or `localStorage` and you attempt to access it.
  60836. *
  60837. * @returns {localStorage}
  60838. * @api private
  60839. */
  60840. function storage () {
  60841. try {
  60842. return window.localStorage;
  60843. } catch (e) {
  60844. }
  60845. }
  60846. /**
  60847. * To enable console logging, type this in the Console of your Dev Tools:
  60848. *
  60849. * localStorage.logs = 1
  60850. *
  60851. * To disable console logging:
  60852. *
  60853. * localStorage.logs = 0
  60854. *
  60855. */
  60856. var ls = storage();
  60857. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  60858. debug.enable('*');
  60859. } else {
  60860. debug.enable('*:error,*:info,*:warn');
  60861. }
  60862. if (process.browser) { window.logs = debug; }
  60863. module.exports = debug;
  60864. }).call(this,_dereq_('_process'))
  60865. },{"_process":49,"debug":8,"object-assign":39}],201:[function(_dereq_,module,exports){
  60866. (function (process){
  60867. var error = _dereq_('debug')('device:error');
  60868. var vrDisplay;
  60869. var supportsVRSession = false;
  60870. var supportsARSession = false;
  60871. /**
  60872. * Oculus Browser 7 doesn't support the WebXR gamepads module.
  60873. * We fallback to WebVR API and will hotfix when implementation is complete.
  60874. */
  60875. var isWebXRAvailable = module.exports.isWebXRAvailable = !window.debug && navigator.xr !== undefined;
  60876. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  60877. window.addEventListener('vrdisplayactivate', function (evt) {
  60878. var canvasEl;
  60879. // WebXR takes priority if available.
  60880. if (isWebXRAvailable) { return; }
  60881. canvasEl = document.createElement('canvas');
  60882. vrDisplay = evt.display;
  60883. // We need to make sure the canvas has a WebGL context associated with it.
  60884. // Otherwise, the requestPresent could be denied.
  60885. canvasEl.getContext('webgl', {});
  60886. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  60887. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  60888. });
  60889. // Support both WebVR and WebXR APIs.
  60890. if (isWebXRAvailable) {
  60891. var updateEnterInterfaces = function () {
  60892. var sceneEl = document.querySelector('a-scene');
  60893. if (!sceneEl) {
  60894. window.addEventListener('DOMContentLoaded', updateEnterInterfaces);
  60895. return;
  60896. }
  60897. if (sceneEl.hasLoaded) {
  60898. sceneEl.components['vr-mode-ui'].updateEnterInterfaces();
  60899. } else {
  60900. sceneEl.addEventListener('loaded', updateEnterInterfaces);
  60901. }
  60902. };
  60903. var errorHandler = function (err) {
  60904. error('WebXR session support error: ' + err.message);
  60905. };
  60906. if (navigator.xr.isSessionSupported) {
  60907. // Current WebXR spec uses a boolean-returning isSessionSupported promise
  60908. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  60909. supportsVRSession = supported;
  60910. updateEnterInterfaces();
  60911. }).catch(errorHandler);
  60912. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  60913. supportsARSession = supported;
  60914. updateEnterInterfaces();
  60915. }).catch(function () {});
  60916. } else if (navigator.xr.supportsSession) {
  60917. // Fallback for implementations that haven't updated to the new spec yet,
  60918. // the old version used supportsSession which is rejected for missing
  60919. // support.
  60920. navigator.xr.supportsSession('immersive-vr').then(function () {
  60921. supportsVRSession = true;
  60922. updateEnterInterfaces();
  60923. }).catch(errorHandler);
  60924. navigator.xr.supportsSession('immersive-ar').then(function () {
  60925. supportsARSession = true;
  60926. updateEnterInterfaces();
  60927. }).catch(function () {});
  60928. } else {
  60929. error('WebXR has neither isSessionSupported or supportsSession?!');
  60930. }
  60931. } else {
  60932. if (navigator.getVRDisplays) {
  60933. navigator.getVRDisplays().then(function (displays) {
  60934. var sceneEl = document.querySelector('a-scene');
  60935. vrDisplay = displays.length && displays[0];
  60936. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  60937. });
  60938. }
  60939. }
  60940. function getVRDisplay () { return vrDisplay; }
  60941. module.exports.getVRDisplay = getVRDisplay;
  60942. /**
  60943. * Determine if a headset is connected by checking if a vrDisplay is available.
  60944. */
  60945. function checkHeadsetConnected () {
  60946. return supportsVRSession || supportsARSession || !!getVRDisplay();
  60947. }
  60948. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  60949. function checkARSupport () { return supportsARSession; }
  60950. module.exports.checkARSupport = checkARSupport;
  60951. /**
  60952. * Checks if browser is mobile and not stand-alone dedicated vr device.
  60953. * @return {Boolean} True if mobile browser detected.
  60954. */
  60955. var isMobile = (function () {
  60956. var _isMobile = false;
  60957. (function (a) {
  60958. // eslint-disable-next-line no-useless-escape
  60959. if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
  60960. _isMobile = true;
  60961. }
  60962. if (isIOS() || isTablet() || isR7()) {
  60963. _isMobile = true;
  60964. }
  60965. if (isMobileVR()) {
  60966. _isMobile = false;
  60967. }
  60968. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  60969. return function () { return _isMobile; };
  60970. })();
  60971. module.exports.isMobile = isMobile;
  60972. /**
  60973. * Detect tablet devices.
  60974. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  60975. */
  60976. function isTablet (mockUserAgent) {
  60977. var userAgent = mockUserAgent || window.navigator.userAgent;
  60978. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  60979. }
  60980. module.exports.isTablet = isTablet;
  60981. function isIOS () {
  60982. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  60983. }
  60984. module.exports.isIOS = isIOS;
  60985. function isMobileDeviceRequestingDesktopSite () {
  60986. return !isMobile() && !isMobileVR() && window.orientation !== undefined;
  60987. }
  60988. module.exports.isMobileDeviceRequestingDesktopSite = isMobileDeviceRequestingDesktopSite;
  60989. /**
  60990. * Detect Oculus Browser (standalone headset)
  60991. */
  60992. function isOculusBrowser () {
  60993. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  60994. }
  60995. module.exports.isOculusBrowser = isOculusBrowser;
  60996. /**
  60997. * Detect Firefox Reality (standalone headset)
  60998. */
  60999. function isFirefoxReality () {
  61000. return /(Mobile VR)/i.test(window.navigator.userAgent);
  61001. }
  61002. module.exports.isFirefoxReality = isFirefoxReality;
  61003. /**
  61004. * Detect browsers in Stand-Alone headsets
  61005. */
  61006. function isMobileVR () {
  61007. return isOculusBrowser() || isFirefoxReality();
  61008. }
  61009. module.exports.isMobileVR = isMobileVR;
  61010. function isR7 () {
  61011. return /R7 Build/.test(window.navigator.userAgent);
  61012. }
  61013. module.exports.isR7 = isR7;
  61014. /**
  61015. * Checks mobile device orientation.
  61016. * @return {Boolean} True if landscape orientation.
  61017. */
  61018. module.exports.isLandscape = function () {
  61019. var orientation = window.orientation;
  61020. if (isR7()) { orientation += 90; }
  61021. return orientation === 90 || orientation === -90;
  61022. };
  61023. /**
  61024. * Check if running in a browser or spoofed browser (bundler).
  61025. * We need to check a node api that isn't mocked on either side.
  61026. * `require` and `module.exports` are mocked in browser by bundlers.
  61027. * `window` is mocked in node.
  61028. * `process` is also mocked by browserify, but has custom properties.
  61029. */
  61030. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  61031. /**
  61032. * Check if running in node on the server.
  61033. */
  61034. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  61035. }).call(this,_dereq_('_process'))
  61036. },{"_process":49,"debug":8}],202:[function(_dereq_,module,exports){
  61037. /**
  61038. * Split a delimited component property string (e.g., `material.color`) to an object
  61039. * containing `component` name and `property` name. If there is no delimiter, just return the
  61040. * string back.
  61041. *
  61042. * Cache arrays from splitting strings via delimiter to save on memory.
  61043. *
  61044. * @param {string} str - e.g., `material.opacity`.
  61045. * @param {string} delimiter - e.g., `.`.
  61046. * @returns {array} e.g., `['material', 'opacity']`.
  61047. */
  61048. var propertyPathCache = {};
  61049. function getComponentPropertyPath (str, delimiter) {
  61050. delimiter = delimiter || '.';
  61051. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  61052. if (str.indexOf(delimiter) !== -1) {
  61053. propertyPathCache[delimiter][str] = str.split(delimiter);
  61054. } else {
  61055. propertyPathCache[delimiter][str] = str;
  61056. }
  61057. return propertyPathCache[delimiter][str];
  61058. }
  61059. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  61060. module.exports.propertyPathCache = propertyPathCache;
  61061. /**
  61062. * Get component property using encoded component name + component property name with a
  61063. * delimiter.
  61064. */
  61065. module.exports.getComponentProperty = function (el, name, delimiter) {
  61066. var splitName;
  61067. delimiter = delimiter || '.';
  61068. if (name.indexOf(delimiter) !== -1) {
  61069. splitName = getComponentPropertyPath(name, delimiter);
  61070. if (splitName.constructor === String) {
  61071. return el.getAttribute(splitName);
  61072. }
  61073. return el.getAttribute(splitName[0])[splitName[1]];
  61074. }
  61075. return el.getAttribute(name);
  61076. };
  61077. /**
  61078. * Set component property using encoded component name + component property name with a
  61079. * delimiter.
  61080. */
  61081. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  61082. var splitName;
  61083. delimiter = delimiter || '.';
  61084. if (name.indexOf(delimiter) !== -1) {
  61085. splitName = getComponentPropertyPath(name, delimiter);
  61086. if (splitName.constructor === String) {
  61087. el.setAttribute(splitName, value);
  61088. } else {
  61089. el.setAttribute(splitName[0], splitName[1], value);
  61090. }
  61091. return;
  61092. }
  61093. el.setAttribute(name, value);
  61094. };
  61095. },{}],203:[function(_dereq_,module,exports){
  61096. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  61097. var width = canvasEl.style.width;
  61098. var height = canvasEl.style.height;
  61099. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  61100. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  61101. // By changing the size 1 pixel and restoring the previous value
  61102. // we trigger a size recalculation cycle.
  61103. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  61104. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  61105. setTimeout(function () {
  61106. canvasEl.style.width = width;
  61107. canvasEl.style.height = height;
  61108. }, 200);
  61109. };
  61110. },{}],204:[function(_dereq_,module,exports){
  61111. /* global location */
  61112. /* Centralized place to reference utilities since utils is exposed to the user. */
  61113. var debug = _dereq_('./debug');
  61114. var deepAssign = _dereq_('deep-assign');
  61115. var device = _dereq_('./device');
  61116. var objectAssign = _dereq_('object-assign');
  61117. var objectPool = _dereq_('./object-pool');
  61118. var warn = debug('utils:warn');
  61119. module.exports.bind = _dereq_('./bind');
  61120. module.exports.coordinates = _dereq_('./coordinates');
  61121. module.exports.debug = debug;
  61122. module.exports.device = device;
  61123. module.exports.entity = _dereq_('./entity');
  61124. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  61125. module.exports.isIE11 = _dereq_('./is-ie11');
  61126. module.exports.material = _dereq_('./material');
  61127. module.exports.objectPool = objectPool;
  61128. module.exports.split = _dereq_('./split').split;
  61129. module.exports.styleParser = _dereq_('./styleParser');
  61130. module.exports.trackedControls = _dereq_('./tracked-controls');
  61131. module.exports.checkHeadsetConnected = function () {
  61132. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  61133. return device.checkHeadsetConnected(arguments);
  61134. };
  61135. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  61136. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  61137. };
  61138. module.exports.isIOS = function () {
  61139. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  61140. return device.isIOS(arguments);
  61141. };
  61142. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  61143. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  61144. };
  61145. module.exports.isMobile = function () {
  61146. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  61147. return device.isMobile(arguments);
  61148. };
  61149. /**
  61150. * Returns throttle function that gets called at most once every interval.
  61151. *
  61152. * @param {function} functionToThrottle
  61153. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  61154. * @param {object} optionalContext - If given, bind function to throttle to this context.
  61155. * @returns {function} Throttled function.
  61156. */
  61157. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  61158. var lastTime;
  61159. if (optionalContext) {
  61160. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  61161. }
  61162. return function () {
  61163. var time = Date.now();
  61164. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  61165. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  61166. lastTime = time;
  61167. functionToThrottle.apply(null, arguments);
  61168. }
  61169. };
  61170. };
  61171. /**
  61172. * Returns throttle function that gets called at most once every interval.
  61173. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  61174. *
  61175. * @param {function} functionToThrottle
  61176. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  61177. * @param {object} optionalContext - If given, bind function to throttle to this context.
  61178. * @returns {function} Throttled function.
  61179. */
  61180. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  61181. var lastTime;
  61182. if (optionalContext) {
  61183. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  61184. }
  61185. return function (time, delta) {
  61186. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  61187. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  61188. lastTime = time;
  61189. functionToThrottle(time, sinceLastTime);
  61190. }
  61191. };
  61192. };
  61193. /**
  61194. * Returns debounce function that gets called only once after a set of repeated calls.
  61195. *
  61196. * @param {function} functionToDebounce
  61197. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  61198. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  61199. * @returns {function} Debounced function.
  61200. */
  61201. module.exports.debounce = function (func, wait, immediate) {
  61202. var timeout;
  61203. return function () {
  61204. var context = this;
  61205. var args = arguments;
  61206. var later = function () {
  61207. timeout = null;
  61208. if (!immediate) func.apply(context, args);
  61209. };
  61210. var callNow = immediate && !timeout;
  61211. clearTimeout(timeout);
  61212. timeout = setTimeout(later, wait);
  61213. if (callNow) func.apply(context, args);
  61214. };
  61215. };
  61216. /**
  61217. * Mix the properties of source object(s) into a destination object.
  61218. *
  61219. * @param {object} dest - The object to which properties will be copied.
  61220. * @param {...object} source - The object(s) from which properties will be copied.
  61221. */
  61222. module.exports.extend = objectAssign;
  61223. module.exports.extendDeep = deepAssign;
  61224. module.exports.clone = function (obj) {
  61225. return JSON.parse(JSON.stringify(obj));
  61226. };
  61227. /**
  61228. * Checks if two values are equal.
  61229. * Includes objects and arrays and nested objects and arrays.
  61230. * Try to keep this function performant as it will be called often to see if a component
  61231. * should be updated.
  61232. *
  61233. * @param {object} a - First object.
  61234. * @param {object} b - Second object.
  61235. * @returns {boolean} Whether two objects are deeply equal.
  61236. */
  61237. var deepEqual = (function () {
  61238. var arrayPool = objectPool.createPool(function () { return []; });
  61239. return function (a, b) {
  61240. var key;
  61241. var keysA;
  61242. var keysB;
  61243. var i;
  61244. var valA;
  61245. var valB;
  61246. // If not objects or arrays, compare as values.
  61247. if (a === undefined || b === undefined || a === null || b === null ||
  61248. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  61249. (a.constructor === Array && b.constructor === Array))) {
  61250. return a === b;
  61251. }
  61252. // Different number of keys, not equal.
  61253. keysA = arrayPool.use();
  61254. keysB = arrayPool.use();
  61255. keysA.length = 0;
  61256. keysB.length = 0;
  61257. for (key in a) { keysA.push(key); }
  61258. for (key in b) { keysB.push(key); }
  61259. if (keysA.length !== keysB.length) {
  61260. arrayPool.recycle(keysA);
  61261. arrayPool.recycle(keysB);
  61262. return false;
  61263. }
  61264. // Return `false` at the first sign of inequality.
  61265. for (i = 0; i < keysA.length; ++i) {
  61266. valA = a[keysA[i]];
  61267. valB = b[keysA[i]];
  61268. // Check nested array and object.
  61269. if ((typeof valA === 'object' || typeof valB === 'object') ||
  61270. (Array.isArray(valA) && Array.isArray(valB))) {
  61271. if (valA === valB) { continue; }
  61272. if (!deepEqual(valA, valB)) {
  61273. arrayPool.recycle(keysA);
  61274. arrayPool.recycle(keysB);
  61275. return false;
  61276. }
  61277. } else if (valA !== valB) {
  61278. arrayPool.recycle(keysA);
  61279. arrayPool.recycle(keysB);
  61280. return false;
  61281. }
  61282. }
  61283. arrayPool.recycle(keysA);
  61284. arrayPool.recycle(keysB);
  61285. return true;
  61286. };
  61287. })();
  61288. module.exports.deepEqual = deepEqual;
  61289. /**
  61290. * Computes the difference between two objects.
  61291. *
  61292. * @param {object} a - First object to compare (e.g., oldData).
  61293. * @param {object} b - Second object to compare (e.g., newData).
  61294. * @returns {object}
  61295. * Difference object where set of keys note which values were not equal, and values are
  61296. * `b`'s values.
  61297. */
  61298. module.exports.diff = (function () {
  61299. var keys = [];
  61300. return function (a, b, targetObject) {
  61301. var aVal;
  61302. var bVal;
  61303. var bKey;
  61304. var diff;
  61305. var key;
  61306. var i;
  61307. var isComparingObjects;
  61308. diff = targetObject || {};
  61309. // Collect A keys.
  61310. keys.length = 0;
  61311. for (key in a) { keys.push(key); }
  61312. if (!b) { return diff; }
  61313. // Collect B keys.
  61314. for (bKey in b) {
  61315. if (keys.indexOf(bKey) === -1) {
  61316. keys.push(bKey);
  61317. }
  61318. }
  61319. for (i = 0; i < keys.length; i++) {
  61320. key = keys[i];
  61321. aVal = a[key];
  61322. bVal = b[key];
  61323. isComparingObjects = aVal && bVal &&
  61324. aVal.constructor === Object && bVal.constructor === Object;
  61325. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  61326. (!isComparingObjects && aVal !== bVal)) {
  61327. diff[key] = bVal;
  61328. }
  61329. }
  61330. return diff;
  61331. };
  61332. })();
  61333. /**
  61334. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  61335. * @param {Event} event Event object.
  61336. * @returns {Boolean} Whether the key event should be captured.
  61337. */
  61338. module.exports.shouldCaptureKeyEvent = function (event) {
  61339. if (event.metaKey) { return false; }
  61340. return document.activeElement === document.body;
  61341. };
  61342. /**
  61343. * Splits a string into an array based on a delimiter.
  61344. *
  61345. * @param {string=} [str=''] Source string
  61346. * @param {string=} [delimiter=' '] Delimiter to use
  61347. * @returns {array} Array of delimited strings
  61348. */
  61349. module.exports.splitString = function (str, delimiter) {
  61350. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  61351. // First collapse the whitespace (or whatever the delimiter is).
  61352. var regex = new RegExp(delimiter, 'g');
  61353. str = (str || '').replace(regex, delimiter);
  61354. // Then split.
  61355. return str.split(delimiter);
  61356. };
  61357. /**
  61358. * Extracts data from the element given an object that contains expected keys.
  61359. *
  61360. * @param {Element} Source element.
  61361. * @param {Object} [defaults={}] Object of default key-value pairs.
  61362. * @returns {Object}
  61363. */
  61364. module.exports.getElData = function (el, defaults) {
  61365. defaults = defaults || {};
  61366. var data = {};
  61367. Object.keys(defaults).forEach(copyAttribute);
  61368. function copyAttribute (key) {
  61369. if (el.hasAttribute(key)) {
  61370. data[key] = el.getAttribute(key);
  61371. }
  61372. }
  61373. return data;
  61374. };
  61375. /**
  61376. * Retrieves querystring value.
  61377. * @param {String} name Name of querystring key.
  61378. * @return {String} Value
  61379. */
  61380. module.exports.getUrlParameter = function (name) {
  61381. // eslint-disable-next-line no-useless-escape
  61382. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  61383. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  61384. var results = regex.exec(location.search);
  61385. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  61386. };
  61387. /**
  61388. * Detects whether context is within iframe.
  61389. */
  61390. module.exports.isIframed = function () {
  61391. return window.top !== window.self;
  61392. };
  61393. /**
  61394. * Finds all elements under the element that have the isScene
  61395. * property set to true
  61396. */
  61397. module.exports.findAllScenes = function (el) {
  61398. var matchingElements = [];
  61399. var allElements = el.getElementsByTagName('*');
  61400. for (var i = 0, n = allElements.length; i < n; i++) {
  61401. if (allElements[i].isScene) {
  61402. // Element exists with isScene set.
  61403. matchingElements.push(allElements[i]);
  61404. }
  61405. }
  61406. return matchingElements;
  61407. };
  61408. // Must be at bottom to avoid circular dependency.
  61409. module.exports.srcLoader = _dereq_('./src-loader');
  61410. },{"./bind":198,"./coordinates":199,"./debug":200,"./device":201,"./entity":202,"./forceCanvasResizeSafariMobile":203,"./is-ie11":206,"./material":208,"./object-pool":209,"./split":210,"./src-loader":211,"./styleParser":212,"./tracked-controls":213,"deep-assign":10,"object-assign":39}],205:[function(_dereq_,module,exports){
  61411. // Safari regression introduced in iOS 12 and remains in iOS 13.
  61412. // https://stackoverflow.com/questions/62717621/white-space-at-page-bottom-after-device-rotation-in-ios-safari
  61413. window.addEventListener('orientationchange', function () {
  61414. document.documentElement.style.height = `initial`;
  61415. setTimeout(function () {
  61416. document.documentElement.style.height = `100%`;
  61417. setTimeout(function () {
  61418. // this line prevents the content
  61419. // from hiding behind the address bar
  61420. window.scrollTo(0, 1);
  61421. }, 500);
  61422. }, 500);
  61423. });
  61424. },{}],206:[function(_dereq_,module,exports){
  61425. // https://stackoverflow.com/a/17907562
  61426. function getInternetExplorerVersion () {
  61427. var version = -1;
  61428. var userAgent = navigator.userAgent;
  61429. var re;
  61430. if (navigator.appName === 'Microsoft Internet Explorer') {
  61431. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  61432. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61433. } else if (navigator.appName === 'Netscape') {
  61434. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  61435. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61436. }
  61437. return version;
  61438. }
  61439. module.exports = getInternetExplorerVersion() === 11;
  61440. },{}],207:[function(_dereq_,module,exports){
  61441. /**
  61442. * Check if device is iOS and older than version 10.
  61443. */
  61444. module.exports = function isIOSOlderThan10 (userAgent) {
  61445. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  61446. };
  61447. },{}],208:[function(_dereq_,module,exports){
  61448. var THREE = _dereq_('../lib/three');
  61449. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  61450. var COLOR_MAPS = new Set([
  61451. 'emissiveMap',
  61452. 'envMap',
  61453. 'map',
  61454. 'specularMap'
  61455. ]);
  61456. /**
  61457. * Update `material` texture property (usually but not always `map`)
  61458. * from `data` property (usually but not always `src`)
  61459. *
  61460. * @param {object} shader - A-Frame shader instance.
  61461. * @param {object} data
  61462. */
  61463. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  61464. var el = shader.el;
  61465. var material = shader.material;
  61466. var rendererSystem = el.sceneEl.systems.renderer;
  61467. var src = data[dataName];
  61468. // Because a single material / shader may have multiple textures,
  61469. // we need to remember the source value for this data property
  61470. // to avoid redundant operations which can be expensive otherwise
  61471. // (e.g. video texture loads).
  61472. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  61473. if (!src) {
  61474. // Forget the prior material src.
  61475. delete shader.materialSrcs[materialName];
  61476. // Remove the texture.
  61477. setMap(null);
  61478. return;
  61479. }
  61480. // Don't process if material src hasn't changed.
  61481. if (src === shader.materialSrcs[materialName]) { return; }
  61482. // Remember the new src for this texture (there may be multiple).
  61483. shader.materialSrcs[materialName] = src;
  61484. // If the new material src is already a texture, just use it.
  61485. if (src instanceof THREE.Texture) { setMap(src); } else {
  61486. // Load texture for the new material src.
  61487. // (And check if we should still use it once available in callback.)
  61488. el.sceneEl.systems.material.loadTexture(src,
  61489. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  61490. checkSetMap);
  61491. }
  61492. function checkSetMap (texture) {
  61493. // If the source has been changed, don't use loaded texture.
  61494. if (shader.materialSrcs[materialName] !== src) { return; }
  61495. setMap(texture);
  61496. }
  61497. function setMap (texture) {
  61498. material[materialName] = texture;
  61499. if (texture && COLOR_MAPS.has(materialName)) {
  61500. rendererSystem.applyColorCorrection(texture);
  61501. }
  61502. material.needsUpdate = true;
  61503. handleTextureEvents(el, texture);
  61504. }
  61505. };
  61506. /**
  61507. * Update `material.map` given `data.src`. For standard and flat shaders.
  61508. *
  61509. * @param {object} shader - A-Frame shader instance.
  61510. * @param {object} data
  61511. */
  61512. module.exports.updateMap = function (shader, data) {
  61513. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  61514. };
  61515. /**
  61516. * Updates the material's maps which give the illusion of extra geometry.
  61517. *
  61518. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  61519. * @param {object} shader - A-Frame shader instance
  61520. * @param {object} data
  61521. */
  61522. module.exports.updateDistortionMap = function (longType, shader, data) {
  61523. var shortType = longType;
  61524. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  61525. var el = shader.el;
  61526. var material = shader.material;
  61527. var rendererSystem = el.sceneEl.systems.renderer;
  61528. var src = data[longType + 'Map'];
  61529. var info = {};
  61530. info.src = src;
  61531. // Pass through the repeat and offset to be handled by the material loader.
  61532. info.offset = data[longType + 'TextureOffset'];
  61533. info.repeat = data[longType + 'TextureRepeat'];
  61534. info.wrap = data[longType + 'TextureWrap'];
  61535. if (src) {
  61536. if (src === shader[longType + 'TextureSrc']) { return; }
  61537. // Texture added or changed.
  61538. shader[longType + 'TextureSrc'] = src;
  61539. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  61540. return;
  61541. }
  61542. // Texture removed.
  61543. if (!material.map) { return; }
  61544. setMap(null);
  61545. function setMap (texture) {
  61546. var slot = shortType + 'Map';
  61547. material[slot] = texture;
  61548. if (texture && COLOR_MAPS.has(slot)) {
  61549. rendererSystem.applyColorCorrection(texture);
  61550. }
  61551. material.needsUpdate = true;
  61552. handleTextureEvents(el, texture);
  61553. }
  61554. };
  61555. /**
  61556. * Emit event on entities on texture-related events.
  61557. *
  61558. * @param {Element} el - Entity.
  61559. * @param {object} texture - three.js Texture.
  61560. */
  61561. function handleTextureEvents (el, texture) {
  61562. if (!texture) { return; }
  61563. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  61564. // Video events.
  61565. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  61566. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  61567. // Check to see if we need to use iOS 10 HLS shader.
  61568. // Only override the shader if it is stock shader that we know doesn't correct.
  61569. if (!el.components || !el.components.material) { return; }
  61570. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  61571. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  61572. el.setAttribute('material', 'shader', 'ios10hls');
  61573. }
  61574. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  61575. });
  61576. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  61577. // Works for non-looping videos only.
  61578. el.emit('materialvideoended', {src: texture.image, texture: texture});
  61579. });
  61580. }
  61581. module.exports.handleTextureEvents = handleTextureEvents;
  61582. /**
  61583. * Given video element src and type, guess whether stream is HLS.
  61584. *
  61585. * @param {string} src - src from video element (generally URL to content).
  61586. * @param {string} type - type from video element (generally MIME type if present).
  61587. */
  61588. module.exports.isHLS = function (src, type) {
  61589. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  61590. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  61591. return false;
  61592. };
  61593. },{"../lib/three":178}],209:[function(_dereq_,module,exports){
  61594. /*
  61595. Adapted deePool by Kyle Simpson.
  61596. MIT License: http://getify.mit-license.org
  61597. */
  61598. var EMPTY_SLOT = Object.freeze(Object.create(null));
  61599. // Default object factory.
  61600. function defaultObjectFactory () { return {}; }
  61601. /**
  61602. * Create a new pool.
  61603. */
  61604. module.exports.createPool = function createPool (objectFactory) {
  61605. var objPool = [];
  61606. var nextFreeSlot = null; // Pool location to look for a free object to use.
  61607. objectFactory = objectFactory || defaultObjectFactory;
  61608. function use () {
  61609. var objToUse;
  61610. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  61611. grow(objPool.length || 5);
  61612. }
  61613. objToUse = objPool[nextFreeSlot];
  61614. objPool[nextFreeSlot++] = EMPTY_SLOT;
  61615. clearObject(objToUse);
  61616. return objToUse;
  61617. }
  61618. function recycle (obj) {
  61619. if (!(obj instanceof Object)) { return; }
  61620. if (nextFreeSlot === null || nextFreeSlot === -1) {
  61621. objPool[objPool.length] = obj;
  61622. return;
  61623. }
  61624. objPool[--nextFreeSlot] = obj;
  61625. }
  61626. function grow (count) {
  61627. var currentLength;
  61628. var i;
  61629. count = count === undefined ? objPool.length : count;
  61630. if (count > 0 && nextFreeSlot == null) {
  61631. nextFreeSlot = 0;
  61632. }
  61633. if (count > 0) {
  61634. currentLength = objPool.length;
  61635. objPool.length += Number(count);
  61636. for (i = currentLength; i < objPool.length; i++) {
  61637. // Add new obj to pool.
  61638. objPool[i] = objectFactory();
  61639. }
  61640. }
  61641. return objPool.length;
  61642. }
  61643. function size () {
  61644. return objPool.length;
  61645. }
  61646. return {
  61647. grow: grow,
  61648. pool: objPool,
  61649. recycle: recycle,
  61650. size: size,
  61651. use: use
  61652. };
  61653. };
  61654. function clearObject (obj) {
  61655. var key;
  61656. if (!obj || obj.constructor !== Object) { return; }
  61657. for (key in obj) { obj[key] = undefined; }
  61658. }
  61659. module.exports.clearObject = clearObject;
  61660. function removeUnusedKeys (obj, schema) {
  61661. var key;
  61662. if (!obj || obj.constructor !== Object) { return; }
  61663. for (key in obj) {
  61664. if (!(key in schema)) {
  61665. delete obj[key];
  61666. }
  61667. }
  61668. }
  61669. module.exports.removeUnusedKeys = removeUnusedKeys;
  61670. },{}],210:[function(_dereq_,module,exports){
  61671. /**
  61672. * String split with cached result.
  61673. */
  61674. module.exports.split = (function () {
  61675. var splitCache = {};
  61676. return function (str, delimiter) {
  61677. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  61678. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  61679. splitCache[delimiter][str] = str.split(delimiter);
  61680. return splitCache[delimiter][str];
  61681. };
  61682. })();
  61683. },{}],211:[function(_dereq_,module,exports){
  61684. /* global Image, XMLHttpRequest */
  61685. var debug = _dereq_('./debug');
  61686. var warn = debug('utils:src-loader:warn');
  61687. /**
  61688. * Validate a texture, either as a selector or as a URL.
  61689. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  61690. * callback.
  61691. *
  61692. * `src` will be passed into the callback
  61693. *
  61694. * @params {string|Element} src - URL or media element.
  61695. * @params {function} isImageCb - callback if texture is an image.
  61696. * @params {function} isVideoCb - callback if texture is a video.
  61697. */
  61698. function validateSrc (src, isImageCb, isVideoCb) {
  61699. checkIsImage(src, function isAnImageUrl (isImage) {
  61700. if (isImage) {
  61701. isImageCb(src);
  61702. return;
  61703. }
  61704. isVideoCb(src);
  61705. });
  61706. }
  61707. /**
  61708. * Validates six images as a cubemap, either as selector or comma-separated
  61709. * URLs.
  61710. *
  61711. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61712. must be wrapped by `url()`.
  61713. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61714. must be wrapped by `url()`.
  61715. */
  61716. function validateCubemapSrc (src, cb) {
  61717. var aCubemap;
  61718. var cubemapSrcRegex = '';
  61719. var i;
  61720. var urls;
  61721. var validatedUrls = [];
  61722. for (i = 0; i < 5; i++) {
  61723. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  61724. }
  61725. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  61726. urls = src.match(new RegExp(cubemapSrcRegex));
  61727. // `src` is a comma-separated list of URLs.
  61728. // In this case, re-use validateSrc for each side of the cube.
  61729. function isImageCb (url) {
  61730. validatedUrls.push(url);
  61731. if (validatedUrls.length === 6) {
  61732. cb(validatedUrls);
  61733. }
  61734. }
  61735. if (urls) {
  61736. for (i = 1; i < 7; i++) {
  61737. validateSrc(parseUrl(urls[i]), isImageCb);
  61738. }
  61739. return;
  61740. }
  61741. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  61742. aCubemap = validateAndGetQuerySelector(src);
  61743. if (!aCubemap) { return; }
  61744. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  61745. return cb(aCubemap.srcs);
  61746. }
  61747. // Else if aCubeMap is not a <a-cubemap>.
  61748. warn('Selector "%s" does not point to <a-cubemap>', src);
  61749. }
  61750. /**
  61751. * Parses src from `url(src)`.
  61752. * @param {string} src - String to parse.
  61753. * @return {string} The parsed src, if parseable.
  61754. */
  61755. function parseUrl (src) {
  61756. var parsedSrc = src.match(/\url\((.+)\)/);
  61757. if (!parsedSrc) { return; }
  61758. return parsedSrc[1];
  61759. }
  61760. /**
  61761. * Call back whether `src` is an image.
  61762. *
  61763. * @param {string|Element} src - URL or element that will be tested.
  61764. * @param {function} onResult - Callback with whether `src` is an image.
  61765. */
  61766. function checkIsImage (src, onResult) {
  61767. var request;
  61768. if (src.tagName) {
  61769. onResult(src.tagName === 'IMG');
  61770. return;
  61771. }
  61772. request = new XMLHttpRequest();
  61773. // Try to send HEAD request to check if image first.
  61774. request.open('HEAD', src);
  61775. request.addEventListener('load', function (event) {
  61776. var contentType;
  61777. if (request.status >= 200 && request.status < 300) {
  61778. contentType = request.getResponseHeader('Content-Type');
  61779. if (contentType == null) {
  61780. checkIsImageFallback(src, onResult);
  61781. } else {
  61782. if (contentType.startsWith('image')) {
  61783. onResult(true);
  61784. } else {
  61785. onResult(false);
  61786. }
  61787. }
  61788. } else {
  61789. checkIsImageFallback(src, onResult);
  61790. }
  61791. request.abort();
  61792. });
  61793. request.send();
  61794. }
  61795. function checkIsImageFallback (src, onResult) {
  61796. var tester = new Image();
  61797. tester.addEventListener('load', onLoad);
  61798. function onLoad () { onResult(true); }
  61799. tester.addEventListener('error', onError);
  61800. function onError () { onResult(false); }
  61801. tester.src = src;
  61802. }
  61803. /**
  61804. * Query and validate a query selector,
  61805. *
  61806. * @param {string} selector - DOM selector.
  61807. * @return {object|null|undefined} Selected DOM element if exists.
  61808. null if query yields no results.
  61809. undefined if `selector` is not a valid selector.
  61810. */
  61811. function validateAndGetQuerySelector (selector) {
  61812. try {
  61813. var el = document.querySelector(selector);
  61814. if (!el) {
  61815. warn('No element was found matching the selector: "%s"', selector);
  61816. }
  61817. return el;
  61818. } catch (e) { // Capture exception if it's not a valid selector.
  61819. warn('"%s" is not a valid selector', selector);
  61820. return undefined;
  61821. }
  61822. }
  61823. module.exports = {
  61824. parseUrl: parseUrl,
  61825. validateSrc: validateSrc,
  61826. validateCubemapSrc: validateCubemapSrc
  61827. };
  61828. },{"./debug":200}],212:[function(_dereq_,module,exports){
  61829. /**
  61830. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  61831. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  61832. * by Josh Johnston (MIT License).
  61833. */
  61834. var DASH_REGEX = /-([a-z])/g;
  61835. /**
  61836. * Deserialize style-like string into an object of properties.
  61837. *
  61838. * @param {string} value - HTML attribute value.
  61839. * @param {object} obj - Reused object for object pooling.
  61840. * @returns {object} Property data.
  61841. */
  61842. module.exports.parse = function (value, obj) {
  61843. var parsedData;
  61844. if (typeof value !== 'string') { return value; }
  61845. parsedData = styleParse(value, obj);
  61846. // The style parser returns an object { "" : "test"} when fed a string
  61847. if (parsedData['']) { return value; }
  61848. return transformKeysToCamelCase(parsedData);
  61849. };
  61850. /**
  61851. * Serialize an object of properties into a style-like string.
  61852. *
  61853. * @param {object} data - Property data.
  61854. * @returns {string}
  61855. */
  61856. module.exports.stringify = function (data) {
  61857. if (typeof data === 'string') { return data; }
  61858. return styleStringify(data);
  61859. };
  61860. /**
  61861. * Converts string from hyphen to camelCase.
  61862. *
  61863. * @param {string} str - String to camelCase.
  61864. * @return {string} CamelCased string.
  61865. */
  61866. function toCamelCase (str) {
  61867. return str.replace(DASH_REGEX, upperCase);
  61868. }
  61869. module.exports.toCamelCase = toCamelCase;
  61870. /**
  61871. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  61872. * `maxValue`).
  61873. *
  61874. * @param {object} obj - The object to camelCase keys.
  61875. * @return {object} The object with keys camelCased.
  61876. */
  61877. function transformKeysToCamelCase (obj) {
  61878. var camelKey;
  61879. var key;
  61880. for (key in obj) {
  61881. camelKey = toCamelCase(key);
  61882. if (key === camelKey) { continue; }
  61883. obj[camelKey] = obj[key];
  61884. delete obj[key];
  61885. }
  61886. return obj;
  61887. }
  61888. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  61889. /**
  61890. * Split a string into chunks matching `<key>: <value>`
  61891. */
  61892. var getKeyValueChunks = (function () {
  61893. var chunks = [];
  61894. var hasUnclosedUrl = /url\([^)]+$/;
  61895. return function getKeyValueChunks (raw) {
  61896. var chunk = '';
  61897. var nextSplit;
  61898. var offset = 0;
  61899. var sep = ';';
  61900. chunks.length = 0;
  61901. while (offset < raw.length) {
  61902. nextSplit = raw.indexOf(sep, offset);
  61903. if (nextSplit === -1) { nextSplit = raw.length; }
  61904. chunk += raw.substring(offset, nextSplit);
  61905. // data URIs can contain semicolons, so make sure we get the whole thing
  61906. if (hasUnclosedUrl.test(chunk)) {
  61907. chunk += ';';
  61908. offset = nextSplit + 1;
  61909. continue;
  61910. }
  61911. chunks.push(chunk.trim());
  61912. chunk = '';
  61913. offset = nextSplit + 1;
  61914. }
  61915. return chunks;
  61916. };
  61917. })();
  61918. /**
  61919. * Convert a style attribute string to an object.
  61920. *
  61921. * @param {object} str - Attribute string.
  61922. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  61923. */
  61924. function styleParse (str, obj) {
  61925. var chunks;
  61926. var i;
  61927. var item;
  61928. var pos;
  61929. var key;
  61930. var val;
  61931. obj = obj || {};
  61932. chunks = getKeyValueChunks(str);
  61933. for (i = 0; i < chunks.length; i++) {
  61934. item = chunks[i];
  61935. if (!item) { continue; }
  61936. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  61937. pos = item.indexOf(':');
  61938. key = item.substr(0, pos).trim();
  61939. val = item.substr(pos + 1).trim();
  61940. obj[key] = val;
  61941. }
  61942. return obj;
  61943. }
  61944. /**
  61945. * Convert an object into an attribute string
  61946. **/
  61947. function styleStringify (obj) {
  61948. var key;
  61949. var keyCount = 0;
  61950. var i = 0;
  61951. var str = '';
  61952. for (key in obj) { keyCount++; }
  61953. for (key in obj) {
  61954. str += (key + ': ' + obj[key]);
  61955. if (i < keyCount - 1) { str += '; '; }
  61956. i++;
  61957. }
  61958. return str;
  61959. }
  61960. function upperCase (str) { return str[1].toUpperCase(); }
  61961. },{}],213:[function(_dereq_,module,exports){
  61962. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  61963. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  61964. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  61965. /**
  61966. * Called on controller component `.play` handlers.
  61967. * Check if controller matches parameters and inject tracked-controls component.
  61968. * Handle event listeners.
  61969. * Generate controllerconnected or controllerdisconnected events.
  61970. *
  61971. * @param {object} component - Tracked controls component.
  61972. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  61973. * @param {object} queryObject - Map of values to match.
  61974. */
  61975. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  61976. var el = component.el;
  61977. var controller;
  61978. var hasWebXR = el.sceneEl.hasWebXR;
  61979. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  61980. var isPresent;
  61981. controller = isControllerPresent(component, idPrefix, queryObject);
  61982. isPresent = !!controller;
  61983. // If component was previously paused and now playing, re-add event listeners.
  61984. // Handle the event listeners here since this helper method is control of calling
  61985. // `.addEventListeners` and `.removeEventListeners`.
  61986. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  61987. component.addEventListeners();
  61988. }
  61989. // Nothing changed, no need to do anything.
  61990. if (isPresent === component.controllerPresent) { return isPresent; }
  61991. component.controllerPresent = isPresent;
  61992. // Update controller presence.
  61993. if (isPresent) {
  61994. component.addEventListeners();
  61995. component.injectTrackedControls(controller);
  61996. el.emit('controllerconnected', {name: component.name, component: component});
  61997. } else {
  61998. component.removeEventListeners();
  61999. el.emit('controllerdisconnected', {name: component.name, component: component});
  62000. }
  62001. };
  62002. /**
  62003. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  62004. *
  62005. * @param {object} component - Tracked controls component.
  62006. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  62007. * @param {object} queryObject - Map of values to match.
  62008. */
  62009. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  62010. var gamepads;
  62011. var sceneEl = component.el.sceneEl;
  62012. var trackedControlsSystem;
  62013. var filterControllerIndex = queryObject.index || 0;
  62014. if (!idPrefix) { return false; }
  62015. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  62016. if (!trackedControlsSystem) { return false; }
  62017. gamepads = trackedControlsSystem.controllers;
  62018. if (!gamepads.length) { return false; }
  62019. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  62020. filterControllerIndex);
  62021. }
  62022. /**
  62023. *
  62024. * @param {object} component - Tracked controls component.
  62025. */
  62026. function isControllerPresentWebXR (component, id, queryObject) {
  62027. var controllers;
  62028. var sceneEl = component.el.sceneEl;
  62029. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  62030. if (!trackedControlsSystem) { return false; }
  62031. controllers = trackedControlsSystem.controllers;
  62032. if (!controllers || !controllers.length) { return false; }
  62033. return findMatchingControllerWebXR(
  62034. controllers, id,
  62035. queryObject.hand, queryObject.index, queryObject.iterateControllerProfiles, queryObject.handTracking);
  62036. }
  62037. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  62038. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  62039. /**
  62040. * Walk through the given controllers to find any where the device ID equals
  62041. * filterIdExact, or startsWith filterIdPrefix.
  62042. * A controller where this considered true is considered a 'match'.
  62043. *
  62044. * For each matching controller:
  62045. * If filterHand is set, and the controller:
  62046. * is handed, we further verify that controller.hand equals filterHand.
  62047. * is unhanded (controller.hand is ''), we skip until we have found a
  62048. * number of matching controllers that equals filterControllerIndex
  62049. * If filterHand is not set, we skip until we have found the nth matching
  62050. * controller, where n equals filterControllerIndex
  62051. *
  62052. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  62053. * one or both of: [filterHand, filterControllerIndex]
  62054. *
  62055. * @param {object} controllers - Array of gamepads to search
  62056. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  62057. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  62058. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  62059. * @param {object} filterControllerIndex - Find the nth matching controller,
  62060. * where n equals filterControllerIndex. defaults to 0.
  62061. */
  62062. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  62063. filterControllerIndex) {
  62064. var controller;
  62065. var i;
  62066. var matchingControllerOccurence = 0;
  62067. var targetControllerMatch = filterControllerIndex >= 0 ? filterControllerIndex : 0;
  62068. for (i = 0; i < controllers.length; i++) {
  62069. controller = controllers[i];
  62070. // Determine if the controller ID matches our criteria.
  62071. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  62072. continue;
  62073. }
  62074. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  62075. // If the hand filter and controller handedness are defined we compare them.
  62076. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  62077. // If we have detected an unhanded controller and the component was asking
  62078. // for a particular hand, we need to treat the controllers in the array as
  62079. // pairs of controllers. This effectively means that we need to skip
  62080. // NUM_HANDS matches for each controller number, instead of 1.
  62081. if (filterHand && !controller.hand) {
  62082. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  62083. } else {
  62084. return controller;
  62085. }
  62086. // We are looking for the nth occurence of a matching controller
  62087. // (n equals targetControllerMatch).
  62088. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  62089. ++matchingControllerOccurence;
  62090. }
  62091. return undefined;
  62092. }
  62093. function findMatchingControllerWebXR (controllers, idPrefix, handedness, index, iterateProfiles, handTracking) {
  62094. var i;
  62095. var j;
  62096. var controller;
  62097. var controllerMatch = false;
  62098. var controllerHasHandedness;
  62099. var profiles;
  62100. for (i = 0; i < controllers.length; i++) {
  62101. controller = controllers[i];
  62102. profiles = controller.profiles;
  62103. if (handTracking) {
  62104. controllerMatch = controller.hand;
  62105. } else {
  62106. if (iterateProfiles) {
  62107. for (j = 0; j < profiles.length; j++) {
  62108. controllerMatch = profiles[j].startsWith(idPrefix);
  62109. if (controllerMatch) { break; }
  62110. }
  62111. } else {
  62112. controllerMatch = profiles.length > 0 && profiles[0].startsWith(idPrefix);
  62113. }
  62114. }
  62115. if (!controllerMatch) { continue; }
  62116. // Vive controllers are assigned handedness at runtime and it might not be always available.
  62117. controllerHasHandedness = controller.handedness === 'right' || controller.handedness === 'left';
  62118. if (controllerHasHandedness) {
  62119. if (controller.handedness === handedness) { return controllers[i]; }
  62120. } else { // Fallback to index if controller has no handedness.
  62121. if ((i === index)) { return controllers[i]; }
  62122. }
  62123. }
  62124. return undefined;
  62125. }
  62126. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  62127. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  62128. /**
  62129. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  62130. *
  62131. * @param {object} component - Controller component in use.
  62132. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  62133. * @param {object} evt - Event to process.
  62134. */
  62135. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  62136. var axes;
  62137. var buttonType;
  62138. var changed;
  62139. var detail;
  62140. var j;
  62141. for (buttonType in axesMapping) {
  62142. axes = axesMapping[buttonType];
  62143. changed = false;
  62144. for (j = 0; j < axes.length; j++) {
  62145. if (evt.detail.changed[axes[j]]) { changed = true; }
  62146. }
  62147. if (!changed) { continue; }
  62148. // Axis has changed. Emit the specific moved event with axis values in detail.
  62149. detail = {};
  62150. for (j = 0; j < axes.length; j++) {
  62151. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  62152. }
  62153. component.el.emit(buttonType + 'moved', detail);
  62154. }
  62155. };
  62156. /**
  62157. * Handle a button event and reemits the events.
  62158. *
  62159. * @param {string} id - id of the button.
  62160. * @param {string} evtName - name of the reemitted event
  62161. * @param {object} component - reference to the component
  62162. * @param {string} hand - handedness of the controller: left or right.
  62163. */
  62164. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  62165. var mapping = hand ? component.mapping[hand] : component.mapping;
  62166. var buttonName = mapping.buttons[id];
  62167. component.el.emit(buttonName + evtName);
  62168. if (component.updateModel) {
  62169. component.updateModel(buttonName, evtName);
  62170. }
  62171. };
  62172. },{"../constants":122}],214:[function(_dereq_,module,exports){
  62173. /**
  62174. * @author richt / http://richt.me
  62175. * @author WestLangley / http://github.com/WestLangley
  62176. *
  62177. * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
  62178. */
  62179. THREE.DeviceOrientationControls = function ( object ) {
  62180. var scope = this;
  62181. this.object = object;
  62182. this.object.rotation.reorder( 'YXZ' );
  62183. this.enabled = true;
  62184. this.deviceOrientation = {};
  62185. this.screenOrientation = 0;
  62186. this.alphaOffset = 0; // radians
  62187. var onDeviceOrientationChangeEvent = function ( event ) {
  62188. scope.deviceOrientation = event;
  62189. };
  62190. var onScreenOrientationChangeEvent = function () {
  62191. scope.screenOrientation = window.orientation || 0;
  62192. };
  62193. // The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
  62194. var setObjectQuaternion = function () {
  62195. var zee = new THREE.Vector3( 0, 0, 1 );
  62196. var euler = new THREE.Euler();
  62197. var q0 = new THREE.Quaternion();
  62198. var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis
  62199. return function ( quaternion, alpha, beta, gamma, orient ) {
  62200. euler.set( beta, alpha, - gamma, 'YXZ' ); // 'ZXY' for the device, but 'YXZ' for us
  62201. quaternion.setFromEuler( euler ); // orient the device
  62202. quaternion.multiply( q1 ); // camera looks out the back of the device, not the top
  62203. quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) ); // adjust for screen orientation
  62204. };
  62205. }();
  62206. this.connect = function () {
  62207. onScreenOrientationChangeEvent();
  62208. window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  62209. window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  62210. scope.enabled = true;
  62211. };
  62212. this.disconnect = function () {
  62213. window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  62214. window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  62215. scope.enabled = false;
  62216. };
  62217. this.update = function () {
  62218. if ( scope.enabled === false ) return;
  62219. var device = scope.deviceOrientation;
  62220. if ( device ) {
  62221. var alpha = device.alpha ? THREE.Math.degToRad( device.alpha ) + scope.alphaOffset : 0; // Z
  62222. var beta = device.beta ? THREE.Math.degToRad( device.beta ) : 0; // X'
  62223. var gamma = device.gamma ? THREE.Math.degToRad( device.gamma ) : 0; // Y''
  62224. var orient = scope.screenOrientation ? THREE.Math.degToRad( scope.screenOrientation ) : 0; // O
  62225. setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );
  62226. }
  62227. };
  62228. this.dispose = function () {
  62229. scope.disconnect();
  62230. };
  62231. this.connect();
  62232. };
  62233. },{}],215:[function(_dereq_,module,exports){
  62234. window.glStats = function () {
  62235. var _rS = null;
  62236. var _totalDrawArraysCalls = 0,
  62237. _totalDrawElementsCalls = 0,
  62238. _totalUseProgramCalls = 0,
  62239. _totalFaces = 0,
  62240. _totalVertices = 0,
  62241. _totalPoints = 0,
  62242. _totalBindTexures = 0;
  62243. function _h ( f, c ) {
  62244. return function () {
  62245. c.apply( this, arguments );
  62246. f.apply( this, arguments );
  62247. };
  62248. }
  62249. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  62250. _totalDrawArraysCalls++;
  62251. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  62252. else _totalVertices += arguments[ 2 ];
  62253. } );
  62254. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  62255. _totalDrawElementsCalls++;
  62256. _totalFaces += arguments[ 1 ] / 3;
  62257. _totalVertices += arguments[ 1 ];
  62258. } );
  62259. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  62260. _totalUseProgramCalls++;
  62261. } );
  62262. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  62263. _totalBindTexures++;
  62264. } );
  62265. var _values = {
  62266. allcalls: {
  62267. over: 3000,
  62268. caption: 'Calls (hook)'
  62269. },
  62270. drawelements: {
  62271. caption: 'drawElements (hook)'
  62272. },
  62273. drawarrays: {
  62274. caption: 'drawArrays (hook)'
  62275. }
  62276. };
  62277. var _groups = [ {
  62278. caption: 'WebGL',
  62279. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  62280. } ];
  62281. var _fractions = [ {
  62282. base: 'allcalls',
  62283. steps: [ 'drawelements', 'drawarrays' ]
  62284. } ];
  62285. function _update () {
  62286. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  62287. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  62288. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  62289. _rS( 'bindTexture' ).set( _totalBindTexures );
  62290. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  62291. _rS( 'glfaces' ).set( _totalFaces );
  62292. _rS( 'glvertices' ).set( _totalVertices );
  62293. _rS( 'glpoints' ).set( _totalPoints );
  62294. }
  62295. function _start () {
  62296. _totalDrawArraysCalls = 0;
  62297. _totalDrawElementsCalls = 0;
  62298. _totalUseProgramCalls = 0;
  62299. _totalFaces = 0;
  62300. _totalVertices = 0;
  62301. _totalPoints = 0;
  62302. _totalBindTexures = 0;
  62303. }
  62304. function _end () {}
  62305. function _attach ( r ) {
  62306. _rS = r;
  62307. }
  62308. return {
  62309. update: _update,
  62310. start: _start,
  62311. end: _end,
  62312. attach: _attach,
  62313. values: _values,
  62314. groups: _groups,
  62315. fractions: _fractions
  62316. };
  62317. };
  62318. window.threeStats = function ( renderer ) {
  62319. var _rS = null;
  62320. var _values = {
  62321. 'renderer.info.memory.geometries': {
  62322. caption: 'Geometries'
  62323. },
  62324. 'renderer.info.memory.textures': {
  62325. caption: 'Textures'
  62326. },
  62327. 'renderer.info.programs': {
  62328. caption: 'Programs'
  62329. },
  62330. 'renderer.info.render.calls': {
  62331. caption: 'Calls'
  62332. },
  62333. 'renderer.info.render.triangles': {
  62334. caption: 'Triangles',
  62335. over: 1000
  62336. },
  62337. 'renderer.info.render.points': {
  62338. caption: 'Points'
  62339. }
  62340. };
  62341. var _groups = [ {
  62342. caption: 'Three.js - Memory',
  62343. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  62344. }, {
  62345. caption: 'Three.js - Render',
  62346. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  62347. } ];
  62348. var _fractions = [];
  62349. function _update () {
  62350. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  62351. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  62352. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  62353. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  62354. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  62355. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  62356. }
  62357. function _start () {}
  62358. function _end () {}
  62359. function _attach ( r ) {
  62360. _rS = r;
  62361. }
  62362. return {
  62363. update: _update,
  62364. start: _start,
  62365. end: _end,
  62366. attach: _attach,
  62367. values: _values,
  62368. groups: _groups,
  62369. fractions: _fractions
  62370. };
  62371. };
  62372. /*
  62373. * From https://github.com/paulirish/memory-stats.js
  62374. */
  62375. window.BrowserStats = function () {
  62376. var _rS = null;
  62377. var _usedJSHeapSize = 0,
  62378. _totalJSHeapSize = 0;
  62379. if ( window.performance && !performance.memory ) {
  62380. performance.memory = {
  62381. usedJSHeapSize: 0,
  62382. totalJSHeapSize: 0
  62383. };
  62384. }
  62385. if ( performance.memory.totalJSHeapSize === 0 ) {
  62386. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  62387. }
  62388. var _values = {
  62389. memory: {
  62390. caption: 'Used Memory',
  62391. average: true,
  62392. avgMs: 1000,
  62393. over: 22
  62394. },
  62395. total: {
  62396. caption: 'Total Memory'
  62397. }
  62398. };
  62399. var _groups = [ {
  62400. caption: 'Browser',
  62401. values: [ 'memory', 'total' ]
  62402. } ];
  62403. var _fractions = [ {
  62404. base: 'total',
  62405. steps: [ 'memory' ]
  62406. } ];
  62407. var log1024 = Math.log( 1024 );
  62408. function _size ( v ) {
  62409. var precision = 100; //Math.pow(10, 2);
  62410. var i = Math.floor( Math.log( v ) / log1024 );
  62411. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  62412. }
  62413. function _update () {
  62414. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  62415. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  62416. _rS( 'memory' ).set( _usedJSHeapSize );
  62417. _rS( 'total' ).set( _totalJSHeapSize );
  62418. }
  62419. function _start () {
  62420. _usedJSHeapSize = 0;
  62421. }
  62422. function _end () {}
  62423. function _attach ( r ) {
  62424. _rS = r;
  62425. }
  62426. return {
  62427. update: _update,
  62428. start: _start,
  62429. end: _end,
  62430. attach: _attach,
  62431. values: _values,
  62432. groups: _groups,
  62433. fractions: _fractions
  62434. };
  62435. };
  62436. if (typeof module === 'object') {
  62437. module.exports = {
  62438. glStats: window.glStats,
  62439. threeStats: window.threeStats,
  62440. BrowserStats: window.BrowserStats
  62441. };
  62442. }
  62443. },{}],216:[function(_dereq_,module,exports){
  62444. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  62445. 'use strict';
  62446. ( function () {
  62447. if ( 'performance' in window == false ) {
  62448. window.performance = {};
  62449. }
  62450. var performance = window.performance;
  62451. if ( 'now' in performance == false ) {
  62452. var nowOffset = Date.now();
  62453. if ( performance.timing && performance.timing.navigationStart ) {
  62454. nowOffset = performance.timing.navigationStart;
  62455. }
  62456. performance.now = function now () {
  62457. return Date.now() - nowOffset;
  62458. };
  62459. }
  62460. if( !performance.mark ) {
  62461. performance.mark = function(){}
  62462. }
  62463. if( !performance.measure ) {
  62464. performance.measure = function(){}
  62465. }
  62466. } )();
  62467. window.rStats = function rStats ( settings ) {
  62468. function iterateKeys ( array, callback ) {
  62469. var keys = Object.keys( array );
  62470. for ( var j = 0, l = keys.length; j < l; j++ ) {
  62471. callback( keys[ j ] );
  62472. }
  62473. }
  62474. function importCSS ( url ) {
  62475. var element = document.createElement( 'link' );
  62476. element.href = url;
  62477. element.rel = 'stylesheet';
  62478. element.type = 'text/css';
  62479. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  62480. }
  62481. var _settings = settings || {};
  62482. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  62483. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  62484. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  62485. var _css = _settings.css || [ _cssFont, _cssRStats ];
  62486. _css.forEach(function (uri) {
  62487. importCSS( uri );
  62488. });
  62489. if ( !_settings.values ) _settings.values = {};
  62490. var _base, _div, _elHeight = 10, _elWidth = 200;
  62491. var _perfCounters = {};
  62492. function Graph ( _dom, _id, _defArg ) {
  62493. var _def = _defArg || {};
  62494. var _canvas = document.createElement( 'canvas' ),
  62495. _ctx = _canvas.getContext( '2d' ),
  62496. _max = 0,
  62497. _current = 0;
  62498. var c = _def.color ? _def.color : '#666666';
  62499. var _dotCanvas = document.createElement( 'canvas' ),
  62500. _dotCtx = _dotCanvas.getContext( '2d' );
  62501. _dotCanvas.width = 1;
  62502. _dotCanvas.height = 2 * _elHeight;
  62503. _dotCtx.fillStyle = '#444444';
  62504. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62505. _dotCtx.fillStyle = c;
  62506. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62507. _dotCtx.fillStyle = '#ffffff';
  62508. _dotCtx.globalAlpha = 0.5;
  62509. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  62510. _dotCtx.globalAlpha = 1;
  62511. var _alarmCanvas = document.createElement( 'canvas' ),
  62512. _alarmCtx = _alarmCanvas.getContext( '2d' );
  62513. _alarmCanvas.width = 1;
  62514. _alarmCanvas.height = 2 * _elHeight;
  62515. _alarmCtx.fillStyle = '#444444';
  62516. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62517. _alarmCtx.fillStyle = '#b70000';
  62518. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62519. _alarmCtx.globalAlpha = 0.5;
  62520. _alarmCtx.fillStyle = '#ffffff';
  62521. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  62522. _alarmCtx.globalAlpha = 1;
  62523. function _init () {
  62524. _canvas.width = _elWidth;
  62525. _canvas.height = _elHeight;
  62526. _canvas.style.width = _canvas.width + 'px';
  62527. _canvas.style.height = _canvas.height + 'px';
  62528. _canvas.className = 'rs-canvas';
  62529. _dom.appendChild( _canvas );
  62530. _ctx.fillStyle = '#444444';
  62531. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62532. }
  62533. function _draw ( v, alarm ) {
  62534. _current += ( v - _current ) * 0.1;
  62535. _max *= 0.99;
  62536. if ( _current > _max ) _max = _current;
  62537. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62538. if ( alarm ) {
  62539. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62540. } else {
  62541. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62542. }
  62543. }
  62544. _init();
  62545. return {
  62546. draw: _draw
  62547. };
  62548. }
  62549. function StackGraph ( _dom, _num ) {
  62550. var _canvas = document.createElement( 'canvas' ),
  62551. _ctx = _canvas.getContext( '2d' );
  62552. function _init () {
  62553. _canvas.width = _elWidth;
  62554. _canvas.height = _elHeight * _num;
  62555. _canvas.style.width = _canvas.width + 'px';
  62556. _canvas.style.height = _canvas.height + 'px';
  62557. _canvas.className = 'rs-canvas';
  62558. _dom.appendChild( _canvas );
  62559. _ctx.fillStyle = '#444444';
  62560. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62561. }
  62562. function _draw ( v ) {
  62563. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62564. var th = 0;
  62565. iterateKeys( v, function ( j ) {
  62566. var h = v[ j ] * _canvas.height;
  62567. _ctx.fillStyle = _colours[ j ];
  62568. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  62569. th += h;
  62570. } );
  62571. }
  62572. _init();
  62573. return {
  62574. draw: _draw
  62575. };
  62576. }
  62577. function PerfCounter ( id, group ) {
  62578. var _id = id,
  62579. _time,
  62580. _value = 0,
  62581. _total = 0,
  62582. _averageValue = 0,
  62583. _accumValue = 0,
  62584. _accumStart = performance.now(),
  62585. _accumSamples = 0,
  62586. _dom = document.createElement( 'div' ),
  62587. _spanId = document.createElement( 'span' ),
  62588. _spanValue = document.createElement( 'div' ),
  62589. _spanValueText = document.createTextNode( '' ),
  62590. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  62591. _graph = new Graph( _dom, _id, _def ),
  62592. _started = false;
  62593. _spanId.className = 'rs-counter-id';
  62594. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  62595. _spanValue.className = 'rs-counter-value';
  62596. _spanValue.appendChild( _spanValueText );
  62597. _dom.appendChild( _spanId );
  62598. _dom.appendChild( _spanValue );
  62599. if ( group ) group.div.appendChild( _dom );
  62600. else _div.appendChild( _dom );
  62601. _time = performance.now();
  62602. function _average ( v ) {
  62603. if ( _def && _def.average ) {
  62604. _accumValue += v;
  62605. _accumSamples++;
  62606. var t = performance.now();
  62607. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  62608. _averageValue = _accumValue / _accumSamples;
  62609. _accumValue = 0;
  62610. _accumStart = t;
  62611. _accumSamples = 0;
  62612. }
  62613. }
  62614. }
  62615. function _start () {
  62616. _time = performance.now();
  62617. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  62618. _started = true;
  62619. }
  62620. function _end () {
  62621. _value = performance.now() - _time;
  62622. if( _settings.userTimingAPI ) {
  62623. performance.mark( _id + '-end' );
  62624. if( _started ) {
  62625. performance.measure( _id, _id + '-start', _id + '-end' );
  62626. }
  62627. }
  62628. _average( _value );
  62629. }
  62630. function _tick () {
  62631. _end();
  62632. _start();
  62633. }
  62634. function _draw () {
  62635. var v = ( _def && _def.average ) ? _averageValue : _value;
  62636. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  62637. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  62638. _graph.draw( _value, a );
  62639. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  62640. }
  62641. function _frame () {
  62642. var t = performance.now();
  62643. var e = t - _time;
  62644. _total++;
  62645. if ( e > 1000 ) {
  62646. if ( _def && _def.interpolate === false ) {
  62647. _value = _total;
  62648. } else {
  62649. _value = _total * 1000 / e;
  62650. }
  62651. _total = 0;
  62652. _time = t;
  62653. _average( _value );
  62654. }
  62655. }
  62656. function _set ( v ) {
  62657. _value = v;
  62658. _average( _value );
  62659. }
  62660. return {
  62661. set: _set,
  62662. start: _start,
  62663. tick: _tick,
  62664. end: _end,
  62665. frame: _frame,
  62666. value: function () {
  62667. return _value;
  62668. },
  62669. draw: _draw
  62670. };
  62671. }
  62672. function sample () {
  62673. var _value = 0;
  62674. function _set ( v ) {
  62675. _value = v;
  62676. }
  62677. return {
  62678. set: _set,
  62679. value: function () {
  62680. return _value;
  62681. }
  62682. };
  62683. }
  62684. function _perf ( idArg ) {
  62685. var id = idArg.toLowerCase();
  62686. if ( id === undefined ) id = 'default';
  62687. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  62688. var group = null;
  62689. if ( _settings && _settings.groups ) {
  62690. iterateKeys( _settings.groups, function ( j ) {
  62691. var g = _settings.groups[ parseInt( j, 10 ) ];
  62692. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  62693. group = g;
  62694. }
  62695. } );
  62696. }
  62697. var p = new PerfCounter( id, group );
  62698. _perfCounters[ id ] = p;
  62699. return p;
  62700. }
  62701. function _init () {
  62702. if ( _settings.plugins ) {
  62703. if ( !_settings.values ) _settings.values = {};
  62704. if ( !_settings.groups ) _settings.groups = [];
  62705. if ( !_settings.fractions ) _settings.fractions = [];
  62706. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  62707. _settings.plugins[ j ].attach( _perf );
  62708. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  62709. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  62710. } );
  62711. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  62712. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  62713. }
  62714. } else {
  62715. _settings.plugins = {};
  62716. }
  62717. _base = document.createElement( 'div' );
  62718. _base.className = 'rs-base';
  62719. _div = document.createElement( 'div' );
  62720. _div.className = 'rs-container';
  62721. _div.style.height = 'auto';
  62722. _base.appendChild( _div );
  62723. document.body.appendChild( _base );
  62724. if ( !_settings ) return;
  62725. if ( _settings.groups ) {
  62726. iterateKeys( _settings.groups, function ( j ) {
  62727. var g = _settings.groups[ parseInt( j, 10 ) ];
  62728. var div = document.createElement( 'div' );
  62729. div.className = 'rs-group';
  62730. g.div = div;
  62731. var h1 = document.createElement( 'h1' );
  62732. h1.textContent = g.caption;
  62733. h1.addEventListener( 'click', function ( e ) {
  62734. this.classList.toggle( 'hidden' );
  62735. e.preventDefault();
  62736. }.bind( div ) );
  62737. _div.appendChild( h1 );
  62738. _div.appendChild( div );
  62739. } );
  62740. }
  62741. if ( _settings.fractions ) {
  62742. iterateKeys( _settings.fractions, function ( j ) {
  62743. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62744. var div = document.createElement( 'div' );
  62745. div.className = 'rs-fraction';
  62746. var legend = document.createElement( 'div' );
  62747. legend.className = 'rs-legend';
  62748. var h = 0;
  62749. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  62750. var p = document.createElement( 'p' );
  62751. p.textContent = _settings.fractions[ j ].steps[ k ];
  62752. p.style.color = _colours[ h ];
  62753. legend.appendChild( p );
  62754. h++;
  62755. } );
  62756. div.appendChild( legend );
  62757. div.style.height = h * _elHeight + 'px';
  62758. f.div = div;
  62759. var graph = new StackGraph( div, h );
  62760. f.graph = graph;
  62761. _div.appendChild( div );
  62762. } );
  62763. }
  62764. }
  62765. function _update () {
  62766. iterateKeys( _settings.plugins, function ( j ) {
  62767. _settings.plugins[ j ].update();
  62768. } );
  62769. iterateKeys( _perfCounters, function ( j ) {
  62770. _perfCounters[ j ].draw();
  62771. } );
  62772. if ( _settings && _settings.fractions ) {
  62773. iterateKeys( _settings.fractions, function ( j ) {
  62774. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62775. var v = [];
  62776. var base = _perfCounters[ f.base.toLowerCase() ];
  62777. if ( base ) {
  62778. base = base.value();
  62779. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  62780. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  62781. var val = _perfCounters[ s ];
  62782. if ( val ) {
  62783. v.push( val.value() / base );
  62784. }
  62785. } );
  62786. }
  62787. f.graph.draw( v );
  62788. } );
  62789. }
  62790. /*if( _height != _div.clientHeight ) {
  62791. _height = _div.clientHeight;
  62792. _base.style.height = _height + 2 * _elHeight + 'px';
  62793. console.log( _base.clientHeight );
  62794. }*/
  62795. }
  62796. _init();
  62797. return function ( id ) {
  62798. if ( id ) return _perf( id );
  62799. return {
  62800. element: _base,
  62801. update: _update
  62802. };
  62803. };
  62804. }
  62805. if (typeof module === 'object') {
  62806. module.exports = window.rStats;
  62807. }
  62808. },{}],217:[function(_dereq_,module,exports){
  62809. // https://stackoverflow.com/a/36213464
  62810. if (!String.prototype.startsWith) {
  62811. String.prototype.startsWith = function(searchString, position){
  62812. position = position || 0;
  62813. return this.substr(position, searchString.length) === searchString;
  62814. };
  62815. }
  62816. },{}],218:[function(_dereq_,module,exports){
  62817. /*
  62818. * Copyright 2015 Google Inc. All Rights Reserved.
  62819. * Licensed under the Apache License, Version 2.0 (the "License");
  62820. * you may not use this file except in compliance with the License.
  62821. * You may obtain a copy of the License at
  62822. *
  62823. * http://www.apache.org/licenses/LICENSE-2.0
  62824. *
  62825. * Unless required by applicable law or agreed to in writing, software
  62826. * distributed under the License is distributed on an "AS IS" BASIS,
  62827. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62828. * See the License for the specific language governing permissions and
  62829. * limitations under the License.
  62830. */
  62831. var Util = {};
  62832. Util.base64 = function(mimeType, base64) {
  62833. return 'data:' + mimeType + ';base64,' + base64;
  62834. };
  62835. Util.isMobile = function() {
  62836. var check = false;
  62837. (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  62838. return check;
  62839. };
  62840. Util.isIOS = function() {
  62841. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  62842. };
  62843. Util.isIFrame = function() {
  62844. try {
  62845. return window.self !== window.top;
  62846. } catch (e) {
  62847. return true;
  62848. }
  62849. };
  62850. Util.appendQueryParameter = function(url, key, value) {
  62851. // Determine delimiter based on if the URL already GET parameters in it.
  62852. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  62853. url += delimiter + key + '=' + value;
  62854. return url;
  62855. };
  62856. // From http://goo.gl/4WX3tg
  62857. Util.getQueryParameter = function(name) {
  62858. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  62859. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  62860. results = regex.exec(location.search);
  62861. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  62862. };
  62863. Util.isLandscapeMode = function() {
  62864. return (window.orientation == 90 || window.orientation == -90);
  62865. };
  62866. module.exports = Util;
  62867. },{}],219:[function(_dereq_,module,exports){
  62868. /*
  62869. * Copyright 2015 Google Inc. All Rights Reserved.
  62870. * Licensed under the Apache License, Version 2.0 (the "License");
  62871. * you may not use this file except in compliance with the License.
  62872. * You may obtain a copy of the License at
  62873. *
  62874. * http://www.apache.org/licenses/LICENSE-2.0
  62875. *
  62876. * Unless required by applicable law or agreed to in writing, software
  62877. * distributed under the License is distributed on an "AS IS" BASIS,
  62878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62879. * See the License for the specific language governing permissions and
  62880. * limitations under the License.
  62881. */
  62882. var Util = _dereq_('./util.js');
  62883. /**
  62884. * Android and iOS compatible wakelock implementation.
  62885. *
  62886. * Refactored thanks to dkovalev@.
  62887. */
  62888. function AndroidWakeLock() {
  62889. var video = document.createElement('video');
  62890. video.addEventListener('ended', function() {
  62891. video.play();
  62892. });
  62893. this.request = function() {
  62894. if (video.paused) {
  62895. // Base64 version of videos_src/no-sleep-60s.webm.
  62896. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  62897. video.play();
  62898. }
  62899. };
  62900. this.release = function() {
  62901. video.pause();
  62902. video.src = '';
  62903. };
  62904. }
  62905. function iOSWakeLock() {
  62906. var timer = null;
  62907. this.request = function() {
  62908. if (!timer) {
  62909. timer = setInterval(function() {
  62910. window.location.href = '/';
  62911. setTimeout(window.stop, 0);
  62912. }, 15000);
  62913. }
  62914. }
  62915. this.release = function() {
  62916. if (timer) {
  62917. clearInterval(timer);
  62918. timer = null;
  62919. }
  62920. }
  62921. }
  62922. function getWakeLock() {
  62923. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  62924. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  62925. return iOSWakeLock;
  62926. } else {
  62927. return AndroidWakeLock;
  62928. }
  62929. }
  62930. module.exports = getWakeLock();
  62931. },{"./util.js":218}]},{},[176])(176)
  62932. });
  62933. //# sourceMappingURL=aframe-master.js.map